@draht/codemode 2026.10.20 → 2026.10.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/cloudflare.d.ts +53 -0
  2. package/dist/cloudflare.d.ts.map +1 -0
  3. package/dist/cloudflare.js +64 -0
  4. package/dist/cloudflare.js.map +1 -0
  5. package/dist/declarations.d.ts +7 -17
  6. package/dist/declarations.d.ts.map +1 -1
  7. package/dist/declarations.js +115 -125
  8. package/dist/declarations.js.map +1 -1
  9. package/dist/index.d.ts +6 -3
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +5 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/portable.d.ts +15 -0
  14. package/dist/portable.d.ts.map +1 -0
  15. package/dist/portable.js +12 -0
  16. package/dist/portable.js.map +1 -0
  17. package/dist/runtime/execution.d.ts +68 -0
  18. package/dist/runtime/execution.d.ts.map +1 -0
  19. package/dist/runtime/execution.js +513 -0
  20. package/dist/runtime/execution.js.map +1 -0
  21. package/dist/runtime/host.d.ts +8 -31
  22. package/dist/runtime/host.d.ts.map +1 -1
  23. package/dist/runtime/host.js +52 -296
  24. package/dist/runtime/host.js.map +1 -1
  25. package/dist/runtime/inline.d.ts +63 -0
  26. package/dist/runtime/inline.d.ts.map +1 -0
  27. package/dist/runtime/inline.js +80 -0
  28. package/dist/runtime/inline.js.map +1 -0
  29. package/dist/runtime/prelude-source.d.ts +18 -4
  30. package/dist/runtime/prelude-source.d.ts.map +1 -1
  31. package/dist/runtime/prelude-source.js +202 -21
  32. package/dist/runtime/prelude-source.js.map +1 -1
  33. package/dist/runtime/protocol.d.ts +49 -6
  34. package/dist/runtime/protocol.d.ts.map +1 -1
  35. package/dist/runtime/protocol.js +6 -1
  36. package/dist/runtime/protocol.js.map +1 -1
  37. package/dist/runtime/remote.d.ts +102 -0
  38. package/dist/runtime/remote.d.ts.map +1 -0
  39. package/dist/runtime/remote.js +175 -0
  40. package/dist/runtime/remote.js.map +1 -0
  41. package/dist/runtime/vm.d.ts +24 -0
  42. package/dist/runtime/vm.d.ts.map +1 -0
  43. package/dist/runtime/vm.js +297 -0
  44. package/dist/runtime/vm.js.map +1 -0
  45. package/dist/runtime/worker.js +11 -110
  46. package/dist/runtime/worker.js.map +1 -1
  47. package/dist/source.d.ts +2 -1
  48. package/dist/source.d.ts.map +1 -1
  49. package/dist/source.js +8 -2
  50. package/dist/source.js.map +1 -1
  51. package/dist/types.d.ts +129 -15
  52. package/dist/types.d.ts.map +1 -1
  53. package/dist/types.js.map +1 -1
  54. package/package.json +16 -4
@@ -9,23 +9,37 @@
9
9
  *
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
- * `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script
13
- * successfully. `console.*` appends text items like `text()`.
12
+ * `{ image_url }` object, or an image block `{ type: "image", data, mimeType }`, and `exit()` ends the script
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
17
17
  * with a successful "done".
18
18
  *
19
- * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.
19
+ * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson, preLockdownSource) => { settle, run, stalled }`.
20
+ * `settle(id, ok, payload, propertiesJson)` settles call `id`; a rejection's `Error` gets the own properties of the
21
+ * `propertiesJson` object, except `name`, `message`, and `stack`.
20
22
  * `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the
21
23
  * tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.
22
24
  * `stalled()` reports a script that has not finished while no host call is pending: with no timers
23
25
  * or I/O in the VM, nothing can ever resume it.
24
26
  * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
25
27
  * `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).
