@earendil-works/pi-codemode 1.0.3 → 1.1.0

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.
package/README.md CHANGED
@@ -39,7 +39,7 @@ await sandbox.close();
39
39
 
40
40
  - `tools.<name>(args)` returns a promise. Arguments and results make a JSON round trip. A tool that throws rejects with an `Error` carrying the same message. Tool names are also exposed as identifiers: characters that are not valid in identifiers become `_` (`toCodemodeIdentifier`), so `my-tool` is `tools.my_tool` as well as `tools["my-tool"]`.
41
41
  - `ALL_TOOLS` lists `{ name, description }` for every tool, with `name` as the identifier.
42
- - `text(value)` appends a text item to `result.output`; values other than strings are JSON-stringified. `console.log/info/warn/error/debug` append text items too.
42
+ - `text(value)` appends a text item to `result.output`; values other than strings are JSON-stringified. `console.log/info/warn/error/debug` append text items with `console: true`.
43
43
  - `image(urlOrItem)` appends an image item. It accepts a base64 `data:` URL, `{ image_url }`, or an MCP `ImageContent` block (`{ type: "image", data, mimeType }`). Remote URLs are rejected.
44
44
  - `exit()` ends the script successfully right away, keeping its output and store writes.
45
45
  - `globals` passed to the sandbox are called as top-level functions, for example a host helper `image(ref)`. They behave like tools but are not recorded in `result.calls`. A name like `models.classify` puts the function on a frozen `models` object. With `spread: true`, `execute` receives all call arguments as an array instead of the first one, and `signature` replaces the declaration generated from the schemas.
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAIX,sBAAsB,EAEtB,cAAc,EACd,sBAAsB,EAEtB,YAAY,EACZ,MAAM,aAAa,CAAC;AAuQrB;;;;;;;;GAQG;AACH,qBAAa,eAAe;IAC3B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAmC;IAC/D,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAmC;IACjE,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,gBAAg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I,EAAE,YAAY,GAAG,IAAI,CAGrC;IAED,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEpC;IAED,IAAI,KAAK,IAAI,YAAY,EAAE,CAE1B;IAED,IAAI,OAAO,IAAI,YAAY,EAAE,CAE5B;IAED;;;;OAIG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,cAAc,CAAC,CAenF;IAED,8FAA8F;IACxF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAG3B;CACD"}
@@ -27,16 +27,52 @@ function serializeStore(store) {
27
27
  }
28
28
  return serialized;
29
29
  }
