@ny4n/codemode 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +324 -2
- package/dist/cloudflare.d.ts +53 -0
- package/dist/cloudflare.d.ts.map +1 -0
- package/dist/cloudflare.js +64 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/declarations.d.ts +58 -0
- package/dist/declarations.d.ts.map +1 -0
- package/dist/declarations.js +334 -0
- package/dist/declarations.js.map +1 -0
- package/dist/identifier.d.ts +6 -0
- package/dist/identifier.d.ts.map +1 -0
- package/dist/identifier.js +13 -0
- package/dist/identifier.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/portable.d.ts +15 -0
- package/dist/portable.d.ts.map +1 -0
- package/dist/portable.js +12 -0
- package/dist/portable.js.map +1 -0
- package/dist/runtime/execution.d.ts +54 -0
- package/dist/runtime/execution.d.ts.map +1 -0
- package/dist/runtime/execution.js +371 -0
- package/dist/runtime/execution.js.map +1 -0
- package/dist/runtime/host.d.ts +13 -0
- package/dist/runtime/host.d.ts.map +1 -0
- package/dist/runtime/host.js +72 -0
- package/dist/runtime/host.js.map +1 -0
- package/dist/runtime/inline.d.ts +63 -0
- package/dist/runtime/inline.d.ts.map +1 -0
- package/dist/runtime/inline.js +79 -0
- package/dist/runtime/inline.js.map +1 -0
- package/dist/runtime/prelude-source.d.ts +43 -0
- package/dist/runtime/prelude-source.d.ts.map +1 -0
- package/dist/runtime/prelude-source.js +510 -0
- package/dist/runtime/prelude-source.js.map +1 -0
- package/dist/runtime/protocol.d.ts +75 -0
- package/dist/runtime/protocol.d.ts.map +1 -0
- package/dist/runtime/protocol.js +10 -0
- package/dist/runtime/protocol.js.map +1 -0
- package/dist/runtime/remote.d.ts +102 -0
- package/dist/runtime/remote.d.ts.map +1 -0
- package/dist/runtime/remote.js +170 -0
- package/dist/runtime/remote.js.map +1 -0
- package/dist/runtime/vm.d.ts +22 -0
- package/dist/runtime/vm.d.ts.map +1 -0
- package/dist/runtime/vm.js +171 -0
- package/dist/runtime/vm.js.map +1 -0
- package/dist/runtime/worker.d.ts +2 -0
- package/dist/runtime/worker.d.ts.map +1 -0
- package/dist/runtime/worker.js +38 -0
- package/dist/runtime/worker.js.map +1 -0
- package/dist/source.d.ts +35 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +92 -0
- package/dist/source.js.map +1 -0
- package/dist/types.d.ts +148 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/wasm.d.ts +12 -0
- package/dist/wasm.d.ts.map +1 -0
- package/dist/wasm.js +24 -0
- package/dist/wasm.js.map +1 -0
- package/package.json +75 -5
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { CodemodeSandboxBase, errorMessage } from "./execution.js";
|
|
2
|
+
import { startVm } from "./vm.js";
|
|
3
|
+
export const DEFAULT_INTERRUPT_BUDGET = 100_000;
|
|
4
|
+
/** Allows recursion about 1,000 calls deep and trips well before a 1 MB host stack overflows. */
|
|
5
|
+
export const INLINE_MAX_STACK_SIZE = 256 * 1024;
|
|
6
|
+
export function inlineLauncher(wasm, interruptBudget = DEFAULT_INTERRUPT_BUDGET) {
|
|
7
|
+
return async (data, events) => {
|
|
8
|
+
let module;
|
|
9
|
+
try {
|
|
10
|
+
module = await wasm;
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
throw new Error(`Failed to load QuickJS: ${errorMessage(error)}`);
|
|
14
|
+
}
|
|
15
|
+
let stopped = false;
|
|
16
|
+
let settled = false;
|
|
17
|
+
let polls = 0;
|
|
18
|
+
let exhausted = false;
|
|
19
|
+
const session = await startVm({
|
|
20
|
+
data,
|
|
21
|
+
wasm: module,
|
|
22
|
+
maxStackSize: INLINE_MAX_STACK_SIZE,
|
|
23
|
+
shouldInterrupt: () => {
|
|
24
|
+
if (stopped || settled || exhausted)
|
|
25
|
+
return true;
|
|
26
|
+
if (++polls <= interruptBudget)
|
|
27
|
+
return false;
|
|
28
|
+
exhausted = true;
|
|
29
|
+
return true;
|
|
30
|
+
},
|
|
31
|
+
post: (message) => {
|
|
32
|
+
const terminal = message.type === "done" || message.type === "crash";
|
|
33
|
+
// Only the first terminal message counts: a crash caused by interrupting a settled VM is noise.
|
|
34
|
+
if (terminal && settled)
|
|
35
|
+
return;
|
|
36
|
+
if (terminal)
|
|
37
|
+
settled = true;
|
|
38
|
+
queueMicrotask(() => {
|
|
39
|
+
if (stopped)
|
|
40
|
+
return;
|
|
41
|
+
// The interrupt surfaces as a crash or a failed done; report what caused it instead.
|
|
42
|
+
if (exhausted && (message.type === "done" || message.type === "crash")) {
|
|
43
|
+
events.failure({
|
|
44
|
+
kind: "timeout",
|
|
45
|
+
message: `Execution exceeded its interrupt budget of ${interruptBudget}`,
|
|
46
|
+
});
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
events.message(message);
|
|
50
|
+
});
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
return {
|
|
54
|
+
post: (message) => {
|
|
55
|
+
if (!stopped)
|
|
56
|
+
session.deliver(message);
|
|
57
|
+
},
|
|
58
|
+
stop: async () => {
|
|
59
|
+
if (stopped)
|
|
60
|
+
return;
|
|
61
|
+
stopped = true;
|
|
62
|
+
session.dispose();
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Runs each execution's QuickJS VM on the calling thread. Works in any runtime with WebAssembly
|
|
69
|
+
* and microtasks; needs no worker threads, files, or Node built-ins. A script that computes
|
|
70
|
+
* blocks the caller's thread until it awaits a tool or uses up its interrupt budget, so prefer
|
|
71
|
+
* `CodemodeSandbox` where worker threads exist, and `RemoteCodemodeSandbox` to keep scripts off a
|
|
72
|
+
* thread that must stay responsive (such as a Durable Object that serves a session).
|
|
73
|
+
*/
|
|
74
|
+
export class InlineCodemodeSandbox extends CodemodeSandboxBase {
|
|
75
|
+
constructor(options) {
|
|
76
|
+
super(options, inlineLauncher(options.wasm, options.interruptBudget));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=inline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inline.js","sourceRoot":"","sources":["../../src/runtime/inline.ts"],"names":[],"mappings":"AAmCA,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC;AACpF,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,MAAM,CAAC,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAEhD,iGAAiG;AACjG,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,GAAG,IAAI,CAAC;AAehD,MAAM,UAAU,cAAc,CAC7B,IAAsD,EACtD,eAAe,GAAW,wBAAwB;IAElD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE;QAC7B,IAAI,MAA0B,CAAC;QAC/B,IAAI,CAAC;YACJ,MAAM,GAAG,MAAM,IAAI,CAAC;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,2BAA2B,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACnE,CAAC;QACD,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,SAAS,GAAG,KAAK,CAAC;QACtB,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC;YAC7B,IAAI;YACJ,IAAI,EAAE,MAAM;YACZ,YAAY,EAAE,qBAAqB;YACnC,eAAe,EAAE,GAAG,EAAE;gBACrB,IAAI,OAAO,IAAI,OAAO,IAAI,SAAS;oBAAE,OAAO,IAAI,CAAC;gBACjD,IAAI,EAAE,KAAK,IAAI,eAAe;oBAAE,OAAO,KAAK,CAAC;gBAC7C,SAAS,GAAG,IAAI,CAAC;gBACjB,OAAO,IAAI,CAAC;YACb,CAAC;YACD,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE;gBACjB,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC;gBACrE,gGAAgG;gBAChG,IAAI,QAAQ,IAAI,OAAO;oBAAE,OAAO;gBAChC,IAAI,QAAQ;oBAAE,OAAO,GAAG,IAAI,CAAC;gBAC7B,cAAc,CAAC,GAAG,EAAE;oBACnB,IAAI,OAAO;wBAAE,OAAO;oBACpB,qFAAqF;oBACrF,IAAI,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC,EAAE,CAAC;wBACxE,MAAM,CAAC,OAAO,CAAC;4BACd,IAAI,EAAE,SAAS;4BACf,OAAO,EAAE,8CAA8C,eAAe,EAAE;yBACxE,CAAC,CAAC;wBACH,OAAO;oBACR,CAAC;oBACD,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;gBACzB,CAAC,CAAC,CAAC;YACJ,CAAC;SACD,CAAC,CAAC;QACH,OAAO;YACN,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE;gBACjB,IAAI,CAAC,OAAO;oBAAE,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACxC,CAAC;YACD,IAAI,EAAE,KAAK,IAAI,EAAE;gBAChB,IAAI,OAAO;oBAAE,OAAO;gBACpB,OAAO,GAAG,IAAI,CAAC;gBACf,OAAO,CAAC,OAAO,EAAE,CAAC;YACnB,CAAC;SACD,CAAC;IACH,CAAC,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,OAAO,qBAAsB,SAAQ,mBAAmB;IAC7D,YAAY,OAAqC;QAChD,KAAK,CAAC,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC;IACvE,CAAC;CACD","sourcesContent":["/**\n * Runs the VM on the calling thread, for runtimes without worker threads (Cloudflare Workers and\n * Durable Objects, browsers) and for the server side of `RemoteCodemodeSandbox`.\n *\n * Problem: QuickJS runs synchronously. While a script computes, the host's event loop does not\n * run, so neither the deadline timer nor an abort signal can fire. On Workers even `Date.now()` is\n * frozen during synchronous execution, so the VM cannot check a clock either. Example: with a\n * worker thread, `while (true) {}` is stopped by the host's 200 ms timer; on the calling thread\n * that timer never gets a chance to run.\n *\n * Solution: an interrupt budget. QuickJS polls its interrupt handler periodically while a script\n * runs; this launcher counts the polls across the whole execution and interrupts the script once\n * the count passes the budget. The execution then fails with `kind: \"timeout\"`. The deadline and\n * abort signal still work whenever the script waits on a tool, since the event loop runs then.\n *\n * The rate of polls depends on the code and the machine. Measured with a tight loop: about 50,000\n * per second of CPU on an Apple M-series laptop and about 10,000 per second on Cloudflare Durable\n * Objects (October 2026). The default of 100,000 allows roughly 2 to 10 seconds of uninterrupted\n * computation; keep it well below the platform's own CPU limit, because hitting that limit resets\n * a Durable Object instead of failing one script.\n *\n * Once the VM reports `done` or `crash`, the result is decided, so the VM is interrupted at the\n * next poll instead of running on until the host stops it. Example: a script that keeps printing in\n * a `for (;;)` loop after its output limit was reached would otherwise run until the budget ran out\n * and be reported as a timeout.\n *\n * Stack: the VM runs on the caller's stack, which is smaller than a worker thread's (about 1 MB\n * on Node's main thread), so QuickJS's stack guard is set to {@link INLINE_MAX_STACK_SIZE}.\n *\n * Reentrancy: VM callbacks run inside QuickJS. Messages from the VM are delivered to the host in\n * a microtask, after the VM has returned, so host code (tool calls, `finish()`, disposal) never\n * runs inside a VM callback and never re-enters the VM.\n */\nimport type { CodemodeSandboxBaseOptions } from \"../types.ts\";\nimport type { CodemodeWasmModule } from \"../wasm.ts\";\nimport { CodemodeSandboxBase, errorMessage, type VmLauncher } from \"./execution.ts\";\nimport { startVm } from \"./vm.ts\";\n\nexport const DEFAULT_INTERRUPT_BUDGET = 100_000;\n\n/** Allows recursion about 1,000 calls deep and trips well before a 1 MB host stack overflows. */\nexport const INLINE_MAX_STACK_SIZE = 256 * 1024;\n\nexport interface InlineCodemodeSandboxOptions extends CodemodeSandboxBaseOptions {\n\t/**\n\t * Compiled `quickjs-wasi/quickjs.wasm`. On Cloudflare, import it with Wrangler's `CompiledWasm`\n\t * rule (`@ny4n/codemode/cloudflare` does this); on Node, `loadQuickJSWasm()`.\n\t */\n\twasm: CodemodeWasmModule | Promise<CodemodeWasmModule>;\n\t/**\n\t * Interrupt polls an execution may use before it fails with `kind: \"timeout\"`. The only limit on\n\t * a script that computes without awaiting a tool. Default: {@link DEFAULT_INTERRUPT_BUDGET}.\n\t */\n\tinterruptBudget?: number;\n}\n\nexport function inlineLauncher(\n\twasm: CodemodeWasmModule | Promise<CodemodeWasmModule>,\n\tinterruptBudget: number = DEFAULT_INTERRUPT_BUDGET,\n): VmLauncher {\n\treturn async (data, events) => {\n\t\tlet module: CodemodeWasmModule;\n\t\ttry {\n\t\t\tmodule = await wasm;\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Failed to load QuickJS: ${errorMessage(error)}`);\n\t\t}\n\t\tlet stopped = false;\n\t\tlet settled = false;\n\t\tlet polls = 0;\n\t\tlet exhausted = false;\n\t\tconst session = await startVm({\n\t\t\tdata,\n\t\t\twasm: module,\n\t\t\tmaxStackSize: INLINE_MAX_STACK_SIZE,\n\t\t\tshouldInterrupt: () => {\n\t\t\t\tif (stopped || settled || exhausted) return true;\n\t\t\t\tif (++polls <= interruptBudget) return false;\n\t\t\t\texhausted = true;\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tpost: (message) => {\n\t\t\t\tconst terminal = message.type === \"done\" || message.type === \"crash\";\n\t\t\t\t// Only the first terminal message counts: a crash caused by interrupting a settled VM is noise.\n\t\t\t\tif (terminal && settled) return;\n\t\t\t\tif (terminal) settled = true;\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\tif (stopped) return;\n\t\t\t\t\t// The interrupt surfaces as a crash or a failed done; report what caused it instead.\n\t\t\t\t\tif (exhausted && (message.type === \"done\" || message.type === \"crash\")) {\n\t\t\t\t\t\tevents.failure({\n\t\t\t\t\t\t\tkind: \"timeout\",\n\t\t\t\t\t\t\tmessage: `Execution exceeded its interrupt budget of ${interruptBudget}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tevents.message(message);\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t\treturn {\n\t\t\tpost: (message) => {\n\t\t\t\tif (!stopped) session.deliver(message);\n\t\t\t},\n\t\t\tstop: async () => {\n\t\t\t\tif (stopped) return;\n\t\t\t\tstopped = true;\n\t\t\t\tsession.dispose();\n\t\t\t},\n\t\t};\n\t};\n}\n\n/**\n * Runs each execution's QuickJS VM on the calling thread. Works in any runtime with WebAssembly\n * and microtasks; needs no worker threads, files, or Node built-ins. A script that computes\n * blocks the caller's thread until it awaits a tool or uses up its interrupt budget, so prefer\n * `CodemodeSandbox` where worker threads exist, and `RemoteCodemodeSandbox` to keep scripts off a\n * thread that must stay responsive (such as a Durable Object that serves a session).\n */\nexport class InlineCodemodeSandbox extends CodemodeSandboxBase {\n\tconstructor(options: InlineCodemodeSandboxOptions) {\n\t\tsuper(options, inlineLauncher(options.wasm, options.interruptBudget));\n\t}\n}\n"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JavaScript evaluated inside the QuickJS VM before the script runs.
|
|
3
|
+
*
|
|
4
|
+
* The VM is its own wasm instance, so nothing here guards a realm boundary.
|
|
5
|
+
* The prelude keeps the host bridge in a closure so the script cannot call it
|
|
6
|
+
* directly, and builds `tools`, `ALL_TOOLS`, the output helpers (`text`, `image`,
|
|
7
|
+
* `exit`, `console`), and globals on top of it. Tool arguments and results cross
|
|
8
|
+
* as JSON strings and are parsed on this side.
|
|
9
|
+
*
|
|
10
|
+
* Output helpers: `text(value)` appends a text item (non-strings are
|
|
11
|
+
* JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an
|
|
12
|
+
* `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script
|
|
13
|
+
* successfully. `console.*` appends text items marked as console output.
|
|
14
|
+
*
|
|
15
|
+
* `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of
|
|
16
|
+
* JSON text passed in as `storeJson`, and the keys the script wrote are reported
|
|
17
|
+
* with a successful "done".
|
|
18
|
+
*
|
|
19
|
+
* Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.
|
|
20
|
+
* `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the
|
|
21
|
+
* tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.
|
|
22
|
+
* `stalled()` reports a script that has not finished while no host call is pending: with no timers
|
|
23
|
+
* or I/O in the VM, nothing can ever resume it.
|
|
24
|
+
* `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
|
|
25
|
+
* `bridge(kind, a, b, c)` with kind "call" or "global" (id, name, argsJson),
|
|
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.
|
|
31
|
+
*/
|
|
32
|
+
export declare const MAX_STORE_VALUE_CHARS: number;
|
|
33
|
+
export declare const MAX_STORE_TOTAL_CHARS: number;
|
|
34
|
+
/**
|
|
35
|
+
* Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and
|
|
36
|
+
* base64 image data, and items. The host keeps all output until the script ends, so without a
|
|
37
|
+
* limit a script that prints in a loop grows the host's memory until it crashes. The item limit
|
|
38
|
+
* covers loops that print empty strings.
|
|
39
|
+
*/
|
|
40
|
+
export declare const MAX_OUTPUT_CHARS: number;
|
|
41
|
+
export declare const MAX_OUTPUT_ITEMS = 100000;
|
|
42
|
+
export declare const PRELUDE_SOURCE: string;
|
|
43
|
+
//# sourceMappingURL=prelude-source.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JavaScript evaluated inside the QuickJS VM before the script runs.
|
|
3
|
+
*
|
|
4
|
+
* The VM is its own wasm instance, so nothing here guards a realm boundary.
|
|
5
|
+
* The prelude keeps the host bridge in a closure so the script cannot call it
|
|
6
|
+
* directly, and builds `tools`, `ALL_TOOLS`, the output helpers (`text`, `image`,
|
|
7
|
+
* `exit`, `console`), and globals on top of it. Tool arguments and results cross
|
|
8
|
+
* as JSON strings and are parsed on this side.
|
|
9
|
+
*
|
|
10
|
+
* Output helpers: `text(value)` appends a text item (non-strings are
|
|
11
|
+
* JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an
|
|
12
|
+
* `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script
|
|
13
|
+
* successfully. `console.*` appends text items marked as console output.
|
|
14
|
+
*
|
|
15
|
+
* `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of
|
|
16
|
+
* JSON text passed in as `storeJson`, and the keys the script wrote are reported
|
|
17
|
+
* with a successful "done".
|
|
18
|
+
*
|
|
19
|
+
* Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.
|
|
20
|
+
* `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the
|
|
21
|
+
* tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.
|
|
22
|
+
* `stalled()` reports a script that has not finished while no host call is pending: with no timers
|
|
23
|
+
* or I/O in the VM, nothing can ever resume it.
|
|
24
|
+
* `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
|
|
25
|
+
* `bridge(kind, a, b, c)` with kind "call" or "global" (id, name, argsJson),
|
|
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.
|
|
31
|
+
*/
|
|
32
|
+
export const MAX_STORE_VALUE_CHARS = 256 * 1024;
|
|
33
|
+
export const MAX_STORE_TOTAL_CHARS = 1024 * 1024;
|
|
34
|
+
/**
|
|
35
|
+
* Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and
|
|
36
|
+
* base64 image data, and items. The host keeps all output until the script ends, so without a
|
|
37
|
+
* limit a script that prints in a loop grows the host's memory until it crashes. The item limit
|
|
38
|
+
* covers loops that print empty strings.
|
|
39
|
+
*/
|
|
40
|
+
export const MAX_OUTPUT_CHARS = 16 * 1024 * 1024;
|
|
41
|
+
export const MAX_OUTPUT_ITEMS = 100_000;
|
|
42
|
+
const IMAGE_HELPER_EXPECTS = "image expects a non-empty image URL string, an object with image_url, or a raw MCP image block";
|
|
43
|
+
export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJson) {
|
|
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
|
+
})();
|
|
135
|
+
const stringify = JSON.stringify;
|
|
136
|
+
const parse = JSON.parse;
|
|
137
|
+
const promiseThen = Promise.prototype.then;
|
|
138
|
+
const ErrorCtor = Error;
|
|
139
|
+
const TypeErrorCtor = TypeError;
|
|
140
|
+
const RangeErrorCtor = RangeError;
|
|
141
|
+
const pending = new Map();
|
|
142
|
+
let nextId = 1;
|
|
143
|
+
let finished = false;
|
|
144
|
+
// Thrown by exit() to unwind the script after it already reported success.
|
|
145
|
+
const EXIT = Object.freeze({});
|
|
146
|
+
|
|
147
|
+
function done(ok, payload, writes) {
|
|
148
|
+
if (finished) return;
|
|
149
|
+
finished = true;
|
|
150
|
+
bridge("done", ok, payload, writes);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function serialize(value) {
|
|
154
|
+
return value === undefined ? undefined : stringify(value);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
|
|
158
|
+
// text reads the same as a Node error, and drop this prelude's frames.
|
|
159
|
+
function errorText(error) {
|
|
160
|
+
const head = error.message ? error.name + ": " + error.message : String(error.name);
|
|
161
|
+
const frames =
|
|
162
|
+
typeof error.stack === "string"
|
|
163
|
+
? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
|
|
164
|
+
: [];
|
|
165
|
+
return [head, ...frames].join("\\n");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function format(value) {
|
|
169
|
+
if (typeof value === "string") return value;
|
|
170
|
+
if (value instanceof ErrorCtor) return errorText(value);
|
|
171
|
+
try {
|
|
172
|
+
const json = stringify(value);
|
|
173
|
+
return json === undefined ? String(value) : json;
|
|
174
|
+
} catch {
|
|
175
|
+
return String(value);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
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.
|
|
181
|
+
function describeError(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" });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function caller(kind, name, spread) {
|
|
193
|
+
return (...args) =>
|
|
194
|
+
new Promise((resolve, reject) => {
|
|
195
|
+
let json;
|
|
196
|
+
try {
|
|
197
|
+
json = serialize(spread ? args : args[0]);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
reject(error);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const id = nextId++;
|
|
203
|
+
pending.set(id, { resolve, reject });
|
|
204
|
+
bridge(kind, id, name, json);
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const tools = Object.create(null);
|
|
209
|
+
const allTools = [];
|
|
210
|
+
for (const { name, jsName, description } of parse(toolsJson)) {
|
|
211
|
+
const fn = caller("call", name);
|
|
212
|
+
// The first tool wins when two names normalize to the same identifier.
|
|
213
|
+
if (!(jsName in tools)) {
|
|
214
|
+
tools[jsName] = fn;
|
|
215
|
+
allTools.push(Object.freeze({ name: jsName, description }));
|
|
216
|
+
}
|
|
217
|
+
if (!(name in tools)) tools[name] = fn;
|
|
218
|
+
}
|
|
219
|
+
Object.freeze(tools);
|
|
220
|
+
Object.freeze(allTools);
|
|
221
|
+
|
|
222
|
+
// Reading a member that does not exist throws an error that names the close matches, instead of
|
|
223
|
+
// a later "not a function". \`in\` checks still work.
|
|
224
|
+
const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
225
|
+
function guard(target, label, names, hint) {
|
|
226
|
+
return new Proxy(target, {
|
|
227
|
+
get(object, property, receiver) {
|
|
228
|
+
if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
|
|
229
|
+
return Reflect.get(object, property, receiver);
|
|
230
|
+
}
|
|
231
|
+
const wanted = comparable(property);
|
|
232
|
+
const exact = names.filter((name) => comparable(name) === wanted);
|
|
233
|
+
const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
|
|
234
|
+
let message = label + "." + property + " does not exist.";
|
|
235
|
+
if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
|
|
236
|
+
else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
|
|
237
|
+
if (hint) message += " " + hint;
|
|
238
|
+
message += ' Check for a member with "' + property + '" in ' + label + ".";
|
|
239
|
+
throw new TypeErrorCtor(message);
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
const toolsProxy = guard(
|
|
244
|
+
tools,
|
|
245
|
+
"tools",
|
|
246
|
+
allTools.map((tool) => tool.name),
|
|
247
|
+
"ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
|
|
248
|
+
);
|
|
249
|
+
|
|
250
|
+
const namespaces = new Map();
|
|
251
|
+
for (const { name, spread } of parse(globalsJson)) {
|
|
252
|
+
const fn = caller("global", name, spread);
|
|
253
|
+
const dot = name.indexOf(".");
|
|
254
|
+
if (dot === -1) {
|
|
255
|
+
Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
const namespace = name.slice(0, dot);
|
|
259
|
+
if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
|
|
260
|
+
namespaces.get(namespace)[name.slice(dot + 1)] = fn;
|
|
261
|
+
}
|
|
262
|
+
for (const [namespace, members] of namespaces) {
|
|
263
|
+
Object.freeze(members);
|
|
264
|
+
const value = guard(members, namespace, Object.keys(members));
|
|
265
|
+
Object.defineProperty(globalThis, namespace, { value, enumerable: true });
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// key -> JSON text. Sizes count key and JSON characters.
|
|
269
|
+
const stored = new Map(Object.entries(parse(storeJson)));
|
|
270
|
+
const writes = new Map();
|
|
271
|
+
let storedChars = 0;
|
|
272
|
+
for (const [key, json] of stored) storedChars += key.length + json.length;
|
|
273
|
+
|
|
274
|
+
const STORE_HINT =
|
|
275
|
+
"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.";
|
|
276
|
+
|
|
277
|
+
function checkKey(name, key) {
|
|
278
|
+
if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function store(key, value) {
|
|
282
|
+
checkKey("store", key);
|
|
283
|
+
const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
|
|
284
|
+
if (value === undefined) {
|
|
285
|
+
stored.delete(key);
|
|
286
|
+
storedChars -= previous;
|
|
287
|
+
writes.set(key, undefined);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
let json;
|
|
291
|
+
try {
|
|
292
|
+
json = stringify(value);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
|
|
295
|
+
}
|
|
296
|
+
if (json === undefined) {
|
|
297
|
+
throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
|
|
298
|
+
}
|
|
299
|
+
if (json.length > ${MAX_STORE_VALUE_CHARS}) {
|
|
300
|
+
throw new RangeError(
|
|
301
|
+
"store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. " +
|
|
302
|
+
STORE_HINT,
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
const next = storedChars - previous + key.length + json.length;
|
|
306
|
+
if (next > ${MAX_STORE_TOTAL_CHARS}) {
|
|
307
|
+
throw new RangeError(
|
|
308
|
+
"store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). " +
|
|
309
|
+
STORE_HINT,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
stored.set(key, json);
|
|
313
|
+
storedChars = next;
|
|
314
|
+
writes.set(key, json);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function load(key) {
|
|
318
|
+
checkKey("load", key);
|
|
319
|
+
const json = stored.get(key);
|
|
320
|
+
return json === undefined ? undefined : parse(json);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function serializeWrites() {
|
|
324
|
+
const entries = [];
|
|
325
|
+
for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
|
|
326
|
+
return stringify(entries);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
|
|
330
|
+
Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
|
|
331
|
+
|
|
332
|
+
let outputChars = 0;
|
|
333
|
+
let outputItems = 0;
|
|
334
|
+
|
|
335
|
+
// Past the output limits the script fails: done() reports the error, so catching it does not
|
|
336
|
+
// resume output, and the host ends the script.
|
|
337
|
+
function output(kind, data, mimeType) {
|
|
338
|
+
if (finished) return;
|
|
339
|
+
outputChars += data.length;
|
|
340
|
+
outputItems++;
|
|
341
|
+
if (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {
|
|
342
|
+
const error = new RangeErrorCtor(
|
|
343
|
+
"script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. " +
|
|
344
|
+
"Print a summary instead, or write large data to a file with a tool.",
|
|
345
|
+
);
|
|
346
|
+
done(false, describeError(error));
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
bridge("output", kind, data, mimeType);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Primitives become their string form, everything else JSON.
|
|
353
|
+
function outputText(value) {
|
|
354
|
+
if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
|
|
355
|
+
return String(value);
|
|
356
|
+
}
|
|
357
|
+
const json = stringify(value);
|
|
358
|
+
return json === undefined ? String(value) : json;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function text(value) {
|
|
362
|
+
let rendered;
|
|
363
|
+
try {
|
|
364
|
+
rendered = outputText(value);
|
|
365
|
+
} catch (error) {
|
|
366
|
+
throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
|
|
367
|
+
}
|
|
368
|
+
output("text", rendered);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function imageUrl(value) {
|
|
372
|
+
if (typeof value === "string") return value;
|
|
373
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
374
|
+
throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
375
|
+
}
|
|
376
|
+
if (value.image_url !== undefined) {
|
|
377
|
+
if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
378
|
+
return value.image_url;
|
|
379
|
+
}
|
|
380
|
+
if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
381
|
+
if (value.type !== "image") {
|
|
382
|
+
throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
|
|
383
|
+
}
|
|
384
|
+
if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
|
|
385
|
+
if (value.data.toLowerCase().startsWith("data:")) return value.data;
|
|
386
|
+
return "data:;base64," + value.data;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
|
|
390
|
+
// JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
|
|
391
|
+
const IMAGE_SIGNATURES = [
|
|
392
|
+
["image/png", /^iVBORw0KGg/],
|
|
393
|
+
["image/jpeg", /^[/]9j[/](?!9)/],
|
|
394
|
+
["image/gif", /^R0lGOD[dl]h/],
|
|
395
|
+
["image/webp", /^UklG.{8}RUJQ/],
|
|
396
|
+
];
|
|
397
|
+
|
|
398
|
+
function image(value) {
|
|
399
|
+
const url = imageUrl(value);
|
|
400
|
+
if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
401
|
+
const colon = url.indexOf(":");
|
|
402
|
+
const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
|
|
403
|
+
if (scheme === "http" || scheme === "https") {
|
|
404
|
+
throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
|
|
405
|
+
}
|
|
406
|
+
const comma = url.indexOf(",");
|
|
407
|
+
const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
|
|
408
|
+
if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
|
|
409
|
+
throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
|
|
410
|
+
}
|
|
411
|
+
// Providers reject the whole request on a bad image, and a persisted image block would be
|
|
412
|
+
// resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
|
|
413
|
+
// is ignored in favor of the detected one, as providers also reject mismatches.
|
|
414
|
+
const data = url.slice(comma + 1).replace(/\\s+/g, "");
|
|
415
|
+
if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
|
|
416
|
+
throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
|
|
417
|
+
}
|
|
418
|
+
const head = data.slice(0, 16);
|
|
419
|
+
const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
|
|
420
|
+
if (!signature) {
|
|
421
|
+
throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
|
|
422
|
+
}
|
|
423
|
+
output("image", data, signature[0]);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function exit() {
|
|
427
|
+
let writesJson;
|
|
428
|
+
try {
|
|
429
|
+
writesJson = serializeWrites();
|
|
430
|
+
} catch (error) {
|
|
431
|
+
done(false, describeError(error));
|
|
432
|
+
throw EXIT;
|
|
433
|
+
}
|
|
434
|
+
done(true, undefined, writesJson);
|
|
435
|
+
throw EXIT;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const console = {};
|
|
439
|
+
for (const level of ["log", "info", "warn", "error", "debug"]) {
|
|
440
|
+
console[level] = (...args) => {
|
|
441
|
+
output("console", args.map(format).join(" "));
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
Object.freeze(console);
|
|
445
|
+
|
|
446
|
+
Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
|
|
447
|
+
Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
|
|
448
|
+
Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
|
|
449
|
+
Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
|
|
450
|
+
Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
|
|
451
|
+
Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
|
|
452
|
+
|
|
453
|
+
return {
|
|
454
|
+
settle(id, ok, payload) {
|
|
455
|
+
const entry = pending.get(id);
|
|
456
|
+
if (!entry) return;
|
|
457
|
+
pending.delete(id);
|
|
458
|
+
if (!ok) {
|
|
459
|
+
entry.reject(new ErrorCtor(payload));
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
let value;
|
|
463
|
+
try {
|
|
464
|
+
value = payload === undefined ? undefined : parse(payload);
|
|
465
|
+
} catch (error) {
|
|
466
|
+
entry.reject(error);
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
entry.resolve(value);
|
|
470
|
+
},
|
|
471
|
+
run(fn) {
|
|
472
|
+
let promise;
|
|
473
|
+
try {
|
|
474
|
+
promise = fn(toolsProxy, console);
|
|
475
|
+
} catch (error) {
|
|
476
|
+
done(false, describeError(error));
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
promiseThen.call(
|
|
480
|
+
promise,
|
|
481
|
+
(value) => {
|
|
482
|
+
let json;
|
|
483
|
+
try {
|
|
484
|
+
json = serialize(value);
|
|
485
|
+
} catch (error) {
|
|
486
|
+
done(false, describeError(error));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
done(true, json, serializeWrites());
|
|
490
|
+
},
|
|
491
|
+
(error) => {
|
|
492
|
+
done(false, describeError(error));
|
|
493
|
+
},
|
|
494
|
+
);
|
|
495
|
+
},
|
|
496
|
+
stalled() {
|
|
497
|
+
if (finished || pending.size > 0) return false;
|
|
498
|
+
done(
|
|
499
|
+
false,
|
|
500
|
+
stringify({
|
|
501
|
+
name: "Error",
|
|
502
|
+
message:
|
|
503
|
+
"The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
|
|
504
|
+
}),
|
|
505
|
+
);
|
|
506
|
+
return true;
|
|
507
|
+
},
|
|
508
|
+
};
|
|
509
|
+
})`;
|
|
510
|
+
//# sourceMappingURL=prelude-source.js.map
|