28
+ * "output" ("text" or "console", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
29
+ *
30
+ * After running the trusted host hook, the prelude freezes the built-ins and makes the built-in globals read-only.
31
+ * The prelude shares them with the script, so a script that patched one (for example
32
+ * `Array.prototype.toJSON`) could otherwise corrupt what the prelude reports to the host.
27
33
  */
28
34
  export declare const MAX_STORE_VALUE_CHARS: number;
29
35
  export declare const MAX_STORE_TOTAL_CHARS: number;
36
+ /**
37
+ * Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and
38
+ * base64 image data, and items. The host keeps all output until the script ends, so without a
39
+ * limit a script that prints in a loop grows the host's memory until it crashes. The item limit
40
+ * covers loops that print empty strings.
41
+ */
42
+ export declare const MAX_OUTPUT_CHARS: number;
43
+ export declare const MAX_OUTPUT_ITEMS = 100000;
30
44
  export declare const PRELUDE_SOURCE: string;
31
45
  //# sourceMappingURL=prelude-source.d.ts.map
@@ -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;AAKjD,eAAO,MAAM,cAAc,EAAE,MAsT1B,CAAC"}
1
+ {"version":3,"file":"prelude-source.d.ts","sourceRoot":"","sources":["../../src/runtime/prelude-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;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,MA6d1B,CAAC"}
@@ -9,32 +9,140 @@
9
9
  *
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
- * `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script
13
- * successfully. `console.*` appends text items like `text()`.
12
+ * `{ image_url }` object, or an image block `{ type: "image", data, mimeType }`, and `exit()` ends the script
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
17
17
  * with a successful "done".
18
18
  *
19
- * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.
19
+ * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson, preLockdownSource) => { settle, run, stalled }`.
20
+ * `settle(id, ok, payload, propertiesJson)` settles call `id`; a rejection's `Error` gets the own properties of the
21
+ * `propertiesJson` object, except `name`, `message`, and `stack`.
20
22
  * `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the
21
23
  * tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.
22
24
  * `stalled()` reports a script that has not finished while no host call is pending: with no timers
23
25
  * or I/O in the VM, nothing can ever resume it.
24
26
  * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
25
27
  * `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).
28
+ * "output" ("text" or "console", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
29
+ *
30
+ * After running the trusted host hook, the prelude freezes the built-ins and makes the built-in globals read-only.
31
+ * The prelude shares them with the script, so a script that patched one (for example
32
+ * `Array.prototype.toJSON`) could otherwise corrupt what the prelude reports to the host.
27
33
  */
28
34
  export const MAX_STORE_VALUE_CHARS = 256 * 1024;
29
35
  export const MAX_STORE_TOTAL_CHARS = 1024 * 1024;
30
- const IMAGE_HELPER_EXPECTS = "image expects a non-empty image URL string, an object with image_url, or a raw MCP image block";
31
- export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJson) {
36
+ /**
37
+ * Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and
38
+ * base64 image data, and items. The host keeps all output until the script ends, so without a
39
+ * limit a script that prints in a loop grows the host's memory until it crashes. The item limit
40
+ * covers loops that print empty strings.
41
+ */
42
+ export const MAX_OUTPUT_CHARS = 16 * 1024 * 1024;
43
+ export const MAX_OUTPUT_ITEMS = 100_000;
44
+ const IMAGE_HELPER_EXPECTS = 'image expects a non-empty image URL string, an object with image_url, or an image block { type: "image", data, mimeType }';
45
+ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJson, preLockdownSource) {
32
46
  "use strict";
47
+
48
+ // Only the host supplies this source. A separate function keeps its bindings private.
49
+ if (preLockdownSource) Function(preLockdownSource)();
50
+
51
+ // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
52
+ // reachable from instances (iterator and generator prototypes, %TypedArray%).
53
+ //
54
+ // Freezing alone breaks ordinary code through the "override mistake": a data property that is
55
+ // read-only on a prototype cannot be assigned on an instance either, so
56
+ // this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
57
+ // become accessors whose setter defines an own property on the instance instead.
58
+ (function lockdown() {
59
+ const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
60
+ const seen = new Set([globalThis]);
61
+ const queue = [];
62
+ const add = (value) => {
63
+ if ((typeof value === "object" && value !== null) || typeof value === "function") {
64
+ if (!seen.has(value)) {
65
+ seen.add(value);
66
+ queue.push(value);
67
+ }
68
+ }
69
+ };
70
+
71
+ // Accessors from an object literal have no own prototype object, unlike function expressions,
72
+ // whose prototype.constructor would be converted again without end.
73
+ function allowOverride(object, key, value, enumerable) {
74
+ const { get, set } = Object.getOwnPropertyDescriptor(
75
+ {
76
+ get accessor() {
77
+ return value;
78
+ },
79
+ set accessor(next) {
80
+ if (this === object) {
81
+ throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
82
+ }
83
+ if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
84
+ Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
85
+ },
86
+ },
87
+ "accessor",
88
+ );
89
+ Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
90
+ add(get);
91
+ add(set);
92
+ }
93
+
94
+ for (const key of Reflect.ownKeys(globalThis)) {
95
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
96
+ add(descriptor.value);
97
+ add(descriptor.get);
98
+ add(descriptor.set);
99
+ if ("value" in descriptor && descriptor.configurable) {
100
+ Object.defineProperty(globalThis, key, { value: descriptor.value, writable: false, configurable: false });
101
+ }
102
+ }
103
+ add(Object.getPrototypeOf(function* () {}));
104
+ add(Object.getPrototypeOf(async function () {}));
105
+ add(Object.getPrototypeOf(async function* () {}));
106
+ add(Object.getPrototypeOf(Int8Array));
107
+ add(Object.getPrototypeOf([][Symbol.iterator]()));
108
+ add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
109
+ add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
110
+ add(Object.getPrototypeOf(""[Symbol.iterator]()));
111
+ add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
112
+ if (typeof Iterator === "function") {
113
+ if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
114
+ if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
115
+ }
116
+
117
+ while (queue.length > 0) {
118
+ const object = queue.pop();
119
+ add(Object.getPrototypeOf(object));
120
+ const descriptors = Object.getOwnPropertyDescriptors(object);
121
+ for (const key of Reflect.ownKeys(descriptors)) {
122
+ const descriptor = descriptors[key];
123
+ if ("value" in descriptor) {
124
+ add(descriptor.value);
125
+ if (
126
+ descriptor.writable &&
127
+ descriptor.configurable &&
128
+ (object === Object.prototype || OVERRIDABLE.has(key))
129
+ ) {
130
+ allowOverride(object, key, descriptor.value, descriptor.enumerable);
131
+ }
132
+ } else {
133
+ add(descriptor.get);
134
+ add(descriptor.set);
135
+ }
136
+ }
137
+ Object.freeze(object);
138
+ }
139
+ })();
33
140
  const stringify = JSON.stringify;
34
141
  const parse = JSON.parse;
35
142
  const promiseThen = Promise.prototype.then;
36
143
  const ErrorCtor = Error;
37
144
  const TypeErrorCtor = TypeError;
145
+ const RangeErrorCtor = RangeError;
38
146
  const pending = new Map();
39
147
  let nextId = 1;
40
148
  let finished = false;
@@ -73,11 +181,17 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
73
181
  }
74
182
  }
