Skip to content
Sign in Create account

Browser code interpreter

The @cloakapi/sdk/browser code interpreter turns a model’s declarative file spec or Python source into files on the caller’s device. Your app sends the model its prompt, supplies the local placeholder map and inputs to the interpreter, and decides whether to display, download, or send the resulting files. The interpreter makes no CloakAPI gateway call.

Use the SDK

codeInterpreter(config?) returns a capability with systemPrompt and tools for your model integration, parse(call) to validate a call, and run(call, options?) to produce its files. describeCodeInterpreter() and capability.describe() return the capability manifest. A call has a kind of make_file or run_python and a body containing the file spec or Python source.

import { codeInterpreter } from '@cloakapi/sdk/browser';
const interpreter = codeInterpreter({ theme: 'dark' });
const result = await interpreter.run({
kind: 'make_file',
body: {
format: 'csv',
filename: 'sales',
rows: 'INPUT_ROWS',
},
}, {
inputs: { INPUT_ROWS: [{ Quarter: 'Q1', Sales: 120 }] },
});
const download = result.files[0]; // name, mime, bytes
WhereOptions
Capability defaultstheme for charts, runPython with workerUrl, mirrorBase, timeoutMs, and loadTimeoutMs, and attestByDefault for optional receipts.
Each run callmap maps placeholders to originals. inputs binds local data to names such as INPUT_ROWS, INPUT_TABLE, and INPUT_TEXT. theme, zipName, and attest control chart styling, the ZIP filename, and receipt signing. Python calls also take the four worker settings and an onProgress callback.
Direct Tier A helpersparseFileSpec(raw), buildFile(spec, options?), makeFiles(body, options?), and makeFilesWithBundle(body, options?). Build options are map, inputs, and theme. The bundle helper also accepts zipName.
Direct Tier B helpersparseRunPython(raw), runPython(body, options?), and runPythonWithBundle(body, options?). Python options include map, inputs, the four worker settings, onProgress, and optional packages and wheels overrides. The bundle helper also accepts zipName.

Each generated file gives you its name, mime, and bytes. The capability and the bundle helpers add a ZIP when they return more than one file. Set attest to request a signed device receipt for local file-build facts, or call capability.attest(kind, files) for files already produced. The receipt contains no measurement of network egress.

Tier A — declarative files with make_file

Tier A runs in the calling JavaScript context. The builders bind local input handles and replace recognized placeholders using the supplied map. A recognized placeholder with no local mapping raises an error.

FormatSupported spec
CSVRows with optional column names.
JSONA data value or rows.
XLSXA table or a workbook with multiple sheets.
DOCX, PDFHeadings, paragraphs, lists, and tables. A chart block emits a text note. Request a separate chart file for the graphic.
SVG, PNGBar, line, scatter, and pie charts. SVG is generated directly. PNG requires working 2D canvas encoding in the page or worker.

For a PNG request that cannot be encoded, the file ends in .svg, has MIME image/svg+xml, and carries formatSubstitution: { requested: 'png', actual: 'svg', reason: 'png-rendering-unavailable' }. Use the returned filename and MIME for downloads and report the substitution in your UI.

Tier B — Python with run_python

Tier B runs Python with Pyodide in a fresh classic Web Worker for each SDK call. Serve PYODIDE_WORKER_SOURCE under /_cloak/pyodide-worker or /_cloak/pyodide-worker.js on your app origin. Pass that URL as workerUrl. If you omit it, the SDK creates a Blob worker. Python execution requires a Web Worker.

The runner replaces recognized placeholders in the Python source and passes structured inputs separately as Python globals. Write files under OUT_DIR (/out). The worker reads files recursively from that directory. The runner returns their bytes, with MIME types inferred from extensions. Progress can include Python stdout and stderr. Treat all files and progress messages as output from the supplied code.

Runtime and package files

Host the Pyodide 0.26.4 distribution on the embedding app’s own HTTP(S) origin under /pyodide/v0.26.4/. Include pyodide.js, pyodide.mjs, pyodide.asm.js, pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json, and the distribution files for the selected packages and their dependencies. The SDK starts with pyodide.js and uses this directory as Pyodide’s indexURL. The host and worker both check the origin and exact versioned index path. mirrorBase defaults to /pyodide/ and must resolve to that same pinned path after appending the version.

