Scripts runtime
What the swarm-scripts runtime exposes to user code, what it does NOT expose, and how the typecheck stays aligned.
Swarm scripts are TypeScript modules persisted in the catalog via
/api/scripts/upsert and executed by the
scripts-runtime. The save-time typecheck and the runtime are deliberately
aligned — what passes the typecheck is what actually runs. This page documents
the full surface so script authors don't have to bisect.
Authoring contract
The default export always receives args first and ctx second. A
one-parameter function (ctx) treats the script arguments as ctx at runtime,
so every ctx.* access fails. For named scripts, export an argsSchema so
callers, schedules, and workflows can discover the JSON input contract:
import type { ScriptContext } from "swarm-sdk";
import * as z from "zod";
export const argsSchema = z.object({
taskId: z.string(),
limit: z.number().optional(),
});
export default async function (args: z.infer<typeof argsSchema>, ctx: ScriptContext) {
const response = await ctx.swarm.task_get({ taskId: args.taskId });
const task = ((response as { data?: unknown }).data ?? response) as {
title?: string;
};
return { title: task.title };
}Inline source passed to script-run skips the compile-time typecheck.
script-upsert typechecks before saving, so importing ScriptContext also
makes inline code promotion-safe. Use script-query-types for the authoritative
SDK and stdlib declarations. There is no ambient task context: values such as
taskId must arrive through args; the agent identity is propagated
automatically.
What the runtime provides
Scripts run inside a bun run subprocess (src/scripts-runtime/eval-harness.ts)
with the environment stripped to a small allowlist. Everything below is
available as a plain global in user code AND typechecks cleanly.
ES2022 standard library
The typecheck loads lib.es2022.d.ts. All standard ES2022 built-ins resolve:
- Primitives + boxed types:
Number,String,Boolean,Symbol,BigInt - Collections:
Array,Map,Set,WeakMap,WeakSet - Errors:
Error,TypeError,RangeError,SyntaxError,ReferenceError - Async:
Promise,Promise.all,Promise.allSettled,Promise.race,Promise.any - Iteration:
Iterator,IterableIterator,Generator - Reflection:
Object,Reflect,Proxy - JSON / Math / Date / RegExp
- Free functions:
isFinite,isNaN,parseInt,parseFloat,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI
Array<T>, Promise<T>, Record<K, V>, and structural object types all work
as you'd expect. No any-everywhere required.
Web platform — fetch, URL, encoding, timers, abort
These are exposed by Bun's runtime and explicitly declared in the typecheck runtime-globals shim:
fetch,Request,Response,Headers,RequestInit,ResponseInit,Blob,FormDataURL,URLSearchParamssetTimeout,clearTimeout,setInterval,clearInterval,setImmediate,clearImmediate,queueMicrotaskAbortController,AbortSignalTextEncoder,TextDecoder,atob,btoa,structuredClonecrypto.randomUUID(),crypto.getRandomValues(...),crypto.subtle
The fetch available in the runtime IS the one Bun provides — same shape as
Node 18+'s undici fetch. Prefer ctx.stdlib.fetch / ctx.stdlib.fetchJson for
built-in retries; bare fetch works too. See Retries.
For external APIs that need secrets, prefer
script connections for typed ctx.api /
ctx.mcp access, or the
scripts credential broker when you
truly need a hand-written fetch(). In both cases, avoid putting raw tokens in
source or args.
When a run ends
A run ends when the script's default export resolves. On native, a call
the script started but did not await (a fetch, a ctx.swarm.kv_set, a nested
ctx.swarm.script_run) gets 2 s more to settle. Anything still pending then is
stopped, and stderr says so. A run with nothing pending ends at once. On
quickjs the executor aborts open host calls as soon as the run ends (see
Executors). Await every call whose effect must land.
This lets a Promise.race deadline bound a run. A nested script_run that
lost the race is not cancelled: it keeps running on the server under its own
wall-clock limit and records its own run.
Console + logger
console.log / .warn / .error / .info / .debug are global. They also
hang off ctx.logger. Both write to the subprocess stderr (captured by the
executor and returned in the HTTP response's stderr field).
Node-compat surface
Bun's Node compatibility layer makes these available:
Buffer(Uint8Array-compatible, withBuffer.from(...),Buffer.concat(...), etc.)process.env— typed asRecord<string, string | undefined>. The environment is stripped to a small allowlist before the user script runs. You should NOT assume any specific env keys exist. Today's surviving keys:HOME,LANG,LC_ALL,PATH,TMPDIR,SWARM_SCRIPT_*(internal).process.platform,process.arch,process.version,process.cwd(),process.hrtime()
Retries
Three layers retry transient failures: status 429, 502, 503 or 504, or a network error.
ctx.swarm and ctx.mcp calls go to the API over loopback
(http://127.0.0.1:<PORT>), not through MCP_BASE_URL, so a public proxy in
front of the API is not in their path. The deployment env SCRIPT_API_BASE_URL
overrides this address. ctx.swarm.config.mcpBaseUrl still holds
MCP_BASE_URL, for scripts that fetch the API themselves.
ctx.swarmretries on its own. A 429 retries on every call, honouringRetry-After. A 502, 503, 504 or network error retries only on a read (GET routes and read tools such asdb_query,kv_get,get_*,list_*) or on a write whose route dedupes by itsIdempotency-Keyheader, such asworkflow_triggerwithidempotencyKey. Any other write is not repeated: it may have landed. Retries of a read stop after about 5 seconds, including a retry that hangs: the call then returns the earlier failure. A write's retry, keyed or not, is never cut off: it may be the write's first real run, and cutting it off would report a failure for work that went ahead.ctx.stdlib.fetch/fetchJsonretry by method. A 429 retries on every method. A 502, 503, 504 or network error retries on GET, HEAD, OPTIONS, PUT and DELETE, and on a POST or PATCH only when it carries anIdempotency-Keyheader.retry: { idempotencyKey: true }sends one generated UUID on every attempt (pass a string to choose it). The key prevents a duplicate only when the server dedupes by it. A stream body or a consumedRequestgets one attempt.retry: falsemakes one attempt; an object takes theretry()options below.retries: n(total attempts) still works but is deprecated.retry(fn, options?)wraps any function, sync or async. It callsfn(attempt)(1-based) and returns a Promise of its result. By default it retries any throw, plus a returned failedResponse,ctx.apiraw result orctx.swarmenvelope ({ success: false, status }) with a transient status. Options:retries(default 3),minDelayMs(200, doubled per retry with jitter),maxDelayMs(5000, also caps aRetry-Afterwait),budgetMs(30000 in total),retryOn(errorOrResult, attempt)to replace the default rule, andsignal: once it aborts,retrystops waiting and rejects with its reason (ctx.stdlib.fetchpasses its ownsignal). When attempts or budget run out it rethrows the last error or returns the last result.retry.wrap(fn, options?)returns a reusable function withfn's arguments.
const rows = await ctx.stdlib.retry(async () => {
const res = await ctx.swarm.db_query({ sql: "SELECT 1" });
if (!res.success) throw new Error(`db_query failed: ${res.status}`);
return res.data;
});
await ctx.stdlib.fetch("https://api.example.com/orders", {
method: "POST",
body: JSON.stringify(order),
retry: { idempotencyKey: true },
});Swarm-specific imports
import { fetch, fetchJson, grep, glob, table, retry, Redacted } from "stdlib";
// stdlib also flows through ctx.stdlib at runtimeimport type { ScriptContext, ScriptMain, SwarmConfig, Redacted } from "swarm-sdk";The ScriptContext passed to your default export carries:
ctx.swarm— typed SDK for in-swarm operations (memory, kv, tasks, scripts, repos, schedules). Method allowlist: seesrc/scripts-runtime/sdk-allowlist.ts.ctx.swarm.config—apiKey,agentId,mcpBaseUrl(all wrapped inRedacted<string>), plusctx.swarm.config.get("KEY")for swarm config resolved for the invoking agent (agent scope over global). An unset key returnsundefined. Unwrap withctx.stdlib.Redacted.value(...)only where the value is used, such as a request header. Redacted values stringify and serialize as<redacted>; never unwrap one into a return value, log line, or request body assembled by hand.ctx.api.<slug>/ctx.mcp.<slug>— typed clients for registered script connections. They exist only for configured connections; inspectObject.keys(ctx.api ?? {})orObject.keys(ctx.mcp ?? {})before use.- App-generated namespaces — each registered Swarm App contributes declarations
for its named queries and actions, including typed
app_queryoverloads, to the save-time script type environment. Inspect the effective declarations withscript-query-types; the surface follows the app definition available when the script is authored or updated. ctx.fsandctx.sh— the run's virtual filesystem (the agent's agent-fs drive at/afs, memory everywhere else) and a bash interpreter over it. See Files and shell.ctx.db: the SQL dialect of the swarm database (ctx.db.dialect) and a query helper that returns rows as objects (ctx.db.query). See SQL.ctx.stdlib— the runtime helpers (fetch,fetchJson,grep,glob,table,retry,Redacted). See Retries.ctx.logger— Console-compatible logger; same destination as the globalconsole.
Most SDK results are wrapper objects { success, status, data }; read
response.data ?? response before narrowing the payload. success is false
when the HTTP call failed, and also when a tool reached through the generic MCP
bridge refused the call (HTTP 200 with data.success === false); a refusal
also copies data.message to message. Failures
resolve; they do not throw, except for script_search and script_run. Prefer registered connections for authenticated calls:
credentials are attached server-side and do not enter script source or args.
Stored scripts are not automatically re-typechecked when an app definition or
registered connection changes. After a schema change, run script-query-types
and upsert affected scripts again so stale assumptions fail during validation
instead of at runtime.
ctx.swarm.* receives the complete scrubbed SDK response instead of the
10,000-byte model-facing MCP replacement. Both inline/named scripts and durable
workflow scripts stream these responses through a separate 64 MiB hard limit.
Crossing that limit cancels the response and throws an error asking you to
narrow or paginate the query; the runtime never silently truncates a field.
The wider boundary applies only inside the script sandbox. When a script
returns its result through script-run, that result crosses the agent-facing
MCP boundary again: responses over 10,000 serialized UTF-8 bytes are replaced
with a bounded preview or omission plus the per-agent KV spill pointer. Process
large collections inside the script and return only the compact derived value
the model needs.
SQL
The swarm database runs on SQLite or on PostgreSQL. ctx.db.dialect is
"sqlite" or "postgres". The API sets it when the run starts, from its
storage engine, so a script does not need a probe query to learn it.
ctx.db.query(sql, params?) runs read-only SQL through ctx.swarm.db_query,
with the same permissions, row cap, budget and errors. It returns the rows as
objects keyed by column name. Unlike db_query, it throws when the query fails.
sql is portable text, or an object with one text for each dialect. The helper
runs the text of the active dialect:
export default async function (args: { scriptName: string }, ctx: ScriptContext) {
const runs = await ctx.db.query<{ status: string; n: number }>(
'SELECT status, count(*) AS n FROM script_runs WHERE "scriptName" = $1 GROUP BY status',
[args.scriptName],
);
const slow = await ctx.db.query({
sqlite: `SELECT id FROM script_runs WHERE (julianday("finishedAt") - julianday("startedAt")) * 86400 > 60 LIMIT 20`,
postgres: `SELECT id FROM script_runs WHERE extract(epoch FROM "finishedAt" - "startedAt") > 60 LIMIT 20`,
});
return { dialect: ctx.db.dialect, runs, slow };
}An object without both texts throws a TypeError. The db_query response
still carries its dialect field. Durable workflow runs do not get ctx.db.
Files and shell
Each run gets one virtual filesystem. ctx.fs reads and writes it, and
ctx.sh runs bash commands over the same files.
import type { ScriptContext } from "swarm-sdk";
export default async function (_args: unknown, ctx: ScriptContext) {
// The agent's agent-fs drive: persistent, versioned.
await ctx.fs.writeFile("/afs/reports/today.md", "# Today\n");
// The working directory is /afs, so this appends to the same file.
await ctx.sh("echo '- shipped the release' >> reports/today.md");
// Scratch memory: gone when the run ends.
await ctx.fs.writeFile("/tmp/ids.txt", "b\na\nb\n");
const { stdout, exitCode } = await ctx.sh("sort -u /tmp/ids.txt | wc -l");
return { unique: Number(stdout.trim()), exitCode };
}| Path | Backing | Lifetime |
|---|---|---|
/afs/... | The invoking agent's default agent-fs drive, with that agent's permissions | Persistent, versioned |
Any other path (/tmp, /work, ...) | Memory | One run |
ctx.fshasreadFile,writeFile,appendFile,readdir,stat,exists,mkdir,rm,cp, andmv. Content is UTF-8 text.statreturnsisFile,isDirectory,size, andmtime(ISO 8601).ctx.sh(command, { cwd, env, stdin })returns{ stdout, stderr, exitCode }. A failed command returns a non-zeroexitCode. It does not throw.- Relative paths resolve against
/afs(against/when the drive is not mounted). - Files stay across
ctx.shcalls in one run. The working directory,env, and shell variables reset on each call.
ctx.sh runs just-bash, a bash
interpreter written in TypeScript. It starts no process. Pipes, redirects,
globs, loops, and text tools work: grep, sed, awk, jq, sort, uniq,
wc, head, tail, cut, find, xargs, and more. There are no real
binaries (git, curl, node, python) and no network. Some output differs
from GNU tools: for example, grep -r pattern . prints file:line without the
./ prefix.
When /afs is mounted. The API mounts the drive only when it finds all of
these for the invoking agent:
AGENT_FS_API_URL,AGENT_FS_DEFAULT_ORG_ID, andAGENT_FS_DEFAULT_DRIVE_ID, from swarm config first, then the API environment.- The agent's own agent-scoped
AGENT_FS_API_KEYrow. The runner provisions one for each agent (see agent-fs co-deployment). A global or repo row and the API's bootstrap key never mount the drive, so a run without an invoking agent has no/afs.
Without the drive, scratch paths and ctx.sh still work. An /afs path fails
with agent-fs is not configured for this agent (...), from ctx.fs and from
shell commands and redirects alike. A scratch symlink to /afs, or a cp or
mv into /, fails the same way. A file that looks persistent never lands in
memory.
With the drive, a scratch symlink cannot reach it: a path that goes through a
symlink into /afs fails with EXDEV. Use the /afs path itself.
ctx.fs and ctx.sh never hold the key: drive requests carry a
credential-broker placeholder, and the egress layer puts the agent's key on
requests to the agent-fs host only. This is not a confinement boundary. Like
the agent's other config secrets, the key is readable through
ctx.swarm.config.get.
Caching. The drive adapter keeps stat and directory listings for 5
seconds. The run's own writes show at once. A change that another agent makes
during the run can take up to 5 seconds to show in ls or stat. File
contents are always read fresh.
Limits. These limits apply to each run, under both executors:
- Scratch files hold at most 64 MiB. A write over the limit fails with
ENOSPC. - Scratch paths, directories, and empty files share an 8 MiB metadata budget.
Each entry costs 256 bytes plus 2 bytes for each path character, which allows
about 30,000 entries. A write over the budget fails with
ENOSPC. Remove files to free the budget. - A scratch name has at most 255 characters, and a scratch path at most 4096. A
longer one fails with
ENAMETOOLONG. - One
ctx.shcommand can read, hold, or print at most 64 MiB. A command over the limit exits with code 126. - One drive response carries at most 64 MiB. A larger
/afsfile fails withEFBIGinctx.fs, and a shell tool reports a read error.
The first ctx.fs or ctx.sh call in a run loads the shell (about 200 ms
under native). Runs that do not use them pay nothing.
Primitive objects
ctx.objects gives agent-fs files on your default drive a stable id. It calls
the object-* MCP tools and runs as your own agent-scoped AGENT_FS_API_KEY,
never the API's service key. Each method returns the tool payload without
success and throws on a refusal. Flat ctx.swarm.objects_* calls keep the
raw envelope.
export default async function (_args, ctx) {
const { object } = await ctx.objects.create({ kind: "board", path: "/boards/roadmap.excalidraw" });
const { objects } = await ctx.objects.list({ kind: "board" });
return { id: object.id, link: object.link, boards: objects.length };
}A board is an Excalidraw scene, and its id lives in the file under swarm.id.
A stock Excalidraw save drops that field. ctx.objects.reindex() then keeps the
id of the row at the same path and writes it back. Durable workflow runs get
ctx.objects too.
The index follows agent-fs edits, deletes and moves on its own when the swarm
can register an agent-fs file.changed webhook on the drive. That needs the
API's agent-fs service key, a PUBLIC_MCP_BASE_URL (or MCP_BASE_URL) that
agent-fs accepts (public https, or a host in its AGENT_FS_WEBHOOK_ALLOWED_HOSTS)
and an agent-fs with webhooks. Registration is best-effort:
without it, object tools work as before and reindex() catches the index up.
reindex() re-reads only files whose version changed, at most 50 per call; run
it again while truncated is true. A deleted file hides its object from
list() until the file comes back.
Without arguments, reindex() writes an id into every id-less file of the kind
on your default drive, including files other people put there. Pass prefix
(the same path-prefix match as list(); one file's path works too) to limit it,
and dryRun: true to get the report with nothing written:
const plan = await ctx.objects.reindex({ kind: "sheet", prefix: "reports/", dryRun: true });
if (plan.adopted.length > 0) await ctx.objects.reindex({ kind: "sheet", prefix: "reports/" });ctx.sheets refuses a workbook whose swarm.id a save dropped, and names the
reindex() call that writes it back.
Sheets
ctx.sheets reads and writes spreadsheets (swarm-sheet/1, a .sheet.json
file on your default drive). Every method calls a sheet-* MCP tool as your own
agent-fs identity, returns the payload without success, and throws on a refusal.
Formulas recompute on every write; a read returns the cached result.
export default async function (_args, ctx) {
const { object } = await ctx.sheets.create({ path: "qa/tracker.sheet.json" });
await ctx.sheets.setRange({
id: object.id,
range: "Sheet1!B2:C3",
values: [[1, "=B2*2"], [2, "=B3*2"]],
});
const { values } = await ctx.sheets.getRange({ id: object.id, range: "B2:C3" });
return values; // [[1, 2], [2, 4]]
}A string starting with = is a formula; start with '= for literal text that
begins with =. Other strings stay text, so send numbers as numbers. A
single-cell range is the top-left corner of the values; a larger one must
match their size. Limits: 20 tabs, 50,000 cells, 5 MiB, 10,000 cells per range
call. Durable workflow runs get ctx.sheets too.
ctx.sheets.importXlsx turns an .xlsx on the drive into a new sheet, and
ctx.sheets.exportXlsx writes a sheet to a new .xlsx. Both return dropped,
the features the other side cannot hold (styles, charts, comments, frozen panes,
and so on). An import refuses a file over 5 MiB, 20 tabs or 50,000 cells, and
creates nothing when it refuses. An export refuses an existing targetPath
unless overwrite: true.
export default async function (_args, ctx) {
const { object, dropped } = await ctx.sheets.importXlsx({
sourcePath: "in/budget.xlsx",
path: "out/budget.sheet.json",
});
const { path } = await ctx.sheets.exportXlsx({
id: object.id,
targetPath: "out/budget-copy.xlsx",
});
return { dropped, path };
}Boards
ctx.boards edits boards as Excalidraw element JSON through the board-* tools.
Arrows name a shape key from the same call or an existing element id, and bind
on both ends. Shapes without x/y are laid out below the existing content.
export default async function (_args, ctx) {
const { object, added } = await ctx.boards.create({
path: "/boards/flow.excalidraw",
shapes: [
{ key: "req", type: "rectangle", label: "Request", color: "blue" },
{ key: "lead", type: "diamond", label: "Lead" },
],
arrows: [{ from: "req", to: "lead", label: "send-task" }],
});
await ctx.boards.updateElements({ id: object.id, patches: [{ elementId: added.lead, label: "Lead routes" }] });
const { elements } = await ctx.boards.get({ id: object.id });
return { link: object.link, elements: elements.length };
}Every write sends the file version as If-Match. On a concurrent change it
re-reads and re-applies, up to three times, and each touched element gets a new
version so an open editor repaints it. Label sizes are Excalifont estimates;
the editor re-measures them on open.
Durable workflow context
Scripts launched through launch-script-run receive a different context:
ctx.run— the durable run'sid,agentId, andargsctx.step.rawLlm(label, config),ctx.step.agentTask(label, config), andctx.step.swarmScript(label, config)— replay-safe, journaled stepsctx.swarm,ctx.stdlib,ctx.logger,ctx.objects, andctx.sheets
Durable runs do not receive ctx.api, ctx.mcp, ctx.fs, ctx.sh, ctx.db, or
ctx.swarm.config. When a durable workflow needs a registered connection or
the drive, call a named script through ctx.step.swarmScript.
Durable objects
A global script can default-export a class that extends DurableObject from
swarm-sdk. Each object id is one instance with its own JSON state. Only one
call runs on an instance at a time.
import { DurableObject } from "swarm-sdk";
export default class Counter extends DurableObject<{ n: number }> {
initialState() { return { n: 0 }; }
async add(args: { by: number }) { this.state.n += args.by; return this.state.n; }
}Call a method with script_run and the object field:
{ "name": "counter", "object": { "id": "team-a", "method": "add" }, "args": { "by": 2 } }The response adds object: { id, stateVersion, destroyed }.
- The API saves
this.state(JSON, at most 2 MiB) only when the method returns without an error. migrate(state, fromVersion)runs once after a new script version.this.destroy()deletes the state.static idleTtlSecexpires idle state.kv_geton namespacedurable:<scriptId>, keystate/<id>, returns the scrubbed snapshot. KV writes ondurable:namespaces are refused.- A busy instance returns 409
object busyafter 30 s (5 s for a nested call). A call to an instance already in the call chain returns 409. More than 16 nested script runs return 400. - Agent-scope upserts and inline runs of a DurableObject class are refused.
Allowed bare imports
The TypeScript import allowlist (src/scripts-runtime/import-allowlist.ts):
stdlibswarm-sdkzod— for declaringexport const argsSchema = z.object({...})zod/mini— the same schemas with a smaller bundle (useful underquickjs). Mini uses functional forms:z.optional(z.string()),z._default(z.number(), 10),z.string().check(z.minLength(1)). Its schemas still have.parse()and.safeParse().
import "fs" / "node:fs" / "path" / any unlisted bare specifier is
rejected at upsert and at run time.
What the runtime does NOT provide
These are rejected by the typecheck and would also fail at runtime — they do NOT exist in the script sandbox:
- DOM APIs —
window,document,localStorage,sessionStorage,HTMLElement,Event, etc. The typecheck does NOT includelib.dom.d.ts. We did this on purpose; the runtime is not a browser. - Filesystem —
fs,node:fs,node:fs/promises. Usectx.fs(see Files and shell).ctx.stdlib.globandctx.stdlib.grepare for read-only file inspection inworkspace-rwmode (v2 only). - Subprocess —
node:child_process,Bun.spawn. Scripts cannot shell out.ctx.shinterprets bash in TypeScript and starts no process. - Net —
node:net, raw TCP/UDP. Outbound HTTP viafetchonly. Bun.*globals — even though Bun is the runtime, scripts cannot access theBunobject directly. Usectx.stdlibinstead.
Typecheck diagnostics
When script-upsert rejects code, the response is structured:
{
"error": "typecheck_failed",
"diagnostics": ["...colorized full diagnostic..."],
"structured": [
{
"severity": "error",
"code": 2552,
"message": "Cannot find name 'Mat'. Did you mean 'Math'?",
"file": "/virtual/user-script.ts",
"line": 1,
"column": 28,
"endLine": 1,
"endColumn": 31,
"identifier": "Mat",
"suggestion": "Math"
}
]
}Each entry carries the TypeScript diagnostic code (TS2552, TS2304, …),
the precise location, the offending identifier when it's a name lookup, and
the compiler's "did you mean…" hint when one is offered.
Runtime errors
When a script throws at runtime, the HTTP response includes a
runtimeError field beside stderr:
{
"exitCode": 1,
"error": "eval_error",
"stderr": "Error: kaboom from line 4\n at user-script.ts:4:13",
"runtimeError": {
"name": "Error",
"message": "kaboom from line 4",
"stack": "Error: kaboom from line 4\n at .../user-script.ts:4:13\n ...",
"userFrames": [{ "file": "user-script.ts", "line": 4, "column": 13, "raw": "at user-script.ts:4:13" }],
"userScriptLine": 4,
"userScriptColumn": 13
}
}Stack frames inside the harness or node_modules are stripped from the
stderr text shown to clients (they remain in runtimeError.stack for
debugging). The user-script path is normalized to the basename
user-script.ts — absolute tmpdir paths never leak.
Executors
The SCRIPT_EXECUTOR environment variable on the API server selects how
scripts run. The setting applies to every script run on that server.
| Value | How it runs | Per-run overhead (Linux) |
|---|---|---|
native (default) | A sandboxed bun subprocess with ulimit limits. Everything on this page applies. | ~10 ms (process spawn) |
quickjs (experimental) | QuickJS compiled to WASM, in a pool of worker threads inside the API process. | ~1 ms |
Durable script runs (launch-script-run, POST /api/script-runs) have only a
native runner. Under quickjs the server refuses new durable runs with a 400
and marks any durable run it would restart as failed.
Workflow script nodes (inline bash, ts or python) also run as a native
subprocess. Under quickjs the step fails before it spawns. Use a
swarm-script node instead.
Under quickjs, saving a script stores no argsJsonSchema, because reading
the argsSchema export means evaluating the module in native Bun. Runs still
validate their args against argsSchema inside the sandbox.
SCRIPT_QUICKJS_POOL_SIZE (default 4, 1 to 32) caps the quickjs worker
threads. The pool reads it once, when it is first created, so restart the API
after a change. More workers trade memory for concurrent throughput.
quickjs suits short scripts that call the swarm or HTTP APIs, for example
scripts that you expose externally. It
does not suit CPU-heavy scripts: an interpreter runs them 3-11x slower than
Bun. A script that imports zod also pays ~10-25 ms per run to evaluate the
zod code it uses, which can make it slower than native.
The quickjs sandbox has no filesystem, no process APIs, and no network
access except the host calls below. These are the differences from native:
- Available:
ctx.swarm,ctx.api,ctx.mcp,ctx.fs,ctx.sh,ctx.stdlib.fetch,ctx.stdlib.fetchJson,ctx.stdlib.table,ctx.stdlib.retry,ctx.stdlib.Redacted,ctx.logger,console,fetch,Headers,Response,setTimeout,clearTimeout,setInterval,clearInterval,URL,URLSearchParams,TextEncoder,TextDecoder(UTF-8 only),atob,btoa,crypto.randomUUID,crypto.getRandomValues,structuredClone, and thezod,zod/mini,stdlib, andswarm-sdkimports. structuredClone: clones primitives, objects and class instances (as plain objects), sparse arrays, boxed primitives, dates, regular expressions, maps, sets, built-in errors,ArrayBuffer, typed arrays andDataView. Cycles and shared references are preserved. Error subtypes and messages are retained; custom error properties, includingcause, are not. Non-empty transfer lists and shared or resizable buffers throwDataCloneError; proxy objects are outside the shim's supported surface. Cloning runs entirely inside the sandbox.fetchbodies: a request body can be a string, aUint8Arrayor other typed array, anArrayBuffer, orURLSearchParams. A binary body is capped at 16 MiB, and the binary bodies one run has in flight or queued at 64 MiB; a larger request fails before it is sent. A response exposesstatus,ok,headers,text(), andjson(). Streams,Blob,FormData,arrayBuffer(), andAbortSignalare not supported.- Not available:
ctx.stdlib.glob,ctx.stdlib.grep,process,Bun,Buffer,crypto.subtle,Intl(sotoLocaleString(locale, options)ignores its arguments),AbortController, andAbortSignal. The typecheck accepts some of them, soscript-upsert, script API creation, and app writes return awarningslist when the source uses one. The same list flags a literalfetch,ctx.stdlib.fetch, orfetchJsonURL whose host is single-label or private: whether quickjs reaches it depends on the egress policy, which allows private hosts only when the operator opts in. The warnings never block the save. - Top-level
awaitis not supported. Put the work inside the default export. - Limits:
memoryMbis the QuickJS heap limit (error: "oom"), andwallClockMsbounds both synchronous code and awaited calls (error: "timeout"). Runtime errors keep theruntimeErrorshape above, with lines mapped back touser-script.ts. - Host calls: at most 16 host calls (
fetch,ctx.swarm,ctx.api,ctx.mcp,ctx.fs,ctx.sh) run at the same time for one script, and the rest wait.ctx.fsandctx.shrun on the host side, in the API process, so the limits in Files and shell apply instead ofmemoryMb. A run can have at most 1024 host calls and timers in flight or waiting. When the run ends, the executor aborts every host call that is still open, including afetchthat the script did not await.
Egress policy
The quickjs executor checks every outbound request it makes for a
script: fetch, ctx.stdlib.fetch, ctx.stdlib.fetchJson, ctx.api.*, and
requests that carry a credential broker
substitution. By default it refuses these destinations:
- loopback (
127.0.0.0/8,::1),localhost, and*.localhost - private ranges (
10/8,172.16/12,192.168/16,fc00::/7) - link-local, including cloud metadata (
169.254/16,fe80::/10) - CGNAT (
100.64/10),0/8, multicast, reserved ranges, and IPv4-mapped or NAT64 forms of any of these
The check runs on the resolved addresses, so a public name that points at a
private address is refused. The request then connects to the address that was
checked, with the original name kept for the Host header and TLS
certificate check. The check runs again on every redirect hop, with at most 5
hops for the whole chain. A redirect to another origin drops Authorization
and Cookie. The refusal error names the setting to change.
Two settings control the policy. Both apply to new runs after a config reload.
| Key | Default | Effect |
|---|---|---|
SCRIPT_EGRESS_ALLOW_PRIVATE | false | true allows private, loopback and link-local destinations. |
SCRIPT_EGRESS_ALLOWLIST | empty | Comma-separated host[:port] patterns. A leading *. matches subdomains. When set, scripts can reach only these hosts, public or private. Empty means any public host. |
ctx.swarm, ctx.mcp and SQL connection queries (ctx.api.<slug>.query)
still reach the swarm API: only those host calls are exempt from the policy. A direct script request to the swarm API's address
follows the configured policy like any other host. Script code cannot read the
credential the host uses for those calls: Redacted.value(ctx.swarm.config.apiKey) and
Redacted.value(ctx.swarm.config.runtimeInstanceId) throw
host-only credential. agentId, mcpBaseUrl and your own config values stay
readable.
The native executor enforces none of this yet. Native scripts can reach
any host, including private ones, and can read the host credential. Run only
trusted code under native.
The credential broker is not an egress filter. It substitutes a secret only for a binding's allowed hosts, but it does not block requests to other hosts. A redirect goes back through the broker, so a substituted credential never follows a redirect to another host.
Exposing a script externally
A saved script can be opted in to a public HTTP endpoint —
POST /api/x/script/<id> — for callers
outside the swarm, with optional bearer auth and typed input validation
against the same argsJsonSchema this page describes.
Running scripts from the user MCP
The user MCP (/mcp-user) exposes code mode as three tools: script-search,
script-get-types and script-run. A run there acts as the person who called
it:
- Its
ctx.swarmcalls present a short-lived token for that user, revoked when the run ends. The API applies that user's permissions and sends no agent identity, so tools that need an agent fail. - It gets no agent's credential bindings, connections or
/afsdrive, and no deployment egress secrets. - It creates no task. It records a script run with
agentIduser-mcpand the user as requester. - Only global scripts are visible. Inline source is neither typechecked nor saved.
With RBAC on, script-search needs script.search and script-run needs
script.run. Admins hold both; the built-in requester and viewer roles
hold neither. script-get-types is a read open to every user.
When to escalate
If you find code that runs fine in the runtime but fails the typecheck, treat
it as a swarm bug, not a script bug. Add a probe to src/tests/scripts-typecheck.test.ts
and either expand the runtime-globals shim
(SCRIPT_RUNTIME_GLOBALS in src/be/scripts/typecheck.ts) or open an issue
with the failing snippet.
Read and write app rows
Scripts can use ctx.swarm.app_rows_list, app_row_get, app_row_create, app_rows_create, app_row_patch, app_row_delete, and app_rows_delete.
Each method requires appId and model. Results use the usual data wrapper.
export default async function (args, ctx) {
await ctx.swarm.app_row_create({
appId: args.appId,
model: "note",
values: { title: "New note" },
});
const res = await ctx.swarm.app_rows_list({
appId: args.appId,
model: "note",
equals: { title: "New note" },
sort: "createdAt:desc",
limit: 20,
});
return res?.data ?? res;
}Writes record agent:<agentId> as the writer. Source projections and join keys remain read-only.
Row inputs must fit within 1 MiB. Bulk creation accepts 1 to 500 value objects and at most 10 MiB total.
Listing accepts typed equality filters for declared and system columns, sorting, and a limit from 1 to 1000 (default 200).
Bulk deletion requires a non-empty equals filter and defaults to a limit of 1000.
App actions remain REST/MCP-only. Scripts and extensions cannot invoke app-action-run, and the SDK excludes it to prevent recursion.