75
183
 
184
+ // The host requires string fields. A script can set an error's name or message to anything, so
185
+ // they are coerced, and a value whose coercion throws gets a placeholder.
76
186
  function describeError(error) {
77
- if (error instanceof ErrorCtor) {
78
- return stringify({ name: error.name, message: error.message, stack: errorText(error) });
187
+ try {
188
+ if (error instanceof ErrorCtor) {
189
+ return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
190
+ }
191
+ return stringify({ message: String(format(error)) });
192
+ } catch {
193
+ return stringify({ message: "The script threw a value that cannot be described" });
79
194
  }
80
- return stringify({ message: format(error) });
81
195
  }
82
196
 
83
197
  function caller(kind, name, spread) {
@@ -110,6 +224,34 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
110
224
  Object.freeze(tools);
111
225
  Object.freeze(allTools);
112
226
 
227
+ // Reading a member that does not exist throws an error that names the close matches, instead of
228
+ // a later "not a function". \`in\` checks still work.
229
+ const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
230
+ function guard(target, label, names, hint) {
231
+ return new Proxy(target, {
232
+ get(object, property, receiver) {
233
+ if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
234
+ return Reflect.get(object, property, receiver);
235
+ }
236
+ const wanted = comparable(property);
237
+ const exact = names.filter((name) => comparable(name) === wanted);
238
+ const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
239
+ let message = label + "." + property + " does not exist.";
240
+ if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
241
+ else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
242
+ if (hint) message += " " + hint;
243
+ message += ' Check for a member with "' + property + '" in ' + label + ".";
244
+ throw new TypeErrorCtor(message);
245
+ },
246
+ });
247
+ }
248
+ const toolsProxy = guard(
249
+ tools,
250
+ "tools",
251
+ allTools.map((tool) => tool.name),
252
+ "ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
253
+ );
254
+
113
255
  const namespaces = new Map();
114
256
  for (const { name, spread } of parse(globalsJson)) {
115
257
  const fn = caller("global", name, spread);
@@ -123,7 +265,9 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
123
265
  namespaces.get(namespace)[name.slice(dot + 1)] = fn;
124
266
  }
125
267
  for (const [namespace, members] of namespaces) {
126
- Object.defineProperty(globalThis, namespace, { value: Object.freeze(members), enumerable: true });
268
+ Object.freeze(members);
269
+ const value = guard(members, namespace, Object.keys(members));
270
+ Object.defineProperty(globalThis, namespace, { value, enumerable: true });
127
271
  }
128
272
 
129
273
  // key -> JSON text. Sizes count key and JSON characters.
@@ -132,6 +276,9 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
132
276
  let storedChars = 0;
133
277
  for (const [key, json] of stored) storedChars += key.length + json.length;
134
278
 
279
+ const STORE_HINT =
280
+ "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.";
281
+
135
282
  function checkKey(name, key) {
136
283
  if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
137
284
  }
@@ -155,11 +302,17 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
155
302
  throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
156
303
  }