30
+ /**
31
+ * The prelude that serializes values for the host runs in the same VM as the script, so a script
32
+ * that patches built-ins (for example `Array.prototype.toJSON`) can make it send malformed data.
33
+ * Payloads that do not decode throw this error, and the execution fails as a sandbox error.
34
+ */
35
+ class BridgeError extends Error {
36
+ }
37
+ function parseBridgeJson(json, what) {
38
+ try {
39
+ return JSON.parse(json);
40
+ }
41
+ catch {
42
+ throw new BridgeError(`${what} is not valid JSON`);
43
+ }
44
+ }
30
45
  function parseStoreWrites(json) {
46
+ const entries = parseBridgeJson(json, "store writes");
47
+ if (!Array.isArray(entries))
48
+ throw new BridgeError("store writes are not an array");
31
49
  const writes = { set: {}, delete: [] };
32
- for (const [key, value] of JSON.parse(json)) {
50
+ for (const entry of entries) {
51
+ if (!Array.isArray(entry) ||
52
+ typeof entry[0] !== "string" ||
53
+ (entry.length === 2 ? typeof entry[1] !== "string" : entry.length !== 1)) {
54
+ throw new BridgeError("store writes contain a malformed entry");
55
+ }
56
+ const [key, value] = entry;
33
57
  if (value === undefined)
34
58
  writes.delete.push(key);
35
59
  else
36
- writes.set[key] = JSON.parse(value);
60
+ writes.set[key] = parseBridgeJson(value, `store value for ${JSON.stringify(key)}`);
37
61
  }
38
62
  return writes;
39
63
  }
64
+ function parseScriptError(json) {
65
+ const parsed = parseBridgeJson(json, "script error");
66
+ if (typeof parsed !== "object" || parsed === null)
67
+ throw new BridgeError("script error is not an object");
68
+ const { name, message, stack } = parsed;
69
+ if (typeof message !== "string" ||
70
+ (name !== undefined && typeof name !== "string") ||
71
+ (stack !== undefined && typeof stack !== "string")) {
72
+ throw new BridgeError("script error is malformed");
73
+ }
74
+ return { kind: "script", name, message, stack };
75
+ }
40
76
  function defaultWorkerUrl() {
41
77
  // `.ts` when running from source (tests, tsx), `.js` from the published dist.
42
78
  return new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url);
@@ -115,7 +151,20 @@ class Execution {
115
151
  return;
116
152
  }
117
153
  this.worker = worker;
118
- worker.on("message", (message) => this.handleMessage(message));
154
+ worker.on("message", (message) => {
155
+ // An exception here would be uncaught in the host process and leave the execution unsettled.
156
+ try {
157
+ this.handleMessage(message);
158
+ }
159
+ catch (error) {
160
+ this.finish({
161
+ kind: "sandbox",
162
+ message: error instanceof BridgeError
163
+ ? `Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.`
164
+ : `Sandbox host failed: ${errorMessage(error)}`,
165
+ });
166
+ }
167
+ });
119
168
  worker.on("error", (error) => {
120
169
  this.finish({
121
170
  kind: "sandbox",
@@ -135,13 +184,17 @@ class Execution {
135
184
  this.worker?.postMessage(message);
136
185
  }
137
186
  handleMessage(message) {
138
- if (this.finished || !isWorkerToHostMessage(message))
187
+ if (this.finished)
139
188
  return;
189
+ if (!isWorkerToHostMessage(message))
190
+ throw new BridgeError("unknown message from the worker");
140
191
  switch (message.type) {
141
192
  case "output":
142
193
  this.output.push(message.item);
143
194
  break;
144
195
  case "call":
196
+ if (this.pending.has(message.id))
197
+ throw new BridgeError(`duplicate call id ${message.id}`);
145
198
  void this.handleCall(message);
146
199
  break;
147
200
  case "done":
@@ -153,12 +206,13 @@ class Execution {
153
206
  }
154
207
  }
155
208
  handleDone(message) {
209
+ // Decode everything before finish(), which must not throw once it starts.
156
210
  if (!message.ok) {
157
- const parsed = JSON.parse(message.error);
158
- this.finish({ kind: "script", ...parsed });
211
+ this.finish(parseScriptError(message.error));
159
212
  return;
160
213
  }
161
- this.finish(undefined, message.value === undefined ? undefined : JSON.parse(message.value), message.writes);
214
+ const value = message.value === undefined ? undefined : parseBridgeJson(message.value, "return value");
215
+ this.finish(undefined, value, parseStoreWrites(message.writes));
162
216
  }
163
217
  async handleCall(message) {
164
218
  const { id, name } = message;
@@ -213,7 +267,7 @@ class Execution {
213
267
  value,
214
268
  output: this.output,
215
269
  calls: this.calls,
216
- storeWrites: writes === undefined ? { set: {}, delete: [] } : parseStoreWrites(writes),
270
+ storeWrites: writes ?? { set: {}, delete: [] },
217
271
  };
218
272
  if (!this.worker) {
219
273
  this.resolveResult(result);
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAYxD,OAAO,EAA2B,eAAe,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAEN,qBAAqB,GAGrB,MAAM,eAAe,CAAC;AAEvB,MAAM,kBAAkB,GAAG,OAAO,CAAC;AACnC,MAAM,UAAU,GAAG,4BAA4B,CAAC;AAChD,MAAM,gBAAgB,GAAwB,IAAI,GAAG,CAAC;IACrD,OAAO;IACP,WAAW;IACX,SAAS;IACT,MAAM;IACN,OAAO;IACP,MAAM;IACN,YAAY;IACZ,OAAO;IACP,MAAM;CACN,CAAC,CAAC;AAEH,SAAS,YAAY,CAAC,KAAc;IACnC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,cAAc,CAAC,KAAoD;IAC3E,MAAM,UAAU,GAA2B,EAAE,CAAC;IAC9C,KAAK,MAAM,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vC,KAAK,EAAE,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC;YACpC,IAAI,EAAE,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC;YAC9E,SAAS,EAAE,IAAI,CAAC,SAAS;SACzB,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAC5B,OAAO,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;IACxE,CAAC;IAED,8FAA8F;IAC9F,KAAK,CAAC,KAAK;QACV,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAC5F,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { toCodemodeIdentifier } from \"../identifier.ts\";\nimport type {\n\tCodemodeCall,\n\tCodemodeCallStatus,\n\tCodemodeError,\n\tCodemodeExecuteOptions,\n\tCodemodeOutputItem,\n\tCodemodeResult,\n\tCodemodeSandboxOptions,\n\tCodemodeStoreWrites,\n\tCodemodeTool,\n} from \"../types.ts\";\nimport { type CodemodeWasmModule, loadQuickJSWasm } from \"../wasm.ts\";\nimport {\n\ttype HostToWorkerMessage,\n\tisWorkerToHostMessage,\n\ttype WorkerData,\n\ttype WorkerToHostMessage,\n} from \"./protocol.ts\";\n\nconst DEFAULT_TIMEOUT_MS = 300_000;\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst RESERVED_GLOBALS: ReadonlySet<string> = new Set([\n\t\"tools\",\n\t\"ALL_TOOLS\",\n\t\"console\",\n\t\"text\",\n\t\"image\",\n\t\"exit\",\n\t\"globalThis\",\n\t\"store\",\n\t\"load\",\n]);\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction serializeStore(store: Readonly<Record<string, unknown>> | undefined): Record<string, string> {\n\tconst serialized: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(store ?? {})) {\n\t\tconst json = JSON.stringify(value);\n\t\tif (json !== undefined) serialized[key] = json;\n\t}\n\treturn serialized;\n}\n\nfunction parseStoreWrites(json: string): CodemodeStoreWrites {\n\tconst writes: CodemodeStoreWrites = { set: {}, delete: [] };\n\tfor (const [key, value] of JSON.parse(json) as [string, string?][]) {\n\t\tif (value === undefined) writes.delete.push(key);\n\t\telse writes.set[key] = JSON.parse(value);\n\t}\n\treturn writes;\n}\n\nfunction defaultWorkerUrl(): URL {\n\t// `.ts` when running from source (tests, tsx), `.js` from the published dist.\n\treturn new URL(import.meta.url.endsWith(\".ts\") ? \"./worker.ts\" : \"./worker.js\", import.meta.url);\n}\n\ninterface PendingCall {\n\trecord: CodemodeCall | undefined;\n\tstartedAt: number;\n\tcontroller: AbortController;\n}\n\ninterface ExecutionOptions {\n\tcode: string;\n\ttools: ReadonlyMap<string, CodemodeTool>;\n\tglobals: ReadonlyMap<string, CodemodeTool>;\n\ttimeoutMs: number;\n\tsignal: AbortSignal | undefined;\n\tmemoryLimitBytes: number | undefined;\n\tstore: Record<string, string>;\n\twasm: Promise<CodemodeWasmModule>;\n\tworkerUrl: string | URL;\n}\n\n/**\n * One script run in its own worker and QuickJS VM. A fresh worker per run keeps\n * termination simple: a runaway script, including one that only spins the\n * microtask queue, is killed with `terminate()` and cannot poison a later run.\n */\nclass Execution {\n\treadonly promise: Promise<CodemodeResult>;\n\tprivate resolveResult!: (result: CodemodeResult) => void;\n\tprivate worker: Worker | undefined;\n\tprivate readonly interrupt = new SharedArrayBuffer(4);\n\tprivate readonly tools: ReadonlyMap<string, CodemodeTool>;\n\tprivate readonly globals: ReadonlyMap<string, CodemodeTool>;\n\tprivate readonly signal: AbortSignal | undefined;\n\tprivate readonly timer: NodeJS.Timeout | undefined;\n\tprivate readonly output: CodemodeOutputItem[] = [];\n\tprivate readonly calls: CodemodeCall[] = [];\n\tprivate readonly pending = new Map<number, PendingCall>();\n\tprivate finished = false;\n\n\tconstructor(options: ExecutionOptions) {\n\t\tthis.promise = new Promise<CodemodeResult>((resolve) => {\n\t\t\tthis.resolveResult = resolve;\n\t\t});\n\t\tthis.tools = options.tools;\n\t\tthis.globals = options.globals;\n\t\tthis.signal = options.signal;\n\n\t\tif (Number.isFinite(options.timeoutMs)) {\n\t\t\tthis.timer = setTimeout(() => {\n\t\t\t\tthis.finish({ kind: \"timeout\", message: `Execution timed out after ${options.timeoutMs} ms` });\n\t\t\t}, options.timeoutMs);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tif (options.signal.aborted) {\n\t\t\t\tthis.onAbort();\n\t\t\t} else {\n\t\t\t\toptions.signal.addEventListener(\"abort\", this.onAbort, { once: true });\n\t\t\t}\n\t\t}\n\n\t\toptions.wasm.then(\n\t\t\t(wasm) => this.start(options, wasm),\n\t\t\t(error: unknown) => {\n\t\t\t\tthis.finish({ kind: \"sandbox\", message: `Failed to load QuickJS: ${errorMessage(error)}` });\n\t\t\t},\n\t\t);\n\t}\n\n\tabort(message: string): Promise<CodemodeResult> {\n\t\tthis.finish({ kind: \"aborted\", message });\n\t\treturn this.promise;\n\t}\n\n\tprivate start(options: ExecutionOptions, wasm: CodemodeWasmModule): void {\n\t\tif (this.finished) return;\n\t\tconst workerData: WorkerData = {\n\t\t\tcode: options.code,\n\t\t\ttools: [...options.tools.values()].map((tool) => ({\n\t\t\t\tname: tool.name,\n\t\t\t\tjsName: toCodemodeIdentifier(tool.name),\n\t\t\t\tdescription: tool.description ?? \"\",\n\t\t\t})),\n\t\t\tglobals: [...options.globals.values()].map((global) => ({\n\t\t\t\tname: global.name,\n\t\t\t\tspread: global.spread === true,\n\t\t\t})),\n\t\t\twasm,\n\t\t\tmemoryLimitBytes: options.memoryLimitBytes,\n\t\t\tstore: options.store,\n\t\t\tinterrupt: this.interrupt,\n\t\t};\n\t\tlet worker: Worker;\n\t\ttry {\n\t\t\tworker = new Worker(options.workerUrl, { workerData });\n\t\t} catch (error) {\n\t\t\tthis.finish({ kind: \"sandbox\", message: `Failed to start worker: ${errorMessage(error)}` });\n\t\t\treturn;\n\t\t}\n\t\tthis.worker = worker;\n\t\tworker.on(\"message\", (message: unknown) => this.handleMessage(message));\n\t\tworker.on(\"error\", (error: unknown) => {\n\t\t\tthis.finish({\n\t\t\t\tkind: \"sandbox\",\n\t\t\t\tname: error instanceof Error ? error.name : undefined,\n\t\t\t\tmessage: errorMessage(error),\n\t\t\t});\n\t\t});\n\t\tworker.on(\"exit\", (code) => {\n\t\t\tthis.finish({ kind: \"sandbox\", message: `Worker exited with code ${code} before the script settled` });\n\t\t});\n\t}\n\n\tprivate readonly onAbort = (): void => {\n\t\tconst reason: unknown = this.signal?.reason;\n\t\tthis.finish({ kind: \"aborted\", message: reason instanceof Error ? reason.message : \"Execution aborted\" });\n\t};\n\n\tprivate post(message: HostToWorkerMessage): void {\n\t\tthis.worker?.postMessage(message);\n\t}\n\n\tprivate handleMessage(message: unknown): void {\n\t\tif (this.finished || !isWorkerToHostMessage(message)) return;\n\t\tswitch (message.type) {\n\t\t\tcase \"output\":\n\t\t\t\tthis.output.push(message.item);\n\t\t\t\tbreak;\n\t\t\tcase \"call\":\n\t\t\t\tvoid this.handleCall(message);\n\t\t\t\tbreak;\n\t\t\tcase \"done\":\n\t\t\t\tthis.handleDone(message);\n\t\t\t\tbreak;\n\t\t\tcase \"crash\":\n\t\t\t\tthis.finish({ kind: \"sandbox\", message: message.message });\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate handleDone(message: Extract<WorkerToHostMessage, { type: \"done\" }>): void {\n\t\tif (!message.ok) {\n\t\t\tconst parsed = JSON.parse(message.error) as Omit<CodemodeError, \"kind\">;\n\t\t\tthis.finish({ kind: \"script\", ...parsed });\n\t\t\treturn;\n\t\t}\n\t\tthis.finish(undefined, message.value === undefined ? undefined : JSON.parse(message.value), message.writes);\n\t}\n\n\tprivate async handleCall(message: Extract<WorkerToHostMessage, { type: \"call\" }>): Promise<void> {\n\t\tconst { id, name } = message;\n\t\tconst isTool = message.target === \"tool\";\n\t\tconst record: CodemodeCall | undefined = isTool ? { name, status: \"cancelled\", durationMs: 0 } : undefined;\n\t\tif (record) this.calls.push(record);\n\t\tconst pending: PendingCall = { record, startedAt: performance.now(), controller: new AbortController() };\n\t\tthis.pending.set(id, pending);\n\n\t\tlet status: CodemodeCallStatus;\n\t\tlet reply: HostToWorkerMessage;\n\t\ttry {\n\t\t\tconst tool = (isTool ? this.tools : this.globals).get(name);\n\t\t\tif (!tool) throw new Error(`Unknown ${isTool ? \"tool\" : \"global\"} \"${name}\"`);\n\t\t\tconst args: unknown = message.args === undefined ? undefined : JSON.parse(message.args);\n\t\t\tconst value = await tool.execute(args, { signal: pending.controller.signal });\n\t\t\treply = { type: \"result\", id, ok: true, payload: value === undefined ? undefined : JSON.stringify(value) };\n\t\t\tstatus = \"ok\";\n\t\t} catch (error) {\n\t\t\treply = { type: \"result\", id, ok: false, payload: errorMessage(error) };\n\t\t\tstatus = \"error\";\n\t\t}\n\n\t\t// Already cancelled by finish(): the record keeps \"cancelled\" and the\n\t\t// worker is gone or going.\n\t\tif (!this.pending.delete(id)) return;\n\t\tif (record) {\n\t\t\trecord.status = status;\n\t\t\trecord.durationMs = performance.now() - pending.startedAt;\n\t\t}\n\t\tthis.post(reply);\n\t}\n\n\tprivate finish(error: CodemodeError | undefined, value?: unknown, writes?: string): void {\n\t\tif (this.finished) return;\n\t\tthis.finished = true;\n\t\tclearTimeout(this.timer);\n\t\tthis.signal?.removeEventListener(\"abort\", this.onAbort);\n\n\t\tconst now = performance.now();\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tif (pending.record) pending.record.durationMs = now - pending.startedAt;\n\t\t\tpending.controller.abort();\n\t\t}\n\t\tthis.pending.clear();\n\n\t\tconst result: CodemodeResult = error\n\t\t\t? { ok: false, error, output: this.output, calls: this.calls }\n\t\t\t: {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalue,\n\t\t\t\t\toutput: this.output,\n\t\t\t\t\tcalls: this.calls,\n\t\t\t\t\tstoreWrites: writes === undefined ? { set: {}, delete: [] } : parseStoreWrites(writes),\n\t\t\t\t};\n\t\tif (!this.worker) {\n\t\t\tthis.resolveResult(result);\n\t\t\treturn;\n\t\t}\n\t\tAtomics.store(new Int32Array(this.interrupt), 0, 1);\n\t\tthis.worker\n\t\t\t.terminate()\n\t\t\t.catch(() => undefined)\n\t\t\t.then(() => this.resolveResult(result));\n\t}\n}\n\n/**\n * Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker\n * thread. The script sees `tools.<name>(args)` for every registered tool, `ALL_TOOLS`,\n * the output helpers `text`, `image`, `exit`, and `console.*`, `store`/`load`, and the\n * configured globals; nothing else (no timers, `fetch`, `process`, `require`, modules).\n *\n * Each `execute()` gets its own worker and VM; the sandbox only holds the tool\n * table and defaults. `close()` aborts in-flight executions.\n */\nexport class CodemodeSandbox {\n\tprivate readonly toolsByName = new Map<string, CodemodeTool>();\n\tprivate readonly globalsByName = new Map<string, CodemodeTool>();\n\tprivate readonly timeoutMs: number;\n\tprivate readonly memoryLimitBytes: number | undefined;\n\tprivate readonly wasm: CodemodeWasmModule | Promise<CodemodeWasmModule> | undefined;\n\tprivate readonly workerUrl: string | URL;\n\tprivate readonly running = new Set<Execution>();\n\tprivate closed = false;\n\n\tconstructor(options: CodemodeSandboxOptions = {}) {\n\t\tthis.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\t\tthis.memoryLimitBytes = options.memoryLimitBytes;\n\t\tthis.wasm = options.wasm;\n\t\tthis.workerUrl = options.workerUrl ?? defaultWorkerUrl();\n\t\tfor (const tool of options.tools ?? []) this.registerTool(tool);\n\t\tconst namespaces = new Set<string>();\n\t\tfor (const global of options.globals ?? []) {\n\t\t\tconst parts = global.name.split(\".\");\n\t\t\tif (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part)) || RESERVED_GLOBALS.has(parts[0])) {\n\t\t\t\tthrow new Error(`Invalid global name \"${global.name}\"`);\n\t\t\t}\n\t\t\tif (this.globalsByName.has(global.name)) throw new Error(`Global \"${global.name}\" is already registered`);\n\t\t\tif (parts.length === 2) namespaces.add(parts[0]);\n\t\t\tthis.globalsByName.set(global.name, global);\n\t\t}\n\t\tfor (const name of namespaces) {\n\t\t\tif (this.globalsByName.has(name)) throw new Error(`Global \"${name}\" conflicts with the namespace \"${name}\"`);\n\t\t}\n\t}\n\n\t/** Throws if a tool with the same name is already registered. */\n\tregisterTool(tool: CodemodeTool): void {\n\t\tif (this.toolsByName.has(tool.name)) throw new Error(`Tool \"${tool.name}\" is already registered`);\n\t\tthis.toolsByName.set(tool.name, tool);\n\t}\n\n\tunregisterTool(name: string): boolean {\n\t\treturn this.toolsByName.delete(name);\n\t}\n\n\tget tools(): CodemodeTool[] {\n\t\treturn [...this.toolsByName.values()];\n\t}\n\n\tget globals(): CodemodeTool[] {\n\t\treturn [...this.globalsByName.values()];\n\t}\n\n\t/**\n\t * `code` is an async function body: `return` and top-level `await` work.\n\t * Never rejects for script failures; those come back as `{ ok: false }`.\n\t * The script can use `store(key, value)` and `load(key)` on `options.store`.\n\t */\n\texecute(code: string, options: CodemodeExecuteOptions = {}): Promise<CodemodeResult> {\n\t\tif (this.closed) return Promise.reject(new Error(\"Sandbox is closed\"));\n\t\tconst execution = new Execution({\n\t\t\tcode,\n\t\t\ttools: new Map(this.toolsByName),\n\t\t\tglobals: this.globalsByName,\n\t\t\ttimeoutMs: options.timeoutMs ?? this.timeoutMs,\n\t\t\tsignal: options.signal,\n\t\t\tmemoryLimitBytes: this.memoryLimitBytes,\n\t\t\tstore: serializeStore(options.store),\n\t\t\twasm: this.wasm === undefined ? loadQuickJSWasm() : Promise.resolve(this.wasm),\n\t\t\tworkerUrl: this.workerUrl,\n\t\t});\n\t\tthis.running.add(execution);\n\t\treturn execution.promise.finally(() => this.running.delete(execution));\n\t}\n\n\t/** Aborts in-flight executions (they resolve with `kind: \"aborted\"`) and rejects new ones. */\n\tasync close(): Promise<void> {\n\t\tthis.closed = true;\n\t\tawait Promise.all([...this.running].map((execution) => execution.abort(\"Sandbox closed\")));\n\t}\n}\n"]}
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAYxD,OAAO,EAA2B,eAAe,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAEN,qBAAqB,GAGrB,MAAM,eAAe,CAAC;AAEvB,MAAM,kBAAkB,GAAG,OAAO,CAAC;AACnC,MAAM,UAAU,GAAG,4BAA4B,CAAC;AAChD,MAAM,gBAAgB,GAAwB,IAAI,GAAG,CAAC;IACrD,OAAO;IACP,WAAW;IACX,SAAS;IACT,MAAM;IACN,OAAO;IACP,MAAM;IACN,YAAY;IACZ,OAAO;IACP,MAAM;CACN,CAAC,CAAC;AAEH,SAAS,YAAY,CAAC,KAAc;IACnC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,cAAc,CAAC,KAAoD;IAC3E,MAAM,UAAU,GAA2B,EAAE,CAAC;IAC9C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;QACxD,MAAM,IAAI,GAAG,IAAI,CAAC,S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C,CAAC,CAAC,CAAC;IAC5F,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { toCodemodeIdentifier } from \"../identifier.ts\";\nimport type {\n\tCodemodeCall,\n\tCodemodeCallStatus,\n\tCodemodeError,\n\tCodemodeExecuteOptions,\n\tCodemodeOutputItem,\n\tCodemodeResult,\n\tCodemodeSandboxOptions,\n\tCodemodeStoreWrites,\n\tCodemodeTool,\n} from \"../types.ts\";\nimport { type CodemodeWasmModule, loadQuickJSWasm } from \"../wasm.ts\";\nimport {\n\ttype HostToWorkerMessage,\n\tisWorkerToHostMessage,\n\ttype WorkerData,\n\ttype WorkerToHostMessage,\n} from \"./protocol.ts\";\n\nconst DEFAULT_TIMEOUT_MS = 300_000;\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst RESERVED_GLOBALS: ReadonlySet<string> = new Set([\n\t\"tools\",\n\t\"ALL_TOOLS\",\n\t\"console\",\n\t\"text\",\n\t\"image\",\n\t\"exit\",\n\t\"globalThis\",\n\t\"store\",\n\t\"load\",\n]);\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction serializeStore(store: Readonly<Record<string, unknown>> | undefined): Record<string, string> {\n\tconst serialized: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(store ?? {})) {\n\t\tconst json = JSON.stringify(value);\n\t\tif (json !== undefined) serialized[key] = json;\n\t}\n\treturn serialized;\n}\n\n/**\n * The prelude that serializes values for the host runs in the same VM as the script, so a script\n * that patches built-ins (for example `Array.prototype.toJSON`) can make it send malformed data.\n * Payloads that do not decode throw this error, and the execution fails as a sandbox error.\n */\nclass BridgeError extends Error {}\n\nfunction parseBridgeJson(json: string, what: string): unknown {\n\ttry {\n\t\treturn JSON.parse(json);\n\t} catch {\n\t\tthrow new BridgeError(`${what} is not valid JSON`);\n\t}\n}\n\nfunction parseStoreWrites(json: string): CodemodeStoreWrites {\n\tconst entries = parseBridgeJson(json, \"store writes\");\n\tif (!Array.isArray(entries)) throw new BridgeError(\"store writes are not an array\");\n\tconst writes: CodemodeStoreWrites = { set: {}, delete: [] };\n\tfor (const entry of entries) {\n\t\tif (\n\t\t\t!Array.isArray(entry) ||\n\t\t\ttypeof entry[0] !== \"string\" ||\n\t\t\t(entry.length === 2 ? typeof entry[1] !== \"string\" : entry.length !== 1)\n\t\t) {\n\t\t\tthrow new BridgeError(\"store writes contain a malformed entry\");\n\t\t}\n\t\tconst [key, value] = entry as [string, string?];\n\t\tif (value === undefined) writes.delete.push(key);\n\t\telse writes.set[key] = parseBridgeJson(value, `store value for ${JSON.stringify(key)}`);\n\t}\n\treturn writes;\n}\n\nfunction parseScriptError(json: string): CodemodeError {\n\tconst parsed = parseBridgeJson(json, \"script error\");\n\tif (typeof parsed !== \"object\" || parsed === null) throw new BridgeError(\"script error is not an object\");\n\tconst { name, message, stack } = parsed as Record<string, unknown>;\n\tif (\n\t\ttypeof message !== \"string\" ||\n\t\t(name !== undefined && typeof name !== \"string\") ||\n\t\t(stack !== undefined && typeof stack !== \"string\")\n\t) {\n\t\tthrow new BridgeError(\"script error is malformed\");\n\t}\n\treturn { kind: \"script\", name, message, stack };\n}\n\nfunction defaultWorkerUrl(): URL {\n\t// `.ts` when running from source (tests, tsx), `.js` from the published dist.\n\treturn new URL(import.meta.url.endsWith(\".ts\") ? \"./worker.ts\" : \"./worker.js\", import.meta.url);\n}\n\ninterface PendingCall {\n\trecord: CodemodeCall | undefined;\n\tstartedAt: number;\n\tcontroller: AbortController;\n}\n\ninterface ExecutionOptions {\n\tcode: string;\n\ttools: ReadonlyMap<string, CodemodeTool>;\n\tglobals: ReadonlyMap<string, CodemodeTool>;\n\ttimeoutMs: number;\n\tsignal: AbortSignal | undefined;\n\tmemoryLimitBytes: number | undefined;\n\tstore: Record<string, string>;\n\twasm: Promise<CodemodeWasmModule>;\n\tworkerUrl: string | URL;\n}\n\n/**\n * One script run in its own worker and QuickJS VM. A fresh worker per run keeps\n * termination simple: a runaway script, including one that only spins the\n * microtask queue, is killed with `terminate()` and cannot poison a later run.\n */\nclass Execution {\n\treadonly promise: Promise<CodemodeResult>;\n\tprivate resolveResult!: (result: CodemodeResult) => void;\n\tprivate worker: Worker | undefined;\n\tprivate readonly interrupt = new SharedArrayBuffer(4);\n\tprivate readonly tools: ReadonlyMap<string, CodemodeTool>;\n\tprivate readonly globals: ReadonlyMap<string, CodemodeTool>;\n\tprivate readonly signal: AbortSignal | undefined;\n\tprivate readonly timer: NodeJS.Timeout | undefined;\n\tprivate readonly output: CodemodeOutputItem[] = [];\n\tprivate readonly calls: CodemodeCall[] = [];\n\tprivate readonly pending = new Map<number, PendingCall>();\n\tprivate finished = false;\n\n\tconstructor(options: ExecutionOptions) {\n\t\tthis.promise = new Promise<CodemodeResult>((resolve) => {\n\t\t\tthis.resolveResult = resolve;\n\t\t});\n\t\tthis.tools = options.tools;\n\t\tthis.globals = options.globals;\n\t\tthis.signal = options.signal;\n\n\t\tif (Number.isFinite(options.timeoutMs)) {\n\t\t\tthis.timer = setTimeout(() => {\n\t\t\t\tthis.finish({ kind: \"timeout\", message: `Execution timed out after ${options.timeoutMs} ms` });\n\t\t\t}, options.timeoutMs);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tif (options.signal.aborted) {\n\t\t\t\tthis.onAbort();\n\t\t\t} else {\n\t\t\t\toptions.signal.addEventListener(\"abort\", this.onAbort, { once: true });\n\t\t\t}\n\t\t}\n\n\t\toptions.wasm.then(\n\t\t\t(wasm) => this.start(options, wasm),\n\t\t\t(error: unknown) => {\n\t\t\t\tthis.finish({ kind: \"sandbox\", message: `Failed to load QuickJS: ${errorMessage(error)}` });\n\t\t\t},\n\t\t);\n\t}\n\n\tabort(message: string): Promise<CodemodeResult> {\n\t\tthis.finish({ kind: \"aborted\", message });\n\t\treturn this.promise;\n\t}\n\n\tprivate start(options: ExecutionOptions, wasm: CodemodeWasmModule): void {\n\t\tif (this.finished) return;\n\t\tconst workerData: WorkerData = {\n\t\t\tcode: options.code,\n\t\t\ttools: [...options.tools.values()].map((tool) => ({\n\t\t\t\tname: tool.name,\n\t\t\t\tjsName: toCodemodeIdentifier(tool.name),\n\t\t\t\tdescription: tool.description ?? \"\",\n\t\t\t})),\n\t\t\tglobals: [...options.globals.values()].map((global) => ({\n\t\t\t\tname: global.name,\n\t\t\t\tspread: global.spread === true,\n\t\t\t})),\n\t\t\twasm,\n\t\t\tmemoryLimitBytes: options.memoryLimitBytes,\n\t\t\tstore: options.store,\n\t\t\tinterrupt: this.interrupt,\n\t\t};\n\t\tlet worker: Worker;\n\t\ttry {\n\t\t\tworker = new Worker(options.workerUrl, { workerData });\n\t\t} catch (error) {\n\t\t\tthis.finish({ kind: \"sandbox\", message: `Failed to start worker: ${errorMessage(error)}` });\n\t\t\treturn;\n\t\t}\n\t\tthis.worker = worker;\n\t\tworker.on(\"message\", (message: unknown) => {\n\t\t\t// An exception here would be uncaught in the host process and leave the execution unsettled.\n\t\t\ttry {\n\t\t\t\tthis.handleMessage(message);\n\t\t\t} catch (error) {\n\t\t\t\tthis.finish({\n\t\t\t\t\tkind: \"sandbox\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\terror instanceof BridgeError\n\t\t\t\t\t\t\t? `Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.`\n\t\t\t\t\t\t\t: `Sandbox host failed: ${errorMessage(error)}`,\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\tworker.on(\"error\", (error: unknown) => {\n\t\t\tthis.finish({\n\t\t\t\tkind: \"sandbox\",\n\t\t\t\tname: error instanceof Error ? error.name : undefined,\n\t\t\t\tmessage: errorMessage(error),\n\t\t\t});\n\t\t});\n\t\tworker.on(\"exit\", (code) => {\n\t\t\tthis.finish({ kind: \"sandbox\", message: `Worker exited with code ${code} before the script settled` });\n\t\t});\n\t}\n\n\tprivate readonly onAbort = (): void => {\n\t\tconst reason: unknown = this.signal?.reason;\n\t\tthis.finish({ kind: \"aborted\", message: reason instanceof Error ? reason.message : \"Execution aborted\" });\n\t};\n\n\tprivate post(message: HostToWorkerMessage): void {\n\t\tthis.worker?.postMessage(message);\n\t}\n\n\tprivate handleMessage(message: unknown): void {\n\t\tif (this.finished) return;\n\t\tif (!isWorkerToHostMessage(message)) throw new BridgeError(\"unknown message from the worker\");\n\t\tswitch (message.type) {\n\t\t\tcase \"output\":\n\t\t\t\tthis.output.push(message.item);\n\t\t\t\tbreak;\n\t\t\tcase \"call\":\n\t\t\t\tif (this.pending.has(message.id)) throw new BridgeError(`duplicate call id ${message.id}`);\n\t\t\t\tvoid this.handleCall(message);\n\t\t\t\tbreak;\n\t\t\tcase \"done\":\n\t\t\t\tthis.handleDone(message);\n\t\t\t\tbreak;\n\t\t\tcase \"crash\":\n\t\t\t\tthis.finish({ kind: \"sandbox\", message: message.message });\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate handleDone(message: Extract<WorkerToHostMessage, { type: \"done\" }>): void {\n\t\t// Decode everything before finish(), which must not throw once it starts.\n\t\tif (!message.ok) {\n\t\t\tthis.finish(parseScriptError(message.error));\n\t\t\treturn;\n\t\t}\n\t\tconst value = message.value === undefined ? undefined : parseBridgeJson(message.value, \"return value\");\n\t\tthis.finish(undefined, value, parseStoreWrites(message.writes));\n\t}\n\n\tprivate async handleCall(message: Extract<WorkerToHostMessage, { type: \"call\" }>): Promise<void> {\n\t\tconst { id, name } = message;\n\t\tconst isTool = message.target === \"tool\";\n\t\tconst record: CodemodeCall | undefined = isTool ? { name, status: \"cancelled\", durationMs: 0 } : undefined;\n\t\tif (record) this.calls.push(record);\n\t\tconst pending: PendingCall = { record, startedAt: performance.now(), controller: new AbortController() };\n\t\tthis.pending.set(id, pending);\n\n\t\tlet status: CodemodeCallStatus;\n\t\tlet reply: HostToWorkerMessage;\n\t\ttry {\n\t\t\tconst tool = (isTool ? this.tools : this.globals).get(name);\n\t\t\tif (!tool) throw new Error(`Unknown ${isTool ? \"tool\" : \"global\"} \"${name}\"`);\n\t\t\tconst args: unknown = message.args === undefined ? undefined : JSON.parse(message.args);\n\t\t\tconst value = await tool.execute(args, { signal: pending.controller.signal });\n\t\t\treply = { type: \"result\", id, ok: true, payload: value === undefined ? undefined : JSON.stringify(value) };\n\t\t\tstatus = \"ok\";\n\t\t} catch (error) {\n\t\t\treply = { type: \"result\", id, ok: false, payload: errorMessage(error) };\n\t\t\tstatus = \"error\";\n\t\t}\n\n\t\t// Already cancelled by finish(): the record keeps \"cancelled\" and the\n\t\t// worker is gone or going.\n\t\tif (!this.pending.delete(id)) return;\n\t\tif (record) {\n\t\t\trecord.status = status;\n\t\t\trecord.durationMs = performance.now() - pending.startedAt;\n\t\t}\n\t\tthis.post(reply);\n\t}\n\n\tprivate finish(error: CodemodeError | undefined, value?: unknown, writes?: CodemodeStoreWrites): void {\n\t\tif (this.finished) return;\n\t\tthis.finished = true;\n\t\tclearTimeout(this.timer);\n\t\tthis.signal?.removeEventListener(\"abort\", this.onAbort);\n\n\t\tconst now = performance.now();\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tif (pending.record) pending.record.durationMs = now - pending.startedAt;\n\t\t\tpending.controller.abort();\n\t\t}\n\t\tthis.pending.clear();\n\n\t\tconst result: CodemodeResult = error\n\t\t\t? { ok: false, error, output: this.output, calls: this.calls }\n\t\t\t: {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalue,\n\t\t\t\t\toutput: this.output,\n\t\t\t\t\tcalls: this.calls,\n\t\t\t\t\tstoreWrites: writes ?? { set: {}, delete: [] },\n\t\t\t\t};\n\t\tif (!this.worker) {\n\t\t\tthis.resolveResult(result);\n\t\t\treturn;\n\t\t}\n\t\tAtomics.store(new Int32Array(this.interrupt), 0, 1);\n\t\tthis.worker\n\t\t\t.terminate()\n\t\t\t.catch(() => undefined)\n\t\t\t.then(() => this.resolveResult(result));\n\t}\n}\n\n/**\n * Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker\n * thread. The script sees `tools.<name>(args)` for every registered tool, `ALL_TOOLS`,\n * the output helpers `text`, `image`, `exit`, and `console.*`, `store`/`load`, and the\n * configured globals; nothing else (no timers, `fetch`, `process`, `require`, modules).\n *\n * Each `execute()` gets its own worker and VM; the sandbox only holds the tool\n * table and defaults. `close()` aborts in-flight executions.\n */\nexport class CodemodeSandbox {\n\tprivate readonly toolsByName = new Map<string, CodemodeTool>();\n\tprivate readonly globalsByName = new Map<string, CodemodeTool>();\n\tprivate readonly timeoutMs: number;\n\tprivate readonly memoryLimitBytes: number | undefined;\n\tprivate readonly wasm: CodemodeWasmModule | Promise<CodemodeWasmModule> | undefined;\n\tprivate readonly workerUrl: string | URL;\n\tprivate readonly running = new Set<Execution>();\n\tprivate closed = false;\n\n\tconstructor(options: CodemodeSandboxOptions = {}) {\n\t\tthis.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\t\tthis.memoryLimitBytes = options.memoryLimitBytes;\n\t\tthis.wasm = options.wasm;\n\t\tthis.workerUrl = options.workerUrl ?? defaultWorkerUrl();\n\t\tfor (const tool of options.tools ?? []) this.registerTool(tool);\n\t\tconst namespaces = new Set<string>();\n\t\tfor (const global of options.globals ?? []) {\n\t\t\tconst parts = global.name.split(\".\");\n\t\t\tif (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part)) || RESERVED_GLOBALS.has(parts[0])) {\n\t\t\t\tthrow new Error(`Invalid global name \"${global.name}\"`);\n\t\t\t}\n\t\t\tif (this.globalsByName.has(global.name)) throw new Error(`Global \"${global.name}\" is already registered`);\n\t\t\tif (parts.length === 2) namespaces.add(parts[0]);\n\t\t\tthis.globalsByName.set(global.name, global);\n\t\t}\n\t\tfor (const name of namespaces) {\n\t\t\tif (this.globalsByName.has(name)) throw new Error(`Global \"${name}\" conflicts with the namespace \"${name}\"`);\n\t\t}\n\t}\n\n\t/** Throws if a tool with the same name is already registered. */\n\tregisterTool(tool: CodemodeTool): void {\n\t\tif (this.toolsByName.has(tool.name)) throw new Error(`Tool \"${tool.name}\" is already registered`);\n\t\tthis.toolsByName.set(tool.name, tool);\n\t}\n\n\tunregisterTool(name: string): boolean {\n\t\treturn this.toolsByName.delete(name);\n\t}\n\n\tget tools(): CodemodeTool[] {\n\t\treturn [...this.toolsByName.values()];\n\t}\n\n\tget globals(): CodemodeTool[] {\n\t\treturn [...this.globalsByName.values()];\n\t}\n\n\t/**\n\t * `code` is an async function body: `return` and top-level `await` work.\n\t * Never rejects for script failures; those come back as `{ ok: false }`.\n\t * The script can use `store(key, value)` and `load(key)` on `options.store`.\n\t */\n\texecute(code: string, options: CodemodeExecuteOptions = {}): Promise<CodemodeResult> {\n\t\tif (this.closed) return Promise.reject(new Error(\"Sandbox is closed\"));\n\t\tconst execution = new Execution({\n\t\t\tcode,\n\t\t\ttools: new Map(this.toolsByName),\n\t\t\tglobals: this.globalsByName,\n\t\t\ttimeoutMs: options.timeoutMs ?? this.timeoutMs,\n\t\t\tsignal: options.signal,\n\t\t\tmemoryLimitBytes: this.memoryLimitBytes,\n\t\t\tstore: serializeStore(options.store),\n\t\t\twasm: this.wasm === undefined ? loadQuickJSWasm() : Promise.resolve(this.wasm),\n\t\t\tworkerUrl: this.workerUrl,\n\t\t});\n\t\tthis.running.add(execution);\n\t\treturn execution.promise.finally(() => this.running.delete(execution));\n\t}\n\n\t/** Aborts in-flight executions (they resolve with `kind: \"aborted\"`) and rejects new ones. */\n\tasync close(): Promise<void> {\n\t\tthis.closed = true;\n\t\tawait Promise.all([...this.running].map((execution) => execution.abort(\"Sandbox closed\")));\n\t}\n}\n"]}
@@ -10,7 +10,7 @@
10
10
  * Output helpers: `text(value)` appends a text item (non-strings are
11
11
  * JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an
12
12
  * `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script
13
- * successfully. `console.*` appends text items like `text()`.
13
+ * successfully. `console.*` appends text items marked as console output.
14
14
  *
15
15
  * `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of
16
16
  * JSON text passed in as `storeJson`, and the keys the script wrote are reported
@@ -23,7 +23,11 @@
23
23
  * or I/O in the VM, nothing can ever resume it.
24
24
  * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
25
25
  * `bridge(kind, a, b, c)` with kind "call" or "global" (id, name, argsJson),
26
- * "output" ("text", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
26
+ * "output" ("text" or "console", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
27
+ *
28
+ * Before anything else the prelude freezes the built-ins and makes the built-in globals read-only.
29
+ * The prelude shares them with the script, so a script that patched one (for example
30
+ * `Array.prototype.toJSON`) could otherwise corrupt what the prelude reports to the host.
27
31
  */
28
32
  export declare const MAX_STORE_VALUE_CHARS: number;
29
33
  export declare const MAX_STORE_TOTAL_CHARS: number;
@@ -1 +1 @@
1
- {"version":3,"file":"prelude-source.d.ts","sourceRoot":"","sources":["../../src/runtime/prelude-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,qBAAqB,QAAa,CAAC;AAChD,eAAO,MAAM,qBAAqB,QAAc,CAAC;AACjD;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,QAAmB,CAAC;AACjD,eAAO,MAAM,gBAAgB,SAAU,CAAC;AAKxC,eAAO,MAAM,cAAc,EAAE,MAkX1B,CAAC"}
1
+ {"version":3,"file":"prelude-source.d.ts","sourceRoot":"","sources":["../../src/runtime/prelude-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,eAAO,MAAM,qBAAqB,QAAa,CAAC;AAChD,eAAO,MAAM,qBAAqB,QAAc,CAAC;AACjD;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,QAAmB,CAAC;AACjD,eAAO,MAAM,gBAAgB,SAAU,CAAC;AAKxC,eAAO,MAAM,cAAc,EAAE,MAkd1B,CAAC"}
@@ -10,7 +10,7 @@
10
10
  * Output helpers: `text(value)` appends a text item (non-strings are
11
11
  * JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an
12
12
  * `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script
13
- * successfully. `console.*` appends text items like `text()`.
13
+ * successfully. `console.*` appends text items marked as console output.
14
14
  *
15
15
  * `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of
16
16
  * JSON text passed in as `storeJson`, and the keys the script wrote are reported
@@ -23,7 +23,11 @@
23
23
  * or I/O in the VM, nothing can ever resume it.
24
24
  * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
25
25
  * `bridge(kind, a, b, c)` with kind "call" or "global" (id, name, argsJson),
26
- * "output" ("text", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
26
+ * "output" ("text" or "console", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
27
+ *
28
+ * Before anything else the prelude freezes the built-ins and makes the built-in globals read-only.
29
+ * The prelude shares them with the script, so a script that patched one (for example
30
+ * `Array.prototype.toJSON`) could otherwise corrupt what the prelude reports to the host.
27
31
  */
28
32
  export const MAX_STORE_VALUE_CHARS = 256 * 1024;
29
33
  export const MAX_STORE_TOTAL_CHARS = 1024 * 1024;
@@ -38,6 +42,96 @@ export const MAX_OUTPUT_ITEMS = 100_000;
38
42
  const IMAGE_HELPER_EXPECTS = "image expects a non-empty image URL string, an object with image_url, or a raw MCP image block";
39
43
  export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJson) {
40
44
  "use strict";
45
+
46
+ // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
47
+ // reachable from instances (iterator and generator prototypes, %TypedArray%).
48
+ //
49
+ // Freezing alone breaks ordinary code through the "override mistake": a data property that is
50
+ // read-only on a prototype cannot be assigned on an instance either, so
51
+ // this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
52
+ // become accessors whose setter defines an own property on the instance instead.
53
+ (function lockdown() {
54
+ const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
55
+ const seen = new Set([globalThis]);
56
+ const queue = [];
57
+ const add = (value) => {
58
+ if ((typeof value === "object" && value !== null) || typeof value === "function") {
59
+ if (!seen.has(value)) {
60
+ seen.add(value);
61
+ queue.push(value);
62
+ }
63
+ }
64
+ };
65
+
66
+ // Accessors from an object literal have no own prototype object, unlike function expressions,
67
+ // whose prototype.constructor would be converted again without end.
68
+ function allowOverride(object, key, value, enumerable) {
69
+ const { get, set } = Object.getOwnPropertyDescriptor(
70
+ {
71
+ get accessor() {
72
+ return value;
73
+ },
74
+ set accessor(next) {
75
+ if (this === object) {
76
+ throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
77
+ }
78
+ if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
79
+ Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
80
+ },
81
+ },
82
+ "accessor",
83
+ );
84
+ Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
85
+ add(get);
86
+ add(set);
87
+ }
88
+
89
+ for (const key of Reflect.ownKeys(globalThis)) {
90
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
91
+ add(descriptor.value);
92
+ add(descriptor.get);
93
+ add(descriptor.set);
94
+ if ("value" in descriptor && descriptor.configurable) {
95
+ Object.defineProperty(globalThis, key, { writable: false, configurable: false });
96
+ }
97
+ }
98
+ add(Object.getPrototypeOf(function* () {}));
99
+ add(Object.getPrototypeOf(async function () {}));
100
+ add(Object.getPrototypeOf(async function* () {}));
101
+ add(Object.getPrototypeOf(Int8Array));
102
+ add(Object.getPrototypeOf([][Symbol.iterator]()));
103
+ add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
104
+ add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
105
+ add(Object.getPrototypeOf(""[Symbol.iterator]()));
106
+ add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
107
+ if (typeof Iterator === "function") {
108
+ if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
109
+ if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
110
+ }
111
+
112
+ while (queue.length > 0) {
113
+ const object = queue.pop();
114
+ add(Object.getPrototypeOf(object));
115
+ const descriptors = Object.getOwnPropertyDescriptors(object);
116
+ for (const key of Reflect.ownKeys(descriptors)) {
117
+ const descriptor = descriptors[key];
118
+ if ("value" in descriptor) {
119
+ add(descriptor.value);
120
+ if (
121
+ descriptor.writable &&
122
+ descriptor.configurable &&
123
+ (object === Object.prototype || OVERRIDABLE.has(key))
124
+ ) {
125
+ allowOverride(object, key, descriptor.value, descriptor.enumerable);
126
+ }
127
+ } else {
128
+ add(descriptor.get);
129
+ add(descriptor.set);
130
+ }
131
+ }
132
+ Object.freeze(object);
133
+ }
134
+ })();
41
135
  const stringify = JSON.stringify;
42
136
  const parse = JSON.parse;
43
137
  const promiseThen = Promise.prototype.then;
@@ -82,11 +176,17 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
82
176
  }
83
177
  }
84
178
 
179
+ // The host requires string fields. A script can set an error's name or message to anything, so
180
+ // they are coerced, and a value whose coercion throws gets a placeholder.
85
181
  function describeError(error) {
86
- if (error instanceof ErrorCtor) {
87
- return stringify({ name: error.name, message: error.message, stack: errorText(error) });
182
+ try {
183
+ if (error instanceof ErrorCtor) {
184
+ return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
185
+ }
186
+ return stringify({ message: String(format(error)) });
187
+ } catch {
188
+ return stringify({ message: "The script threw a value that cannot be described" });
88
189
  }
89
- return stringify({ message: format(error) });
90
190
  }
91
191
 
92
192
  function caller(kind, name, spread) {
@@ -338,7 +438,7 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
338
438
  const console = {};
339
439
  for (const level of ["log", "info", "warn", "error", "debug"]) {
340
440
  console[level] = (...args) => {
341
- output("text", args.map(format).join(" "));
441
+ output("console", args.map(format).join(" "));
342
442
  };
343
443
  }
344
444
  Object.freeze(console);
@@ -1 +1 @@
1
- {"version":3,"file":"prelude-source.js","sourceRoot":"","sources":["../../src/runtime/prelude-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,GAAG,IAAI,CAAC;AAChD,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AAExC,MAAM,oBAAoB,GACzB,gGAAgG,CAAC;AAElG,MAAM,CAAC,MAAM,cAAc,GAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAgKhB,qBAAqB;;8GAEmE,qBAAqB;;;;;eAKpH,qBAAqB;;iDAEa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAiChD,gBAAgB,qBAAqB,gBAAgB;;2CAEhC,gBAAgB,kBAAkB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BA+BhE,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;sEAGK,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;gEAG1C,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;;4CAoBxD,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6G7E,CAAC","sourcesContent":["/**\n * JavaScript evaluated inside the QuickJS VM before the script runs.\n *\n * The VM is its own wasm instance, so nothing here guards a realm boundary.\n * The prelude keeps the host bridge in a closure so the script cannot call it\n * directly, and builds `tools`, `ALL_TOOLS`, the output helpers (`text`, `image`,\n * `exit`, `console`), and globals on top of it. Tool arguments and results cross\n * as JSON strings and are parsed on this side.\n *\n * Output helpers: `text(value)` appends a text item (non-strings are\n * JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an\n * `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script\n * successfully. `console.*` appends text items like `text()`.\n *\n * `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of\n * JSON text passed in as `storeJson`, and the keys the script wrote are reported\n * with a successful \"done\".\n *\n * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.\n * `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the\n * tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.\n * `stalled()` reports a script that has not finished while no host call is pending: with no timers\n * or I/O in the VM, nothing can ever resume it.\n * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.\n * `bridge(kind, a, b, c)` with kind \"call\" or \"global\" (id, name, argsJson),\n * \"output\" (\"text\", text) or (\"image\", data, mimeType), or \"done\" (ok, valueJsonOrErrorJson, writesJson).\n */\nexport const MAX_STORE_VALUE_CHARS = 256 * 1024;\nexport const MAX_STORE_TOTAL_CHARS = 1024 * 1024;\n/**\n * Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and\n * base64 image data, and items. The host keeps all output until the script ends, so without a\n * limit a script that prints in a loop grows the host's memory until it crashes. The item limit\n * covers loops that print empty strings.\n */\nexport const MAX_OUTPUT_CHARS = 16 * 1024 * 1024;\nexport const MAX_OUTPUT_ITEMS = 100_000;\n\nconst IMAGE_HELPER_EXPECTS =\n\t\"image expects a non-empty image URL string, an object with image_url, or a raw MCP image block\";\n\nexport const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson, storeJson) {\n\t\"use strict\";\n\tconst stringify = JSON.stringify;\n\tconst parse = JSON.parse;\n\tconst promiseThen = Promise.prototype.then;\n\tconst ErrorCtor = Error;\n\tconst TypeErrorCtor = TypeError;\n\tconst RangeErrorCtor = RangeError;\n\tconst pending = new Map();\n\tlet nextId = 1;\n\tlet finished = false;\n\t// Thrown by exit() to unwind the script after it already reported success.\n\tconst EXIT = Object.freeze({});\n\n\tfunction done(ok, payload, writes) {\n\t\tif (finished) return;\n\t\tfinished = true;\n\t\tbridge(\"done\", ok, payload, writes);\n\t}\n\n\tfunction serialize(value) {\n\t\treturn value === undefined ? undefined : stringify(value);\n\t}\n\n\t// QuickJS stacks list frames only. Prefix \"Name: message\" like V8 so the\n\t// text reads the same as a Node error, and drop this prelude's frames.\n\tfunction errorText(error) {\n\t\tconst head = error.message ? error.name + \": \" + error.message : String(error.name);\n\t\tconst frames =\n\t\t\ttypeof error.stack === \"string\"\n\t\t\t\t? error.stack.split(\"\\\\n\").filter((line) => line.trim() && !line.includes(\"codemode-prelude.js\"))\n\t\t\t\t: [];\n\t\treturn [head, ...frames].join(\"\\\\n\");\n\t}\n\n\tfunction format(value) {\n\t\tif (typeof value === \"string\") return value;\n\t\tif (value instanceof ErrorCtor) return errorText(value);\n\t\ttry {\n\t\t\tconst json = stringify(value);\n\t\t\treturn json === undefined ? String(value) : json;\n\t\t} catch {\n\t\t\treturn String(value);\n\t\t}\n\t}\n\n\tfunction describeError(error) {\n\t\tif (error instanceof ErrorCtor) {\n\t\t\treturn stringify({ name: error.name, message: error.message, stack: errorText(error) });\n\t\t}\n\t\treturn stringify({ message: format(error) });\n\t}\n\n\tfunction caller(kind, name, spread) {\n\t\treturn (...args) =>\n\t\t\tnew Promise((resolve, reject) => {\n\t\t\t\tlet json;\n\t\t\t\ttry {\n\t\t\t\t\tjson = serialize(spread ? args : args[0]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst id = nextId++;\n\t\t\t\tpending.set(id, { resolve, reject });\n\t\t\t\tbridge(kind, id, name, json);\n\t\t\t});\n\t}\n\n\tconst tools = Object.create(null);\n\tconst allTools = [];\n\tfor (const { name, jsName, description } of parse(toolsJson)) {\n\t\tconst fn = caller(\"call\", name);\n\t\t// The first tool wins when two names normalize to the same identifier.\n\t\tif (!(jsName in tools)) {\n\t\t\ttools[jsName] = fn;\n\t\t\tallTools.push(Object.freeze({ name: jsName, description }));\n\t\t}\n\t\tif (!(name in tools)) tools[name] = fn;\n\t}\n\tObject.freeze(tools);\n\tObject.freeze(allTools);\n\n\t// Reading a member that does not exist throws an error that names the close matches, instead of\n\t// a later \"not a function\". \\`in\\` checks still work.\n\tconst comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n\tfunction guard(target, label, names, hint) {\n\t\treturn new Proxy(target, {\n\t\t\tget(object, property, receiver) {\n\t\t\t\tif (typeof property !== \"string\" || property in object || property in Object.prototype || property === \"then\" || property === \"toJSON\") {\n\t\t\t\t\treturn Reflect.get(object, property, receiver);\n\t\t\t\t}\n\t\t\t\tconst wanted = comparable(property);\n\t\t\t\tconst exact = names.filter((name) => comparable(name) === wanted);\n\t\t\t\tconst close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));\n\t\t\t\tlet message = label + \".\" + property + \" does not exist.\";\n\t\t\t\tif (close.length > 0) message += \" Did you mean \" + close.slice(0, 5).map((name) => label + \".\" + name).join(\", \") + \"?\";\n\t\t\t\telse if (names.length <= 20) message += \" Available: \" + names.join(\", \") + \".\";\n\t\t\t\tif (hint) message += \" \" + hint;\n\t\t\t\tmessage += ' Check for a member with \"' + property + '\" in ' + label + \".\";\n\t\t\t\tthrow new TypeErrorCtor(message);\n\t\t\t},\n\t\t});\n\t}\n\tconst toolsProxy = guard(\n\t\ttools,\n\t\t\"tools\",\n\t\tallTools.map((tool) => tool.name),\n\t\t\"ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.\",\n\t);\n\n\tconst namespaces = new Map();\n\tfor (const { name, spread } of parse(globalsJson)) {\n\t\tconst fn = caller(\"global\", name, spread);\n\t\tconst dot = name.indexOf(\".\");\n\t\tif (dot === -1) {\n\t\t\tObject.defineProperty(globalThis, name, { value: fn, enumerable: true });\n\t\t\tcontinue;\n\t\t}\n\t\tconst namespace = name.slice(0, dot);\n\t\tif (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));\n\t\tnamespaces.get(namespace)[name.slice(dot + 1)] = fn;\n\t}\n\tfor (const [namespace, members] of namespaces) {\n\t\tObject.freeze(members);\n\t\tconst value = guard(members, namespace, Object.keys(members));\n\t\tObject.defineProperty(globalThis, namespace, { value, enumerable: true });\n\t}\n\n\t// key -> JSON text. Sizes count key and JSON characters.\n\tconst stored = new Map(Object.entries(parse(storeJson)));\n\tconst writes = new Map();\n\tlet storedChars = 0;\n\tfor (const [key, json] of stored) storedChars += key.length + json.length;\n\n\tconst STORE_HINT =\n\t\t\"store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool.\";\n\n\tfunction checkKey(name, key) {\n\t\tif (typeof key !== \"string\") throw new TypeError(name + \"() key must be a string\");\n\t}\n\n\tfunction store(key, value) {\n\t\tcheckKey(\"store\", key);\n\t\tconst previous = stored.has(key) ? key.length + stored.get(key).length : 0;\n\t\tif (value === undefined) {\n\t\t\tstored.delete(key);\n\t\t\tstoredChars -= previous;\n\t\t\twrites.set(key, undefined);\n\t\t\treturn;\n\t\t}\n\t\tlet json;\n\t\ttry {\n\t\t\tjson = stringify(value);\n\t\t} catch (error) {\n\t\t\tthrow new TypeError(\"store(\" + stringify(key) + \") value is not JSON-serializable: \" + format(error));\n\t\t}\n\t\tif (json === undefined) {\n\t\t\tthrow new TypeError(\"store(\" + stringify(key) + \") value is not JSON-serializable\");\n\t\t}\n\t\tif (json.length > ${MAX_STORE_VALUE_CHARS}) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"store(\" + stringify(key) + \") value has \" + json.length + \" characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. \" +\n\t\t\t\t\tSTORE_HINT,\n\t\t\t);\n\t\t}\n\t\tconst next = storedChars - previous + key.length + json.length;\n\t\tif (next > ${MAX_STORE_TOTAL_CHARS}) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). \" +\n\t\t\t\t\tSTORE_HINT,\n\t\t\t);\n\t\t}\n\t\tstored.set(key, json);\n\t\tstoredChars = next;\n\t\twrites.set(key, json);\n\t}\n\n\tfunction load(key) {\n\t\tcheckKey(\"load\", key);\n\t\tconst json = stored.get(key);\n\t\treturn json === undefined ? undefined : parse(json);\n\t}\n\n\tfunction serializeWrites() {\n\t\tconst entries = [];\n\t\tfor (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);\n\t\treturn stringify(entries);\n\t}\n\n\tObject.defineProperty(globalThis, \"store\", { value: store, enumerable: true });\n\tObject.defineProperty(globalThis, \"load\", { value: load, enumerable: true });\n\n\tlet outputChars = 0;\n\tlet outputItems = 0;\n\n\t// Past the output limits the script fails: done() reports the error, so catching it does not\n\t// resume output, and the host ends the script.\n\tfunction output(kind, data, mimeType) {\n\t\tif (finished) return;\n\t\toutputChars += data.length;\n\t\toutputItems++;\n\t\tif (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {\n\t\t\tconst error = new RangeErrorCtor(\n\t\t\t\t\"script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. \" +\n\t\t\t\t\t\"Print a summary instead, or write large data to a file with a tool.\",\n\t\t\t);\n\t\t\tdone(false, describeError(error));\n\t\t\tthrow error;\n\t\t}\n\t\tbridge(\"output\", kind, data, mimeType);\n\t}\n\n\t// Primitives become their string form, everything else JSON.\n\tfunction outputText(value) {\n\t\tif (value === undefined || value === null || typeof value !== \"object\" && typeof value !== \"function\") {\n\t\t\treturn String(value);\n\t\t}\n\t\tconst json = stringify(value);\n\t\treturn json === undefined ? String(value) : json;\n\t}\n\n\tfunction text(value) {\n\t\tlet rendered;\n\t\ttry {\n\t\t\trendered = outputText(value);\n\t\t} catch (error) {\n\t\t\tthrow new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));\n\t\t}\n\t\toutput(\"text\", rendered);\n\t}\n\n\tfunction imageUrl(value) {\n\t\tif (typeof value === \"string\") return value;\n\t\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\t\tthrow new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\t}\n\t\tif (value.image_url !== undefined) {\n\t\t\tif (typeof value.image_url !== \"string\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\t\treturn value.image_url;\n\t\t}\n\t\tif (typeof value.type !== \"string\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\tif (value.type !== \"image\") {\n\t\t\tthrow new TypeErrorCtor('image only accepts MCP image blocks, got \"' + value.type + '\"');\n\t\t}\n\t\tif (typeof value.data !== \"string\" || value.data === \"\") throw new TypeErrorCtor(\"image expected MCP image data\");\n\t\tif (value.data.toLowerCase().startsWith(\"data:\")) return value.data;\n\t\treturn \"data:;base64,\" + value.data;\n\t}\n\n\t// Base64 of the signatures of the formats providers accept inline (PNG, JPEG except\n\t// JPEG-LS, GIF, \"RIFF....WEBP\"). Signatures start at byte 0, so their encodings are prefixes.\n\tconst IMAGE_SIGNATURES = [\n\t\t[\"image/png\", /^iVBORw0KGg/],\n\t\t[\"image/jpeg\", /^[/]9j[/](?!9)/],\n\t\t[\"image/gif\", /^R0lGOD[dl]h/],\n\t\t[\"image/webp\", /^UklG.{8}RUJQ/],\n\t];\n\n\tfunction image(value) {\n\t\tconst url = imageUrl(value);\n\t\tif (url === \"\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\tconst colon = url.indexOf(\":\");\n\t\tconst scheme = colon === -1 ? \"\" : url.slice(0, colon).toLowerCase();\n\t\tif (scheme === \"http\" || scheme === \"https\") {\n\t\t\tthrow new TypeErrorCtor(\"remote image URLs are not supported in tool outputs. Pass a base64 data URI instead\");\n\t\t}\n\t\tconst comma = url.indexOf(\",\");\n\t\tconst header = comma === -1 ? [] : url.slice(colon + 1, comma).split(\";\");\n\t\tif (scheme !== \"data\" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== \"base64\")) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. Pass a base64 data URI instead\");\n\t\t}\n\t\t// Providers reject the whole request on a bad image, and a persisted image block would be\n\t\t// resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type\n\t\t// is ignored in favor of the detected one, as providers also reject mismatches.\n\t\tconst data = url.slice(comma + 1).replace(/\\\\s+/g, \"\");\n\t\tif (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. The image data is not valid base64 (truncated or corrupted?)\");\n\t\t}\n\t\tconst head = data.slice(0, 16);\n\t\tconst signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));\n\t\tif (!signature) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image\");\n\t\t}\n\t\toutput(\"image\", data, signature[0]);\n\t}\n\n\tfunction exit() {\n\t\tlet writesJson;\n\t\ttry {\n\t\t\twritesJson = serializeWrites();\n\t\t} catch (error) {\n\t\t\tdone(false, describeError(error));\n\t\t\tthrow EXIT;\n\t\t}\n\t\tdone(true, undefined, writesJson);\n\t\tthrow EXIT;\n\t}\n\n\tconst console = {};\n\tfor (const level of [\"log\", \"info\", \"warn\", \"error\", \"debug\"]) {\n\t\tconsole[level] = (...args) => {\n\t\t\toutput(\"text\", args.map(format).join(\" \"));\n\t\t};\n\t}\n\tObject.freeze(console);\n\n\tObject.defineProperty(globalThis, \"tools\", { value: toolsProxy, enumerable: true });\n\tObject.defineProperty(globalThis, \"ALL_TOOLS\", { value: allTools, enumerable: true });\n\tObject.defineProperty(globalThis, \"console\", { value: console, enumerable: true });\n\tObject.defineProperty(globalThis, \"text\", { value: text, enumerable: true });\n\tObject.defineProperty(globalThis, \"image\", { value: image, enumerable: true });\n\tObject.defineProperty(globalThis, \"exit\", { value: exit, enumerable: true });\n\n\treturn {\n\t\tsettle(id, ok, payload) {\n\t\t\tconst entry = pending.get(id);\n\t\t\tif (!entry) return;\n\t\t\tpending.delete(id);\n\t\t\tif (!ok) {\n\t\t\t\tentry.reject(new ErrorCtor(payload));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet value;\n\t\t\ttry {\n\t\t\t\tvalue = payload === undefined ? undefined : parse(payload);\n\t\t\t} catch (error) {\n\t\t\t\tentry.reject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry.resolve(value);\n\t\t},\n\t\trun(fn) {\n\t\t\tlet promise;\n\t\t\ttry {\n\t\t\t\tpromise = fn(toolsProxy, console);\n\t\t\t} catch (error) {\n\t\t\t\tdone(false, describeError(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpromiseThen.call(\n\t\t\t\tpromise,\n\t\t\t\t(value) => {\n\t\t\t\t\tlet json;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tjson = serialize(value);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tdone(false, describeError(error));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tdone(true, json, serializeWrites());\n\t\t\t\t},\n\t\t\t\t(error) => {\n\t\t\t\t\tdone(false, describeError(error));\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tstalled() {\n\t\t\tif (finished || pending.size > 0) return false;\n\t\t\tdone(\n\t\t\t\tfalse,\n\t\t\t\tstringify({\n\t\t\t\t\tname: \"Error\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.\",\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn true;\n\t\t},\n\t};\n})`;\n"]}
1
+ {"version":3,"file":"prelude-source.js","sourceRoot":"","sources":["../../src/runtime/prelude-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,GAAG,IAAI,CAAC;AAChD,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AAExC,MAAM,oBAAoB,GACzB,gGAAgG,CAAC;AAElG,MAAM,CAAC,MAAM,cAAc,GAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAgQhB,qBAAqB;;8GAEmE,qBAAqB;;;;;eAKpH,qBAAqB;;iDAEa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAiChD,gBAAgB,qBAAqB,gBAAgB;;2CAEhC,gBAAgB,kBAAkB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BA+BhE,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;sEAGK,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;gEAG1C,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;;4CAoBxD,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6G7E,CAAC","sourcesContent":["/**\n * JavaScript evaluated inside the QuickJS VM before the script runs.\n *\n * The VM is its own wasm instance, so nothing here guards a realm boundary.\n * The prelude keeps the host bridge in a closure so the script cannot call it\n * directly, and builds `tools`, `ALL_TOOLS`, the output helpers (`text`, `image`,\n * `exit`, `console`), and globals on top of it. Tool arguments and results cross\n * as JSON strings and are parsed on this side.\n *\n * Output helpers: `text(value)` appends a text item (non-strings are\n * JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an\n * `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script\n * successfully. `console.*` appends text items marked as console output.\n *\n * `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of\n * JSON text passed in as `storeJson`, and the keys the script wrote are reported\n * with a successful \"done\".\n *\n * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.\n * `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the\n * tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.\n * `stalled()` reports a script that has not finished while no host call is pending: with no timers\n * or I/O in the VM, nothing can ever resume it.\n * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.\n * `bridge(kind, a, b, c)` with kind \"call\" or \"global\" (id, name, argsJson),\n * \"output\" (\"text\" or \"console\", text) or (\"image\", data, mimeType), or \"done\" (ok, valueJsonOrErrorJson, writesJson).\n *\n * Before anything else the prelude freezes the built-ins and makes the built-in globals read-only.\n * The prelude shares them with the script, so a script that patched one (for example\n * `Array.prototype.toJSON`) could otherwise corrupt what the prelude reports to the host.\n */\nexport const MAX_STORE_VALUE_CHARS = 256 * 1024;\nexport const MAX_STORE_TOTAL_CHARS = 1024 * 1024;\n/**\n * Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and\n * base64 image data, and items. The host keeps all output until the script ends, so without a\n * limit a script that prints in a loop grows the host's memory until it crashes. The item limit\n * covers loops that print empty strings.\n */\nexport const MAX_OUTPUT_CHARS = 16 * 1024 * 1024;\nexport const MAX_OUTPUT_ITEMS = 100_000;\n\nconst IMAGE_HELPER_EXPECTS =\n\t\"image expects a non-empty image URL string, an object with image_url, or a raw MCP image block\";\n\nexport const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson, storeJson) {\n\t\"use strict\";\n\n\t// Freeze every object reachable from the built-in globals, plus the intrinsics that are only\n\t// reachable from instances (iterator and generator prototypes, %TypedArray%).\n\t//\n\t// Freezing alone breaks ordinary code through the \"override mistake\": a data property that is\n\t// read-only on a prototype cannot be assigned on an instance either, so\n\t// this.name = \"MyError\" in an Error subclass would throw. Commonly overridden properties\n\t// become accessors whose setter defines an own property on the instance instead.\n\t(function lockdown() {\n\t\tconst OVERRIDABLE = new Set([\"constructor\", \"name\", \"message\", \"toString\", \"toLocaleString\", \"valueOf\", \"toJSON\"]);\n\t\tconst seen = new Set([globalThis]);\n\t\tconst queue = [];\n\t\tconst add = (value) => {\n\t\t\tif ((typeof value === \"object\" && value !== null) || typeof value === \"function\") {\n\t\t\t\tif (!seen.has(value)) {\n\t\t\t\t\tseen.add(value);\n\t\t\t\t\tqueue.push(value);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Accessors from an object literal have no own prototype object, unlike function expressions,\n\t\t// whose prototype.constructor would be converted again without end.\n\t\tfunction allowOverride(object, key, value, enumerable) {\n\t\t\tconst { get, set } = Object.getOwnPropertyDescriptor(\n\t\t\t\t{\n\t\t\t\t\tget accessor() {\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t},\n\t\t\t\t\tset accessor(next) {\n\t\t\t\t\t\tif (this === object) {\n\t\t\t\t\t\t\tthrow new TypeError(\"Cannot assign to read only property '\" + String(key) + \"' of a built-in\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((typeof this !== \"object\" || this === null) && typeof this !== \"function\") return;\n\t\t\t\t\t\tObject.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"accessor\",\n\t\t\t);\n\t\t\tObject.defineProperty(object, key, { get, set, enumerable, configurable: false });\n\t\t\tadd(get);\n\t\t\tadd(set);\n\t\t}\n\n\t\tfor (const key of Reflect.ownKeys(globalThis)) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(globalThis, key);\n\t\t\tadd(descriptor.value);\n\t\t\tadd(descriptor.get);\n\t\t\tadd(descriptor.set);\n\t\t\tif (\"value\" in descriptor && descriptor.configurable) {\n\t\t\t\tObject.defineProperty(globalThis, key, { writable: false, configurable: false });\n\t\t\t}\n\t\t}\n\t\tadd(Object.getPrototypeOf(function* () {}));\n\t\tadd(Object.getPrototypeOf(async function () {}));\n\t\tadd(Object.getPrototypeOf(async function* () {}));\n\t\tadd(Object.getPrototypeOf(Int8Array));\n\t\tadd(Object.getPrototypeOf([][Symbol.iterator]()));\n\t\tadd(Object.getPrototypeOf(new Map()[Symbol.iterator]()));\n\t\tadd(Object.getPrototypeOf(new Set()[Symbol.iterator]()));\n\t\tadd(Object.getPrototypeOf(\"\"[Symbol.iterator]()));\n\t\tadd(Object.getPrototypeOf(/a/[Symbol.matchAll](\"\")));\n\t\tif (typeof Iterator === \"function\") {\n\t\t\tif (typeof Iterator.prototype.map === \"function\") add(Object.getPrototypeOf([].values().map((x) => x)));\n\t\t\tif (typeof Iterator.from === \"function\") add(Object.getPrototypeOf(Iterator.from({ next() {} })));\n\t\t}\n\n\t\twhile (queue.length > 0) {\n\t\t\tconst object = queue.pop();\n\t\t\tadd(Object.getPrototypeOf(object));\n\t\t\tconst descriptors = Object.getOwnPropertyDescriptors(object);\n\t\t\tfor (const key of Reflect.ownKeys(descriptors)) {\n\t\t\t\tconst descriptor = descriptors[key];\n\t\t\t\tif (\"value\" in descriptor) {\n\t\t\t\t\tadd(descriptor.value);\n\t\t\t\t\tif (\n\t\t\t\t\t\tdescriptor.writable &&\n\t\t\t\t\t\tdescriptor.configurable &&\n\t\t\t\t\t\t(object === Object.prototype || OVERRIDABLE.has(key))\n\t\t\t\t\t) {\n\t\t\t\t\t\tallowOverride(object, key, descriptor.value, descriptor.enumerable);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tadd(descriptor.get);\n\t\t\t\t\tadd(descriptor.set);\n\t\t\t\t}\n\t\t\t}\n\t\t\tObject.freeze(object);\n\t\t}\n\t})();\n\tconst stringify = JSON.stringify;\n\tconst parse = JSON.parse;\n\tconst promiseThen = Promise.prototype.then;\n\tconst ErrorCtor = Error;\n\tconst TypeErrorCtor = TypeError;\n\tconst RangeErrorCtor = RangeError;\n\tconst pending = new Map();\n\tlet nextId = 1;\n\tlet finished = false;\n\t// Thrown by exit() to unwind the script after it already reported success.\n\tconst EXIT = Object.freeze({});\n\n\tfunction done(ok, payload, writes) {\n\t\tif (finished) return;\n\t\tfinished = true;\n\t\tbridge(\"done\", ok, payload, writes);\n\t}\n\n\tfunction serialize(value) {\n\t\treturn value === undefined ? undefined : stringify(value);\n\t}\n\n\t// QuickJS stacks list frames only. Prefix \"Name: message\" like V8 so the\n\t// text reads the same as a Node error, and drop this prelude's frames.\n\tfunction errorText(error) {\n\t\tconst head = error.message ? error.name + \": \" + error.message : String(error.name);\n\t\tconst frames =\n\t\t\ttypeof error.stack === \"string\"\n\t\t\t\t? error.stack.split(\"\\\\n\").filter((line) => line.trim() && !line.includes(\"codemode-prelude.js\"))\n\t\t\t\t: [];\n\t\treturn [head, ...frames].join(\"\\\\n\");\n\t}\n\n\tfunction format(value) {\n\t\tif (typeof value === \"string\") return value;\n\t\tif (value instanceof ErrorCtor) return errorText(value);\n\t\ttry {\n\t\t\tconst json = stringify(value);\n\t\t\treturn json === undefined ? String(value) : json;\n\t\t} catch {\n\t\t\treturn String(value);\n\t\t}\n\t}\n\n\t// The host requires string fields. A script can set an error's name or message to anything, so\n\t// they are coerced, and a value whose coercion throws gets a placeholder.\n\tfunction describeError(error) {\n\t\ttry {\n\t\t\tif (error instanceof ErrorCtor) {\n\t\t\t\treturn stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });\n\t\t\t}\n\t\t\treturn stringify({ message: String(format(error)) });\n\t\t} catch {\n\t\t\treturn stringify({ message: \"The script threw a value that cannot be described\" });\n\t\t}\n\t}\n\n\tfunction caller(kind, name, spread) {\n\t\treturn (...args) =>\n\t\t\tnew Promise((resolve, reject) => {\n\t\t\t\tlet json;\n\t\t\t\ttry {\n\t\t\t\t\tjson = serialize(spread ? args : args[0]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst id = nextId++;\n\t\t\t\tpending.set(id, { resolve, reject });\n\t\t\t\tbridge(kind, id, name, json);\n\t\t\t});\n\t}\n\n\tconst tools = Object.create(null);\n\tconst allTools = [];\n\tfor (const { name, jsName, description } of parse(toolsJson)) {\n\t\tconst fn = caller(\"call\", name);\n\t\t// The first tool wins when two names normalize to the same identifier.\n\t\tif (!(jsName in tools)) {\n\t\t\ttools[jsName] = fn;\n\t\t\tallTools.push(Object.freeze({ name: jsName, description }));\n\t\t}\n\t\tif (!(name in tools)) tools[name] = fn;\n\t}\n\tObject.freeze(tools);\n\tObject.freeze(allTools);\n\n\t// Reading a member that does not exist throws an error that names the close matches, instead of\n\t// a later \"not a function\". \\`in\\` checks still work.\n\tconst comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n\tfunction guard(target, label, names, hint) {\n\t\treturn new Proxy(target, {\n\t\t\tget(object, property, receiver) {\n\t\t\t\tif (typeof property !== \"string\" || property in object || property in Object.prototype || property === \"then\" || property === \"toJSON\") {\n\t\t\t\t\treturn Reflect.get(object, property, receiver);\n\t\t\t\t}\n\t\t\t\tconst wanted = comparable(property);\n\t\t\t\tconst exact = names.filter((name) => comparable(name) === wanted);\n\t\t\t\tconst close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));\n\t\t\t\tlet message = label + \".\" + property + \" does not exist.\";\n\t\t\t\tif (close.length > 0) message += \" Did you mean \" + close.slice(0, 5).map((name) => label + \".\" + name).join(\", \") + \"?\";\n\t\t\t\telse if (names.length <= 20) message += \" Available: \" + names.join(\", \") + \".\";\n\t\t\t\tif (hint) message += \" \" + hint;\n\t\t\t\tmessage += ' Check for a member with \"' + property + '\" in ' + label + \".\";\n\t\t\t\tthrow new TypeErrorCtor(message);\n\t\t\t},\n\t\t});\n\t}\n\tconst toolsProxy = guard(\n\t\ttools,\n\t\t\"tools\",\n\t\tallTools.map((tool) => tool.name),\n\t\t\"ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.\",\n\t);\n\n\tconst namespaces = new Map();\n\tfor (const { name, spread } of parse(globalsJson)) {\n\t\tconst fn = caller(\"global\", name, spread);\n\t\tconst dot = name.indexOf(\".\");\n\t\tif (dot === -1) {\n\t\t\tObject.defineProperty(globalThis, name, { value: fn, enumerable: true });\n\t\t\tcontinue;\n\t\t}\n\t\tconst namespace = name.slice(0, dot);\n\t\tif (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));\n\t\tnamespaces.get(namespace)[name.slice(dot + 1)] = fn;\n\t}\n\tfor (const [namespace, members] of namespaces) {\n\t\tObject.freeze(members);\n\t\tconst value = guard(members, namespace, Object.keys(members));\n\t\tObject.defineProperty(globalThis, namespace, { value, enumerable: true });\n\t}\n\n\t// key -> JSON text. Sizes count key and JSON characters.\n\tconst stored = new Map(Object.entries(parse(storeJson)));\n\tconst writes = new Map();\n\tlet storedChars = 0;\n\tfor (const [key, json] of stored) storedChars += key.length + json.length;\n\n\tconst STORE_HINT =\n\t\t\"store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool.\";\n\n\tfunction checkKey(name, key) {\n\t\tif (typeof key !== \"string\") throw new TypeError(name + \"() key must be a string\");\n\t}\n\n\tfunction store(key, value) {\n\t\tcheckKey(\"store\", key);\n\t\tconst previous = stored.has(key) ? key.length + stored.get(key).length : 0;\n\t\tif (value === undefined) {\n\t\t\tstored.delete(key);\n\t\t\tstoredChars -= previous;\n\t\t\twrites.set(key, undefined);\n\t\t\treturn;\n\t\t}\n\t\tlet json;\n\t\ttry {\n\t\t\tjson = stringify(value);\n\t\t} catch (error) {\n\t\t\tthrow new TypeError(\"store(\" + stringify(key) + \") value is not JSON-serializable: \" + format(error));\n\t\t}\n\t\tif (json === undefined) {\n\t\t\tthrow new TypeError(\"store(\" + stringify(key) + \") value is not JSON-serializable\");\n\t\t}\n\t\tif (json.length > ${MAX_STORE_VALUE_CHARS}) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"store(\" + stringify(key) + \") value has \" + json.length + \" characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. \" +\n\t\t\t\t\tSTORE_HINT,\n\t\t\t);\n\t\t}\n\t\tconst next = storedChars - previous + key.length + json.length;\n\t\tif (next > ${MAX_STORE_TOTAL_CHARS}) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). \" +\n\t\t\t\t\tSTORE_HINT,\n\t\t\t);\n\t\t}\n\t\tstored.set(key, json);\n\t\tstoredChars = next;\n\t\twrites.set(key, json);\n\t}\n\n\tfunction load(key) {\n\t\tcheckKey(\"load\", key);\n\t\tconst json = stored.get(key);\n\t\treturn json === undefined ? undefined : parse(json);\n\t}\n\n\tfunction serializeWrites() {\n\t\tconst entries = [];\n\t\tfor (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);\n\t\treturn stringify(entries);\n\t}\n\n\tObject.defineProperty(globalThis, \"store\", { value: store, enumerable: true });\n\tObject.defineProperty(globalThis, \"load\", { value: load, enumerable: true });\n\n\tlet outputChars = 0;\n\tlet outputItems = 0;\n\n\t// Past the output limits the script fails: done() reports the error, so catching it does not\n\t// resume output, and the host ends the script.\n\tfunction output(kind, data, mimeType) {\n\t\tif (finished) return;\n\t\toutputChars += data.length;\n\t\toutputItems++;\n\t\tif (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {\n\t\t\tconst error = new RangeErrorCtor(\n\t\t\t\t\"script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. \" +\n\t\t\t\t\t\"Print a summary instead, or write large data to a file with a tool.\",\n\t\t\t);\n\t\t\tdone(false, describeError(error));\n\t\t\tthrow error;\n\t\t}\n\t\tbridge(\"output\", kind, data, mimeType);\n\t}\n\n\t// Primitives become their string form, everything else JSON.\n\tfunction outputText(value) {\n\t\tif (value === undefined || value === null || typeof value !== \"object\" && typeof value !== \"function\") {\n\t\t\treturn String(value);\n\t\t}\n\t\tconst json = stringify(value);\n\t\treturn json === undefined ? String(value) : json;\n\t}\n\n\tfunction text(value) {\n\t\tlet rendered;\n\t\ttry {\n\t\t\trendered = outputText(value);\n\t\t} catch (error) {\n\t\t\tthrow new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));\n\t\t}\n\t\toutput(\"text\", rendered);\n\t}\n\n\tfunction imageUrl(value) {\n\t\tif (typeof value === \"string\") return value;\n\t\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\t\tthrow new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\t}\n\t\tif (value.image_url !== undefined) {\n\t\t\tif (typeof value.image_url !== \"string\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\t\treturn value.image_url;\n\t\t}\n\t\tif (typeof value.type !== \"string\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\tif (value.type !== \"image\") {\n\t\t\tthrow new TypeErrorCtor('image only accepts MCP image blocks, got \"' + value.type + '\"');\n\t\t}\n\t\tif (typeof value.data !== \"string\" || value.data === \"\") throw new TypeErrorCtor(\"image expected MCP image data\");\n\t\tif (value.data.toLowerCase().startsWith(\"data:\")) return value.data;\n\t\treturn \"data:;base64,\" + value.data;\n\t}\n\n\t// Base64 of the signatures of the formats providers accept inline (PNG, JPEG except\n\t// JPEG-LS, GIF, \"RIFF....WEBP\"). Signatures start at byte 0, so their encodings are prefixes.\n\tconst IMAGE_SIGNATURES = [\n\t\t[\"image/png\", /^iVBORw0KGg/],\n\t\t[\"image/jpeg\", /^[/]9j[/](?!9)/],\n\t\t[\"image/gif\", /^R0lGOD[dl]h/],\n\t\t[\"image/webp\", /^UklG.{8}RUJQ/],\n\t];\n\n\tfunction image(value) {\n\t\tconst url = imageUrl(value);\n\t\tif (url === \"\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\tconst colon = url.indexOf(\":\");\n\t\tconst scheme = colon === -1 ? \"\" : url.slice(0, colon).toLowerCase();\n\t\tif (scheme === \"http\" || scheme === \"https\") {\n\t\t\tthrow new TypeErrorCtor(\"remote image URLs are not supported in tool outputs. Pass a base64 data URI instead\");\n\t\t}\n\t\tconst comma = url.indexOf(\",\");\n\t\tconst header = comma === -1 ? [] : url.slice(colon + 1, comma).split(\";\");\n\t\tif (scheme !== \"data\" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== \"base64\")) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. Pass a base64 data URI instead\");\n\t\t}\n\t\t// Providers reject the whole request on a bad image, and a persisted image block would be\n\t\t// resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type\n\t\t// is ignored in favor of the detected one, as providers also reject mismatches.\n\t\tconst data = url.slice(comma + 1).replace(/\\\\s+/g, \"\");\n\t\tif (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. The image data is not valid base64 (truncated or corrupted?)\");\n\t\t}\n\t\tconst head = data.slice(0, 16);\n\t\tconst signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));\n\t\tif (!signature) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image\");\n\t\t}\n\t\toutput(\"image\", data, signature[0]);\n\t}\n\n\tfunction exit() {\n\t\tlet writesJson;\n\t\ttry {\n\t\t\twritesJson = serializeWrites();\n\t\t} catch (error) {\n\t\t\tdone(false, describeError(error));\n\t\t\tthrow EXIT;\n\t\t}\n\t\tdone(true, undefined, writesJson);\n\t\tthrow EXIT;\n\t}\n\n\tconst console = {};\n\tfor (const level of [\"log\", \"info\", \"warn\", \"error\", \"debug\"]) {\n\t\tconsole[level] = (...args) => {\n\t\t\toutput(\"console\", args.map(format).join(\" \"));\n\t\t};\n\t}\n\tObject.freeze(console);\n\n\tObject.defineProperty(globalThis, \"tools\", { value: toolsProxy, enumerable: true });\n\tObject.defineProperty(globalThis, \"ALL_TOOLS\", { value: allTools, enumerable: true });\n\tObject.defineProperty(globalThis, \"console\", { value: console, enumerable: true });\n\tObject.defineProperty(globalThis, \"text\", { value: text, enumerable: true });\n\tObject.defineProperty(globalThis, \"image\", { value: image, enumerable: true });\n\tObject.defineProperty(globalThis, \"exit\", { value: exit, enumerable: true });\n\n\treturn {\n\t\tsettle(id, ok, payload) {\n\t\t\tconst entry = pending.get(id);\n\t\t\tif (!entry) return;\n\t\t\tpending.delete(id);\n\t\t\tif (!ok) {\n\t\t\t\tentry.reject(new ErrorCtor(payload));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet value;\n\t\t\ttry {\n\t\t\t\tvalue = payload === undefined ? undefined : parse(payload);\n\t\t\t} catch (error) {\n\t\t\t\tentry.reject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry.resolve(value);\n\t\t},\n\t\trun(fn) {\n\t\t\tlet promise;\n\t\t\ttry {\n\t\t\t\tpromise = fn(toolsProxy, console);\n\t\t\t} catch (error) {\n\t\t\t\tdone(false, describeError(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpromiseThen.call(\n\t\t\t\tpromise,\n\t\t\t\t(value) => {\n\t\t\t\t\tlet json;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tjson = serialize(value);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tdone(false, describeError(error));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tdone(true, json, serializeWrites());\n\t\t\t\t},\n\t\t\t\t(error) => {\n\t\t\t\t\tdone(false, describeError(error));\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tstalled() {\n\t\t\tif (finished || pending.size > 0) return false;\n\t\t\tdone(\n\t\t\t\tfalse,\n\t\t\t\tstringify({\n\t\t\t\t\tname: \"Error\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.\",\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn true;\n\t\t},\n\t};\n})`;\n"]}
@@ -73,7 +73,9 @@ async function main(data) {
73
73
  type: "output",
74
74
  item: a.toString() === "image"
75
75
  ? { type: "image", data: b.toString(), mimeType: c.toString() }
76
- : { type: "text", text: b.toString() },
76
+ : a.toString() === "console"
77
+ ? { type: "text", text: b.toString(), console: true }
78
+ : { type: "text", text: b.toString() },
77
79
  });
78
80
  break;
79
81
  case "done":
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../src/runtime/worker.ts"],"names":[],"m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AAC,CAAC,CAAC,EAAE,CAAC,KAAK,EAC/B,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAC5E,CAAC;YACH,CAAC,CAAC,CAAC;YACH,KAAK,EAAE,CAAC;QACT,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,KAAK,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,4EAA4E;IAC5E,+BAA+B;IAC/B,IAAI,EAAiB,CAAC;IACtB,IAAI,CAAC;QACJ,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,+BAA+B,IAAI,CAAC,IAAI,MAAM,EAAE,aAAa,CAAC,CAAC;IACjF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC,CAAC,KAAK,YAAY,WAAW,CAAC;YAAE,MAAM,KAAK,CAAC;QACjD,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACnE,OAAO;IACR,CAAC;IACD,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;IACxC,EAAE,CAAC,OAAO,EAAE,CAAC;IACb,KAAK,EAAE,CAAC;AACT,CAAC;AAED,IAAI,UAAU,EAAE,CAAC;IAChB,IAAI,CAAC,UAAwB,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC7C,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 * `@earendil-works/pi-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,WAAW,EAAsB,cAAc,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OA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AAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAC5E,CAAC;YACH,CAAC,CAAC,CAAC;YACH,KAAK,EAAE,CAAC;QACT,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,KAAK,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,4EAA4E;IAC5E,+BAA+B;IAC/B,IAAI,EAAiB,CAAC;IACtB,IAAI,CAAC;QACJ,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,+BAA+B,IAAI,CAAC,IAAI,MAAM,EAAE,aAAa,CAAC,CAAC;IACjF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC,CAAC,KAAK,YAAY,WAAW,CAAC;YAAE,MAAM,KAAK,CAAC;QACjD,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACnE,OAAO;IACR,CAAC;IACD,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;IACxC,EAAE,CAAC,OAAO,EAAE,CAAC;IACb,KAAK,EAAE,CAAC;AACT,CAAC;AAED,IAAI,UAAU,EAAE,CAAC;IAChB,IAAI,CAAC,UAAwB,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC7C,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 * `@earendil-works/pi-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: a.toString() === \"console\"\n\t\t\t\t\t\t\t\t? { type: \"text\", text: b.toString(), console: true }\n\t\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"]}
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;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAEpD,MAAM,WAAW,mBAAmB;IACnC;;;OAGG;IACH,MAAM,EAAE,WAAW,CAAC;CACpB;AAED,qGAAqG;AACrG,MAAM,MAAM,kBAAkB,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC;AAEtE,MAAM,WAAW,YAAY;IAC5B;;;;;OAKG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,iGAAiG;IACjG,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6FAA6F;IAC7F,WAAW,CAAC,EAAE,kBAAkB,CAAC;IACjC,0FAA0F;IAC1F,YAAY,CAAC,EAAE,kBAAkB,CAAC;IAClC,gGAAgG;IAChG,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;CACjF;AAED;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAEpH,MAAM,MAAM,kBAAkB,GAAG,IAAI,GAAG,OAAO,GAAG,WAAW,CAAC;AAE9D,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,MAAM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ACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;OAIG;IACH,IAAI,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACxD;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CACzB;AAED,MAAM,WAAW,sBAAsB;IACtC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;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 * 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 `@earendil-works/pi-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/** 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 * 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 `@earendil-works/pi-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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-codemode",
3
- "version": "1.0.3",
3
+ "version": "1.1.0",
4
4
  "description": "Sandboxed JavaScript execution where the only capability is calling injected tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -58,7 +58,7 @@
58
58
  "quickjs-wasi": "3.6.2"
59
59
  },
60
60
  "devDependencies": {
61
- "shx": "0.4.0",
61
+ "shx": "0.3.4",
62
62
  "vitest": "4.1.11"
63
63
  }
64
64
  }