The default distribution packages are numpy, pandas, matplotlib, Pillow, and lxml. The worker also loads micropip to install these files under /pyodide/v0.26.4/wheels/:

  • openpyxl-3.1.5-py2.py3-none-any.whl
  • et_xmlfile-2.0.0-py3-none-any.whl
  • python_docx-1.1.2-py3-none-any.whl
  • typing_extensions-4.12.2-py3-none-any.whl

The SDK’s wheel bootstrap passes explicit local URLs to micropip.install with deps: false, so this step uses the vendored dependency set. The SDK checks URLs and pins the version and wheel filenames. It supplies no independent runtime digest check or Subresource Integrity for the loader or these wheels. Verify the contents of your mirror before serving them.

Request guard and worker boundary

For the generated worker, the guard starts before the runtime loader. It checks that covered URLs use HTTP(S) and the worker’s own origin and are under /pyodide/v0.26.4/. The canonical URL must have no embedded credentials, query, or fragment, and its path must have no percent encoding. The table lists guard behavior for the worker SDK source under src/browser/code-interpreter/.

APIStatus and scopeSDK source
fetchBlocked outside the mirror. Mirror GETs must have no body or caller headers. The guard sends them without credentials or a referrer and rejects redirects.tier-b/network-block.ts:56–128, tier-b/worker-source.ts:16–20
XMLHttpRequestBlocked by replacing the constructor when available.tier-b/network-block.ts:130–137
WebSocketBlocked by a throwing global replacement.tier-b/network-block.ts:139–142
EventSourceBlocked by a throwing global replacement.tier-b/network-block.ts:143–145
importScriptsBlocked outside the allowed mirror URL path. The wrapper delegates allowed script loads to the browser.tier-b/network-block.ts:159–174, tier-b/worker-source.ts:16–20, 76–79
Dynamic import()Outside the JS guard. Browser CSP and browser support determine what can load.tier-b/network-block.ts:101–174
pyodide.http / pyfetchNo Python-level block. Calls that use the worker’s wrapped fetch inherit its restrictions.tier-b/network-block.ts:101–128, tier-b/worker-source.ts:77–83
micropipAvailable. The SDK bootstrap installs the explicit mirror wheel URLs with dependency resolution off. Later calls are subject to the wrapped APIs they use.tier-b/worker-source.ts:99–107
navigator.sendBeaconInapplicable as a standard dedicated-worker API. The guard attempts to replace it if a navigator object is present.tier-b/network-block.ts:147–157
Nested workersOutside the JS guard. Control worker creation with CSP.tier-b/network-block.ts:101–174
postMessage to the pageAvailable. The SDK uses it for readiness, progress, output files, and errors.tier-b/worker-source.ts:44–45, 137–151

The load timeout defaults to the greater of 180 seconds and the compute timeout. Runtime and package progress reset the load timer. At the first run progress message, the fixed compute timeout begins. Its default is 60 seconds. The runner terminates the worker on completion, error, or timeout. The SDK sets no separate heap or output-size limit.

What your application must enforce

Use a dedicated worker response with CSP and configure the embedding page’s worker-src to allow your trusted worker URL. Allow blob: only if you use the Blob fallback, which depends on the creating page’s policy. Apply restrictive connect-src, script-src, and worker-src on the served worker response. Allow the mirror resources and WebAssembly compilation needed by your deployment, and deny other script, connection, and descendant worker sources. If you use origin-wide sources such as 'self', those sources also match other endpoints on that origin.

Serve the pinned runtime and wheels as static files from your own origin. Keep the mirror free of user uploads and redirects, including for importScripts. Configure COOP and COEP if your application needs cross-origin isolation for features such as shared memory.

The isolation boundary is a browser worker with JavaScript request wrappers and the CSP you apply. OS-level isolation of hostile code, complete egress prevention, and trust in generated output are outside the SDK’s guarantees. Keep secrets such as credentials and API keys out of the code, input bindings, and placeholder map. Validate outputs before display or onward transfer and avoid rendering generated HTML or SVG as trusted application content.