157
304
  if (json.length > ${MAX_STORE_VALUE_CHARS}) {
158
- throw new RangeError("store(" + stringify(key) + ") value exceeds ${MAX_STORE_VALUE_CHARS} characters of JSON");
305
+ throw new RangeError(
306
+ "store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. " +
307
+ STORE_HINT,
308
+ );
159
309
  }
160
310
  const next = storedChars - previous + key.length + json.length;
161
311
  if (next > ${MAX_STORE_TOTAL_CHARS}) {
162
- throw new RangeError("store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON");
312
+ throw new RangeError(
313
+ "store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). " +
314
+ STORE_HINT,
315
+ );
163
316
  }
164
317
  stored.set(key, json);
165
318
  storedChars = next;
@@ -181,6 +334,26 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
181
334
  Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
182
335
  Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
183
336
 
337
+ let outputChars = 0;
338
+ let outputItems = 0;
339
+
340
+ // Past the output limits the script fails: done() reports the error, so catching it does not
341
+ // resume output, and the host ends the script.
342
+ function output(kind, data, mimeType) {
343
+ if (finished) return;
344
+ outputChars += data.length;
345
+ outputItems++;
346
+ if (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {
347
+ const error = new RangeErrorCtor(
348
+ "script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. " +
349
+ "Print a summary instead, or write large data to a file with a tool.",
350
+ );
351
+ done(false, describeError(error));
352
+ throw error;
353
+ }
354
+ bridge("output", kind, data, mimeType);
355
+ }
356
+
184
357
  // Primitives become their string form, everything else JSON.
185
358
  function outputText(value) {
186
359
  if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
@@ -197,7 +370,7 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
197
370
  } catch (error) {
198
371
  throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
199
372
  }
200
- if (!finished) bridge("output", "text", rendered);
373
+ output("text", rendered);
201
374
  }
202
375
 
203
376
  function imageUrl(value) {
@@ -211,9 +384,9 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
211
384
  }
212
385
  if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
213
386
  if (value.type !== "image") {
214
- throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
387
+ throw new TypeErrorCtor('image only accepts image blocks, got "' + value.type + '"');
215
388
  }
216
- if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
389
+ if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected image block data");
217
390
  if (value.data.toLowerCase().startsWith("data:")) return value.data;
218
391
  return "data:;base64," + value.data;
219
392
  }
@@ -252,7 +425,7 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
252
425
  if (!signature) {
253
426
  throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
254
427
  }
255
- if (!finished) bridge("output", "image", data, signature[0]);
428
+ output("image", data, signature[0]);
256
429
  }
257
430
 
