@ny4n/codemode 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +324 -2
  3. package/dist/cloudflare.d.ts +53 -0
  4. package/dist/cloudflare.d.ts.map +1 -0
  5. package/dist/cloudflare.js +64 -0
  6. package/dist/cloudflare.js.map +1 -0
  7. package/dist/declarations.d.ts +58 -0
  8. package/dist/declarations.d.ts.map +1 -0
  9. package/dist/declarations.js +334 -0
  10. package/dist/declarations.js.map +1 -0
  11. package/dist/identifier.d.ts +6 -0
  12. package/dist/identifier.d.ts.map +1 -0
  13. package/dist/identifier.js +13 -0
  14. package/dist/identifier.js.map +1 -0
  15. package/dist/index.d.ts +11 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +10 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/portable.d.ts +15 -0
  20. package/dist/portable.d.ts.map +1 -0
  21. package/dist/portable.js +12 -0
  22. package/dist/portable.js.map +1 -0
  23. package/dist/runtime/execution.d.ts +54 -0
  24. package/dist/runtime/execution.d.ts.map +1 -0
  25. package/dist/runtime/execution.js +371 -0
  26. package/dist/runtime/execution.js.map +1 -0
  27. package/dist/runtime/host.d.ts +13 -0
  28. package/dist/runtime/host.d.ts.map +1 -0
  29. package/dist/runtime/host.js +72 -0
  30. package/dist/runtime/host.js.map +1 -0
  31. package/dist/runtime/inline.d.ts +63 -0
  32. package/dist/runtime/inline.d.ts.map +1 -0
  33. package/dist/runtime/inline.js +79 -0
  34. package/dist/runtime/inline.js.map +1 -0
  35. package/dist/runtime/prelude-source.d.ts +43 -0
  36. package/dist/runtime/prelude-source.d.ts.map +1 -0
  37. package/dist/runtime/prelude-source.js +510 -0
  38. package/dist/runtime/prelude-source.js.map +1 -0
  39. package/dist/runtime/protocol.d.ts +75 -0
  40. package/dist/runtime/protocol.d.ts.map +1 -0
  41. package/dist/runtime/protocol.js +10 -0
  42. package/dist/runtime/protocol.js.map +1 -0
  43. package/dist/runtime/remote.d.ts +102 -0
  44. package/dist/runtime/remote.d.ts.map +1 -0
  45. package/dist/runtime/remote.js +170 -0
  46. package/dist/runtime/remote.js.map +1 -0
  47. package/dist/runtime/vm.d.ts +22 -0
  48. package/dist/runtime/vm.d.ts.map +1 -0
  49. package/dist/runtime/vm.js +171 -0
  50. package/dist/runtime/vm.js.map +1 -0
  51. package/dist/runtime/worker.d.ts +2 -0
  52. package/dist/runtime/worker.d.ts.map +1 -0
  53. package/dist/runtime/worker.js +38 -0
  54. package/dist/runtime/worker.js.map +1 -0
  55. package/dist/source.d.ts +35 -0
  56. package/dist/source.d.ts.map +1 -0
  57. package/dist/source.js +92 -0
  58. package/dist/source.js.map +1 -0
  59. package/dist/types.d.ts +148 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/types.js +2 -0
  62. package/dist/types.js.map +1 -0
  63. package/dist/wasm.d.ts +12 -0
  64. package/dist/wasm.d.ts.map +1 -0
  65. package/dist/wasm.js +24 -0
  66. package/dist/wasm.js.map +1 -0
  67. package/package.json +75 -5
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Host side of an execution, shared by every place a VM can run.
3
+ *
4
+ * The host owns everything the script must not influence: the tool table, call records, output,
5
+ * the deadline, the caller's abort signal, and the decoding of what the VM reports. The VM itself
6
+ * runs somewhere a {@link VmLauncher} decides: a worker thread (`CodemodeSandbox`), the calling
7
+ * thread (`InlineCodemodeSandbox`), or another isolate reached over RPC (`RemoteCodemodeSandbox`).
8
+ * The two sides only exchange the messages in `protocol.ts`, so the launchers differ in transport
9
+ * and termination, not in behavior.
10
+ *
11
+ * Lifecycle of one execution:
12
+ * 1. The constructor arms the deadline and abort listener, then asks the launcher for a channel.
13
+ * 2. Messages from the VM arrive through {@link VmEvents.message}; tool calls run here and their
14
+ * results go back through {@link VmChannel.post}. Replies produced before the launcher has
15
+ * returned its channel are queued and flushed when it arrives.
16
+ * 3. The first terminal event wins: `done`, `crash`, a launcher failure, the deadline, or an abort.
17
+ * `finish()` aborts pending tool calls, stops the channel, and resolves the result once the
18
+ * channel reports it stopped. Later events are ignored.
19
+ *
20
+ * The launcher, not this class, is responsible for actually stopping a running VM: a worker is
21
+ * terminated, an in-thread VM is interrupted and disposed, and a remote VM is told to stop at its
22
+ * next exchange.
23
+ */
24
+ import { toCodemodeIdentifier } from "../identifier.js";
25
+ import { isWorkerToHostMessage, } from "./protocol.js";
26
+ const DEFAULT_TIMEOUT_MS = 300_000;
27
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
28
+ const RESERVED_GLOBALS = new Set([
29
+ "tools",
30
+ "ALL_TOOLS",
31
+ "console",
32
+ "text",
33
+ "image",
34
+ "exit",
35
+ "globalThis",
36
+ "store",
37
+ "load",
38
+ ]);
39
+ export function errorMessage(error) {
40
+ return error instanceof Error ? error.message : String(error);
41
+ }
42
+ function serializeStore(store) {
43
+ const serialized = {};
44
+ for (const [key, value] of Object.entries(store ?? {})) {
45
+ const json = JSON.stringify(value);
46
+ if (json !== undefined)
47
+ serialized[key] = json;
48
+ }
49
+ return serialized;
50
+ }
51
+ /**
52
+ * The prelude that serializes values for the host runs in the same VM as the script, so a script
53
+ * that patches built-ins (for example `Array.prototype.toJSON`) can make it send malformed data.
54
+ * Payloads that do not decode throw this error, and the execution fails as a sandbox error.
55
+ */
56
+ class BridgeError extends Error {
57
+ }
58
+ function parseBridgeJson(json, what) {
59
+ try {
60
+ return JSON.parse(json);
61
+ }
62
+ catch {
63
+ throw new BridgeError(`${what} is not valid JSON`);
64
+ }
65
+ }
66
+ function parseStoreWrites(json) {
67
+ const entries = parseBridgeJson(json, "store writes");
68
+ if (!Array.isArray(entries))
69
+ throw new BridgeError("store writes are not an array");
70
+ const writes = { set: {}, delete: [] };
71
+ for (const entry of entries) {
72
+ if (!Array.isArray(entry) ||
73
+ typeof entry[0] !== "string" ||
74
+ (entry.length === 2 ? typeof entry[1] !== "string" : entry.length !== 1)) {
75
+ throw new BridgeError("store writes contain a malformed entry");
76
+ }
77
+ const [key, value] = entry;
78
+ if (value === undefined)
79
+ writes.delete.push(key);
80
+ else
81
+ writes.set[key] = parseBridgeJson(value, `store value for ${JSON.stringify(key)}`);
82
+ }
83
+ return writes;
84
+ }
85
+ function parseScriptError(json) {
86
+ const parsed = parseBridgeJson(json, "script error");
87
+ if (typeof parsed !== "object" || parsed === null)
88
+ throw new BridgeError("script error is not an object");
89
+ const { name, message, stack } = parsed;
90
+ if (typeof message !== "string" ||
91
+ (name !== undefined && typeof name !== "string") ||
92
+ (stack !== undefined && typeof stack !== "string")) {
93
+ throw new BridgeError("script error is malformed");
94
+ }
95
+ return { kind: "script", name, message, stack };
96
+ }
97
+ /** One script run in its own VM. */
98
+ class Execution {
99
+ promise;
100
+ resolveResult;
101
+ channel;
102
+ /** Replies produced before the launcher returned the channel. */
103
+ unsent = [];
104
+ tools;
105
+ globals;
106
+ signal;
107
+ timer;
108
+ output = [];
109
+ calls = [];
110
+ pending = new Map();
111
+ finished = false;
112
+ constructor(options) {
113
+ this.promise = new Promise((resolve) => {
114
+ this.resolveResult = resolve;
115
+ });
116
+ this.tools = options.tools;
117
+ this.globals = options.globals;
118
+ this.signal = options.signal;
119
+ if (Number.isFinite(options.timeoutMs)) {
120
+ this.timer = setTimeout(() => {
121
+ this.finish({ kind: "timeout", message: `Execution timed out after ${options.timeoutMs} ms` });
122
+ }, options.timeoutMs);
123
+ }
124
+ if (options.signal) {
125
+ if (options.signal.aborted) {
126
+ this.onAbort();
127
+ }
128
+ else {
129
+ options.signal.addEventListener("abort", this.onAbort, { once: true });
130
+ }
131
+ }
132
+ if (this.finished)
133
+ return;
134
+ const data = {
135
+ code: options.code,
136
+ tools: [...options.tools.values()].map((tool) => ({
137
+ name: tool.name,
138
+ jsName: toCodemodeIdentifier(tool.name),
139
+ description: tool.description ?? "",
140
+ })),
141
+ globals: [...options.globals.values()].map((global) => ({
142
+ name: global.name,
143
+ spread: global.spread === true,
144
+ })),
145
+ memoryLimitBytes: options.memoryLimitBytes,
146
+ store: options.store,
147
+ };
148
+ const events = {
149
+ message: (message) => this.receive(message),
150
+ failure: (error) => this.finish(error),
151
+ };
152
+ new Promise((resolve) => resolve(options.launch(data, events))).then((channel) => {
153
+ if (this.finished) {
154
+ void channel.stop().catch(() => undefined);
155
+ return;
156
+ }
157
+ this.channel = channel;
158
+ for (const message of this.unsent.splice(0))
159
+ channel.post(message);
160
+ }, (error) => {
161
+ this.finish({ kind: "sandbox", message: errorMessage(error) });
162
+ });
163
+ }
164
+ abort(message) {
165
+ this.finish({ kind: "aborted", message });
166
+ return this.promise;
167
+ }
168
+ onAbort = () => {
169
+ const reason = this.signal?.reason;
170
+ this.finish({ kind: "aborted", message: reason instanceof Error ? reason.message : "Execution aborted" });
171
+ };
172
+ post(message) {
173
+ if (this.channel)
174
+ this.channel.post(message);
175
+ else
176
+ this.unsent.push(message);
177
+ }
178
+ /** An exception here would escape into the launcher's transport and leave the execution unsettled. */
179
+ receive(message) {
180
+ try {
181
+ this.handleMessage(message);
182
+ }
183
+ catch (error) {
184
+ this.finish({
185
+ kind: "sandbox",
186
+ message: error instanceof BridgeError
187
+ ? `Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.`
188
+ : `Sandbox host failed: ${errorMessage(error)}`,
189
+ });
190
+ }
191
+ }
192
+ handleMessage(message) {
193
+ if (this.finished)
194
+ return;
195
+ if (!isWorkerToHostMessage(message))
196
+ throw new BridgeError("unknown message from the worker");
197
+ switch (message.type) {
198
+ case "output":
199
+ this.output.push(message.item);
200
+ break;
201
+ case "call":
202
+ if (this.pending.has(message.id))
203
+ throw new BridgeError(`duplicate call id ${message.id}`);
204
+ void this.handleCall(message);
205
+ break;
206
+ case "done":
207
+ this.handleDone(message);
208
+ break;
209
+ case "crash":
210
+ this.finish({ kind: "sandbox", message: message.message });
211
+ break;
212
+ }
213
+ }
214
+ handleDone(message) {
215
+ // Decode everything before finish(), which must not throw once it starts.
216
+ if (!message.ok) {
217
+ this.finish(parseScriptError(message.error));
218
+ return;
219
+ }
220
+ const value = message.value === undefined ? undefined : parseBridgeJson(message.value, "return value");
221
+ this.finish(undefined, value, parseStoreWrites(message.writes));
222
+ }
223
+ async handleCall(message) {
224
+ const { id, name } = message;
225
+ const isTool = message.target === "tool";
226
+ const record = isTool ? { name, status: "cancelled", durationMs: 0 } : undefined;
227
+ if (record)
228
+ this.calls.push(record);
229
+ const pending = { record, startedAt: performance.now(), controller: new AbortController() };
230
+ this.pending.set(id, pending);
231
+ let status;
232
+ let reply;
233
+ try {
234
+ const tool = (isTool ? this.tools : this.globals).get(name);
235
+ if (!tool)
236
+ throw new Error(`Unknown ${isTool ? "tool" : "global"} "${name}"`);
237
+ const args = message.args === undefined ? undefined : JSON.parse(message.args);
238
+ const value = await tool.execute(args, { signal: pending.controller.signal });
239
+ reply = { type: "result", id, ok: true, payload: value === undefined ? undefined : JSON.stringify(value) };
240
+ status = "ok";
241
+ }
242
+ catch (error) {
243
+ reply = { type: "result", id, ok: false, payload: errorMessage(error) };
244
+ status = "error";
245
+ }
246
+ // Already cancelled by finish(): the record keeps "cancelled" and the
247
+ // VM is gone or going.
248
+ if (!this.pending.delete(id))
249
+ return;
250
+ if (record) {
251
+ record.status = status;
252
+ record.durationMs = performance.now() - pending.startedAt;
253
+ }
254
+ this.post(reply);
255
+ }
256
+ finish(error, value, writes) {
257
+ if (this.finished)
258
+ return;
259
+ this.finished = true;
260
+ clearTimeout(this.timer);
261
+ this.signal?.removeEventListener("abort", this.onAbort);
262
+ const now = performance.now();
263
+ for (const pending of this.pending.values()) {
264
+ if (pending.record)
265
+ pending.record.durationMs = now - pending.startedAt;
266
+ pending.controller.abort();
267
+ }
268
+ this.pending.clear();
269
+ this.unsent = [];
270
+ const result = error
271
+ ? { ok: false, error, output: this.output, calls: this.calls }
272
+ : {
273
+ ok: true,
274
+ value,
275
+ output: this.output,
276
+ calls: this.calls,
277
+ storeWrites: writes ?? { set: {}, delete: [] },
278
+ };
279
+ if (!this.channel) {
280
+ this.resolveResult(result);
281
+ return;
282
+ }
283
+ this.channel
284
+ .stop()
285
+ .catch(() => undefined)
286
+ .then(() => this.resolveResult(result));
287
+ }
288
+ }
289
+ /**
290
+ * Tool table, defaults, and in-flight executions; the behavior every sandbox shares. Subclasses
291
+ * only choose where the VM runs by passing a {@link VmLauncher}.
292
+ *
293
+ * The script sees `tools.<name>(args)` for every registered tool, `ALL_TOOLS`, the output helpers
294
+ * `text`, `image`, `exit`, and `console.*`, `store`/`load`, and the configured globals; nothing
295
+ * else (no timers, `fetch`, `process`, `require`, modules). Each `execute()` gets its own VM; the
296
+ * sandbox only holds the tool table and defaults. `close()` aborts in-flight executions.
297
+ */
298
+ export class CodemodeSandboxBase {
299
+ toolsByName = new Map();
300
+ globalsByName = new Map();
301
+ timeoutMs;
302
+ memoryLimitBytes;
303
+ launch;
304
+ running = new Set();
305
+ closed = false;
306
+ constructor(options, launch) {
307
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
308
+ this.memoryLimitBytes = options.memoryLimitBytes;
309
+ this.launch = launch;
310
+ for (const tool of options.tools ?? [])
311
+ this.registerTool(tool);
312
+ const namespaces = new Set();
313
+ for (const global of options.globals ?? []) {
314
+ const parts = global.name.split(".");
315
+ if (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part)) || RESERVED_GLOBALS.has(parts[0])) {
316
+ throw new Error(`Invalid global name "${global.name}"`);
317
+ }
318
+ if (this.globalsByName.has(global.name))
319
+ throw new Error(`Global "${global.name}" is already registered`);
320
+ if (parts.length === 2)
321
+ namespaces.add(parts[0]);
322
+ this.globalsByName.set(global.name, global);
323
+ }
324
+ for (const name of namespaces) {
325
+ if (this.globalsByName.has(name))
326
+ throw new Error(`Global "${name}" conflicts with the namespace "${name}"`);
327
+ }
328
+ }
329
+ /** Throws if a tool with the same name is already registered. */
330
+ registerTool(tool) {
331
+ if (this.toolsByName.has(tool.name))
332
+ throw new Error(`Tool "${tool.name}" is already registered`);
333
+ this.toolsByName.set(tool.name, tool);
334
+ }
335
+ unregisterTool(name) {
336
+ return this.toolsByName.delete(name);
337
+ }
338
+ get tools() {
339
+ return [...this.toolsByName.values()];
340
+ }
341
+ get globals() {
342
+ return [...this.globalsByName.values()];
343
+ }
344
+ /**
345
+ * `code` is an async function body: `return` and top-level `await` work.
346
+ * Never rejects for script failures; those come back as `{ ok: false }`.
347
+ * The script can use `store(key, value)` and `load(key)` on `options.store`.
348
+ */
349
+ execute(code, options = {}) {
350
+ if (this.closed)
351
+ return Promise.reject(new Error("Sandbox is closed"));
352
+ const execution = new Execution({
353
+ code,
354
+ tools: new Map(this.toolsByName),
355
+ globals: this.globalsByName,
356
+ timeoutMs: options.timeoutMs ?? this.timeoutMs,
357
+ signal: options.signal,
358
+ memoryLimitBytes: this.memoryLimitBytes,
359
+ store: serializeStore(options.store),
360
+ launch: this.launch,
361
+ });
362
+ this.running.add(execution);
363
+ return execution.promise.finally(() => this.running.delete(execution));
364
+ }
365
+ /** Aborts in-flight executions (they resolve with `kind: "aborted"`) and rejects new ones. */
366
+ async close() {
367
+ this.closed = true;
368
+ await Promise.all([...this.running].map((execution) => execution.abort("Sandbox closed")));
369
+ }
370
+ }
371
+ //# sourceMappingURL=execution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution.js","sourceRoot":"","sources":["../../src/runtime/execution.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAYxD,OAAO,EAEN,qBAAqB,GAGrB,MAAM,eAAe,CAAC;AAEvB,MAAM,kBAAkB,GAAG,OAAO,CAAC;AACnC,MAAM,UAAU,GAAG,4BAA4B,CAAC;AAChD,MAAM,gBAAgB,GAAwB,IAAI,GAAG,CAAC;IACrD,OAAO;IACP,WAAW;IACX,SAAS;IACT,MAAM;IACN,OAAO;IACP,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EAAE,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC;YAChC,OAAO,EAAE,IAAI,CAAC,aAAa;YAC3B,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC,SAAS;YAC9C,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;YACvC,KAAK,EAAE,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC;YACpC,MAAM,EAAE,IAAI,CAAC,MAAM;SACnB,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAC5B,OAAO,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;IACxE,CAAC;IAED,8FAA8F;IAC9F,KAAK,CAAC,KAAK;QACV,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAC5F,CAAC;CACD","sourcesContent":["/**\n * Host side of an execution, shared by every place a VM can run.\n *\n * The host owns everything the script must not influence: the tool table, call records, output,\n * the deadline, the caller's abort signal, and the decoding of what the VM reports. The VM itself\n * runs somewhere a {@link VmLauncher} decides: a worker thread (`CodemodeSandbox`), the calling\n * thread (`InlineCodemodeSandbox`), or another isolate reached over RPC (`RemoteCodemodeSandbox`).\n * The two sides only exchange the messages in `protocol.ts`, so the launchers differ in transport\n * and termination, not in behavior.\n *\n * Lifecycle of one execution:\n * 1. The constructor arms the deadline and abort listener, then asks the launcher for a channel.\n * 2. Messages from the VM arrive through {@link VmEvents.message}; tool calls run here and their\n * results go back through {@link VmChannel.post}. Replies produced before the launcher has\n * returned its channel are queued and flushed when it arrives.\n * 3. The first terminal event wins: `done`, `crash`, a launcher failure, the deadline, or an abort.\n * `finish()` aborts pending tool calls, stops the channel, and resolves the result once the\n * channel reports it stopped. Later events are ignored.\n *\n * The launcher, not this class, is responsible for actually stopping a running VM: a worker is\n * terminated, an in-thread VM is interrupted and disposed, and a remote VM is told to stop at its\n * next exchange.\n */\nimport { toCodemodeIdentifier } from \"../identifier.ts\";\nimport type {\n\tCodemodeCall,\n\tCodemodeCallStatus,\n\tCodemodeError,\n\tCodemodeExecuteOptions,\n\tCodemodeOutputItem,\n\tCodemodeResult,\n\tCodemodeSandboxBaseOptions,\n\tCodemodeStoreWrites,\n\tCodemodeTool,\n} from \"../types.ts\";\nimport {\n\ttype HostToWorkerMessage,\n\tisWorkerToHostMessage,\n\ttype VmStartData,\n\ttype WorkerToHostMessage,\n} from \"./protocol.ts\";\n\nconst DEFAULT_TIMEOUT_MS = 300_000;\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst RESERVED_GLOBALS: ReadonlySet<string> = new Set([\n\t\"tools\",\n\t\"ALL_TOOLS\",\n\t\"console\",\n\t\"text\",\n\t\"image\",\n\t\"exit\",\n\t\"globalThis\",\n\t\"store\",\n\t\"load\",\n]);\n\n/** Callbacks a launcher uses to report what its VM does. */\nexport interface VmEvents {\n\t/** A message from the VM. Validated here, so launchers can pass through anything they receive. */\n\tmessage(message: unknown): void;\n\t/** The VM failed or stopped outside the bridge, for example a worker exit or a remote error. */\n\tfailure(error: CodemodeError): void;\n}\n\n/** The host's handle on a running VM. */\nexport interface VmChannel {\n\tpost(message: HostToWorkerMessage): void;\n\t/** Stops the VM. Called once, after the execution has its result. */\n\tstop(): Promise<void>;\n}\n\n/**\n * Starts a VM for one execution. Rejections become `sandbox` errors with the rejection's message.\n * The VM may start reporting messages before the returned promise settles.\n */\nexport type VmLauncher = (data: VmStartData, events: VmEvents) => VmChannel | Promise<VmChannel>;\n\nexport function errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction serializeStore(store: Readonly<Record<string, unknown>> | undefined): Record<string, string> {\n\tconst serialized: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(store ?? {})) {\n\t\tconst json = JSON.stringify(value);\n\t\tif (json !== undefined) serialized[key] = json;\n\t}\n\treturn serialized;\n}\n\n/**\n * The prelude that serializes values for the host runs in the same VM as the script, so a script\n * that patches built-ins (for example `Array.prototype.toJSON`) can make it send malformed data.\n * Payloads that do not decode throw this error, and the execution fails as a sandbox error.\n */\nclass BridgeError extends Error {}\n\nfunction parseBridgeJson(json: string, what: string): unknown {\n\ttry {\n\t\treturn JSON.parse(json);\n\t} catch {\n\t\tthrow new BridgeError(`${what} is not valid JSON`);\n\t}\n}\n\nfunction parseStoreWrites(json: string): CodemodeStoreWrites {\n\tconst entries = parseBridgeJson(json, \"store writes\");\n\tif (!Array.isArray(entries)) throw new BridgeError(\"store writes are not an array\");\n\tconst writes: CodemodeStoreWrites = { set: {}, delete: [] };\n\tfor (const entry of entries) {\n\t\tif (\n\t\t\t!Array.isArray(entry) ||\n\t\t\ttypeof entry[0] !== \"string\" ||\n\t\t\t(entry.length === 2 ? typeof entry[1] !== \"string\" : entry.length !== 1)\n\t\t) {\n\t\t\tthrow new BridgeError(\"store writes contain a malformed entry\");\n\t\t}\n\t\tconst [key, value] = entry as [string, string?];\n\t\tif (value === undefined) writes.delete.push(key);\n\t\telse writes.set[key] = parseBridgeJson(value, `store value for ${JSON.stringify(key)}`);\n\t}\n\treturn writes;\n}\n\nfunction parseScriptError(json: string): CodemodeError {\n\tconst parsed = parseBridgeJson(json, \"script error\");\n\tif (typeof parsed !== \"object\" || parsed === null) throw new BridgeError(\"script error is not an object\");\n\tconst { name, message, stack } = parsed as Record<string, unknown>;\n\tif (\n\t\ttypeof message !== \"string\" ||\n\t\t(name !== undefined && typeof name !== \"string\") ||\n\t\t(stack !== undefined && typeof stack !== \"string\")\n\t) {\n\t\tthrow new BridgeError(\"script error is malformed\");\n\t}\n\treturn { kind: \"script\", name, message, stack };\n}\n\ninterface PendingCall {\n\trecord: CodemodeCall | undefined;\n\tstartedAt: number;\n\tcontroller: AbortController;\n}\n\ninterface ExecutionOptions {\n\tcode: string;\n\ttools: ReadonlyMap<string, CodemodeTool>;\n\tglobals: ReadonlyMap<string, CodemodeTool>;\n\ttimeoutMs: number;\n\tsignal: AbortSignal | undefined;\n\tmemoryLimitBytes: number | undefined;\n\tstore: Record<string, string>;\n\tlaunch: VmLauncher;\n}\n\n/** One script run in its own VM. */\nclass Execution {\n\treadonly promise: Promise<CodemodeResult>;\n\tprivate resolveResult!: (result: CodemodeResult) => void;\n\tprivate channel: VmChannel | undefined;\n\t/** Replies produced before the launcher returned the channel. */\n\tprivate unsent: HostToWorkerMessage[] = [];\n\tprivate readonly tools: ReadonlyMap<string, CodemodeTool>;\n\tprivate readonly globals: ReadonlyMap<string, CodemodeTool>;\n\tprivate readonly signal: AbortSignal | undefined;\n\tprivate readonly timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate readonly output: CodemodeOutputItem[] = [];\n\tprivate readonly calls: CodemodeCall[] = [];\n\tprivate readonly pending = new Map<number, PendingCall>();\n\tprivate finished = false;\n\n\tconstructor(options: ExecutionOptions) {\n\t\tthis.promise = new Promise<CodemodeResult>((resolve) => {\n\t\t\tthis.resolveResult = resolve;\n\t\t});\n\t\tthis.tools = options.tools;\n\t\tthis.globals = options.globals;\n\t\tthis.signal = options.signal;\n\n\t\tif (Number.isFinite(options.timeoutMs)) {\n\t\t\tthis.timer = setTimeout(() => {\n\t\t\t\tthis.finish({ kind: \"timeout\", message: `Execution timed out after ${options.timeoutMs} ms` });\n\t\t\t}, options.timeoutMs);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tif (options.signal.aborted) {\n\t\t\t\tthis.onAbort();\n\t\t\t} else {\n\t\t\t\toptions.signal.addEventListener(\"abort\", this.onAbort, { once: true });\n\t\t\t}\n\t\t}\n\t\tif (this.finished) return;\n\n\t\tconst data: VmStartData = {\n\t\t\tcode: options.code,\n\t\t\ttools: [...options.tools.values()].map((tool) => ({\n\t\t\t\tname: tool.name,\n\t\t\t\tjsName: toCodemodeIdentifier(tool.name),\n\t\t\t\tdescription: tool.description ?? \"\",\n\t\t\t})),\n\t\t\tglobals: [...options.globals.values()].map((global) => ({\n\t\t\t\tname: global.name,\n\t\t\t\tspread: global.spread === true,\n\t\t\t})),\n\t\t\tmemoryLimitBytes: options.memoryLimitBytes,\n\t\t\tstore: options.store,\n\t\t};\n\t\tconst events: VmEvents = {\n\t\t\tmessage: (message) => this.receive(message),\n\t\t\tfailure: (error) => this.finish(error),\n\t\t};\n\t\tnew Promise<VmChannel>((resolve) => resolve(options.launch(data, events))).then(\n\t\t\t(channel) => {\n\t\t\t\tif (this.finished) {\n\t\t\t\t\tvoid channel.stop().catch(() => undefined);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.channel = channel;\n\t\t\t\tfor (const message of this.unsent.splice(0)) channel.post(message);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tthis.finish({ kind: \"sandbox\", message: errorMessage(error) });\n\t\t\t},\n\t\t);\n\t}\n\n\tabort(message: string): Promise<CodemodeResult> {\n\t\tthis.finish({ kind: \"aborted\", message });\n\t\treturn this.promise;\n\t}\n\n\tprivate readonly onAbort = (): void => {\n\t\tconst reason: unknown = this.signal?.reason;\n\t\tthis.finish({ kind: \"aborted\", message: reason instanceof Error ? reason.message : \"Execution aborted\" });\n\t};\n\n\tprivate post(message: HostToWorkerMessage): void {\n\t\tif (this.channel) this.channel.post(message);\n\t\telse this.unsent.push(message);\n\t}\n\n\t/** An exception here would escape into the launcher's transport and leave the execution unsettled. */\n\tprivate receive(message: unknown): void {\n\t\ttry {\n\t\t\tthis.handleMessage(message);\n\t\t} catch (error) {\n\t\t\tthis.finish({\n\t\t\t\tkind: \"sandbox\",\n\t\t\t\tmessage:\n\t\t\t\t\terror instanceof BridgeError\n\t\t\t\t\t\t? `Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.`\n\t\t\t\t\t\t: `Sandbox host failed: ${errorMessage(error)}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate handleMessage(message: unknown): void {\n\t\tif (this.finished) return;\n\t\tif (!isWorkerToHostMessage(message)) throw new BridgeError(\"unknown message from the worker\");\n\t\tswitch (message.type) {\n\t\t\tcase \"output\":\n\t\t\t\tthis.output.push(message.item);\n\t\t\t\tbreak;\n\t\t\tcase \"call\":\n\t\t\t\tif (this.pending.has(message.id)) throw new BridgeError(`duplicate call id ${message.id}`);\n\t\t\t\tvoid this.handleCall(message);\n\t\t\t\tbreak;\n\t\t\tcase \"done\":\n\t\t\t\tthis.handleDone(message);\n\t\t\t\tbreak;\n\t\t\tcase \"crash\":\n\t\t\t\tthis.finish({ kind: \"sandbox\", message: message.message });\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate handleDone(message: Extract<WorkerToHostMessage, { type: \"done\" }>): void {\n\t\t// Decode everything before finish(), which must not throw once it starts.\n\t\tif (!message.ok) {\n\t\t\tthis.finish(parseScriptError(message.error));\n\t\t\treturn;\n\t\t}\n\t\tconst value = message.value === undefined ? undefined : parseBridgeJson(message.value, \"return value\");\n\t\tthis.finish(undefined, value, parseStoreWrites(message.writes));\n\t}\n\n\tprivate async handleCall(message: Extract<WorkerToHostMessage, { type: \"call\" }>): Promise<void> {\n\t\tconst { id, name } = message;\n\t\tconst isTool = message.target === \"tool\";\n\t\tconst record: CodemodeCall | undefined = isTool ? { name, status: \"cancelled\", durationMs: 0 } : undefined;\n\t\tif (record) this.calls.push(record);\n\t\tconst pending: PendingCall = { record, startedAt: performance.now(), controller: new AbortController() };\n\t\tthis.pending.set(id, pending);\n\n\t\tlet status: CodemodeCallStatus;\n\t\tlet reply: HostToWorkerMessage;\n\t\ttry {\n\t\t\tconst tool = (isTool ? this.tools : this.globals).get(name);\n\t\t\tif (!tool) throw new Error(`Unknown ${isTool ? \"tool\" : \"global\"} \"${name}\"`);\n\t\t\tconst args: unknown = message.args === undefined ? undefined : JSON.parse(message.args);\n\t\t\tconst value = await tool.execute(args, { signal: pending.controller.signal });\n\t\t\treply = { type: \"result\", id, ok: true, payload: value === undefined ? undefined : JSON.stringify(value) };\n\t\t\tstatus = \"ok\";\n\t\t} catch (error) {\n\t\t\treply = { type: \"result\", id, ok: false, payload: errorMessage(error) };\n\t\t\tstatus = \"error\";\n\t\t}\n\n\t\t// Already cancelled by finish(): the record keeps \"cancelled\" and the\n\t\t// VM is gone or going.\n\t\tif (!this.pending.delete(id)) return;\n\t\tif (record) {\n\t\t\trecord.status = status;\n\t\t\trecord.durationMs = performance.now() - pending.startedAt;\n\t\t}\n\t\tthis.post(reply);\n\t}\n\n\tprivate finish(error: CodemodeError | undefined, value?: unknown, writes?: CodemodeStoreWrites): void {\n\t\tif (this.finished) return;\n\t\tthis.finished = true;\n\t\tclearTimeout(this.timer);\n\t\tthis.signal?.removeEventListener(\"abort\", this.onAbort);\n\n\t\tconst now = performance.now();\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tif (pending.record) pending.record.durationMs = now - pending.startedAt;\n\t\t\tpending.controller.abort();\n\t\t}\n\t\tthis.pending.clear();\n\t\tthis.unsent = [];\n\n\t\tconst result: CodemodeResult = error\n\t\t\t? { ok: false, error, output: this.output, calls: this.calls }\n\t\t\t: {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalue,\n\t\t\t\t\toutput: this.output,\n\t\t\t\t\tcalls: this.calls,\n\t\t\t\t\tstoreWrites: writes ?? { set: {}, delete: [] },\n\t\t\t\t};\n\t\tif (!this.channel) {\n\t\t\tthis.resolveResult(result);\n\t\t\treturn;\n\t\t}\n\t\tthis.channel\n\t\t\t.stop()\n\t\t\t.catch(() => undefined)\n\t\t\t.then(() => this.resolveResult(result));\n\t}\n}\n\n/**\n * Tool table, defaults, and in-flight executions; the behavior every sandbox shares. Subclasses\n * only choose where the VM runs by passing a {@link VmLauncher}.\n *\n * The script sees `tools.<name>(args)` for every registered tool, `ALL_TOOLS`, the output helpers\n * `text`, `image`, `exit`, and `console.*`, `store`/`load`, and the configured globals; nothing\n * else (no timers, `fetch`, `process`, `require`, modules). Each `execute()` gets its own VM; the\n * sandbox only holds the tool table and defaults. `close()` aborts in-flight executions.\n */\nexport class CodemodeSandboxBase {\n\tprivate readonly toolsByName = new Map<string, CodemodeTool>();\n\tprivate readonly globalsByName = new Map<string, CodemodeTool>();\n\tprivate readonly timeoutMs: number;\n\tprivate readonly memoryLimitBytes: number | undefined;\n\tprivate readonly launch: VmLauncher;\n\tprivate readonly running = new Set<Execution>();\n\tprivate closed = false;\n\n\tconstructor(options: CodemodeSandboxBaseOptions, launch: VmLauncher) {\n\t\tthis.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\t\tthis.memoryLimitBytes = options.memoryLimitBytes;\n\t\tthis.launch = launch;\n\t\tfor (const tool of options.tools ?? []) this.registerTool(tool);\n\t\tconst namespaces = new Set<string>();\n\t\tfor (const global of options.globals ?? []) {\n\t\t\tconst parts = global.name.split(\".\");\n\t\t\tif (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part)) || RESERVED_GLOBALS.has(parts[0])) {\n\t\t\t\tthrow new Error(`Invalid global name \"${global.name}\"`);\n\t\t\t}\n\t\t\tif (this.globalsByName.has(global.name)) throw new Error(`Global \"${global.name}\" is already registered`);\n\t\t\tif (parts.length === 2) namespaces.add(parts[0]);\n\t\t\tthis.globalsByName.set(global.name, global);\n\t\t}\n\t\tfor (const name of namespaces) {\n\t\t\tif (this.globalsByName.has(name)) throw new Error(`Global \"${name}\" conflicts with the namespace \"${name}\"`);\n\t\t}\n\t}\n\n\t/** Throws if a tool with the same name is already registered. */\n\tregisterTool(tool: CodemodeTool): void {\n\t\tif (this.toolsByName.has(tool.name)) throw new Error(`Tool \"${tool.name}\" is already registered`);\n\t\tthis.toolsByName.set(tool.name, tool);\n\t}\n\n\tunregisterTool(name: string): boolean {\n\t\treturn this.toolsByName.delete(name);\n\t}\n\n\tget tools(): CodemodeTool[] {\n\t\treturn [...this.toolsByName.values()];\n\t}\n\n\tget globals(): CodemodeTool[] {\n\t\treturn [...this.globalsByName.values()];\n\t}\n\n\t/**\n\t * `code` is an async function body: `return` and top-level `await` work.\n\t * Never rejects for script failures; those come back as `{ ok: false }`.\n\t * The script can use `store(key, value)` and `load(key)` on `options.store`.\n\t */\n\texecute(code: string, options: CodemodeExecuteOptions = {}): Promise<CodemodeResult> {\n\t\tif (this.closed) return Promise.reject(new Error(\"Sandbox is closed\"));\n\t\tconst execution = new Execution({\n\t\t\tcode,\n\t\t\ttools: new Map(this.toolsByName),\n\t\t\tglobals: this.globalsByName,\n\t\t\ttimeoutMs: options.timeoutMs ?? this.timeoutMs,\n\t\t\tsignal: options.signal,\n\t\t\tmemoryLimitBytes: this.memoryLimitBytes,\n\t\t\tstore: serializeStore(options.store),\n\t\t\tlaunch: this.launch,\n\t\t});\n\t\tthis.running.add(execution);\n\t\treturn execution.promise.finally(() => this.running.delete(execution));\n\t}\n\n\t/** Aborts in-flight executions (they resolve with `kind: \"aborted\"`) and rejects new ones. */\n\tasync close(): Promise<void> {\n\t\tthis.closed = true;\n\t\tawait Promise.all([...this.running].map((execution) => execution.abort(\"Sandbox closed\")));\n\t}\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import type { CodemodeSandboxOptions } from "../types.ts";
2
+ import { CodemodeSandboxBase } from "./execution.ts";
3
+ /**
4
+ * Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker thread. The worker
5
+ * keeps script execution off the host thread: QuickJS runs synchronously, so a spinning script on
6
+ * the host thread would block its event loop. Requires `node:worker_threads` (Node or Bun); see
7
+ * `InlineCodemodeSandbox` and `RemoteCodemodeSandbox` in `@ny4n/codemode/portable`
8
+ * for other runtimes.
9
+ */
10
+ export declare class CodemodeSandbox extends CodemodeSandboxBase {
11
+ constructor(options?: CodemodeSandboxOptions);
12
+ }
13
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAE1D,OAAO,EAAE,mBAAmB,EAAiC,MAAM,gBAAgB,CAAC;AAgEpF;;;;;;GAMG;AACH,qBAAa,eAAgB,SAAQ,mBAAmB;IACvD,YAAY,OAAO,GAAE,sBAA2B,EAE/C;CACD"}
@@ -0,0 +1,72 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { loadQuickJSWasm } from "../wasm.js";
3
+ import { CodemodeSandboxBase, errorMessage } from "./execution.js";
4
+ function defaultWorkerUrl() {
5
+ // `.ts` when running from source (tests, tsx), `.js` from the published dist.
6
+ return new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url);
7
+ }
8
+ /**
9
+ * Each execution gets its own worker thread and QuickJS VM. A fresh worker per run keeps
10
+ * termination simple: a runaway script, including one that only spins the microtask queue, is
11
+ * killed with `terminate()` and cannot poison a later run. Before terminating, the host sets a
12
+ * shared interrupt flag that the VM polls, because Bun's `terminate()` cannot stop a thread that
13
+ * is spinning in wasm.
14
+ */
15
+ function workerLauncher(wasm, workerUrl) {
16
+ return async (data, events) => {
17
+ let module;
18
+ try {
19
+ module = await (wasm ?? loadQuickJSWasm());
20
+ }
21
+ catch (error) {
22
+ throw new Error(`Failed to load QuickJS: ${errorMessage(error)}`);
23
+ }
24
+ const interrupt = new SharedArrayBuffer(4);
25
+ const workerData = { ...data, wasm: module, interrupt };
26
+ let worker;
27
+ try {
28
+ worker = new Worker(workerUrl, { workerData });
29
+ }
30
+ catch (error) {
31
+ throw new Error(`Failed to start worker: ${errorMessage(error)}`);
32
+ }
33
+ worker.on("message", (message) => {
34
+ // Node 24/26 --watch leaks dependency reports onto the worker channel (nodejs/node#65044).
35
+ if (typeof message === "object" &&
36
+ message !== null &&
37
+ ("watch:import" in message || "watch:require" in message))
38
+ return;
39
+ events.message(message);
40
+ });
41
+ worker.on("error", (error) => {
42
+ events.failure({
43
+ kind: "sandbox",
44
+ name: error instanceof Error ? error.name : undefined,
45
+ message: errorMessage(error),
46
+ });
47
+ });
48
+ worker.on("exit", (code) => {
49
+ events.failure({ kind: "sandbox", message: `Worker exited with code ${code} before the script settled` });
50
+ });
51
+ return {
52
+ post: (message) => worker.postMessage(message),
53
+ stop: async () => {
54
+ Atomics.store(new Int32Array(interrupt), 0, 1);
55
+ await worker.terminate().catch(() => undefined);
56
+ },
57
+ };
58
+ };
59
+ }
60
+ /**
61
+ * Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker thread. The worker
62
+ * keeps script execution off the host thread: QuickJS runs synchronously, so a spinning script on
63
+ * the host thread would block its event loop. Requires `node:worker_threads` (Node or Bun); see
64
+ * `InlineCodemodeSandbox` and `RemoteCodemodeSandbox` in `@ny4n/codemode/portable`
65
+ * for other runtimes.
66
+ */
67
+ export class CodemodeSandbox extends CodemodeSandboxBase {
68
+ constructor(options = {}) {
69
+ super(options, workerLauncher(options.wasm, options.workerUrl ?? defaultWorkerUrl()));
70
+ }
71
+ }
72
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAA2B,eAAe,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC;AAGpF,SAAS,gBAAgB;IACxB,8EAA8E;IAC9E,OAAO,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,aAAa,EAAE,OAAO,IAAI,CAAC,GAAG,C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Y,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;gBACrD,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC;aAC5B,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE;YAC1B,MAAM,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,2BAA2B,IAAI,4BAA4B,EAAE,CAAC,CAAC;QAC3G,CAAC,CAAC,CAAC;QACH,OAAO;YACN,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC;YAC9C,IAAI,EAAE,KAAK,IAAI,EAAE;gBAChB,OAAO,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;gBAC/C,MAAM,MAAM,CAAC,SAAS,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YACjD,CAAC;SACD,CAAC;IACH,CAAC,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,OAAO,eAAgB,SAAQ,mBAAmB;IACvD,YAAY,OAAO,GAA2B,EAAE;QAC/C,KAAK,CAAC,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,SAAS,IAAI,gBAAgB,EAAE,CAAC,CAAC,CAAC;IACvF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { CodemodeSandboxOptions } from \"../types.ts\";\nimport { type CodemodeWasmModule, loadQuickJSWasm } from \"../wasm.ts\";\nimport { CodemodeSandboxBase, errorMessage, type VmLauncher } from \"./execution.ts\";\nimport type { WorkerData } from \"./protocol.ts\";\n\nfunction defaultWorkerUrl(): URL {\n\t// `.ts` when running from source (tests, tsx), `.js` from the published dist.\n\treturn new URL(import.meta.url.endsWith(\".ts\") ? \"./worker.ts\" : \"./worker.js\", import.meta.url);\n}\n\n/**\n * Each execution gets its own worker thread and QuickJS VM. A fresh worker per run keeps\n * termination simple: a runaway script, including one that only spins the microtask queue, is\n * killed with `terminate()` and cannot poison a later run. Before terminating, the host sets a\n * shared interrupt flag that the VM polls, because Bun's `terminate()` cannot stop a thread that\n * is spinning in wasm.\n */\nfunction workerLauncher(\n\twasm: CodemodeWasmModule | Promise<CodemodeWasmModule> | undefined,\n\tworkerUrl: string | URL,\n): VmLauncher {\n\treturn async (data, events) => {\n\t\tlet module: CodemodeWasmModule;\n\t\ttry {\n\t\t\tmodule = await (wasm ?? loadQuickJSWasm());\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Failed to load QuickJS: ${errorMessage(error)}`);\n\t\t}\n\t\tconst interrupt = new SharedArrayBuffer(4);\n\t\tconst workerData: WorkerData = { ...data, wasm: module, interrupt };\n\t\tlet worker: Worker;\n\t\ttry {\n\t\t\tworker = new Worker(workerUrl, { workerData });\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Failed to start worker: ${errorMessage(error)}`);\n\t\t}\n\t\tworker.on(\"message\", (message: unknown) => {\n\t\t\t// Node 24/26 --watch leaks dependency reports onto the worker channel (nodejs/node#65044).\n\t\t\tif (\n\t\t\t\ttypeof message === \"object\" &&\n\t\t\t\tmessage !== null &&\n\t\t\t\t(\"watch:import\" in message || \"watch:require\" in message)\n\t\t\t)\n\t\t\t\treturn;\n\t\t\tevents.message(message);\n\t\t});\n\t\tworker.on(\"error\", (error: unknown) => {\n\t\t\tevents.failure({\n\t\t\t\tkind: \"sandbox\",\n\t\t\t\tname: error instanceof Error ? error.name : undefined,\n\t\t\t\tmessage: errorMessage(error),\n\t\t\t});\n\t\t});\n\t\tworker.on(\"exit\", (code) => {\n\t\t\tevents.failure({ kind: \"sandbox\", message: `Worker exited with code ${code} before the script settled` });\n\t\t});\n\t\treturn {\n\t\t\tpost: (message) => worker.postMessage(message),\n\t\t\tstop: async () => {\n\t\t\t\tAtomics.store(new Int32Array(interrupt), 0, 1);\n\t\t\t\tawait worker.terminate().catch(() => undefined);\n\t\t\t},\n\t\t};\n\t};\n}\n\n/**\n * Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker thread. The worker\n * keeps script execution off the host thread: QuickJS runs synchronously, so a spinning script on\n * the host thread would block its event loop. Requires `node:worker_threads` (Node or Bun); see\n * `InlineCodemodeSandbox` and `RemoteCodemodeSandbox` in `@ny4n/codemode/portable`\n * for other runtimes.\n */\nexport class CodemodeSandbox extends CodemodeSandboxBase {\n\tconstructor(options: CodemodeSandboxOptions = {}) {\n\t\tsuper(options, workerLauncher(options.wasm, options.workerUrl ?? defaultWorkerUrl()));\n\t}\n}\n"]}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Runs the VM on the calling thread, for runtimes without worker threads (Cloudflare Workers and
3
+ * Durable Objects, browsers) and for the server side of `RemoteCodemodeSandbox`.
4
+ *
5
+ * Problem: QuickJS runs synchronously. While a script computes, the host's event loop does not
6
+ * run, so neither the deadline timer nor an abort signal can fire. On Workers even `Date.now()` is
7
+ * frozen during synchronous execution, so the VM cannot check a clock either. Example: with a
8
+ * worker thread, `while (true) {}` is stopped by the host's 200 ms timer; on the calling thread
9
+ * that timer never gets a chance to run.
10
+ *
11
+ * Solution: an interrupt budget. QuickJS polls its interrupt handler periodically while a script
12
+ * runs; this launcher counts the polls across the whole execution and interrupts the script once
13
+ * the count passes the budget. The execution then fails with `kind: "timeout"`. The deadline and
14
+ * abort signal still work whenever the script waits on a tool, since the event loop runs then.
15
+ *
16
+ * The rate of polls depends on the code and the machine. Measured with a tight loop: about 50,000
17
+ * per second of CPU on an Apple M-series laptop and about 10,000 per second on Cloudflare Durable
18
+ * Objects (October 2026). The default of 100,000 allows roughly 2 to 10 seconds of uninterrupted
19
+ * computation; keep it well below the platform's own CPU limit, because hitting that limit resets
20
+ * a Durable Object instead of failing one script.
21
+ *
22
+ * Once the VM reports `done` or `crash`, the result is decided, so the VM is interrupted at the
23
+ * next poll instead of running on until the host stops it. Example: a script that keeps printing in
24
+ * a `for (;;)` loop after its output limit was reached would otherwise run until the budget ran out
25
+ * and be reported as a timeout.
26
+ *
27
+ * Stack: the VM runs on the caller's stack, which is smaller than a worker thread's (about 1 MB
28
+ * on Node's main thread), so QuickJS's stack guard is set to {@link INLINE_MAX_STACK_SIZE}.
29
+ *
30
+ * Reentrancy: VM callbacks run inside QuickJS. Messages from the VM are delivered to the host in
31
+ * a microtask, after the VM has returned, so host code (tool calls, `finish()`, disposal) never
32
+ * runs inside a VM callback and never re-enters the VM.
33
+ */
34
+ import type { CodemodeSandboxBaseOptions } from "../types.ts";
35
+ import type { CodemodeWasmModule } from "../wasm.ts";
36
+ import { CodemodeSandboxBase, type VmLauncher } from "./execution.ts";
37
+ export declare const DEFAULT_INTERRUPT_BUDGET = 100000;
38
+ /** Allows recursion about 1,000 calls deep and trips well before a 1 MB host stack overflows. */
39
+ export declare const INLINE_MAX_STACK_SIZE: number;
40
+ export interface InlineCodemodeSandboxOptions extends CodemodeSandboxBaseOptions {
41
+ /**
42
+ * Compiled `quickjs-wasi/quickjs.wasm`. On Cloudflare, import it with Wrangler's `CompiledWasm`
43
+ * rule (`@ny4n/codemode/cloudflare` does this); on Node, `loadQuickJSWasm()`.
44
+ */
45
+ wasm: CodemodeWasmModule | Promise<CodemodeWasmModule>;
46
+ /**
47
+ * Interrupt polls an execution may use before it fails with `kind: "timeout"`. The only limit on
48
+ * a script that computes without awaiting a tool. Default: {@link DEFAULT_INTERRUPT_BUDGET}.
49
+ */
50
+ interruptBudget?: number;
51
+ }
52
+ export declare function inlineLauncher(wasm: CodemodeWasmModule | Promise<CodemodeWasmModule>, interruptBudget?: number): VmLauncher;
53
+ /**
54
+ * Runs each execution's QuickJS VM on the calling thread. Works in any runtime with WebAssembly
55
+ * and microtasks; needs no worker threads, files, or Node built-ins. A script that computes
56
+ * blocks the caller's thread until it awaits a tool or uses up its interrupt budget, so prefer
57
+ * `CodemodeSandbox` where worker threads exist, and `RemoteCodemodeSandbox` to keep scripts off a
58
+ * thread that must stay responsive (such as a Durable Object that serves a session).
59
+ */
60
+ export declare class InlineCodemodeSandbox extends CodemodeSandboxBase {
61
+ constructor(options: InlineCodemodeSandboxOptions);
62
+ }
63
+ //# sourceMappingURL=inline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inline.d.ts","sourceRoot":"","sources":["../../src/runtime/inline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC;AAC9D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,mBAAmB,EAAgB,KAAK,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAGpF,eAAO,MAAM,wBAAwB,SAAU,CAAC;AAEhD,iGAAiG;AACjG,eAAO,MAAM,qBAAqB,QAAa,CAAC;AAEhD,MAAM,WAAW,4BAA6B,SAAQ,0BAA0B;IAC/E;;;OAGG;IACH,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACvD;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,cAAc,CAC7B,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,EACtD,eAAe,GAAE,MAAiC,GAChD,UAAU,CAoDZ;AAED;;;;;;GAMG;AACH,qBAAa,qBAAsB,SAAQ,mBAAmB;IAC7D,YAAY,OAAO,EAAE,4BAA4B,EAEhD;CACD"}