@draht/codemode 2026.10.20-1 → 2026.10.23-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/cloudflare.d.ts +53 -0
  2. package/dist/cloudflare.d.ts.map +1 -0
  3. package/dist/cloudflare.js +64 -0
  4. package/dist/cloudflare.js.map +1 -0
  5. package/dist/declarations.d.ts +7 -17
  6. package/dist/declarations.d.ts.map +1 -1
  7. package/dist/declarations.js +115 -125
  8. package/dist/declarations.js.map +1 -1
  9. package/dist/index.d.ts +6 -3
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +5 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/portable.d.ts +15 -0
  14. package/dist/portable.d.ts.map +1 -0
  15. package/dist/portable.js +12 -0
  16. package/dist/portable.js.map +1 -0
  17. package/dist/runtime/execution.d.ts +68 -0
  18. package/dist/runtime/execution.d.ts.map +1 -0
  19. package/dist/runtime/execution.js +513 -0
  20. package/dist/runtime/execution.js.map +1 -0
  21. package/dist/runtime/host.d.ts +8 -31
  22. package/dist/runtime/host.d.ts.map +1 -1
  23. package/dist/runtime/host.js +52 -296
  24. package/dist/runtime/host.js.map +1 -1
  25. package/dist/runtime/inline.d.ts +63 -0
  26. package/dist/runtime/inline.d.ts.map +1 -0
  27. package/dist/runtime/inline.js +80 -0
  28. package/dist/runtime/inline.js.map +1 -0
  29. package/dist/runtime/prelude-source.d.ts +18 -4
  30. package/dist/runtime/prelude-source.d.ts.map +1 -1
  31. package/dist/runtime/prelude-source.js +202 -21
  32. package/dist/runtime/prelude-source.js.map +1 -1
  33. package/dist/runtime/protocol.d.ts +49 -6
  34. package/dist/runtime/protocol.d.ts.map +1 -1
  35. package/dist/runtime/protocol.js +6 -1
  36. package/dist/runtime/protocol.js.map +1 -1
  37. package/dist/runtime/remote.d.ts +102 -0
  38. package/dist/runtime/remote.d.ts.map +1 -0
  39. package/dist/runtime/remote.js +175 -0
  40. package/dist/runtime/remote.js.map +1 -0
  41. package/dist/runtime/vm.d.ts +24 -0
  42. package/dist/runtime/vm.d.ts.map +1 -0
  43. package/dist/runtime/vm.js +297 -0
  44. package/dist/runtime/vm.js.map +1 -0
  45. package/dist/runtime/worker.js +11 -110
  46. package/dist/runtime/worker.js.map +1 -1
  47. package/dist/source.d.ts +2 -1
  48. package/dist/source.d.ts.map +1 -1
  49. package/dist/source.js +8 -2
  50. package/dist/source.js.map +1 -1
  51. package/dist/types.d.ts +129 -15
  52. package/dist/types.d.ts.map +1 -1
  53. package/dist/types.js.map +1 -1
  54. package/package.json +16 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vm.js","sourceRoot":"","sources":["../../src/runtime/vm.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAsB,cAAc,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEpG,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAyBrD;;;GAGG;AACH,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,iGAAiG;AACjG,SAAS,KAAK,CAAC,IAAY;IAC1B,IAAI,IAAI,GAAG,UAAU,CAAC;IACtB,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QAClD,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QAC/B,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IACpC,CAAC;IACD,OAAO,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AACnD,CAAC;AAED,MAAM,YAAY,GAAG,KAAK,CAAC,cAAc,CAAC,CA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CAAC,EAAE,CAAC,CAAC;YACnE,OAAO,OAAO,CAAC;QAChB,CAAC;QACD,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;QACxC,EAAE,CAAC,OAAO,EAAE,CAAC;QACb,KAAK,EAAE,CAAC;QACR,IAAI,KAAK;YAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;IACnD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Drives one QuickJS VM through one script, independent of the transport that connects it to the\n * host. The worker thread, the in-thread launcher, and the remote server all run the VM through\n * this module, so the bridge between prelude and host exists once.\n *\n * Contract with the caller:\n * - `post` receives every message for the host, synchronously from inside VM callbacks. The\n * caller must not re-enter the VM from `post` (no `deliver`, no `dispose`); a worker posts to\n * another thread, and the in-thread launcher defers delivery to a microtask.\n * - `deliver` hands the VM a tool result and runs the script until it waits again. It must only be\n * called while the VM is idle, which holds for any caller that never re-enters from `post`.\n * - `shouldInterrupt` is polled by QuickJS while the script runs, and here between batches of\n * promise jobs. Returning true throws an uncatchable error in the script; the VM then reports\n * `crash` or a failed `done`. The job batches matter for a script such as `while (true) await\n * null`: every iteration is a separate job that executes only a few opcodes, so QuickJS's own\n * polling, which counts opcodes, would let it run for a long time between polls.\n * - The VM never decides on its own when it is finished: after `done` or `crash` it stays alive\n * until the caller disposes it (or terminates the worker that hosts it).\n *\n * Failures after the VM exists are reported as a `crash` message; `startVm` only rejects when the\n * VM cannot be created at all.\n *\n * Deterministic mode (`data.deterministic`, used by `CodemodeSandboxBase.start()`): a script must make the same\n * calls with the same arguments every time it runs with the same results, so a host can replay it after a restart.\n * The VM is otherwise deterministic, because it only runs when the host delivers something and has no timers.\n * What remains is fixed here:\n * - Time: every WASI clock reads virtual time, `startedAt` and then the `now` of the result being processed, never going backwards.\n * While the context is created, the realtime clock reads a value derived from the seed instead, because QuickJS\n * seeds `Math.random()` from the first clock read, and which read comes first is the engine's business.\n * - Randomness: `random_get` draws from a PRNG over the seed.\n * - Timezone: UTC, not the host's.\n * - Garbage collection: `WeakRef` and `FinalizationRegistry` are not available; collection timing is not.\n * - Delivery order: results carry a `seq` and are applied strictly in that order, buffering early ones, because a\n * transport (RPC replies) may deliver them in another order than the host sent them.\n * The VM reports `started` with its fingerprint before the script runs, and `idle` with the number of calls issued\n * after each drain, so the host can check a replay step by step.\n */\nimport { Intrinsics, JSException, type JSValueHandle, MAX_STACK_SIZE, QuickJS } from \"quickjs-wasi\";\nimport type { CodemodeWasmModule } from \"../wasm.ts\";\nimport { PRELUDE_SOURCE } from \"./prelude-source.ts\";\nimport type { HostToWorkerMessage, VmStartData, WorkerToHostMessage } from \"./protocol.ts\";\n\nexport interface VmSession {\n\tdeliver(message: HostToWorkerMessage): void;\n\t/** Releases the VM's wasm instance. The session must not be used afterwards. */\n\tdispose(): void;\n}\n\nexport interface StartVmOptions {\n\tdata: VmStartData;\n\twasm: CodemodeWasmModule;\n\t/**\n\t * QuickJS's guard on its own stack, which turns deep recursion into a catchable `RangeError`.\n\t * The wasm frames also use the host thread's native stack, so the guard must trip before that\n\t * stack runs out: a host overflow fails the whole execution instead. Default: `MAX_STACK_SIZE`\n\t * (512 KiB), which fits the 4 MB stack of a Node worker thread but not a 1 MB main thread.\n\t */\n\tmaxStackSize?: number;\n\t/** Interrupt polls this VM may use, if the launcher counts them; part of the fingerprint. */\n\tinterruptBudget?: number;\n\tpost(message: WorkerToHostMessage): void;\n\tshouldInterrupt(): boolean;\n}\n\n/**\n * Bumped whenever this module or the prelude changes what a deterministic script observes, beyond what the\n * fingerprint's other parts (engine versions, prelude hash, limits) already capture.\n */\nconst DETERMINISTIC_VERSION = 1;\n\n/** FNV-1a over UTF-16 code units, as 8 hex digits: identifies the prelude in the fingerprint. */\nfunction fnv1a(text: string): string {\n\tlet hash = 0x811c9dc5;\n\tfor (let index = 0; index < text.length; index++) {\n\t\thash ^= text.charCodeAt(index);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nconst PRELUDE_HASH = fnv1a(PRELUDE_SOURCE);\n\n/** mulberry32: a small, fast PRNG; one 32-bit draw per call. */\nfunction prng(seed: number): () => number {\n\tlet state = seed >>> 0;\n\treturn () => {\n\t\tstate = (state + 0x6d2b79f5) >>> 0;\n\t\tlet value = Math.imul(state ^ (state >>> 15), 1 | state);\n\t\tvalue = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;\n\t\treturn (value ^ (value >>> 14)) >>> 0;\n\t};\n}\n\n/** The deterministic VM's clock: seed-derived while the context is created, then virtual time. */\ninterface VirtualClock {\n\tcreating: boolean;\n\tstartedAt: number;\n\tnow: number;\n\tseed: number;\n}\n\n/** WASI clock and random functions for deterministic mode, on top of {@link discardOutput}. */\nfunction deterministicWasi(clock: VirtualClock) {\n\tconst random = prng(clock.seed ^ 0x9e3779b9);\n\treturn (memory: { readonly buffer: ArrayBufferLike }) => ({\n\t\t...discardOutput(memory),\n\t\tclock_time_get(clockId: number, _precision: bigint, resultPtr: number): number {\n\t\t\tlet nanoseconds: bigint;\n\t\t\t// QuickJS seeds Math.random() from this reading in microseconds and turns 0 into 1, so seed s reads s + 1.\n\t\t\tif (clock.creating) nanoseconds = clockId === 0 ? BigInt(clock.seed + 1) * 1000n : 0n;\n\t\t\telse if (clockId === 0) nanoseconds = BigInt(Math.round(clock.now)) * 1_000_000n;\n\t\t\telse nanoseconds = BigInt(Math.round(clock.now - clock.startedAt)) * 1_000_000n;\n\t\t\tnew DataView(memory.buffer).setBigUint64(resultPtr, nanoseconds, true);\n\t\t\treturn 0;\n\t\t},\n\t\trandom_get(bufPtr: number, bufLen: number): number {\n\t\t\tconst bytes = new Uint8Array(memory.buffer, bufPtr, bufLen);\n\t\t\tfor (let index = 0; index < bufLen; index += 4) {\n\t\t\t\tconst value = random();\n\t\t\t\tfor (let byte = 0; byte < 4 && index + byte < bufLen; byte++) bytes[index + byte] = value >>> (byte * 8);\n\t\t\t}\n\t\t\treturn 0;\n\t\t},\n\t});\n}\n\n/**\n * QuickJS writes engine diagnostics to fd 1 and 2, which the default shim\n * forwards to the host's stdout and stderr. That output belongs to the host\n * application (for example a TUI), so it is discarded. Reporting every byte as\n * written keeps libc from retrying.\n */\nfunction discardOutput(memory: { readonly buffer: ArrayBufferLike }) {\n\treturn {\n\t\tfd_write(_fd: number, iovsPtr: number, iovsLen: number, nwrittenPtr: number): number {\n\t\t\tconst view = new DataView(memory.buffer);\n\t\t\tlet written = 0;\n\t\t\tfor (let i = 0; i < iovsLen; i++) {\n\t\t\t\twritten += view.getUint32(iovsPtr + i * 8 + 4, true);\n\t\t\t}\n\t\t\tview.setUint32(nwrittenPtr, written, true);\n\t\t\treturn 0;\n\t\t},\n\t};\n}\n\nfunction describeException(error: JSException): string {\n\tconst head = error.message ? `${error.name}: ${error.message}` : error.name;\n\tconst stack = error.stack?.trimEnd();\n\treturn JSON.stringify({ name: error.name, message: error.message, stack: stack ? `${head}\\n${stack}` : head });\n}\n\n/** Promise jobs run between two `shouldInterrupt` polls while draining the job queue. */\nconst JOBS_PER_POLL = 50;\n\nfunction crashMessage(error: unknown): WorkerToHostMessage {\n\treturn { type: \"crash\", message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };\n}\n\nexport async function startVm(options: StartVmOptions): Promise<VmSession> {\n\tconst { data, post } = options;\n\tconst maxStackSize = options.maxStackSize ?? MAX_STACK_SIZE;\n\tconst deterministic = data.deterministic;\n\tconst clock: VirtualClock | undefined = deterministic && {\n\t\tcreating: true,\n\t\tstartedAt: deterministic.startedAt,\n\t\tnow: deterministic.startedAt,\n\t\tseed: deterministic.seed >>> 0,\n\t};\n\tconst vm = await QuickJS.create({\n\t\twasm: options.wasm,\n\t\tmemoryLimit: data.memoryLimitBytes,\n\t\t// Without a guard, deep recursion overflows the wasm stack and traps instead of throwing a\n\t\t// catchable RangeError.\n\t\tmaxStackSize,\n\t\tinterruptHandler: options.shouldInterrupt,\n\t\twasi: clock ? deterministicWasi(clock) : discardOutput,\n\t\t...(clock ? { timezoneOffset: 0, intrinsics: Intrinsics.ALL & ~Intrinsics.WEAK_REF } : {}),\n\t});\n\tif (clock) clock.creating = false;\n\tlet disposed = false;\n\t/** Calls the script has issued, tools and globals; reported with every `idle`. */\n\tlet issued = 0;\n\t/** Deterministic mode: the next result to apply, and results that arrived before it. */\n\tlet nextSeq = 1;\n\t/** The result being processed, 0 during the script's first run; reported with `done`. */\n\tlet current = 0;\n\tconst early = new Map<number, HostToWorkerMessage>();\n\tconst apply = (message: HostToWorkerMessage): void => {\n\t\tvm.withScope(() => {\n\t\t\tvm.callFunction(\n\t\t\t\tsettle,\n\t\t\t\tapi,\n\t\t\t\tvm.newNumber(message.id),\n\t\t\t\tmessage.ok ? vm.true : vm.false,\n\t\t\t\tmessage.payload === undefined ? vm.undefined : vm.newString(message.payload),\n\t\t\t\tmessage.properties === undefined ? vm.undefined : vm.newString(message.properties),\n\t\t\t);\n\t\t});\n\t\tdrain();\n\t};\n\tconst session: VmSession = {\n\t\tdeliver(message) {\n\t\t\tif (disposed) return;\n\t\t\ttry {\n\t\t\t\tif (!clock) {\n\t\t\t\t\tapply(message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst { seq } = message;\n\t\t\t\tif (seq === undefined || !Number.isInteger(seq) || seq < nextSeq || early.has(seq)) {\n\t\t\t\t\tthrow new Error(`Result ${message.id} has sequence number ${seq}, expected ${nextSeq} or later, once`);\n\t\t\t\t}\n\t\t\t\tearly.set(seq, message);\n\t\t\t\tfor (let next = early.get(nextSeq); next !== undefined; next = early.get(nextSeq)) {\n\t\t\t\t\tearly.delete(nextSeq);\n\t\t\t\t\t// Never backwards: a resumed host's clock may be behind the one that started the run.\n\t\t\t\t\tif (next.now !== undefined && Number.isFinite(next.now)) clock.now = Math.max(clock.now, next.now);\n\t\t\t\t\tcurrent = nextSeq;\n\t\t\t\t\tapply(next);\n\t\t\t\t\tpost({ type: \"idle\", seq: nextSeq, issued });\n\t\t\t\t\tnextSeq++;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tpost(crashMessage(error));\n\t\t\t}\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tvm.dispose();\n\t\t},\n\t};\n\n\tlet api: JSValueHandle;\n\tlet settle: JSValueHandle;\n\tlet stalled: JSValueHandle;\n\t// `executePendingJobs()` runs the queue to empty without a chance to interrupt, so jobs run one at a\n\t// time through the (internal, but public) exports; quickjs-wasi is pinned to an exact version.\n\tconst exports = vm._getExports();\n\t/** Run queued jobs, then fail a script that waits on nothing that can ever resume it. */\n\tconst drain = () => {\n\t\tlet jobs = 0;\n\t\twhile (exports.qjs_is_job_pending()) {\n\t\t\t// A job only fails for uncatchable errors, such as an interrupt.\n\t\t\tif (exports.qjs_execute_pending_job() < 0) throw new Error(\"Promise job failed\");\n\t\t\tif (++jobs % JOBS_PER_POLL === 0 && options.shouldInterrupt()) throw new Error(\"Execution interrupted\");\n\t\t}\n\t\tvm.callFunction(stalled, api).dispose();\n\t};\n\n\ttry {\n\t\t// Called from the prelude with primitives only.\n\t\tconst bridge = vm.newFunction(\"bridge\", (kind, a, b, c) => {\n\t\t\tswitch (kind.toString()) {\n\t\t\t\tcase \"call\":\n\t\t\t\tcase \"global\":\n\t\t\t\t\tissued++;\n\t\t\t\t\tpost({\n\t\t\t\t\t\ttype: \"call\",\n\t\t\t\t\t\tid: a.toNumber(),\n\t\t\t\t\t\ttarget: kind.toString() === \"call\" ? \"tool\" : \"global\",\n\t\t\t\t\t\tname: b.toString(),\n\t\t\t\t\t\targs: c === undefined || c.isUndefined ? undefined : c.toString(),\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"output\":\n\t\t\t\t\tpost({\n\t\t\t\t\t\ttype: \"output\",\n\t\t\t\t\t\titem:\n\t\t\t\t\t\t\ta.toString() === \"image\"\n\t\t\t\t\t\t\t\t? { type: \"image\", data: b.toString(), mimeType: c.toString() }\n\t\t\t\t\t\t\t\t: a.toString() === \"console\"\n\t\t\t\t\t\t\t\t\t? { type: \"text\", text: b.toString(), console: true }\n\t\t\t\t\t\t\t\t\t: { type: \"text\", text: b.toString() },\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"done\": {\n\t\t\t\t\t// The host stops the VM on `done`, so the `idle` of this drain never arrives: report its numbers here.\n\t\t\t\t\tconst during = clock ? { during: { seq: current, issued } } : {};\n\t\t\t\t\tif (a.toBoolean()) {\n\t\t\t\t\t\tpost({\n\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\tok: true,\n\t\t\t\t\t\t\tvalue: b === undefined || b.isUndefined ? undefined : b.toString(),\n\t\t\t\t\t\t\twrites: c.toString(),\n\t\t\t\t\t\t\t...during,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpost({ type: \"done\", ok: false, error: b.toString(), ...during });\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn vm.undefined;\n\t\t});\n\n\t\t// These handles live as long as the VM, which the caller disposes as a whole.\n\t\tapi = vm.withScope((scope) =>\n\t\t\tscope.escape(\n\t\t\t\tvm.callFunction(\n\t\t\t\t\tvm.evalCode(PRELUDE_SOURCE, \"codemode-prelude.js\"),\n\t\t\t\t\tvm.undefined,\n\t\t\t\t\tbridge,\n\t\t\t\t\tvm.newString(JSON.stringify(data.tools)),\n\t\t\t\t\tvm.newString(JSON.stringify(data.globals)),\n\t\t\t\t\tvm.newString(JSON.stringify(data.store)),\n\t\t\t\t\tvm.newString(data.preLockdownSource ?? \"\"),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\tsettle = api.getProp(\"settle\");\n\t\tconst run = api.getProp(\"run\");\n\t\tstalled = api.getProp(\"stalled\");\n\t\tif (clock) {\n\t\t\tconst versions = vm.versions;\n\t\t\tconst budget = options.interruptBudget ?? \"none\";\n\t\t\t// Trusted host replacements change script behavior and must invalidate a replay too.\n\t\t\tconst preludeHash = data.preLockdownSource\n\t\t\t\t? fnv1a(`${PRELUDE_SOURCE}\\n${data.preLockdownSource}`)\n\t\t\t\t: PRELUDE_HASH;\n\t\t\tpost({\n\t\t\t\ttype: \"started\",\n\t\t\t\tfingerprint: `quickjs-wasi ${versions[\"quickjs-wasi\"]}, quickjs ${versions.quickjs}, prelude ${preludeHash}, deterministic ${DETERMINISTIC_VERSION}, stack ${maxStackSize}, heap ${data.memoryLimitBytes ?? \"none\"}, budget ${budget}`,\n\t\t\t});\n\t\t}\n\n\t\t// The prefix shares the first line with the script so reported line numbers\n\t\t// match the script as written.\n\t\tlet fn: JSValueHandle;\n\t\ttry {\n\t\t\tfn = vm.evalCode(`(async (tools, console) => {${data.code}\\n})`, \"codemode.js\");\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof JSException)) throw error;\n\t\t\tpost({ type: \"done\", ok: false, error: describeException(error) });\n\t\t\treturn session;\n\t\t}\n\t\tvm.callFunction(run, api, fn).dispose();\n\t\tfn.dispose();\n\t\tdrain();\n\t\tif (clock) post({ type: \"idle\", seq: 0, issued });\n\t} catch (error) {\n\t\tpost(crashMessage(error));\n\t}\n\treturn session;\n}\n"]}
@@ -11,127 +11,28 @@
11
11
  * or embedded-module string specifier as `workerUrl`.
12
12
  */
13
13
  import { parentPort, workerData } from "node:worker_threads";
14
- import { JSException, MAX_STACK_SIZE, QuickJS } from "quickjs-wasi";
15
- import { PRELUDE_SOURCE } from "./prelude-source.js";
16
14
  import { isHostToWorkerMessage } from "./protocol.js";
15
+ import { startVm } from "./vm.js";
17
16
  function post(message) {
18
17
  parentPort?.postMessage(message);
19
18
  }
20
- function crash(error) {
21
- post({ type: "crash", message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
22
- }
23
- /**
24
- * QuickJS writes engine diagnostics to fd 1 and 2, which the default shim
25
- * forwards to the host's stdout and stderr. That output belongs to the host
26
- * application (for example a TUI), so it is discarded. Reporting every byte as
27
- * written keeps libc from retrying.
28
- */
29
- function discardOutput(memory) {
30
- return {
31
- fd_write(_fd, iovsPtr, iovsLen, nwrittenPtr) {
32
- const view = new DataView(memory.buffer);
33
- let written = 0;
34
- for (let i = 0; i < iovsLen; i++) {
35
- written += view.getUint32(iovsPtr + i * 8 + 4, true);
36
- }
37
- view.setUint32(nwrittenPtr, written, true);
38
- return 0;
39
- },
40
- };
41
- }
42
- function describeException(error) {
43
- const head = error.message ? `${error.name}: ${error.message}` : error.name;
44
- const stack = error.stack?.trimEnd();
45
- return JSON.stringify({ name: error.name, message: error.message, stack: stack ? `${head}\n${stack}` : head });
46
- }
47
19
  async function main(data) {
48
20
  const interrupt = new Int32Array(data.interrupt);
49
- const vm = await QuickJS.create({
21
+ // The VM lives until the host terminates the worker, so the session is never disposed.
22
+ const session = await startVm({
23
+ data,
50
24
  wasm: data.wasm,
51
- memoryLimit: data.memoryLimitBytes,
52
- // Without a guard, deep recursion overflows the wasm stack and traps instead of throwing a
53
- // catchable RangeError.
54
- maxStackSize: MAX_STACK_SIZE,
55
- interruptHandler: () => Atomics.load(interrupt, 0) !== 0,
56
- wasi: discardOutput,
57
- });
58
- // Called from the prelude with primitives only.
59
- const bridge = vm.newFunction("bridge", (kind, a, b, c) => {
60
- switch (kind.toString()) {
61
- case "call":
62
- case "global":
63
- post({
64
- type: "call",
65
- id: a.toNumber(),
66
- target: kind.toString() === "call" ? "tool" : "global",
67
- name: b.toString(),
68
- args: c === undefined || c.isUndefined ? undefined : c.toString(),
69
- });
70
- break;
71
- case "output":
72
- post({
73
- type: "output",
74
- item: a.toString() === "image"
75
- ? { type: "image", data: b.toString(), mimeType: c.toString() }
76
- : { type: "text", text: b.toString() },
77
- });
78
- break;
79
- case "done":
80
- if (a.toBoolean()) {
81
- post({
82
- type: "done",
83
- ok: true,
84
- value: b === undefined || b.isUndefined ? undefined : b.toString(),
85
- writes: c.toString(),
86
- });
87
- }
88
- else {
89
- post({ type: "done", ok: false, error: b.toString() });
90
- }
91
- break;
92
- }
93
- return vm.undefined;
25
+ post,
26
+ shouldInterrupt: () => Atomics.load(interrupt, 0) !== 0,
94
27
  });
95
- // The VM lives until the host terminates the worker, so these handles are never disposed.
96
- const api = vm.withScope((scope) => scope.escape(vm.callFunction(vm.evalCode(PRELUDE_SOURCE, "codemode-prelude.js"), vm.undefined, bridge, vm.newString(JSON.stringify(data.tools)), vm.newString(JSON.stringify(data.globals)), vm.newString(JSON.stringify(data.store)))));
97
- const settle = api.getProp("settle");
98
- const run = api.getProp("run");
99
- const stalled = api.getProp("stalled");
100
- /** Run queued jobs, then fail a script that waits on nothing that can ever resume it. */
101
- const drain = () => {
102
- vm.executePendingJobs();
103
- vm.callFunction(stalled, api).dispose();
104
- };
105
28
  parentPort?.on("message", (message) => {
106
- if (!isHostToWorkerMessage(message))
107
- return;
108
- try {
109
- vm.withScope(() => {
110
- vm.callFunction(settle, api, vm.newNumber(message.id), message.ok ? vm.true : vm.false, message.payload === undefined ? vm.undefined : vm.newString(message.payload));
111
- });
112
- drain();
113
- }
114
- catch (error) {
115
- crash(error);
116
- }
29
+ if (isHostToWorkerMessage(message))
30
+ session.deliver(message);
117
31
  });
118
- // The prefix shares the first line with the script so reported line numbers
119
- // match the script as written.
120
- let fn;
121
- try {
122
- fn = vm.evalCode(`(async (tools, console) => {${data.code}\n})`, "codemode.js");
123
- }
124
- catch (error) {
125
- if (!(error instanceof JSException))
126
- throw error;
127
- post({ type: "done", ok: false, error: describeException(error) });
128
- return;
129
- }
130
- vm.callFunction(run, api, fn).dispose();
131
- fn.dispose();
132
- drain();
133
32
  }
134
33
  if (parentPort) {
135
- main(workerData).catch(crash);
34
+ main(workerData).catch((error) => {
35
+ post({ type: "crash", message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
36
+ });
136
37
  }
137
38
  //# sourceMappingURL=worker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../src/runtime/worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAsB,cAAc,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAA6C,MAAM,eAAe,CAAC;AAEjG,SAAS,IAAI,CAAC,OAA4B;IACzC,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,KAAK,CAAC,KAAc;IAC5B,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAC9G,CAAC;AAED;;;;;GAKG;AACH,SAAS,aAAa,CAAC,MAA4C;IAClE,OAAO;QACN,QAAQ,CAAC,GAAW,EAAE,OAAe,EAAE,OAAe,EAAE,WAAmB;YAC1E,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACzC,IAAI,OAAO,GAAG,CAAC,CAAC;YAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE,CAAC;gBAClC,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC;YACtD,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AC","sourcesContent":["/**\n * Worker thread entry. One worker runs one script inside a fresh QuickJS VM\n * (a separate wasm instance), relays tool calls and output to the host, and\n * reports the result. The host terminates the worker when the script settles,\n * times out, or is aborted; the worker exists so that a spinning script never\n * blocks the host thread.\n *\n * Importing this module starts the worker. Hosts that bundle their code (for\n * example a Bun compiled executable) add a file that imports\n * `@draht/codemode/worker` as a separate entrypoint and pass its URL\n * or embedded-module string specifier as `workerUrl`.\n */\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport { JSException, type JSValueHandle, MAX_STACK_SIZE, QuickJS } from \"quickjs-wasi\";\nimport { PRELUDE_SOURCE } from \"./prelude-source.ts\";\nimport { isHostToWorkerMessage, type WorkerData, type WorkerToHostMessage } from \"./protocol.ts\";\n\nfunction post(message: WorkerToHostMessage): void {\n\tparentPort?.postMessage(message);\n}\n\nfunction crash(error: unknown): void {\n\tpost({ type: \"crash\", message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });\n}\n\n/**\n * QuickJS writes engine diagnostics to fd 1 and 2, which the default shim\n * forwards to the host's stdout and stderr. That output belongs to the host\n * application (for example a TUI), so it is discarded. Reporting every byte as\n * written keeps libc from retrying.\n */\nfunction discardOutput(memory: { readonly buffer: ArrayBufferLike }) {\n\treturn {\n\t\tfd_write(_fd: number, iovsPtr: number, iovsLen: number, nwrittenPtr: number): number {\n\t\t\tconst view = new DataView(memory.buffer);\n\t\t\tlet written = 0;\n\t\t\tfor (let i = 0; i < iovsLen; i++) {\n\t\t\t\twritten += view.getUint32(iovsPtr + i * 8 + 4, true);\n\t\t\t}\n\t\t\tview.setUint32(nwrittenPtr, written, true);\n\t\t\treturn 0;\n\t\t},\n\t};\n}\n\nfunction describeException(error: JSException): string {\n\tconst head = error.message ? `${error.name}: ${error.message}` : error.name;\n\tconst stack = error.stack?.trimEnd();\n\treturn JSON.stringify({ name: error.name, message: error.message, stack: stack ? `${head}\\n${stack}` : head });\n}\n\nasync function main(data: WorkerData): Promise<void> {\n\tconst interrupt = new Int32Array(data.interrupt);\n\tconst vm = await QuickJS.create({\n\t\twasm: data.wasm,\n\t\tmemoryLimit: data.memoryLimitBytes,\n\t\t// Without a guard, deep recursion overflows the wasm stack and traps instead of throwing a\n\t\t// catchable RangeError.\n\t\tmaxStackSize: MAX_STACK_SIZE,\n\t\tinterruptHandler: () => Atomics.load(interrupt, 0) !== 0,\n\t\twasi: discardOutput,\n\t});\n\n\t// Called from the prelude with primitives only.\n\tconst bridge = vm.newFunction(\"bridge\", (kind, a, b, c) => {\n\t\tswitch (kind.toString()) {\n\t\t\tcase \"call\":\n\t\t\tcase \"global\":\n\t\t\t\tpost({\n\t\t\t\t\ttype: \"call\",\n\t\t\t\t\tid: a.toNumber(),\n\t\t\t\t\ttarget: kind.toString() === \"call\" ? \"tool\" : \"global\",\n\t\t\t\t\tname: b.toString(),\n\t\t\t\t\targs: c === undefined || c.isUndefined ? undefined : c.toString(),\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"output\":\n\t\t\t\tpost({\n\t\t\t\t\ttype: \"output\",\n\t\t\t\t\titem:\n\t\t\t\t\t\ta.toString() === \"image\"\n\t\t\t\t\t\t\t? { type: \"image\", data: b.toString(), mimeType: c.toString() }\n\t\t\t\t\t\t\t: { type: \"text\", text: b.toString() },\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"done\":\n\t\t\t\tif (a.toBoolean()) {\n\t\t\t\t\tpost({\n\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tvalue: b === undefined || b.isUndefined ? undefined : b.toString(),\n\t\t\t\t\t\twrites: c.toString(),\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tpost({ type: \"done\", ok: false, error: b.toString() });\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t\treturn vm.undefined;\n\t});\n\n\t// The VM lives until the host terminates the worker, so these handles are never disposed.\n\tconst api = vm.withScope((scope) =>\n\t\tscope.escape(\n\t\t\tvm.callFunction(\n\t\t\t\tvm.evalCode(PRELUDE_SOURCE, \"codemode-prelude.js\"),\n\t\t\t\tvm.undefined,\n\t\t\t\tbridge,\n\t\t\t\tvm.newString(JSON.stringify(data.tools)),\n\t\t\t\tvm.newString(JSON.stringify(data.globals)),\n\t\t\t\tvm.newString(JSON.stringify(data.store)),\n\t\t\t),\n\t\t),\n\t);\n\tconst settle = api.getProp(\"settle\");\n\tconst run = api.getProp(\"run\");\n\tconst stalled = api.getProp(\"stalled\");\n\t/** Run queued jobs, then fail a script that waits on nothing that can ever resume it. */\n\tconst drain = () => {\n\t\tvm.executePendingJobs();\n\t\tvm.callFunction(stalled, api).dispose();\n\t};\n\n\tparentPort?.on(\"message\", (message: unknown) => {\n\t\tif (!isHostToWorkerMessage(message)) return;\n\t\ttry {\n\t\t\tvm.withScope(() => {\n\t\t\t\tvm.callFunction(\n\t\t\t\t\tsettle,\n\t\t\t\t\tapi,\n\t\t\t\t\tvm.newNumber(message.id),\n\t\t\t\t\tmessage.ok ? vm.true : vm.false,\n\t\t\t\t\tmessage.payload === undefined ? vm.undefined : vm.newString(message.payload),\n\t\t\t\t);\n\t\t\t});\n\t\t\tdrain();\n\t\t} catch (error) {\n\t\t\tcrash(error);\n\t\t}\n\t});\n\n\t// The prefix shares the first line with the script so reported line numbers\n\t// match the script as written.\n\tlet fn: JSValueHandle;\n\ttry {\n\t\tfn = vm.evalCode(`(async (tools, console) => {${data.code}\\n})`, \"codemode.js\");\n\t} catch (error) {\n\t\tif (!(error instanceof JSException)) throw error;\n\t\tpost({ type: \"done\", ok: false, error: describeException(error) });\n\t\treturn;\n\t}\n\tvm.callFunction(run, api, fn).dispose();\n\tfn.dispose();\n\tdrain();\n}\n\nif (parentPort) {\n\tmain(workerData as WorkerData).catch(crash);\n}\n"]}
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../src/runtime/worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAA6C,MAAM,eAAe,CAAC;AACjG,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,SAAS,IAAI,CAAC,OAA4B;IACzC,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,KAAK,UAAU,IAAI,CAAC,IAAgB;IACnC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACjD,uFAAuF;IACvF,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC;QAC7B,IAAI;QACJ,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,IAAI;QACJ,eAAe,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC;KACvD,CAAC,CAAC;IACH,UAAU,EAAE,EAAE,CAAC,SAAS,EAAE,CAAC,OAAgB,EAAE,EAAE;QAC9C,IAAI,qBAAqB,CAAC,OAAO,CAAC;YAAE,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9D,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,IAAI,UAAU,EAAE,CAAC;IAChB,IAAI,CAAC,UAAwB,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACvD,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC9G,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Worker thread entry. One worker runs one script inside a fresh QuickJS VM\n * (a separate wasm instance), relays tool calls and output to the host, and\n * reports the result. The host terminates the worker when the script settles,\n * times out, or is aborted; the worker exists so that a spinning script never\n * blocks the host thread.\n *\n * Importing this module starts the worker. Hosts that bundle their code (for\n * example a Bun compiled executable) add a file that imports\n * `@draht/codemode/worker` as a separate entrypoint and pass its URL\n * or embedded-module string specifier as `workerUrl`.\n */\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport { isHostToWorkerMessage, type WorkerData, type WorkerToHostMessage } from \"./protocol.ts\";\nimport { startVm } from \"./vm.ts\";\n\nfunction post(message: WorkerToHostMessage): void {\n\tparentPort?.postMessage(message);\n}\n\nasync function main(data: WorkerData): Promise<void> {\n\tconst interrupt = new Int32Array(data.interrupt);\n\t// The VM lives until the host terminates the worker, so the session is never disposed.\n\tconst session = await startVm({\n\t\tdata,\n\t\twasm: data.wasm,\n\t\tpost,\n\t\tshouldInterrupt: () => Atomics.load(interrupt, 0) !== 0,\n\t});\n\tparentPort?.on(\"message\", (message: unknown) => {\n\t\tif (isHostToWorkerMessage(message)) session.deliver(message);\n\t});\n}\n\nif (parentPort) {\n\tmain(workerData as WorkerData).catch((error: unknown) => {\n\t\tpost({ type: \"crash\", message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });\n\t});\n}\n"]}
package/dist/source.d.ts CHANGED
@@ -29,7 +29,8 @@ export declare class CodemodeSourceError extends Error {
29
29
  }
30
30
  /**
31
31
  * Split an optional first-line `// @options: {...}` from the script. Throws
32
- * {@link CodemodeSourceError} for empty input and invalid options.
32
+ * {@link CodemodeSourceError} for empty input, invalid options, and an options line that is not the
33
+ * first line, which would otherwise be ignored without notice.
33
34
  */
34
35
  export declare function parseCodemodeSource(input: string): ParsedCodemodeSource;
35
36
  //# sourceMappingURL=source.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"source.d.ts","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,uBAAuB,iBAAiB,CAAC;AAOtD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAQnC,CAAC;AAEF,MAAM,WAAW,qBAAqB;IACrC,4CAA4C;IAC5C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gFAAgF;IAChF,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,oBAAoB;IACpC,iGAAiG;IACjG,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,qBAAqB,CAAC;CAC/B;AAED,qBAAa,mBAAoB,SAAQ,KAAK;IAC7C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AA8CD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,oBAAoB,CAevE"}
1
+ {"version":3,"file":"source.d.ts","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,uBAAuB,iBAAiB,CAAC;AAOtD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAQnC,CAAC;AAEF,MAAM,WAAW,qBAAqB;IACrC,4CAA4C;IAC5C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gFAAgF;IAChF,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,oBAAoB;IACpC,iGAAiG;IACjG,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,qBAAqB,CAAC;CAC/B;AAED,qBAAa,mBAAoB,SAAQ,KAAK;IAC7C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AA8CD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,oBAAoB,CAwBvE"}
package/dist/source.js CHANGED
@@ -72,14 +72,20 @@ function parseOptions(directive) {
72
72
  }
73
73
  /**
74
74
  * Split an optional first-line `// @options: {...}` from the script. Throws
75
- * {@link CodemodeSourceError} for empty input and invalid options.
75
+ * {@link CodemodeSourceError} for empty input, invalid options, and an options line that is not the
76
+ * first line, which would otherwise be ignored without notice.
76
77
  */
77
78
  export function parseCodemodeSource(input) {
78
79
  if (input.trim() === "") {
79
80
  throw new CodemodeSourceError('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.');
80
81
  }
82
+ const lines = input.split("\n");
83
+ const misplaced = lines.findIndex((line, index) => index > 0 && line.trimStart().startsWith(CODEMODE_OPTIONS_PREFIX));
84
+ if (misplaced !== -1) {
85
+ throw new CodemodeSourceError(`The ${CODEMODE_OPTIONS_PREFIX} line must be the first line of the input; found one on line ${misplaced + 1}`);
86
+ }
81
87
  const newline = input.indexOf("\n");
82
- const firstLine = (newline === -1 ? input : input.slice(0, newline)).replace(/\r$/, "");
88
+ const firstLine = lines[0].replace(/\r$/, "");
83
89
  const trimmed = firstLine.trimStart();
84
90
  if (!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX))
85
91
  return { code: input, options: {} };
@@ -1 +1 @@
1
- {"version":3,"file":"source.js","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,cAAc,CAAC;AAEtD,MAAM,gBAAgB,GAAG,CAAC,mBAAmB,EAAE,YAAY,CAAU,CAAC;AACtE,MAAM,qBAAqB,GAAG,sCAAsC,CAAC;AACrE,sEAAsE;AACtE,MAAM,cAAc,GAAG,aAAa,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC,GAAG,CAAA;;;;;;;;CAQhD,CAAC;AAeF,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC7C,YAAY,OAAe;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACnC,CAAC;CACD;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AAC/E,CAAC;AAED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AC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;AAC9F,CAAC","sourcesContent":["/**\n * Codemode source format: JavaScript, optionally preceded by one options line.\n *\n * ```js\n * // @options: {\"max_output_tokens\": 2000, \"timeout_ms\": 30000}\n * const text = await tools.read({ path: \"package.json\" });\n * text(JSON.parse(text).name);\n * ```\n */\n\nexport const CODEMODE_OPTIONS_PREFIX = \"// @options:\";\n\nconst SUPPORTED_FIELDS = [\"max_output_tokens\", \"timeout_ms\"] as const;\nconst SUPPORTED_FIELDS_TEXT = \"`max_output_tokens` and `timeout_ms`\";\n/** Largest delay `setTimeout` supports, which bounds `timeout_ms`. */\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * Lark grammar for providers with grammar-constrained tool input. It only fixes the shape of the\n * options line; the options JSON and the code are checked by {@link parseCodemodeSource}.\n */\nexport const CODEMODE_SOURCE_GRAMMAR = String.raw`\nstart: options_source | plain_source\noptions_source: OPTIONS_LINE NEWLINE SOURCE\nplain_source: SOURCE\n\nOPTIONS_LINE: /[ \\t]*\\/\\/ @options:[^\\r\\n]*/\nNEWLINE: /\\r?\\n/\nSOURCE: /[\\s\\S]+/\n`;\n\nexport interface CodemodeSourceOptions {\n\t/** Token budget for the script's output. */\n\tmaxOutputTokens?: number;\n\t/** Hard deadline for the whole script in milliseconds, including tool calls. */\n\ttimeoutMs?: number;\n}\n\nexport interface ParsedCodemodeSource {\n\t/** The script with the options line replaced by an empty line, so line numbers are unchanged. */\n\tcode: string;\n\toptions: CodemodeSourceOptions;\n}\n\nexport class CodemodeSourceError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"CodemodeSourceError\";\n\t}\n}\n\nfunction isSafeInteger(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction parseOptions(directive: string): CodemodeSourceOptions {\n\tif (directive === \"\") {\n\t\tthrow new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);\n\t}\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(directive);\n\t} catch (error) {\n\t\tthrow new CodemodeSourceError(\n\t\t\t`@options must be valid JSON with supported fields ${SUPPORTED_FIELDS_TEXT}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);\n\t}\n\tconst fields = value as Record<string, unknown>;\n\tfor (const key of Object.keys(fields)) {\n\t\tif (!(SUPPORTED_FIELDS as readonly string[]).includes(key)) {\n\t\t\tthrow new CodemodeSourceError(`@options only supports ${SUPPORTED_FIELDS_TEXT}; got \\`${key}\\``);\n\t\t}\n\t}\n\tconst options: CodemodeSourceOptions = {};\n\tconst { max_output_tokens, timeout_ms } = fields;\n\tif (max_output_tokens !== undefined) {\n\t\tif (!isSafeInteger(max_output_tokens)) {\n\t\t\tthrow new CodemodeSourceError(\"@options field `max_output_tokens` must be a non-negative safe integer\");\n\t\t}\n\t\toptions.maxOutputTokens = max_output_tokens;\n\t}\n\tif (timeout_ms !== undefined) {\n\t\tif (!isSafeInteger(timeout_ms) || timeout_ms === 0 || timeout_ms > MAX_TIMEOUT_MS) {\n\t\t\tthrow new CodemodeSourceError(\n\t\t\t\t`@options field \\`timeout_ms\\` must be a positive integer up to ${MAX_TIMEOUT_MS}`,\n\t\t\t);\n\t\t}\n\t\toptions.timeoutMs = timeout_ms;\n\t}\n\treturn options;\n}\n\n/**\n * Split an optional first-line `// @options: {...}` from the script. Throws\n * {@link CodemodeSourceError} for empty input and invalid options.\n */\nexport function parseCodemodeSource(input: string): ParsedCodemodeSource {\n\tif (input.trim() === \"\") {\n\t\tthrow new CodemodeSourceError(\n\t\t\t'Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {\"max_output_tokens\": 1000}`.',\n\t\t);\n\t}\n\tconst newline = input.indexOf(\"\\n\");\n\tconst firstLine = (newline === -1 ? input : input.slice(0, newline)).replace(/\\r$/, \"\");\n\tconst trimmed = firstLine.trimStart();\n\tif (!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX)) return { code: input, options: {} };\n\tconst code = newline === -1 ? \"\" : input.slice(newline);\n\tif (code.trim() === \"\") {\n\t\tthrow new CodemodeSourceError(\"The @options line must be followed by JavaScript source on subsequent lines\");\n\t}\n\treturn { code, options: parseOptions(trimmed.slice(CODEMODE_OPTIONS_PREFIX.length).trim()) };\n}\n"]}
1
+ {"version":3,"file":"source.js","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,cAAc,CAAC;AAEtD,MAAM,gBAAgB,GAAG,CAAC,mBAAmB,EAAE,YAAY,CAAU,CAAC;AACtE,MAAM,qBAAqB,GAAG,sCAAsC,CAAC;AACrE,sEAAsE;AACtE,MAAM,cAAc,GAAG,aAAa,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC,GAAG,CAAA;;;;;;;;CAQhD,CAAC;AAeF,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC7C,YAAY,OAAe;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACnC,CAAC;CACD;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AAC/E,CAAC;AAED,SAAS,YAAY,CAAC,SAAiB;IACtC,IAAI,SAAS,KAAK,EAAE,EAAE,CAAC;QACtB,MAAM,IAA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C,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACxD,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACxB,MAAM,IAAI,mBAAmB,CAAC,6EAA6E,CAAC,CAAC;IAC9G,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;AAC9F,CAAC","sourcesContent":["/**\n * Codemode source format: JavaScript, optionally preceded by one options line.\n *\n * ```js\n * // @options: {\"max_output_tokens\": 2000, \"timeout_ms\": 30000}\n * const text = await tools.read({ path: \"package.json\" });\n * text(JSON.parse(text).name);\n * ```\n */\n\nexport const CODEMODE_OPTIONS_PREFIX = \"// @options:\";\n\nconst SUPPORTED_FIELDS = [\"max_output_tokens\", \"timeout_ms\"] as const;\nconst SUPPORTED_FIELDS_TEXT = \"`max_output_tokens` and `timeout_ms`\";\n/** Largest delay `setTimeout` supports, which bounds `timeout_ms`. */\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * Lark grammar for providers with grammar-constrained tool input. It only fixes the shape of the\n * options line; the options JSON and the code are checked by {@link parseCodemodeSource}.\n */\nexport const CODEMODE_SOURCE_GRAMMAR = String.raw`\nstart: options_source | plain_source\noptions_source: OPTIONS_LINE NEWLINE SOURCE\nplain_source: SOURCE\n\nOPTIONS_LINE: /[ \\t]*\\/\\/ @options:[^\\r\\n]*/\nNEWLINE: /\\r?\\n/\nSOURCE: /[\\s\\S]+/\n`;\n\nexport interface CodemodeSourceOptions {\n\t/** Token budget for the script's output. */\n\tmaxOutputTokens?: number;\n\t/** Hard deadline for the whole script in milliseconds, including tool calls. */\n\ttimeoutMs?: number;\n}\n\nexport interface ParsedCodemodeSource {\n\t/** The script with the options line replaced by an empty line, so line numbers are unchanged. */\n\tcode: string;\n\toptions: CodemodeSourceOptions;\n}\n\nexport class CodemodeSourceError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"CodemodeSourceError\";\n\t}\n}\n\nfunction isSafeInteger(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction parseOptions(directive: string): CodemodeSourceOptions {\n\tif (directive === \"\") {\n\t\tthrow new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);\n\t}\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(directive);\n\t} catch (error) {\n\t\tthrow new CodemodeSourceError(\n\t\t\t`@options must be valid JSON with supported fields ${SUPPORTED_FIELDS_TEXT}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);\n\t}\n\tconst fields = value as Record<string, unknown>;\n\tfor (const key of Object.keys(fields)) {\n\t\tif (!(SUPPORTED_FIELDS as readonly string[]).includes(key)) {\n\t\t\tthrow new CodemodeSourceError(`@options only supports ${SUPPORTED_FIELDS_TEXT}; got \\`${key}\\``);\n\t\t}\n\t}\n\tconst options: CodemodeSourceOptions = {};\n\tconst { max_output_tokens, timeout_ms } = fields;\n\tif (max_output_tokens !== undefined) {\n\t\tif (!isSafeInteger(max_output_tokens)) {\n\t\t\tthrow new CodemodeSourceError(\"@options field `max_output_tokens` must be a non-negative safe integer\");\n\t\t}\n\t\toptions.maxOutputTokens = max_output_tokens;\n\t}\n\tif (timeout_ms !== undefined) {\n\t\tif (!isSafeInteger(timeout_ms) || timeout_ms === 0 || timeout_ms > MAX_TIMEOUT_MS) {\n\t\t\tthrow new CodemodeSourceError(\n\t\t\t\t`@options field \\`timeout_ms\\` must be a positive integer up to ${MAX_TIMEOUT_MS}`,\n\t\t\t);\n\t\t}\n\t\toptions.timeoutMs = timeout_ms;\n\t}\n\treturn options;\n}\n\n/**\n * Split an optional first-line `// @options: {...}` from the script. Throws\n * {@link CodemodeSourceError} for empty input, invalid options, and an options line that is not the\n * first line, which would otherwise be ignored without notice.\n */\nexport function parseCodemodeSource(input: string): ParsedCodemodeSource {\n\tif (input.trim() === \"\") {\n\t\tthrow new CodemodeSourceError(\n\t\t\t'Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {\"max_output_tokens\": 1000}`.',\n\t\t);\n\t}\n\tconst lines = input.split(\"\\n\");\n\tconst misplaced = lines.findIndex(\n\t\t(line, index) => index > 0 && line.trimStart().startsWith(CODEMODE_OPTIONS_PREFIX),\n\t);\n\tif (misplaced !== -1) {\n\t\tthrow new CodemodeSourceError(\n\t\t\t`The ${CODEMODE_OPTIONS_PREFIX} line must be the first line of the input; found one on line ${misplaced + 1}`,\n\t\t);\n\t}\n\tconst newline = input.indexOf(\"\\n\");\n\tconst firstLine = lines[0].replace(/\\r$/, \"\");\n\tconst trimmed = firstLine.trimStart();\n\tif (!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX)) return { code: input, options: {} };\n\tconst code = newline === -1 ? \"\" : input.slice(newline);\n\tif (code.trim() === \"\") {\n\t\tthrow new CodemodeSourceError(\"The @options line must be followed by JavaScript source on subsequent lines\");\n\t}\n\treturn { code, options: parseOptions(trimmed.slice(CODEMODE_OPTIONS_PREFIX.length).trim()) };\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -40,11 +40,12 @@ export interface CodemodeTool {
40
40
  }
41
41
  /**
42
42
  * One item of the script's output, in the order the script produced it: `text()` and `console.*`
43
- * produce text items, `image()` image items. `data` is base64.
43
+ * produce text items, with `console: true` for `console.*`, and `image()` image items. `data` is base64.
44
44
  */
45
45
  export type CodemodeOutputItem = {
46
46
  type: "text";
47
47
  text: string;
48
+ console?: true;
48
49
  } | {
49
50
  type: "image";
50
51
  data: string;
@@ -59,11 +60,17 @@ export interface CodemodeCall {
59
60
  export type CodemodeErrorKind =
60
61
  /** The script threw or failed to parse. `name` and `stack` come from the script's error. */
61
62
  "script"
62
- /** The overall deadline expired. The worker was terminated. */
63
+ /**
64
+ * The overall deadline expired, or a VM on the calling thread used up its interrupt budget.
65
+ * The execution ended and the VM was asked to stop; a worker or remote VM may still be computing.
66
+ */
63
67
  | "timeout"
64
- /** The caller's signal fired or the sandbox was closed. The worker was terminated. */
68
+ /** The caller's signal fired or the sandbox was closed. The execution ended and the VM was asked to stop. */
65
69
  | "aborted"
66
- /** The worker or VM failed outside the script's control (for example a wasm trap or a missing worker file). */
70
+ /**
71
+ * The VM or its transport failed outside the script's control (for example a wasm trap, a missing
72
+ * worker file, or a remote sandbox that failed).
73
+ */
67
74
  | "sandbox";
68
75
  export interface CodemodeError {
69
76
  kind: CodemodeErrorKind;
@@ -77,20 +84,41 @@ export interface CodemodeStoreWrites {
77
84
  /** Keys stored as `undefined`. */
78
85
  delete: string[];
79
86
  }
80
- /** `output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`. */
87
+ /**
88
+ * `output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`.
89
+ * `during`: in a {@link CodemodeSandboxBase.start} run that the script itself ended (it returned, threw, or exited),
90
+ * the result being processed when it did.
91
+ */
81
92
  export type CodemodeResult = {
82
93
  ok: true;
83
94
  value: unknown;
84
95
  output: CodemodeOutputItem[];
85
96
  calls: CodemodeCall[];
86
97
  storeWrites: CodemodeStoreWrites;
98
+ during?: CodemodeDuring;
87
99
  } | {
88
100
  ok: false;
89
101
  error: CodemodeError;
90
102
  output: CodemodeOutputItem[];
91
103
  calls: CodemodeCall[];
104
+ during?: CodemodeDuring;
92
105
  };
93
- export interface CodemodeSandboxOptions {
106
+ /** Options every sandbox accepts, wherever its VM runs. */
107
+ export interface CodemodeSandboxBaseOptions {
108
+ /**
109
+ * Trusted host code evaluated in the VM before built-ins are frozen. Never populate this
110
+ * from script input. Runs once per execution and is not exposed to the script.
111
+ */
112
+ preLockdownSource?: string;
113
+ /**
114
+ * Maximum combined character count across every `text()`, `console.*`, and `image()` output
115
+ * item. The VM's memory limit only bounds its own heap; output is copied into the host process
116
+ * and kept there for the life of the execution (`result.output`), so a script that only calls
117
+ * `console.log` in a loop would otherwise grow the host's memory without bound. Crossing it ends
118
+ * the execution with a `sandbox` error; `result.output` keeps the items received up to and
119
+ * including the one that crossed the limit. Default: no limit.
120
+ */
121
+ maxOutputChars?: number;
94
122
  tools?: CodemodeTool[];
95
123
  /**
96
124
  * Functions exposed as top-level identifiers instead of on `tools`, for host helpers such as
@@ -110,15 +138,9 @@ export interface CodemodeSandboxOptions {
110
138
  * `InternalError: out of memory`. Default: no limit beyond wasm32's 4 GiB address space.
111
139
  */
112
140
  memoryLimitBytes?: number;
113
- /**
114
- * Maximum combined character count across every `text()`, `console.*`, and `image()` output
115
- * item. The VM's memory limit only bounds its own heap; output is copied into the host process
116
- * and kept there for the life of the execution (`result.output`), so a script that only calls
117
- * `console.log` in a loop would otherwise grow the host's memory without bound. Crossing it ends
118
- * the execution with a `sandbox` error; `result.output` keeps the items received up to and
119
- * including the one that crossed the limit. Default: no limit.
120
- */
121
- maxOutputChars?: number;
141
+ }
142
+ /** Options of `CodemodeSandbox`, which runs each VM in a Node or Bun worker thread. */
143
+ export interface CodemodeSandboxOptions extends CodemodeSandboxBaseOptions {
122
144
  /**
123
145
  * Compiled `quickjs-wasi/quickjs.wasm`, usually from {@link loadQuickJSWasm}. Default:
124
146
  * `loadQuickJSWasm()`, the file in the installed `quickjs-wasi` package. Pass it when that file
@@ -132,6 +154,98 @@ export interface CodemodeSandboxOptions {
132
154
  * specifier of an embedded build entrypoint; other hosts usually use a URL.
133
155
  */
134
156
  workerUrl?: string | URL;
157
+ /**
158
+ * Synchronously reserves capacity immediately before creating each worker, after loading wasm.
159
+ * Throw to deny admission without starting a worker. Return a release callback, called once if
160
+ * worker construction fails or when the worker actually exits, not when the result settles.
161
+ * The release callback must not throw. Reservations can be shared across sandbox instances.
162
+ */
163
+ acquireWorker?(): () => void;
164
+ /**
165
+ * Called once for each worker started by execute() or start(). `exited` resolves when that worker
166
+ * actually exits, which may be after the result and close() settle: on Bun a non-interruptible
167
+ * built-in can delay termination. Use it to keep the worker counted against host concurrency
168
+ * limits until it exits. A thrown callback error fails the execution and requests worker termination.
169
+ */
170
+ onWorkerStarted?(exited: Promise<void>): void;
171
+ }
172
+ /** A call the script made in a {@link CodemodeSandboxBase.start} run, answered with `CodemodeRun.deliver()`. */
173
+ export interface CodemodeHostCall {
174
+ /** The VM's own number for the call, `1`, `2`, ... in the order the script made its calls (tools and globals). */
175
+ id: number;
176
+ target: "tool" | "global";
177
+ name: string;
178
+ /** What the script passed, after a JSON round trip; for spread globals the argument list. */
179
+ args: unknown;
180
+ }
181
+ /** A tool as a {@link CodemodeSandboxBase.start} run's script sees it: `tools.<name>` and its `ALL_TOOLS` entry. */
182
+ export interface CodemodeDeclaredTool {
183
+ name: string;
184
+ /**
185
+ * The identifier the script uses, `tools.<jsName>`. Default: `toCodemodeIdentifier(name)`. A host that replays a run
186
+ * passes the one the run started with, so a changed mapping cannot rename a tool under a resumed script.
187
+ */
188
+ jsName?: string;
189
+ description?: string;
190
+ }
191
+ /** A global as a {@link CodemodeSandboxBase.start} run's script sees it; the same names as `globals` allow. */
192
+ export interface CodemodeDeclaredGlobal {
193
+ name: string;
194
+ spread?: boolean;
195
+ }
196
+ /**
197
+ * A call's answer. A rejection becomes an `Error` with `message` in the script, carrying the own properties of
198
+ * `properties` (JSON values; `name`, `message`, and `stack` are ignored), for example `{ structuredOutput }`.
199
+ */
200
+ export type CodemodeOutcome = {
201
+ ok: true;
202
+ value: unknown;
203
+ } | {
204
+ ok: false;
205
+ message: string;
206
+ properties?: Record<string, unknown>;
207
+ };
208
+ /** In a {@link CodemodeSandboxBase.start} run: the result the VM was processing when the script finished, 0 for its first run, and the calls issued by then. */
209
+ export interface CodemodeDuring {
210
+ seq: number;
211
+ issued: number;
212
+ }
213
+ export interface CodemodeRunOptions {
214
+ /** The VM clock's start, in ms since the epoch: `Date.now()` until the first result arrives. */
215
+ startedAt: number;
216
+ /** Seeds `Math.random()` and the VM's other randomness. A 32-bit unsigned integer. */
217
+ seed: number;
218
+ tools?: CodemodeDeclaredTool[];
219
+ globals?: CodemodeDeclaredGlobal[];
220
+ store?: Readonly<Record<string, unknown>>;
221
+ signal?: AbortSignal;
222
+ /** Deadline of this run in ms. Default: none (not the sandbox's default). */
223
+ timeoutMs?: number;
224
+ /** The VM's fingerprint, before the script runs and before any of its calls. */
225
+ onStarted?(fingerprint: string): void;
226
+ /** The script made a call. Answer it with `CodemodeRun.deliver()`, now or later. */
227
+ onCall(call: CodemodeHostCall): void;
228
+ /**
229
+ * The VM processed result `seq` (`0`: the script's first run, before any result) and waits again, having issued
230
+ * `issued` calls in total.
231
+ */
232
+ onIdle?(seq: number, issued: number): void;
233
+ }
234
+ /** A running {@link CodemodeSandboxBase.start} execution. */
235
+ export interface CodemodeRun {
236
+ readonly result: Promise<CodemodeResult>;
237
+ /**
238
+ * Whether the run has its outcome: the script ended, timed out, or failed, or the run was aborted. Set when that is
239
+ * decided, before `result` settles; calls can no longer be answered. It does not mean the VM has exited.
240
+ */
241
+ readonly finished: boolean;
242
+ /**
243
+ * Answer call `id` as result number `seq`. Results are numbered 1, 2, ... without gaps, and the VM applies them
244
+ * strictly in that order, whatever order they arrive in: after a gap it waits for the missing number. While it
245
+ * processes this one, its clock reads `now` (ms since the epoch), or the previous value if `now` is earlier.
246
+ * Throws for a call that is not waiting for an answer, a `seq` used before, or a `now` that is not finite.
247
+ */
248
+ deliver(seq: number, now: number, id: number, outcome: CodemodeOutcome): void;
135
249
  }
136
250
  export interface CodemodeExecuteOptions {
137
251
  signal?: AbortSignal;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,C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AC;CAC1C"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { CodemodeWasmModule } from \"./wasm.ts\";\n\nexport interface CodemodeToolContext {\n\t/**\n\t * Aborted when the script finishes (including unawaited calls), the\n\t * execution times out, the caller aborts, or the sandbox is closed.\n\t */\n\tsignal: AbortSignal;\n}\n\n/** A JSON Schema document. Only used to render declarations; values are not validated against it. */\nexport type CodemodeJsonSchema = { [key: string]: unknown } | boolean;\n\nexport interface CodemodeTool {\n\t/**\n\t * The script calls tools as `tools.<id>(args)`, where `<id>` is the name with characters that\n\t * are not valid in identifiers replaced by `_` (see `toCodemodeIdentifier`), and also as\n\t * `tools[\"<name>\"](args)`. Globals are called as `<name>(args)` and must be identifiers, or\n\t * `<namespace>.<member>`, which groups them into a frozen namespace object.\n\t */\n\tname: string;\n\t/** Shown as a doc comment in {@link renderDeclarations}, and listed in `ALL_TOOLS` for tools. */\n\tdescription?: string;\n\t/** Schema of the single argument. Rendered as the parameter type; `unknown` when omitted. */\n\tinputSchema?: CodemodeJsonSchema;\n\t/** Schema of the resolved value. Rendered as the promise type; `unknown` when omitted. */\n\toutputSchema?: CodemodeJsonSchema;\n\t/** Globals only: `execute` receives all call arguments as an array instead of the first one. */\n\tspread?: boolean;\n\t/**\n\t * Globals only: TypeScript parameter list and return type for {@link renderDeclarations}, for\n\t * example `(type: string, id?: string): Promise<Model[]>`. Replaces the rendering from the schemas.\n\t */\n\tsignature?: string;\n\t/**\n\t * `args` is whatever the script passed, after a JSON round trip. The return\n\t * value must be JSON-serializable; a thrown error surfaces in the script as\n\t * an `Error` with the same message.\n\t */\n\texecute(args: unknown, context: CodemodeToolContext): Promise<unknown> | unknown;\n}\n\n/**\n * One item of the script's output, in the order the script produced it: `text()` and `console.*`\n * produce text items, `image()` image items. `data` is base64.\n */\nexport type CodemodeOutputItem = { type: \"text\"; text: string } | { type: \"image\"; data: string; mimeType: string };\n\nexport type CodemodeCallStatus = \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeCall {\n\tname: string;\n\tstatus: CodemodeCallStatus;\n\tdurationMs: number;\n}\n\nexport type CodemodeErrorKind =\n\t/** The script threw or failed to parse. `name` and `stack` come from the script's error. */\n\t| \"script\"\n\t/** The overall deadline expired. The worker was terminated. */\n\t| \"timeout\"\n\t/** The caller's signal fired or the sandbox was closed. The worker was terminated. */\n\t| \"aborted\"\n\t/** The worker or VM failed outside the script's control (for example a wasm trap or a missing worker file). */\n\t| \"sandbox\";\n\nexport interface CodemodeError {\n\tkind: CodemodeErrorKind;\n\tname?: string;\n\tmessage: string;\n\tstack?: string;\n}\n\n/** Keys the script changed with `store()`. Only successful executions report writes. */\nexport interface CodemodeStoreWrites {\n\tset: Record<string, unknown>;\n\t/** Keys stored as `undefined`. */\n\tdelete: string[];\n}\n\n/** `output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`. */\nexport type CodemodeResult =\n\t| {\n\t\t\tok: true;\n\t\t\tvalue: unknown;\n\t\t\toutput: CodemodeOutputItem[];\n\t\t\tcalls: CodemodeCall[];\n\t\t\tstoreWrites: CodemodeStoreWrites;\n\t }\n\t| { ok: false; error: CodemodeError; output: CodemodeOutputItem[]; calls: CodemodeCall[] };\n\nexport interface CodemodeSandboxOptions {\n\ttools?: CodemodeTool[];\n\t/**\n\t * Functions exposed as top-level identifiers instead of on `tools`, for host helpers such as\n\t * attaching an image to the result. They behave like tools (JSON round trip, promise result)\n\t * but are not recorded in `result.calls`. Names must be identifiers and may not shadow the\n\t * built-in globals (`tools`, `ALL_TOOLS`, `console`, `text`, `image`, `exit`, `store`, `load`).\n\t */\n\tglobals?: CodemodeTool[];\n\t/**\n\t * Overall deadline per execution, including time spent in tools. `Infinity` disables the\n\t * deadline; the execution then only ends when the script settles or is aborted.\n\t * Default: 300000.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum memory the QuickJS VM may allocate. Allocations beyond it fail inside the script as\n\t * `InternalError: out of memory`. Default: no limit beyond wasm32's 4 GiB address space.\n\t */\n\tmemoryLimitBytes?: number;\n\t/**\n\t * Maximum combined character count across every `text()`, `console.*`, and `image()` output\n\t * item. The VM's memory limit only bounds its own heap; output is copied into the host process\n\t * and kept there for the life of the execution (`result.output`), so a script that only calls\n\t * `console.log` in a loop would otherwise grow the host's memory without bound. Crossing it ends\n\t * the execution with a `sandbox` error; `result.output` keeps the items received up to and\n\t * including the one that crossed the limit. Default: no limit.\n\t */\n\tmaxOutputChars?: number;\n\t/**\n\t * Compiled `quickjs-wasi/quickjs.wasm`, usually from {@link loadQuickJSWasm}. Default:\n\t * `loadQuickJSWasm()`, the file in the installed `quickjs-wasi` package. Pass it when that file\n\t * is not on disk, for example in a Bun compiled executable.\n\t */\n\twasm?: CodemodeWasmModule | Promise<CodemodeWasmModule>;\n\t/**\n\t * Worker entry that imports `@draht/codemode/worker`. Default: this package's own\n\t * worker file. Pass it when this package is bundled, since the default is resolved relative to\n\t * the module that creates the sandbox. Bun compiled executables require the relative string\n\t * specifier of an embedded build entrypoint; other hosts usually use a URL.\n\t */\n\tworkerUrl?: string | URL;\n}\n\nexport interface CodemodeExecuteOptions {\n\tsignal?: AbortSignal;\n\t/** Overrides the sandbox default for this execution. */\n\ttimeoutMs?: number;\n\t/**\n\t * Values the script reads with `load(key)`. Must be JSON-serializable. The script's own\n\t * `store()` calls come back as `result.storeWrites`; persisting them is up to the caller.\n\t */\n\tstore?: Readonly<Record<string, unknown>>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { CodemodeWasmModule } from \"./wasm.ts\";\n\nexport interface CodemodeToolContext {\n\t/**\n\t * Aborted when the script finishes (including unawaited calls), the\n\t * execution times out, the caller aborts, or the sandbox is closed.\n\t */\n\tsignal: AbortSignal;\n}\n\n/** A JSON Schema document. Only used to render declarations; values are not validated against it. */\nexport type CodemodeJsonSchema = { [key: string]: unknown } | boolean;\n\nexport interface CodemodeTool {\n\t/**\n\t * The script calls tools as `tools.<id>(args)`, where `<id>` is the name with characters that\n\t * are not valid in identifiers replaced by `_` (see `toCodemodeIdentifier`), and also as\n\t * `tools[\"<name>\"](args)`. Globals are called as `<name>(args)` and must be identifiers, or\n\t * `<namespace>.<member>`, which groups them into a frozen namespace object.\n\t */\n\tname: string;\n\t/** Shown as a doc comment in {@link renderDeclarations}, and listed in `ALL_TOOLS` for tools. */\n\tdescription?: string;\n\t/** Schema of the single argument. Rendered as the parameter type; `unknown` when omitted. */\n\tinputSchema?: CodemodeJsonSchema;\n\t/** Schema of the resolved value. Rendered as the promise type; `unknown` when omitted. */\n\toutputSchema?: CodemodeJsonSchema;\n\t/** Globals only: `execute` receives all call arguments as an array instead of the first one. */\n\tspread?: boolean;\n\t/**\n\t * Globals only: TypeScript parameter list and return type for {@link renderDeclarations}, for\n\t * example `(type: string, id?: string): Promise<Model[]>`. Replaces the rendering from the schemas.\n\t */\n\tsignature?: string;\n\t/**\n\t * `args` is whatever the script passed, after a JSON round trip. The return\n\t * value must be JSON-serializable; a thrown error surfaces in the script as\n\t * an `Error` with the same message.\n\t */\n\texecute(args: unknown, context: CodemodeToolContext): Promise<unknown> | unknown;\n}\n\n/**\n * One item of the script's output, in the order the script produced it: `text()` and `console.*`\n * produce text items, with `console: true` for `console.*`, and `image()` image items. `data` is base64.\n */\nexport type CodemodeOutputItem =\n\t| { type: \"text\"; text: string; console?: true }\n\t| { type: \"image\"; data: string; mimeType: string };\n\nexport type CodemodeCallStatus = \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeCall {\n\tname: string;\n\tstatus: CodemodeCallStatus;\n\tdurationMs: number;\n}\n\nexport type CodemodeErrorKind =\n\t/** The script threw or failed to parse. `name` and `stack` come from the script's error. */\n\t| \"script\"\n\t/**\n\t * The overall deadline expired, or a VM on the calling thread used up its interrupt budget.\n\t * The execution ended and the VM was asked to stop; a worker or remote VM may still be computing.\n\t */\n\t| \"timeout\"\n\t/** The caller's signal fired or the sandbox was closed. The execution ended and the VM was asked to stop. */\n\t| \"aborted\"\n\t/**\n\t * The VM or its transport failed outside the script's control (for example a wasm trap, a missing\n\t * worker file, or a remote sandbox that failed).\n\t */\n\t| \"sandbox\";\n\nexport interface CodemodeError {\n\tkind: CodemodeErrorKind;\n\tname?: string;\n\tmessage: string;\n\tstack?: string;\n}\n\n/** Keys the script changed with `store()`. Only successful executions report writes. */\nexport interface CodemodeStoreWrites {\n\tset: Record<string, unknown>;\n\t/** Keys stored as `undefined`. */\n\tdelete: string[];\n}\n\n/**\n * `output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`.\n * `during`: in a {@link CodemodeSandboxBase.start} run that the script itself ended (it returned, threw, or exited),\n * the result being processed when it did.\n */\nexport type CodemodeResult =\n\t| {\n\t\t\tok: true;\n\t\t\tvalue: unknown;\n\t\t\toutput: CodemodeOutputItem[];\n\t\t\tcalls: CodemodeCall[];\n\t\t\tstoreWrites: CodemodeStoreWrites;\n\t\t\tduring?: CodemodeDuring;\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\terror: CodemodeError;\n\t\t\toutput: CodemodeOutputItem[];\n\t\t\tcalls: CodemodeCall[];\n\t\t\tduring?: CodemodeDuring;\n\t };\n\n/** Options every sandbox accepts, wherever its VM runs. */\nexport interface CodemodeSandboxBaseOptions {\n\t/**\n\t * Trusted host code evaluated in the VM before built-ins are frozen. Never populate this\n\t * from script input. Runs once per execution and is not exposed to the script.\n\t */\n\tpreLockdownSource?: string;\n\t/**\n\t * Maximum combined character count across every `text()`, `console.*`, and `image()` output\n\t * item. The VM's memory limit only bounds its own heap; output is copied into the host process\n\t * and kept there for the life of the execution (`result.output`), so a script that only calls\n\t * `console.log` in a loop would otherwise grow the host's memory without bound. Crossing it ends\n\t * the execution with a `sandbox` error; `result.output` keeps the items received up to and\n\t * including the one that crossed the limit. Default: no limit.\n\t */\n\tmaxOutputChars?: number;\n\n\ttools?: CodemodeTool[];\n\t/**\n\t * Functions exposed as top-level identifiers instead of on `tools`, for host helpers such as\n\t * attaching an image to the result. They behave like tools (JSON round trip, promise result)\n\t * but are not recorded in `result.calls`. Names must be identifiers and may not shadow the\n\t * built-in globals (`tools`, `ALL_TOOLS`, `console`, `text`, `image`, `exit`, `store`, `load`).\n\t */\n\tglobals?: CodemodeTool[];\n\t/**\n\t * Overall deadline per execution, including time spent in tools. `Infinity` disables the\n\t * deadline; the execution then only ends when the script settles or is aborted.\n\t * Default: 300000.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum memory the QuickJS VM may allocate. Allocations beyond it fail inside the script as\n\t * `InternalError: out of memory`. Default: no limit beyond wasm32's 4 GiB address space.\n\t */\n\tmemoryLimitBytes?: number;\n}\n\n/** Options of `CodemodeSandbox`, which runs each VM in a Node or Bun worker thread. */\nexport interface CodemodeSandboxOptions extends CodemodeSandboxBaseOptions {\n\t/**\n\t * Compiled `quickjs-wasi/quickjs.wasm`, usually from {@link loadQuickJSWasm}. Default:\n\t * `loadQuickJSWasm()`, the file in the installed `quickjs-wasi` package. Pass it when that file\n\t * is not on disk, for example in a Bun compiled executable.\n\t */\n\twasm?: CodemodeWasmModule | Promise<CodemodeWasmModule>;\n\t/**\n\t * Worker entry that imports `@draht/codemode/worker`. Default: this package's own\n\t * worker file. Pass it when this package is bundled, since the default is resolved relative to\n\t * the module that creates the sandbox. Bun compiled executables require the relative string\n\t * specifier of an embedded build entrypoint; other hosts usually use a URL.\n\t */\n\tworkerUrl?: string | URL;\n\t/**\n\t * Synchronously reserves capacity immediately before creating each worker, after loading wasm.\n\t * Throw to deny admission without starting a worker. Return a release callback, called once if\n\t * worker construction fails or when the worker actually exits, not when the result settles.\n\t * The release callback must not throw. Reservations can be shared across sandbox instances.\n\t */\n\tacquireWorker?(): () => void;\n\t/**\n\t * Called once for each worker started by execute() or start(). `exited` resolves when that worker\n\t * actually exits, which may be after the result and close() settle: on Bun a non-interruptible\n\t * built-in can delay termination. Use it to keep the worker counted against host concurrency\n\t * limits until it exits. A thrown callback error fails the execution and requests worker termination.\n\t */\n\tonWorkerStarted?(exited: Promise<void>): void;\n}\n\n/** A call the script made in a {@link CodemodeSandboxBase.start} run, answered with `CodemodeRun.deliver()`. */\nexport interface CodemodeHostCall {\n\t/** The VM's own number for the call, `1`, `2`, ... in the order the script made its calls (tools and globals). */\n\tid: number;\n\ttarget: \"tool\" | \"global\";\n\tname: string;\n\t/** What the script passed, after a JSON round trip; for spread globals the argument list. */\n\targs: unknown;\n}\n\n/** A tool as a {@link CodemodeSandboxBase.start} run's script sees it: `tools.<name>` and its `ALL_TOOLS` entry. */\nexport interface CodemodeDeclaredTool {\n\tname: string;\n\t/**\n\t * The identifier the script uses, `tools.<jsName>`. Default: `toCodemodeIdentifier(name)`. A host that replays a run\n\t * passes the one the run started with, so a changed mapping cannot rename a tool under a resumed script.\n\t */\n\tjsName?: string;\n\tdescription?: string;\n}\n\n/** A global as a {@link CodemodeSandboxBase.start} run's script sees it; the same names as `globals` allow. */\nexport interface CodemodeDeclaredGlobal {\n\tname: string;\n\tspread?: boolean;\n}\n\n/**\n * A call's answer. A rejection becomes an `Error` with `message` in the script, carrying the own properties of\n * `properties` (JSON values; `name`, `message`, and `stack` are ignored), for example `{ structuredOutput }`.\n */\nexport type CodemodeOutcome =\n\t| { ok: true; value: unknown }\n\t| { ok: false; message: string; properties?: Record<string, unknown> };\n\n/** In a {@link CodemodeSandboxBase.start} run: the result the VM was processing when the script finished, 0 for its first run, and the calls issued by then. */\nexport interface CodemodeDuring {\n\tseq: number;\n\tissued: number;\n}\n\nexport interface CodemodeRunOptions {\n\t/** The VM clock's start, in ms since the epoch: `Date.now()` until the first result arrives. */\n\tstartedAt: number;\n\t/** Seeds `Math.random()` and the VM's other randomness. A 32-bit unsigned integer. */\n\tseed: number;\n\ttools?: CodemodeDeclaredTool[];\n\tglobals?: CodemodeDeclaredGlobal[];\n\tstore?: Readonly<Record<string, unknown>>;\n\tsignal?: AbortSignal;\n\t/** Deadline of this run in ms. Default: none (not the sandbox's default). */\n\ttimeoutMs?: number;\n\t/** The VM's fingerprint, before the script runs and before any of its calls. */\n\tonStarted?(fingerprint: string): void;\n\t/** The script made a call. Answer it with `CodemodeRun.deliver()`, now or later. */\n\tonCall(call: CodemodeHostCall): void;\n\t/**\n\t * The VM processed result `seq` (`0`: the script's first run, before any result) and waits again, having issued\n\t * `issued` calls in total.\n\t */\n\tonIdle?(seq: number, issued: number): void;\n}\n\n/** A running {@link CodemodeSandboxBase.start} execution. */\nexport interface CodemodeRun {\n\treadonly result: Promise<CodemodeResult>;\n\t/**\n\t * Whether the run has its outcome: the script ended, timed out, or failed, or the run was aborted. Set when that is\n\t * decided, before `result` settles; calls can no longer be answered. It does not mean the VM has exited.\n\t */\n\treadonly finished: boolean;\n\t/**\n\t * Answer call `id` as result number `seq`. Results are numbered 1, 2, ... without gaps, and the VM applies them\n\t * strictly in that order, whatever order they arrive in: after a gap it waits for the missing number. While it\n\t * processes this one, its clock reads `now` (ms since the epoch), or the previous value if `now` is earlier.\n\t * Throws for a call that is not waiting for an answer, a `seq` used before, or a `now` that is not finite.\n\t */\n\tdeliver(seq: number, now: number, id: number, outcome: CodemodeOutcome): void;\n}\n\nexport interface CodemodeExecuteOptions {\n\tsignal?: AbortSignal;\n\t/** Overrides the sandbox default for this execution. */\n\ttimeoutMs?: number;\n\t/**\n\t * Values the script reads with `load(key)`. Must be JSON-serializable. The script's own\n\t * `store()` calls come back as `result.storeWrites`; persisting them is up to the caller.\n\t */\n\tstore?: Readonly<Record<string, unknown>>;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@draht/codemode",
3
- "version": "2026.10.20-1",
3
+ "version": "2026.10.23-1",
4
4
  "description": "Sandboxed JavaScript execution where the only capability is calling injected tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -25,6 +25,16 @@
25
25
  "source": "./src/runtime/worker.ts",
26
26
  "types": "./dist/runtime/worker.d.ts",
27
27
  "import": "./dist/runtime/worker.js"
28
+ },
29
+ "./portable": {
30
+ "source": "./src/portable.ts",
31
+ "types": "./dist/portable.d.ts",
32
+ "import": "./dist/portable.js"
33
+ },
34
+ "./cloudflare": {
35
+ "source": "./src/cloudflare.ts",
36
+ "types": "./dist/cloudflare.d.ts",
37
+ "import": "./dist/cloudflare.js"
28
38
  }
29
39
  },
30
40
  "files": [
@@ -42,7 +52,9 @@
42
52
  "codemode",
43
53
  "sandbox",
44
54
  "quickjs",
45
- "wasm"
55
+ "wasm",
56
+ "cloudflare",
57
+ "durable-objects"
46
58
  ],
47
59
  "author": "Oskar Freye",
48
60
  "license": "MIT",
@@ -52,13 +64,13 @@
52
64
  "directory": "packages/codemode"
53
65
  },
54
66
  "engines": {
55
- "node": ">=22.19.0"
67
+ "node": "^22.23.4 || ^24.22.1 || ^26.12.1"
56
68
  },
57
69
  "dependencies": {
58
70
  "quickjs-wasi": "3.6.2"
59
71
  },
60
72
  "devDependencies": {
61
- "shx": "0.4.0",
73
+ "shx": "0.3.4",
62
74
  "vitest": "4.1.11"
63
75
  }
64
76
  }