258
431
  function exit() {
@@ -270,12 +443,12 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
270
443
  const console = {};
271
444
  for (const level of ["log", "info", "warn", "error", "debug"]) {
272
445
  console[level] = (...args) => {
273
- if (!finished) bridge("output", "text", args.map(format).join(" "));
446
+ output("console", args.map(format).join(" "));
274
447
  };
275
448
  }
276
449
  Object.freeze(console);
277
450
 
278
- Object.defineProperty(globalThis, "tools", { value: tools, enumerable: true });
451
+ Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
279
452
  Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
280
453
  Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
281
454
  Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
@@ -283,12 +456,20 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
283
456
  Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
284
457
 
285
458
  return {
286
- settle(id, ok, payload) {
459
+ settle(id, ok, payload, propertiesJson) {
287
460
  const entry = pending.get(id);
288
461
  if (!entry) return;
289
462
  pending.delete(id);
290
463
  if (!ok) {
291
- entry.reject(new ErrorCtor(payload));
464
+ const error = new ErrorCtor(payload);
465
+ if (propertiesJson !== undefined) {
466
+ const properties = parse(propertiesJson);
467
+ for (const key of Object.keys(properties)) {
468
+ if (key === "name" || key === "message" || key === "stack") continue;
469
+ Object.defineProperty(error, key, { value: properties[key], writable: true, enumerable: true, configurable: true });
470
+ }
471
+ }
472
+ entry.reject(error);
292
473
  return;
293
474
  }
294
475
  let value;
@@ -303,7 +484,7 @@ export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJ
303
484
  run(fn) {
304
485
  let promise;
305
486
  try {
306
- promise = fn(tools, console);
487
+ promise = fn(toolsProxy, console);
307
488
  } catch (error) {
308
489
  done(false, describeError(error));
309
490
  return;
@@ -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;AAEjD,MAAM,oBAAoB,GACzB,gGAAgG,CAAC;AAElG,MAAM,CAAC,MAAM,cAAc,GAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBA8HhB,qBAAqB;uEAC4B,qBAAqB;;;eAG7E,qBAAqB;qEACiC,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BA4C7D,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\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 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\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.defineProperty(globalThis, namespace, { value: Object.freeze(members), 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\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(\"store(\" + stringify(key) + \") value exceeds ${MAX_STORE_VALUE_CHARS} characters of JSON\");\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(\"store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON\");\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\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\tif (!finished) bridge(\"output\", \"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\tif (!finished) bridge(\"output\", \"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\tif (!finished) bridge(\"output\", \"text\", args.map(format).join(\" \"));\n\t\t};\n\t}\n\tObject.freeze(console);\n\n\tObject.defineProperty(globalThis, \"tools\", { value: tools, 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(tools, 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;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,2HAA2H,CAAC;AAE7H,MAAM,CAAC,MAAM,cAAc,GAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAmQhB,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqH7E,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 image block `{ type: \"image\", data, mimeType }`, 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, preLockdownSource) => { settle, run, stalled }`.\n * `settle(id, ok, payload, propertiesJson)` settles call `id`; a rejection's `Error` gets the own properties of the\n * `propertiesJson` object, except `name`, `message`, and `stack`.\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 * After running the trusted host hook, 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 an image block { type: \"image\", data, mimeType }';\n\nexport const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson, storeJson, preLockdownSource) {\n\t\"use strict\";\n\n\t// Only the host supplies this source. A separate function keeps its bindings private.\n\tif (preLockdownSource) Function(preLockdownSource)();\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, { value: descriptor.value, 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 image blocks, got \"' + value.type + '\"');\n\t\t}\n\t\tif (typeof value.data !== \"string\" || value.data === \"\") throw new TypeErrorCtor(\"image expected image block 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, propertiesJson) {\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\tconst error = new ErrorCtor(payload);\n\t\t\t\tif (propertiesJson !== undefined) {\n\t\t\t\t\tconst properties = parse(propertiesJson);\n\t\t\t\t\tfor (const key of Object.keys(properties)) {\n\t\t\t\t\t\tif (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n\t\t\t\t\t\tObject.defineProperty(error, key, { value: properties[key], writable: true, enumerable: true, configurable: true });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tentry.reject(error);\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,11 +1,17 @@
1
- import type { CodemodeOutputItem } from "../types.ts";
1
+ import type { CodemodeDuring, CodemodeOutputItem } from "../types.ts";
2
2
  import type { CodemodeWasmModule } from "../wasm.ts";
3
3
  /**
4
4
  * Messages between the host (main thread) and the worker. Tool arguments,
5
5
  * results, and values cross as JSON strings: the worker passes them into and
6
6
  * out of the QuickJS VM as strings and never builds structured values itself.
7
7
  */
8
- export interface WorkerData {
8
+ /**
9
+ * Everything a VM needs to run one script, independent of where it runs. Plain data, so it can
10
+ * cross a `postMessage` or a Workers RPC call unchanged.
11
+ */
12
+ export interface VmStartData {
13
+ /** Trusted host source only; never derived from the script or its store. */
14
+ preLockdownSource?: string;
9
15
  code: string;
10
16
  /** `jsName` is the identifier the script uses; `description` is listed in `ALL_TOOLS`. */
11
17
  tools: {
@@ -17,11 +23,22 @@ export interface WorkerData {
17
23
  name: string;
18
24
  spread: boolean;
19
25
  }[];
20
- /** Compiled `quickjs-wasi` module. Structured clone shares the compiled code with the worker. */
21
- wasm: CodemodeWasmModule;
22
26
  memoryLimitBytes: number | undefined;
23
27
  /** Snapshot for `load()`: key to JSON text. */
24
28
  store: Record<string, string>;
29
+ /**
30
+ * Run deterministically (`CodemodeSandboxBase.start()`): UTC, a virtual clock starting at `startedAt` (ms since
31
+ * the epoch) that moves only with delivered results, randomness from `seed`, no `WeakRef`, results applied in
32
+ * `seq` order, and `started`/`idle` messages.
33
+ */
34
+ deterministic?: {
35
+ startedAt: number;
36
+ seed: number;
37
+ };
38
+ }
39
+ export interface WorkerData extends VmStartData {
40
+ /** Compiled `quickjs-wasi` module. Structured clone shares the compiled code with the worker. */
41
+ wasm: CodemodeWasmModule;
25
42
  /**
26
43
  * One Int32 the host sets to non-zero before terminating the worker. The VM's interrupt handler
27
44
  * polls it, because Bun's `worker.terminate()` cannot stop a thread that is spinning in wasm.
@@ -40,29 +57,55 @@ export type WorkerToHostMessage = {
40
57
  type: "output";
41
58
  item: CodemodeOutputItem;
42
59
  }
43
- /** `writes` is a JSON array of `[key, json]` for `store()` and `[key]` for deletions. */
60
+ /**
61
+ * `writes` is a JSON array of `[key, json]` for `store()` and `[key]` for deletions. Deterministic mode: `during`
62
+ * is the result the VM was processing when the script finished (0: its first run) and the calls issued by then.
63
+ */
44
64
  | {
45
65
  type: "done";
46
66
  ok: true;
47
67
  value: string | undefined;
48
68
  writes: string;
69
+ during?: CodemodeDuring;
49
70
  } | {
50
71
  type: "done";
51
72
  ok: false;
52
73
  error: ScriptErrorJson;
74
+ during?: CodemodeDuring;
53
75
  }
54
76
  /** The VM failed outside the script's control, for example a wasm trap. */
55
77
  | {
56
78
  type: "crash";
57
79
  message: string;
80
+ }
81
+ /** Deterministic mode, before the script runs: what the VM is, so a replay can refuse a different one. */
82
+ | {
83
+ type: "started";
84
+ fingerprint: string;
85
+ }
86
+ /**
87
+ * Deterministic mode, after the script waits again: having processed result `seq` (0: the script's first run), it
88
+ * has issued `issued` calls in total.
89
+ */
90
+ | {
91
+ type: "idle";
92
+ seq: number;
93
+ issued: number;
58
94
  };
59
95
  export type HostToWorkerMessage =
60
- /** `payload` is the JSON result when `ok`, otherwise the error message. */
96
+ /**
97
+ * `payload` is the JSON result when `ok`, otherwise the error message. Deterministic mode: `seq` numbers the
98
+ * results from 1 in the order the VM applies them, and the VM's clock reads `now` while it processes this one.
99
+ */
61
100
  {
62
101
  type: "result";
63
102
  id: number;
64
103
  ok: boolean;
65
104
  payload: string | undefined;
105
+ seq?: number;
106
+ now?: number;
107
+ /** Deterministic mode, `ok: false`: a JSON object whose properties the script's `Error` gets. */
108
+ properties?: string;
66
109
  };
67
110
  export declare function isWorkerToHostMessage(value: unknown): value is WorkerToHostMessage;
68
111
  export declare function isHostToWorkerMessage(value: unknown): value is HostToWorkerMessage;
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../src/runtime/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD;;;;GAIG;AAEH,MAAM,WAAW,UAAU;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,0FAA0F;IAC1F,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC/D,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,EAAE,CAAC;IAC7C,iGAAiG;IACjG,IAAI,EAAE,kBAAkB,CAAC;IACzB,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,+CAA+C;IAC/C,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B;;;OAGG;IACH,SAAS,EAAE,iBAAiB,CAAC;CAC7B;AAED,kFAAkF;AAClF,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC;AAErC,MAAM,MAAM,mBAAmB,GAC5B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,GAAG,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,GAC/F;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,kBAAkB,CAAA;CAAE;AAC9C,yFAAyF;GACvF;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACrE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,eAAe,CAAA;CAAE;AACrD,2EAA2E;GACzE;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtC,MAAM,MAAM,mBAAmB;AAC9B,2EAA2E;AAC3E;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAE1E,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,mBAAmB,CAIlF;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,mBAAmB,CAElF"}
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../src/runtime/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD;;;;GAIG;AAEH;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC3B,4EAA4E;IAC5E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,0FAA0F;IAC1F,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC/D,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,EAAE,CAAC;IAC7C,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,+CAA+C;IAC/C,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B;;;;OAIG;IACH,aAAa,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CACpD;AAED,MAAM,WAAW,UAAW,SAAQ,WAAW;IAC9C,iGAAiG;IACjG,IAAI,EAAE,kBAAkB,CAAC;IACzB;;;OAGG;IACH,SAAS,EAAE,iBAAiB,CAAC;CAC7B;AAED,kFAAkF;AAClF,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC;AAErC,MAAM,MAAM,mBAAmB,GAC5B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,GAAG,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,GAC/F;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,kBAAkB,CAAA;CAAE;AAC9C;;;GAGG;GACD;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,cAAc,CAAA;CAAE,GAC9F;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,eAAe,CAAC;IAAC,MAAM,CAAC,EAAE,cAAc,CAAA;CAAE;AAC9E,2EAA2E;GACzE;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE;AACpC,0GAA0G;GACxG;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE;AAC1C;;;GAGG;GACD;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjD,MAAM,MAAM,mBAAmB;AAC9B;;;GAGG;AACH;IACC,IAAI,EAAE,QAAQ,CAAC;IACf,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,OAAO,CAAC;IACZ,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,iGAAiG;IACjG,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,mBAAmB,CAWlF;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,mBAAmB,CAElF"}
@@ -2,7 +2,12 @@ export function isWorkerToHostMessage(value) {
2
2
  if (typeof value !== "object" || value === null)
3
3
  return false;
4
4
  const type = value.type;
5
- return type === "call" || type === "output" || type === "done" || type === "crash";
5
+ return (type === "call" ||
6
+ type === "output" ||
7
+ type === "done" ||
8
+ type === "crash" ||
9
+ type === "started" ||
10
+ type === "idle");
6
11
  }
7
12
  export function isHostToWorkerMessage(value) {
8
13
  return typeof value === "object" && value !== null && value.type === "result";
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/runtime/protocol.ts"],"names":[],"mappings":"AA0CA,MAAM,UAAU,qBAAqB,CAAC,KAAc;IACnD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,IAAI,GAAI,KAA4B,CAAC,IAAI,CAAC;IAChD,OAAO,IAAI,KAAK,MAAM,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI,KAAK,OAAO,CAAC;AACpF,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAAc;IACnD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAA4B,CAAC,IAAI,KAAK,QAAQ,CAAC;AACvG,CAAC","sourcesContent":["import type { CodemodeOutputItem } from \"../types.ts\";\nimport type { CodemodeWasmModule } from \"../wasm.ts\";\n\n/**\n * Messages between the host (main thread) and the worker. Tool arguments,\n * results, and values cross as JSON strings: the worker passes them into and\n * out of the QuickJS VM as strings and never builds structured values itself.\n */\n\nexport interface WorkerData {\n\tcode: string;\n\t/** `jsName` is the identifier the script uses; `description` is listed in `ALL_TOOLS`. */\n\ttools: { name: string; jsName: string; description: string }[];\n\tglobals: { name: string; spread: boolean }[];\n\t/** Compiled `quickjs-wasi` module. Structured clone shares the compiled code with the worker. */\n\twasm: CodemodeWasmModule;\n\tmemoryLimitBytes: number | undefined;\n\t/** Snapshot for `load()`: key to JSON text. */\n\tstore: Record<string, string>;\n\t/**\n\t * One Int32 the host sets to non-zero before terminating the worker. The VM's interrupt handler\n\t * polls it, because Bun's `worker.terminate()` cannot stop a thread that is spinning in wasm.\n\t */\n\tinterrupt: SharedArrayBuffer;\n}\n\n/** JSON-encoded `{ name?, message, stack? }` of an error thrown by the script. */\nexport type ScriptErrorJson = string;\n\nexport type WorkerToHostMessage =\n\t| { type: \"call\"; id: number; target: \"tool\" | \"global\"; name: string; args: string | undefined }\n\t| { type: \"output\"; item: CodemodeOutputItem }\n\t/** `writes` is a JSON array of `[key, json]` for `store()` and `[key]` for deletions. */\n\t| { type: \"done\"; ok: true; value: string | undefined; writes: string }\n\t| { type: \"done\"; ok: false; error: ScriptErrorJson }\n\t/** The VM failed outside the script's control, for example a wasm trap. */\n\t| { type: \"crash\"; message: string };\n\nexport type HostToWorkerMessage =\n\t/** `payload` is the JSON result when `ok`, otherwise the error message. */\n\t{ type: \"result\"; id: number; ok: boolean; payload: string | undefined };\n\nexport function isWorkerToHostMessage(value: unknown): value is WorkerToHostMessage {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst type = (value as { type?: unknown }).type;\n\treturn type === \"call\" || type === \"output\" || type === \"done\" || type === \"crash\";\n}\n\nexport function isHostToWorkerMessage(value: unknown): value is HostToWorkerMessage {\n\treturn typeof value === \"object\" && value !== null && (value as { type?: unknown }).type === \"result\";\n}\n"]}
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/runtime/protocol.ts"],"names":[],"mappings":"AA+EA,MAAM,UAAU,qBAAqB,CAAC,KAAc;IACnD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,IAAI,GAAI,KAA4B,CAAC,IAAI,CAAC;IAChD,OAAO,CACN,IAAI,KAAK,MAAM;QACf,IAAI,KAAK,QAAQ;QACjB,IAAI,KAAK,MAAM;QACf,IAAI,KAAK,OAAO;QAChB,IAAI,KAAK,SAAS;QAClB,IAAI,KAAK,MAAM,CACf,CAAC;AACH,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAAc;IACnD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAA4B,CAAC,IAAI,KAAK,QAAQ,CAAC;AACvG,CAAC","sourcesContent":["import type { CodemodeDuring, CodemodeOutputItem } from \"../types.ts\";\nimport type { CodemodeWasmModule } from \"../wasm.ts\";\n\n/**\n * Messages between the host (main thread) and the worker. Tool arguments,\n * results, and values cross as JSON strings: the worker passes them into and\n * out of the QuickJS VM as strings and never builds structured values itself.\n */\n\n/**\n * Everything a VM needs to run one script, independent of where it runs. Plain data, so it can\n * cross a `postMessage` or a Workers RPC call unchanged.\n */\nexport interface VmStartData {\n\t/** Trusted host source only; never derived from the script or its store. */\n\tpreLockdownSource?: string;\n\tcode: string;\n\t/** `jsName` is the identifier the script uses; `description` is listed in `ALL_TOOLS`. */\n\ttools: { name: string; jsName: string; description: string }[];\n\tglobals: { name: string; spread: boolean }[];\n\tmemoryLimitBytes: number | undefined;\n\t/** Snapshot for `load()`: key to JSON text. */\n\tstore: Record<string, string>;\n\t/**\n\t * Run deterministically (`CodemodeSandboxBase.start()`): UTC, a virtual clock starting at `startedAt` (ms since\n\t * the epoch) that moves only with delivered results, randomness from `seed`, no `WeakRef`, results applied in\n\t * `seq` order, and `started`/`idle` messages.\n\t */\n\tdeterministic?: { startedAt: number; seed: number };\n}\n\nexport interface WorkerData extends VmStartData {\n\t/** Compiled `quickjs-wasi` module. Structured clone shares the compiled code with the worker. */\n\twasm: CodemodeWasmModule;\n\t/**\n\t * One Int32 the host sets to non-zero before terminating the worker. The VM's interrupt handler\n\t * polls it, because Bun's `worker.terminate()` cannot stop a thread that is spinning in wasm.\n\t */\n\tinterrupt: SharedArrayBuffer;\n}\n\n/** JSON-encoded `{ name?, message, stack? }` of an error thrown by the script. */\nexport type ScriptErrorJson = string;\n\nexport type WorkerToHostMessage =\n\t| { type: \"call\"; id: number; target: \"tool\" | \"global\"; name: string; args: string | undefined }\n\t| { type: \"output\"; item: CodemodeOutputItem }\n\t/**\n\t * `writes` is a JSON array of `[key, json]` for `store()` and `[key]` for deletions. Deterministic mode: `during`\n\t * is the result the VM was processing when the script finished (0: its first run) and the calls issued by then.\n\t */\n\t| { type: \"done\"; ok: true; value: string | undefined; writes: string; during?: CodemodeDuring }\n\t| { type: \"done\"; ok: false; error: ScriptErrorJson; during?: CodemodeDuring }\n\t/** The VM failed outside the script's control, for example a wasm trap. */\n\t| { type: \"crash\"; message: string }\n\t/** Deterministic mode, before the script runs: what the VM is, so a replay can refuse a different one. */\n\t| { type: \"started\"; fingerprint: string }\n\t/**\n\t * Deterministic mode, after the script waits again: having processed result `seq` (0: the script's first run), it\n\t * has issued `issued` calls in total.\n\t */\n\t| { type: \"idle\"; seq: number; issued: number };\n\nexport type HostToWorkerMessage =\n\t/**\n\t * `payload` is the JSON result when `ok`, otherwise the error message. Deterministic mode: `seq` numbers the\n\t * results from 1 in the order the VM applies them, and the VM's clock reads `now` while it processes this one.\n\t */\n\t{\n\t\ttype: \"result\";\n\t\tid: number;\n\t\tok: boolean;\n\t\tpayload: string | undefined;\n\t\tseq?: number;\n\t\tnow?: number;\n\t\t/** Deterministic mode, `ok: false`: a JSON object whose properties the script's `Error` gets. */\n\t\tproperties?: string;\n\t};\n\nexport function isWorkerToHostMessage(value: unknown): value is WorkerToHostMessage {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst type = (value as { type?: unknown }).type;\n\treturn (\n\t\ttype === \"call\" ||\n\t\ttype === \"output\" ||\n\t\ttype === \"done\" ||\n\t\ttype === \"crash\" ||\n\t\ttype === \"started\" ||\n\t\ttype === \"idle\"\n\t);\n}\n\nexport function isHostToWorkerMessage(value: unknown): value is HostToWorkerMessage {\n\treturn typeof value === \"object\" && value !== null && (value as { type?: unknown }).type === \"result\";\n}\n"]}