@mcpview/compose 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +101 -1
  2. package/README.md +113 -22
  3. package/esm/src/code-mode/engine.d.ts +59 -0
  4. package/esm/src/code-mode/engine.d.ts.map +1 -0
  5. package/esm/src/code-mode/engine.js +189 -0
  6. package/esm/src/code-mode/guest-worker.d.ts +2 -5
  7. package/esm/src/code-mode/guest-worker.d.ts.map +1 -1
  8. package/esm/src/code-mode/guest-worker.js +4 -75
  9. package/esm/src/code-mode/sandbox-api.d.ts +37 -0
  10. package/esm/src/code-mode/sandbox-api.d.ts.map +1 -0
  11. package/esm/src/code-mode/sandbox-api.js +36 -0
  12. package/esm/src/code-mode/sandbox-core.d.ts +99 -21
  13. package/esm/src/code-mode/sandbox-core.d.ts.map +1 -1
  14. package/esm/src/code-mode/sandbox-core.js +926 -221
  15. package/esm/src/code-mode/sandbox-worker.d.ts +37 -0
  16. package/esm/src/code-mode/sandbox-worker.d.ts.map +1 -0
  17. package/esm/src/code-mode/sandbox-worker.js +140 -0
  18. package/esm/src/code-mode/sandbox.d.ts +142 -29
  19. package/esm/src/code-mode/sandbox.d.ts.map +1 -1
  20. package/esm/src/code-mode/sandbox.js +399 -67
  21. package/esm/src/code-mode/surface.d.ts +148 -0
  22. package/esm/src/code-mode/surface.d.ts.map +1 -0
  23. package/esm/src/code-mode/surface.js +204 -0
  24. package/esm/src/code-mode/tool.js +1 -1
  25. package/esm/src/code-mode/worker-host.d.ts +39 -11
  26. package/esm/src/code-mode/worker-host.d.ts.map +1 -1
  27. package/esm/src/code-mode/worker-host.js +100 -43
  28. package/esm/src/code-mode/worker-protocol.d.ts +45 -8
  29. package/esm/src/code-mode/worker-protocol.d.ts.map +1 -1
  30. package/esm/src/code-mode/worker-protocol.js +4 -2
  31. package/esm/src/version.d.ts +1 -1
  32. package/esm/src/version.js +1 -1
  33. package/package.json +9 -1
  34. package/script/src/code-mode/engine.d.ts +59 -0
  35. package/script/src/code-mode/engine.d.ts.map +1 -0
  36. package/script/src/code-mode/engine.js +198 -0
  37. package/script/src/code-mode/guest-worker.d.ts +2 -5
  38. package/script/src/code-mode/guest-worker.d.ts.map +1 -1
  39. package/script/src/code-mode/guest-worker.js +4 -98
  40. package/script/src/code-mode/sandbox-api.d.ts +37 -0
  41. package/script/src/code-mode/sandbox-api.d.ts.map +1 -0
  42. package/script/src/code-mode/sandbox-api.js +50 -0
  43. package/script/src/code-mode/sandbox-core.d.ts +99 -21
  44. package/script/src/code-mode/sandbox-core.d.ts.map +1 -1
  45. package/script/src/code-mode/sandbox-core.js +931 -221
  46. package/script/src/code-mode/sandbox-worker.d.ts +37 -0
  47. package/script/src/code-mode/sandbox-worker.d.ts.map +1 -0
  48. package/script/src/code-mode/sandbox-worker.js +166 -0
  49. package/script/src/code-mode/sandbox.d.ts +142 -29
  50. package/script/src/code-mode/sandbox.d.ts.map +1 -1
  51. package/script/src/code-mode/sandbox.js +429 -72
  52. package/script/src/code-mode/surface.d.ts +148 -0
  53. package/script/src/code-mode/surface.d.ts.map +1 -0
  54. package/script/src/code-mode/surface.js +211 -0
  55. package/script/src/code-mode/tool.js +1 -1
  56. package/script/src/code-mode/worker-host.d.ts +39 -11
  57. package/script/src/code-mode/worker-host.d.ts.map +1 -1
  58. package/script/src/code-mode/worker-host.js +100 -42
  59. package/script/src/code-mode/worker-protocol.d.ts +45 -8
  60. package/script/src/code-mode/worker-protocol.d.ts.map +1 -1
  61. package/script/src/code-mode/worker-protocol.js +4 -2
  62. package/script/src/version.d.ts +1 -1
  63. package/script/src/version.js +1 -1
@@ -6,23 +6,21 @@
6
6
  * @module code-mode/sandbox-core
7
7
  */
8
8
  import { Scope } from "quickjs-emscripten";
9
- import { CodeModeError } from "./errors.js";
10
- /** Default limits of a Code Mode program. */
11
- export const CODE_MODE_LIMITS = Object.freeze({
9
+ import { capInitialArena, didHitMemoryLimit, isWasmMemoryTrap, isWasmOom } from "./engine.js";
10
+ import { CodeModeError, codeModeErrorFromFields } from "./errors.js";
11
+ import { resolveSandboxSurface, surfaceUsesReferences } from "./surface.js";
12
+ /** Default resource limits of a program. */
13
+ export const SANDBOX_RESOURCE_LIMITS = Object.freeze({
12
14
  cpuMs: 2_000,
13
15
  wallMs: 30_000,
14
16
  memoryBytes: 12 * 1024 * 1024,
15
17
  stackBytes: 192 * 1024,
16
- providerCalls: 16,
17
- boardOperations: 48,
18
18
  valueLength: 128 * 1024,
19
19
  });
20
- /** Maximum source length accepted by the code-mode execute tool. */
20
+ /** Maximum length of a program's source, in UTF-16 code units. */
21
21
  export const maxCodeLength = 16_384;
22
- const PROVIDER_OPERATIONS = new Set(["listSnippets", "runSnippet"]);
23
- const BOARD_OPERATIONS = new Set(["panel", "sync"]);
24
22
  /** Serialize data crossing the QuickJS boundary within the supplied limit. */
25
- export function encodeValue(value, limit = CODE_MODE_LIMITS.valueLength) {
23
+ export function encodeValue(value, limit = SANDBOX_RESOURCE_LIMITS.valueLength) {
26
24
  const text = JSON.stringify(value);
27
25
  if (text === undefined || text.length > limit) {
28
26
  throw new RangeError("Expected a JSON value within the size limit.");
@@ -33,6 +31,41 @@ export function encodeValue(value, limit = CODE_MODE_LIMITS.valueLength) {
33
31
  export function receiptTooLarge(limit) {
34
32
  return new CodeModeError("RECEIPT_TOO_LARGE", `The operation returned more than ${limit} characters of JSON`, "Select a smaller result", { context: { limit } });
35
33
  }
34
+ /** The error for a host operation that rejected with nothing the program may read. */
35
+ export function operationFailed(namespace, operation) {
36
+ return new CodeModeError("OPERATION_FAILED", `${namespace}.${operation} failed`, "Check the arguments, then retry once", { context: { operation } });
37
+ }
38
+ /**
39
+ * The JSON text of a host operation's result, as it crosses into the program.
40
+ * Throws the error the program is given instead when the value is not JSON or
41
+ * exceeds the limit. This is the host's own serialization, outside the engine:
42
+ * a getter that throws, a cycle or even the host's stack running out fails the
43
+ * operation, and is no fault of the engine.
44
+ */
45
+ export function encodeHostValue(namespace, operation, value, limit) {
46
+ let text;
47
+ try {
48
+ // `undefined` is what a host operation with nothing to say returns.
49
+ text = JSON.stringify(value ?? null);
50
+ }
51
+ catch {
52
+ text = undefined;
53
+ }
54
+ if (text === undefined) {
55
+ throw new CodeModeError("OPERATION_FAILED", `${namespace}.${operation} returned a value that is not JSON`, "Return plain JSON from the host operation", { context: { operation } });
56
+ }
57
+ if (text.length > limit)
58
+ throw receiptTooLarge(limit);
59
+ return text;
60
+ }
61
+ /** The error for a run the sandbox itself could not carry through. */
62
+ export function sandboxFailure() {
63
+ return new CodeModeError("SANDBOX_FAILED", "The sandbox failed while running the program", "Run the program again");
64
+ }
65
+ /** The error for a program that finished with calls it did not wait for. */
66
+ export function unawaitedOperation(namespace, count) {
67
+ return new CodeModeError("UNAWAITED_OPERATION", `The program finished with ${count} ${namespace} ${count === 1 ? "call" : "calls"} it did not wait for. They were not sent`, `Put await before every ${namespace} call, or pass them to Promise.all; use Promise.allSettled when one of them may fail`, { context: { count } });
68
+ }
36
69
  /** Constant text: the message is the engine's, but a program could forge it. */
37
70
  function resourceLimitFor(limits, limit) {
38
71
  const memory = limit === "memory";
@@ -40,50 +73,187 @@ function resourceLimitFor(limits, limit) {
40
73
  ? `The program used more than ${limits.memoryBytes} bytes of memory`
41
74
  : `The program used more than ${limits.stackBytes} bytes of stack`, memory ? "Process less data per run" : "Avoid deep recursion", { context: { limit, bytes: memory ? limits.memoryBytes : limits.stackBytes } });
42
75
  }
43
- const GUEST_ERROR_FACTORY = `(() => {
44
- "use strict";
45
- const define = Object.defineProperty, freeze = Object.freeze, parse = JSON.parse;
46
- class CodeModeError extends Error {
47
- constructor(record) {
48
- super(record.message);
49
- define(this, "name", { value: "CodeModeError", writable: true, configurable: true });
50
- this.code = record.code;
51
- this.recovery = record.recovery;
52
- this.context = freeze(record.context);
53
- define(this, "ref", { value: record.ref });
76
+ /**
77
+ * How a host's own error travels through the sandbox. The program sees
78
+ * `shown`. The run fails with this carrier, whose context names the call, so
79
+ * the host finds the original error it kept: only the object the sandbox
80
+ * handed to the program maps back to it, never one the program built.
81
+ */
82
+ export class HostErrorCarrier extends CodeModeError {
83
+ shown;
84
+ constructor(namespace, operation, call, shown) {
85
+ const plain = operationFailed(namespace, operation);
86
+ super(plain.code, plain.detail, plain.recovery, { context: { operation, hostError: call } });
87
+ this.shown = shown;
54
88
  }
55
- }
56
- return (json) => new CodeModeError(parse(json));
57
- })()`;
58
- function guestProgram(code) {
59
- // Each api call is a lazy thenable: it reaches the host only when awaited,
60
- // so an operation the program forgets to await never runs.
89
+ }
90
+ /**
91
+ * True for the host's own stack overflow. The engine's native functions (JSON
92
+ * serialization of deeply nested data, for one) recurse on the host's stack,
93
+ * which QuickJS's stack limit does not measure: the host then throws through
94
+ * the engine instead of the engine raising its own `stack overflow`.
95
+ */
96
+ function isNativeStackOverflow(error) {
97
+ return error instanceof RangeError && /call stack|recursion/i.test(error.message);
98
+ }
99
+ function nativeStackExhausted() {
100
+ return new CodeModeError("RESOURCE_LIMIT", "The program nested data or calls deeper than the engine can follow", "Avoid deep recursion and deeply nested data", { context: { limit: "stack" } });
101
+ }
102
+ /**
103
+ * The program, compiled on its own: it is not nested in the scope that builds
104
+ * its surface, so it reaches nothing but the object it receives.
105
+ */
106
+ function guestProgram(code, namespace) {
107
+ return `(async function(${namespace}) { "use strict";\n${code}\n})`;
108
+ }
109
+ /**
110
+ * The sandbox's own code inside the program's realm. It runs before any
111
+ * program text and keeps the intrinsics it needs. Afterwards it reads nothing
112
+ * through a prototype: a program can replace `Array.prototype[1]`,
113
+ * `Object.prototype.get` or `Promise.prototype.then` without changing what
114
+ * this code does.
115
+ *
116
+ * It builds the frozen object a program receives (its constants, then its
117
+ * operations) and the functions the host keeps: to hand a result or an error
118
+ * to the program, and to recognise later the objects it handed over.
119
+ * `operations` lists each name with whether it starts when called.
120
+ */
121
+ function guestGlue(operations) {
61
122
  return `(() => {
62
- const declare = globalThis.__declare, start = globalThis.__start, params = globalThis.__params;
123
+ "use strict";
124
+ const declare = globalThis.__declare, start = globalThis.__start;
125
+ const constants = globalThis.__constants, referenceKey = globalThis.__referenceKey;
63
126
  delete globalThis.__declare;
64
127
  delete globalThis.__start;
65
- delete globalThis.__params;
66
- const freeze = Object.freeze;
67
- const lazy = (id) => {
68
- let promise;
69
- const run = () => (promise ??= start(id));
70
- return freeze({
71
- then: (onFulfilled, onRejected) => run().then(onFulfilled, onRejected),
72
- catch: (onRejected) => run().catch(onRejected),
73
- finally: (onFinally) => run().finally(onFinally),
128
+ delete globalThis.__constants;
129
+ delete globalThis.__referenceKey;
130
+ const define = Object.defineProperty, freeze = Object.freeze, keys = Object.keys;
131
+ const parse = JSON.parse, stringify = JSON.stringify, NewPromise = Promise;
132
+ const NewTypeError = TypeError;
133
+ const promiseThen = Function.prototype.call.bind(NewPromise.prototype.then);
134
+ const tracked = referenceKey !== undefined;
135
+ // Result tracking holds an object only as long as the program keeps it.
136
+ const results = new WeakMap();
137
+ const callOfResult = WeakMap.prototype.get.bind(results);
138
+ const keepResult = WeakMap.prototype.set.bind(results);
139
+ const isObject = (value) => typeof value === "object" && value !== null;
140
+ // Defined, never assigned, and with a descriptor that has no prototype. An
141
+ // assignment would go through the prototype of the target, and a plain
142
+ // descriptor would inherit get, set or a flag from Object.prototype.
143
+ const own = (target, name, value, enumerable) =>
144
+ define(target, name, { __proto__: null, value, writable: true, enumerable, configurable: true });
145
+ // Errors carry their host fields in a private field, not a WeakMap: QuickJS
146
+ // frees private fields immediately on refcount zero, whereas WeakMap records
147
+ // wait for mark-and-sweep GC. The secret stops guest code from forging one
148
+ // through error.constructor.
149
+ const secret = {};
150
+ class CodeModeError extends Error {
151
+ #fields;
152
+ constructor(record, fields, token) {
153
+ if (token !== secret) throw new NewTypeError("CodeModeError cannot be constructed directly");
154
+ super();
155
+ this.#fields = fields;
156
+ own(this, "message", record.message, false);
157
+ own(this, "name", "CodeModeError", false);
158
+ own(this, "code", record.code, true);
159
+ own(this, "recovery", record.recovery, true);
160
+ own(this, "context", freeze(record.context), true);
161
+ }
162
+ static fieldsOf(value) {
163
+ return isObject(value) && #fields in value ? value.#fields : undefined;
164
+ }
165
+ }
166
+ const fieldsOf = CodeModeError.fieldsOf;
167
+ freeze(CodeModeError.prototype);
168
+ freeze(CodeModeError);
169
+ // The host recognises an error it handed over by its private field, not by a
170
+ // visible property: the program can neither read, remove nor forge it.
171
+ const makeError = (shown, fields) => new CodeModeError(parse(shown), fields, secret);
172
+ // A result the program can designate must stay what the host kept. The
173
+ // reviver receives every value once, children first: each object is frozen
174
+ // as it is built, with no loop here and no property read through a prototype.
175
+ const frozen = (key, value) => freeze(value);
176
+ const receive = tracked
177
+ ? (json, call) => {
178
+ const value = parse(json, frozen);
179
+ if (isObject(value)) keepResult(value, call);
180
+ return value;
181
+ }
182
+ : (json) => parse(json);
183
+ // Whatever needs room in the engine is made before the host hears of the
184
+ // call. If the engine has none, the program gets the engine's exception and
185
+ // no call was made, or none was started. The host keeps the two functions
186
+ // that settle the promise.
187
+ const promised = () => {
188
+ let resolve, reject;
189
+ const promise = new NewPromise((onResolve, onReject) => {
190
+ resolve = onResolve;
191
+ reject = onReject;
74
192
  });
193
+ return (id) => {
194
+ start(id, resolve, reject);
195
+ return promise;
196
+ };
197
+ };
198
+ // A call is a lazy thenable unless its operation starts when called: it
199
+ // reaches the host only when awaited, so one the program forgets never runs.
200
+ const operation = (name, onCall) => onCall
201
+ ? (...args) => {
202
+ const begin = promised();
203
+ return begin(declare(name, args));
204
+ }
205
+ : (...args) => {
206
+ let id, promise;
207
+ const run = () => (promise ??= promised()(id));
208
+ const thenable = freeze({
209
+ then: (onFulfilled, onRejected) => promiseThen(run(), onFulfilled, onRejected),
210
+ catch: (onRejected) => promiseThen(run(), undefined, onRejected),
211
+ finally: (onFinally) =>
212
+ typeof onFinally === "function"
213
+ ? promiseThen(
214
+ run(),
215
+ (value) => promiseThen(new NewPromise((r) => r(onFinally())), () => value),
216
+ (reason) =>
217
+ promiseThen(new NewPromise((r) => r(onFinally())), () => {
218
+ throw reason;
219
+ }),
220
+ )
221
+ : promiseThen(run(), onFinally, onFinally),
222
+ });
223
+ id = declare(name, args);
224
+ return thenable;
225
+ };
226
+ const callOf = (value) => isObject(value) ? callOfResult(value) : undefined;
227
+ const reference = (key, value) => {
228
+ const call = callOf(value);
229
+ return call === undefined ? value : { __proto__: null, [referenceKey]: call };
75
230
  };
76
- const operation = (name) => (...args) => lazy(declare(name, args));
77
- const api = freeze({
78
- params,
79
- listSnippets: operation("listSnippets"),
80
- runSnippet: operation("runSnippet"),
81
- panel: operation("panel"),
82
- sync: operation("sync"),
231
+ const surface = {};
232
+ const given = parse(constants);
233
+ for (const name of keys(given)) own(surface, name, given[name], true);
234
+ for (const [name, onCall] of ${JSON.stringify(operations)}) own(surface, name, operation(name, onCall), true);
235
+ return freeze({
236
+ __proto__: null,
237
+ surface: freeze(surface),
238
+ stringify: (value) => stringify(value),
239
+ encode: (value) => stringify(value, reference),
240
+ makeError,
241
+ fieldsOf,
242
+ callOf,
243
+ // The value is built before the promise settles: if the engine has no
244
+ // room for it, the call is still open, and the host can refuse it.
245
+ deliver: (resolve, json, id) => { resolve(receive(json, id)); },
246
+ refuse: (reject, shown, fields) => { reject(makeError(shown, fields)); },
247
+ readProp: (target, key) => target[key],
83
248
  });
84
- return (async function(api) { "use strict";\n${code}\n})(api);
85
249
  })()`;
86
250
  }
251
+ /** `a`, `a and b`, `a, b and c`. */
252
+ function listed(names) {
253
+ if (names.length < 2)
254
+ return names.join("");
255
+ return `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
256
+ }
87
257
  /** Error names a program may report. Any other name is reported as `Error`. */
88
258
  const STANDARD_ERROR_NAMES = new Set([
89
259
  "Error",
@@ -103,33 +273,82 @@ function cap(text, length) {
103
273
  const flat = text.replace(/\s+/g, " ").trim();
104
274
  return flat.length > length ? `${flat.slice(0, length - 1)}…` : flat;
105
275
  }
276
+ /** The JSON text of the record of constants, from the JSON text of each. */
277
+ function constantsText(constants = {}) {
278
+ const members = Object.entries(constants).map(([name, text]) => {
279
+ if (typeof text !== "string") {
280
+ throw new RangeError(`Sandbox constant ${name} must reach the driver as JSON text.`);
281
+ }
282
+ return `${JSON.stringify(name)}:${text}`;
283
+ });
284
+ return `{${members.join(",")}}`;
285
+ }
106
286
  /**
107
- * Run a function body in an isolated QuickJS context. Only JSON and the four
108
- * `api` operations cross into the host. Failures are {@link CodeModeError}s.
287
+ * A host error as it crosses into the program: by its fields, the same in
288
+ * both isolations. A carrier keeps what it shows. Anything that is not a
289
+ * sandbox error does not cross.
290
+ */
291
+ function crossing(error) {
292
+ if (error instanceof HostErrorCarrier)
293
+ return error;
294
+ if (!(error instanceof CodeModeError))
295
+ return undefined;
296
+ return codeModeErrorFromFields(CodeModeError.prototype.toJSON.call(error));
297
+ }
298
+ /**
299
+ * Run a function body in an isolated QuickJS context. Only JSON text and the
300
+ * operations its surface declares cross into the host. Resolves to the JSON
301
+ * text of what the program returned, or to undefined when it returned
302
+ * nothing. Failures are {@link CodeModeError}s.
109
303
  *
110
304
  * @example
111
305
  * ```ts
112
- * const value = await runVm({
113
- * quickjs: await getQuickJS(),
114
- * code: "return api.params.n * 2;",
115
- * params: { n: 21 },
116
- * limits: CODE_MODE_LIMITS,
306
+ * const json = await runVm({
307
+ * quickjs: await newEngine(),
308
+ * code: "return shop.params.n * 2;",
309
+ * surface: { namespace: "shop", constants: { params: '{"n":21}' }, operations: {}, budgets: {} },
310
+ * limits: SANDBOX_RESOURCE_LIMITS,
117
311
  * call: () => Promise.reject(new Error("unused")),
118
312
  * isCancelled: () => false,
119
313
  * });
120
314
  * ```
121
315
  */
122
- export function runVm(options) {
123
- const { quickjs, code, params, limits, call, isCancelled } = options;
124
- return Scope.withScopeAsync(async (scope) => {
316
+ export async function runVm(options) {
317
+ const { quickjs, code, limits, call, isCancelled } = options;
318
+ // Checked here too, not only by the caller: an operation whose budget is
319
+ // not listed would otherwise have no limit, and the names go into source.
320
+ // Before the VM exists, so a configuration error is never taken for an engine fault.
321
+ const surface = resolveSandboxSurface(options.surface);
322
+ const constants = constantsText(surface.constants);
323
+ const tracksResults = surfaceUsesReferences(surface);
324
+ const referenceKey = options.referenceKey;
325
+ if (tracksResults && (typeof referenceKey !== "string" || !referenceKey)) {
326
+ throw new RangeError("A sandbox surface that uses references needs a reference key.");
327
+ }
328
+ const scope = new Scope();
329
+ /** True once the engine may hold state it cannot release: its handles are abandoned, not disposed. */
330
+ let faulted = false;
331
+ /** The first fault the sandbox recognised: the run ends with it, whatever follows. */
332
+ let faultCause;
333
+ /** Frees any C-heap padding reserved inside the initial 16 MiB WASM memory. */
334
+ let releaseArena = () => { };
335
+ const drive = async () => {
336
+ const namespace = surface.namespace;
337
+ const operationNames = Object.keys(surface.operations);
125
338
  const keep = (handle) => scope.manage(handle);
339
+ /** Release a handle the sandbox owns. After a fault the engine may not be able to release anything. */
340
+ const drop = (handle) => {
341
+ if (!faulted && handle.alive)
342
+ handle.dispose();
343
+ };
126
344
  const vm = scope.manage(quickjs.newContext());
127
345
  let cpuDeadline = performance.now() + limits.cpuMs;
128
346
  let cpuExpired = false;
129
347
  vm.runtime.setMemoryLimit(limits.memoryBytes);
130
348
  vm.runtime.setMaxStackSize(limits.stackBytes);
349
+ let fatal;
131
350
  vm.runtime.setInterruptHandler(() => {
132
- if (isCancelled())
351
+ if (fatal || isCancelled())
133
352
  return true;
134
353
  if (performance.now() >= cpuDeadline)
135
354
  cpuExpired = true;
@@ -140,137 +359,390 @@ export function runVm(options) {
140
359
  return new CodeModeError("INTERRUPTED", "The program was stopped before it finished", "Run it again if the result is still needed");
141
360
  }
142
361
  if (cpuExpired || performance.now() >= cpuDeadline) {
143
- return new CodeModeError("TIME_LIMIT", `The program used its ${limits.cpuMs} ms of CPU time`, "Do less work per run, or split it into several execute calls", { context: { limit: "cpu", ms: limits.cpuMs } });
362
+ return new CodeModeError("TIME_LIMIT", `The program used its ${limits.cpuMs} ms of CPU time`, "Do less work per run, or split it into several runs", { context: { limit: "cpu", ms: limits.cpuMs } });
144
363
  }
145
364
  return undefined;
146
365
  }
147
- const stringify = keep(vm.unwrapResult(vm.evalCode("JSON.stringify.bind(JSON)")));
148
- const parse = keep(vm.unwrapResult(vm.evalCode("JSON.parse.bind(JSON)")));
149
- const makeError = keep(vm.unwrapResult(vm.evalCode(GUEST_ERROR_FACTORY)));
150
- /** Errors handed to the guest, so an uncaught one maps back to the host record. */
151
- const records = [];
366
+ // Made before the program runs: reading the name or the message of what
367
+ // it throws must not need memory the program may have used up.
368
+ const nameKey = keep(vm.newString("name"));
369
+ const messageKey = keep(vm.newString("message"));
152
370
  const declared = new Map();
371
+ /** True once the program's own promise settled: none of its code is run for a call any more. */
372
+ let finished = false;
373
+ /**
374
+ * The limit error for a host stack overflow or a WebAssembly memory trap
375
+ * that surfaced inside one of our own calls into the engine, or undefined
376
+ * for any other error. The run ends with it even if the program catches
377
+ * what it is thrown.
378
+ */
379
+ function trapped(error) {
380
+ if (isNativeStackOverflow(error)) {
381
+ faulted = true;
382
+ faultCause ??= nativeStackExhausted();
383
+ return fatal ??= faultCause;
384
+ }
385
+ if (isWasmMemoryTrap(error)) {
386
+ faulted = true;
387
+ faultCause ??= resourceLimitFor(limits, "memory");
388
+ return fatal ??= faultCause;
389
+ }
390
+ return undefined;
391
+ }
392
+ /** Convert a host stack overflow, WASM trap or clean `_malloc` refusal into its limit error. */
393
+ function vmFailure(error) {
394
+ const trap = trapped(error);
395
+ if (trap)
396
+ return trap;
397
+ if (isWasmOom(error))
398
+ return resourceLimitFor(limits, "memory");
399
+ return error;
400
+ }
401
+ // Set once the sandbox's own script has run. That script needs the two
402
+ // host functions below, which need it in turn: they only run after it.
403
+ // deno-lint-ignore prefer-const
404
+ let glue;
405
+ /** Started calls, in the order they were started, waiting for their turn to reach the host. */
153
406
  const pending = [];
407
+ /** Calls of awaited operations that were still waiting when the program finished. */
408
+ const dropped = [];
154
409
  let nextId = 0;
155
- let providerCalls = 0;
156
- let boardOperations = 0;
157
- function readJson(handle, fail) {
158
- const result = vm.callFunction(stringify, vm.undefined, handle);
410
+ /** Calls made so far, per budget. */
411
+ const spent = new Map();
412
+ /** A guest string. The engine may have no room for it: that is the program's memory limit. */
413
+ function guestString(text) {
414
+ let handle;
415
+ try {
416
+ handle = vm.newString(text);
417
+ }
418
+ catch (error) {
419
+ throw vmFailure(error);
420
+ }
421
+ if (vm.typeof(handle) === "string")
422
+ return handle;
423
+ drop(handle);
424
+ throw resourceLimitFor(limits, "memory");
425
+ }
426
+ /**
427
+ * Call one of the sandbox's own functions inside the guest. A handle is
428
+ * lent; a string or a number is made for the call. None of these
429
+ * functions runs the program's code in a way that can fail the call, so
430
+ * a failure is the engine's: a stop, or a limit the program reached (it
431
+ * may be too far out of memory for the engine to say which: memory is
432
+ * then the answer). The caller owns the handle it gets.
433
+ */
434
+ function inGuest(fn, ...args) {
435
+ const made = [];
436
+ const make = (handle) => (made.push(handle), handle);
437
+ try {
438
+ const handles = args.map((arg) => {
439
+ if (typeof arg === "number") {
440
+ try {
441
+ return make(vm.newNumber(arg));
442
+ }
443
+ catch (error) {
444
+ throw vmFailure(error);
445
+ }
446
+ }
447
+ return typeof arg === "string" ? make(guestString(arg)) : arg;
448
+ });
449
+ let result;
450
+ try {
451
+ result = vm.callFunction(fn, vm.undefined, ...handles);
452
+ }
453
+ catch (error) {
454
+ throw vmFailure(error);
455
+ }
456
+ if (!result.error)
457
+ return result.value;
458
+ try {
459
+ const thrown = thrownBy(result.error);
460
+ if (thrown instanceof CodeModeError)
461
+ throw thrown;
462
+ // The engine throws null when it cannot even build its own error.
463
+ if (thrown.name === "InternalError" || vm.sameValue(result.error, vm.null)) {
464
+ throw resourceLimitFor(limits, "memory");
465
+ }
466
+ throw new Error(`The sandbox's own code failed with ${thrown.name}`);
467
+ }
468
+ finally {
469
+ drop(result.error);
470
+ }
471
+ }
472
+ finally {
473
+ made.forEach(drop);
474
+ }
475
+ }
476
+ /**
477
+ * The JSON text of a guest value, within the value limit. Serializing
478
+ * runs the program's code (`toJSON`, getters) and the engine's own. A
479
+ * limit it reached, a stop, or an error the host had handed to the
480
+ * program is the failure itself. What the program threw on its own is
481
+ * not quoted: `fail` makes the error, and a host that keeps a program's
482
+ * text out of its errors has one code to watch.
483
+ */
484
+ function jsonText(handle, fail, encoder = glue.stringify) {
485
+ let result;
486
+ try {
487
+ result = vm.callFunction(encoder, vm.undefined, handle);
488
+ }
489
+ catch (error) {
490
+ throw vmFailure(error);
491
+ }
159
492
  if (result.error) {
160
- // Serializing can exhaust the engine's own stack or memory (a recursive
161
- // `toJSON`): that is the program's resource limit, not an invalid value.
162
- const limit = engineLimit(result.error);
163
- result.error.dispose();
164
- throw halted() ?? limit ?? fail();
493
+ let thrown;
494
+ try {
495
+ thrown = thrownBy(result.error);
496
+ }
497
+ finally {
498
+ drop(result.error);
499
+ }
500
+ throw thrown instanceof CodeModeError ? thrown : fail();
165
501
  }
166
- const encoded = result.value;
167
502
  try {
168
- if (vm.typeof(encoded) !== "string")
503
+ if (vm.typeof(result.value) !== "string")
169
504
  throw fail();
170
- const text = vm.getString(encoded);
505
+ const text = vm.getString(result.value);
506
+ // JSON text is never empty: the engine had no room to hand it over.
507
+ if (!text)
508
+ throw resourceLimitFor(limits, "memory");
171
509
  if (text.length > limits.valueLength)
172
510
  throw fail();
173
- return JSON.parse(text);
511
+ return text;
174
512
  }
175
513
  finally {
176
- encoded.dispose();
514
+ drop(result.value);
177
515
  }
178
516
  }
179
- function toGuest(value) {
180
- const text = JSON.stringify(value ?? null);
181
- if (text.length > limits.valueLength)
182
- throw receiptTooLarge(limits.valueLength);
183
- const encoded = vm.newString(text);
184
- let result;
517
+ /** What the program is shown of a host error, and the fields the host finds it by. */
518
+ function shownAndFields(error) {
519
+ // A host's own error shows the program the host's words, not the carrier's.
520
+ const shown = error instanceof HostErrorCarrier ? error.shown : undefined;
521
+ return [
522
+ JSON.stringify({
523
+ message: shown?.message ?? error.message,
524
+ code: shown?.code ?? error.code,
525
+ recovery: shown?.recovery ?? error.recovery,
526
+ context: shown ? {} : error.context,
527
+ }),
528
+ JSON.stringify(CodeModeError.prototype.toJSON.call(error)),
529
+ ];
530
+ }
531
+ /**
532
+ * What a refused call throws into the program: the guest error built for
533
+ * `error`. When the engine cannot build it, the program unwinds with the
534
+ * engine's own exception (or `null` if even allocating the strings failed)
535
+ * and the run ends with that limit, whatever the program catches. The
536
+ * caller owns the handle.
537
+ */
538
+ function refusal(error) {
539
+ const handles = [];
185
540
  try {
186
- result = vm.callFunction(parse, vm.undefined, encoded);
541
+ for (const text of shownAndFields(error))
542
+ handles.push(guestString(text));
543
+ let built;
544
+ try {
545
+ built = vm.callFunction(glue.makeError, vm.undefined, ...handles);
546
+ }
547
+ catch (failure) {
548
+ const mapped = vmFailure(failure);
549
+ if (mapped instanceof CodeModeError) {
550
+ fatal ??= mapped;
551
+ return vm.null;
552
+ }
553
+ throw failure;
554
+ }
555
+ if (!built.error)
556
+ return built.value;
557
+ const thrown = thrownBy(built.error);
558
+ fatal ??= thrown instanceof CodeModeError ? thrown : resourceLimitFor(limits, "memory");
559
+ return built.error;
560
+ }
561
+ catch (failure) {
562
+ const mapped = vmFailure(failure);
563
+ if (mapped instanceof CodeModeError) {
564
+ fatal ??= mapped;
565
+ return vm.null;
566
+ }
567
+ throw failure;
187
568
  }
188
569
  finally {
189
- encoded.dispose();
570
+ handles.forEach(drop);
190
571
  }
191
- if (result.error) {
192
- // Decoding can exhaust the engine's own memory or stack: that is the
193
- // program's resource limit, not a failure of the host operation.
194
- const failure = fromGuest(keep(result.error));
195
- if (failure.code !== "GUEST_ERROR")
196
- throw failure;
197
- throw new Error("The host value could not be decoded");
572
+ }
573
+ /** Read a plain data string property without re-entering guest glue. */
574
+ function rawStringProp(handle, key) {
575
+ const value = vm.getProp(handle, key);
576
+ try {
577
+ return vm.typeof(value) === "string" ? vm.getString(value) : undefined;
578
+ }
579
+ finally {
580
+ drop(value);
198
581
  }
199
- return keep(result.value);
200
582
  }
201
583
  /**
202
- * A guest error object for this host error. The host keeps the handle to
203
- * recognise the object later; pass `.dup()` where QuickJS takes ownership.
584
+ * QuickJS throws `null` when it cannot even allocate `InternalError("out of memory")`.
585
+ * Check both our out-of-band WASM signal (in case unwinding freed local variables)
586
+ * and a live probe, so an intentional `throw null` stays `GUEST_ERROR`.
204
587
  */
205
- function guestError(error) {
206
- const json = vm.newString(JSON.stringify({
207
- message: error.message,
208
- code: error.code,
209
- recovery: error.recovery,
210
- context: error.context,
211
- ref: records.length,
212
- }));
588
+ function oomFromNull() {
589
+ if (didHitMemoryLimit(quickjs))
590
+ return resourceLimitFor(limits, "memory");
213
591
  try {
214
- const handle = keep(vm.unwrapResult(vm.callFunction(makeError, vm.undefined, json)));
215
- records.push({ error, handle });
216
- return handle;
592
+ const probe = vm.newString("x".repeat(256));
593
+ const ok = vm.typeof(probe) === "string";
594
+ drop(probe);
595
+ if (!ok)
596
+ return resourceLimitFor(limits, "memory");
217
597
  }
218
- finally {
219
- json.dispose();
598
+ catch (error) {
599
+ const mapped = vmFailure(error);
600
+ if (mapped instanceof CodeModeError)
601
+ return mapped;
602
+ return resourceLimitFor(limits, "memory");
220
603
  }
604
+ return undefined;
221
605
  }
606
+ /**
607
+ * Read `key` from a thrown guest object. Going through `glue.readProp`
608
+ * lets QuickJS surface a stack overflow or out-of-memory inside a getter
609
+ * instead of silently swallowing `JS_EXCEPTION`.
610
+ */
222
611
  function readString(handle, key) {
223
612
  try {
224
- const value = vm.getProp(handle, key);
613
+ if (!glue)
614
+ return rawStringProp(handle, key);
615
+ const result = vm.callFunction(glue.readProp, vm.undefined, handle, key);
616
+ if (result.error) {
617
+ try {
618
+ if (isCancelled())
619
+ return halted();
620
+ if (fatal)
621
+ return fatal;
622
+ const stop = halted();
623
+ if (stop)
624
+ return stop;
625
+ if (vm.sameValue(result.error, vm.null))
626
+ return oomFromNull();
627
+ if (vm.typeof(result.error) === "object") {
628
+ const name = rawStringProp(result.error, nameKey);
629
+ const message = rawStringProp(result.error, messageKey);
630
+ const limit = name === "InternalError" && message
631
+ ? ENGINE_LIMITS.get(message)
632
+ : undefined;
633
+ if (limit)
634
+ return resourceLimitFor(limits, limit);
635
+ }
636
+ return undefined;
637
+ }
638
+ finally {
639
+ drop(result.error);
640
+ }
641
+ }
225
642
  try {
226
- return vm.typeof(value) === "string" ? vm.getString(value) : undefined;
643
+ return vm.typeof(result.value) === "string" ? vm.getString(result.value) : undefined;
227
644
  }
228
645
  finally {
229
- value.dispose();
646
+ drop(result.value);
230
647
  }
231
648
  }
232
- catch {
649
+ catch (error) {
650
+ // Reading a property runs guest code: a getter can overflow the host's
651
+ // stack or trigger a WASM memory limit inside the engine.
652
+ const mapped = vmFailure(error);
653
+ if (mapped instanceof CodeModeError) {
654
+ if (faulted)
655
+ throw mapped;
656
+ return mapped;
657
+ }
233
658
  return undefined;
234
659
  }
235
660
  }
236
- /** The resource-limit error for an engine failure such as `stack overflow`, if it is one. */
237
- function engineLimit(handle) {
238
- if (vm.typeof(handle) !== "object" || readString(handle, "name") !== "InternalError") {
661
+ /**
662
+ * The host error this very object was built for. Only an object the
663
+ * sandbox built has one; the lookup runs none of the program's code.
664
+ */
665
+ function issuedError(handle) {
666
+ if (!glue)
239
667
  return undefined;
668
+ let found;
669
+ try {
670
+ found = vm.callFunction(glue.fieldsOf, vm.undefined, handle);
671
+ }
672
+ catch (error) {
673
+ const mapped = vmFailure(error);
674
+ if (mapped instanceof CodeModeError) {
675
+ if (faulted)
676
+ throw mapped;
677
+ return mapped;
678
+ }
679
+ throw error;
680
+ }
681
+ if (found.error) {
682
+ drop(found.error);
683
+ return undefined;
684
+ }
685
+ try {
686
+ if (vm.typeof(found.value) !== "string")
687
+ return undefined;
688
+ const text = vm.getString(found.value);
689
+ // Serialized fields JSON is never empty: empty means QuickJS ran out of memory reading it.
690
+ if (!text)
691
+ return resourceLimitFor(limits, "memory");
692
+ return codeModeErrorFromFields(JSON.parse(text));
693
+ }
694
+ finally {
695
+ drop(found.value);
240
696
  }
241
- const limit = ENGINE_LIMITS.get(readString(handle, "message") ?? "");
242
- return limit ? resourceLimitFor(limits, limit) : undefined;
243
697
  }
244
698
  /** Map a value thrown inside the guest to a host error. */
245
699
  function fromGuest(handle) {
700
+ const thrown = thrownBy(handle);
701
+ if (thrown instanceof CodeModeError)
702
+ return thrown;
703
+ const { name, message } = thrown;
704
+ // The guest can only see values the model may also see (it can return
705
+ // them), so its own error text is safe to report, capped.
706
+ return new CodeModeError("GUEST_ERROR", message ? `The program threw ${name}: ${cap(message, 300)}` : `The program threw ${name}`, "Fix the program and run it again", { context: { name } });
707
+ }
708
+ /**
709
+ * What a value thrown inside the guest is: an error of the sandbox (a
710
+ * stop, a limit, an error the host had handed to the program), or the
711
+ * program's own, by its name and message. A program can imitate the
712
+ * engine's limit errors, which are ordinary objects: it then reports a
713
+ * limit it did not reach, in the sandbox's words, and gains nothing.
714
+ */
715
+ function thrownBy(handle) {
716
+ if (isCancelled())
717
+ return halted();
718
+ if (fatal)
719
+ return fatal;
246
720
  const stop = halted();
247
721
  if (stop)
248
722
  return stop;
249
723
  let name = "Error";
250
724
  let message = "";
725
+ if (vm.sameValue(handle, vm.null)) {
726
+ return oomFromNull() ?? { name, message };
727
+ }
251
728
  if (vm.typeof(handle) === "object") {
252
- try {
253
- const refHandle = vm.getProp(handle, "ref");
254
- try {
255
- if (vm.typeof(refHandle) === "number") {
256
- // Only the very object the host created maps back to its record.
257
- const record = records[vm.getNumber(refHandle)];
258
- if (record && vm.sameValue(record.handle, handle))
259
- return record.error;
260
- }
261
- }
262
- finally {
263
- refHandle.dispose();
264
- }
265
- }
266
- catch {
267
- // A hostile getter: fall through to an untyped guest error.
268
- }
269
- const guestName = readString(handle, "name");
729
+ const issued = issuedError(handle);
730
+ if (issued)
731
+ return issued;
732
+ const guestName = readString(handle, nameKey);
733
+ if (guestName instanceof CodeModeError)
734
+ return guestName;
270
735
  if (guestName && STANDARD_ERROR_NAMES.has(guestName))
271
736
  name = guestName;
272
- message = readString(handle, "message") ?? "";
737
+ const guestMessage = readString(handle, messageKey);
738
+ if (guestMessage instanceof CodeModeError)
739
+ return guestMessage;
740
+ message = guestMessage ?? "";
273
741
  // Reading a property runs guest getters: they may have crossed the limits.
742
+ if (isCancelled())
743
+ return halted();
744
+ if (fatal)
745
+ return fatal;
274
746
  const late = halted();
275
747
  if (late)
276
748
  return late;
@@ -281,144 +753,377 @@ export function runVm(options) {
281
753
  const limit = name === "InternalError" ? ENGINE_LIMITS.get(message) : undefined;
282
754
  if (limit)
283
755
  return resourceLimitFor(limits, limit);
284
- // The guest can only see values the model may also see (it can return
285
- // them), so its own error text is safe to report, capped.
286
- return new CodeModeError("GUEST_ERROR", message ? `The program threw ${name}: ${cap(message, 300)}` : `The program threw ${name}`, "Fix the program and run it again", { context: { name } });
756
+ return { name, message };
287
757
  }
288
758
  const declare = keep(vm.newFunction("declare", (nameHandle, argsHandle) => {
289
- const operation = vm.typeof(nameHandle) === "string" ? vm.getString(nameHandle) : "";
290
- const provider = PROVIDER_OPERATIONS.has(operation);
291
- if (!provider && !BOARD_OPERATIONS.has(operation)) {
759
+ if (fatal)
760
+ return { error: vm.null };
761
+ // Only the sandbox's own script calls this, with a name of the table it was built from.
762
+ const operation = vm.getString(nameHandle);
763
+ const declaration = surface.operations[operation];
764
+ const budget = declaration.budget;
765
+ const limit = surface.budgets[budget];
766
+ const used = spent.get(budget) ?? 0;
767
+ if (used >= limit) {
768
+ const members = operationNames.filter((name) => surface.operations[name].budget === budget);
292
769
  return {
293
- error: guestError(new CodeModeError("ARGUMENT_INVALID", "Unknown api operation", "Use api.listSnippets, api.runSnippet, api.panel or api.sync")).dup(),
294
- };
295
- }
296
- const used = provider ? ++providerCalls : ++boardOperations;
297
- const limit = provider ? limits.providerCalls : limits.boardOperations;
298
- if (used > limit) {
299
- return {
300
- error: guestError(new CodeModeError("OPERATION_LIMIT", provider
301
- ? `A program can make at most ${limit} provider calls (listSnippets and runSnippet)`
302
- : `A program can make at most ${limit} board operations (panel and sync)`, "Split the work into several execute calls, or save the chain and replay it", { context: { budget: provider ? "provider" : "board", limit } })).dup(),
770
+ error: refusal(new CodeModeError("OPERATION_LIMIT", `A program can make at most ${limit} ${budget} calls (${listed(members)})`, "Make fewer calls per run, or split the work into several runs", { context: { budget, limit } })),
303
771
  };
304
772
  }
773
+ // The place is taken before the arguments are read: reading them runs
774
+ // the program's code, which can make calls of its own. A call that is
775
+ // refused here was not made, and gives its place back.
776
+ spent.set(budget, used + 1);
777
+ const release = () => spent.set(budget, spent.get(budget) - 1);
305
778
  let args;
306
779
  try {
307
- args = readJson(argsHandle, () => new CodeModeError("ARGUMENT_INVALID", `The arguments of api.${operation} are not JSON within ${limits.valueLength} characters`, "Pass plain JSON values", { context: { operation, limit: limits.valueLength } }));
780
+ args = jsonText(argsHandle, () => new CodeModeError("ARGUMENT_INVALID", `The arguments of ${namespace}.${operation} are not JSON within ${limits.valueLength} characters`, "Pass plain JSON values", { context: { operation, limit: limits.valueLength } }),
781
+ // An earlier result becomes a record that designates its call.
782
+ declaration.resultArguments === "reference" ? glue.encode : undefined);
308
783
  }
309
784
  catch (error) {
310
- return { error: guestError(error).dup() };
785
+ release();
786
+ const mapped = vmFailure(error);
787
+ // After a fault or clean WASM OOM inside the callback, avoid letting a
788
+ // host error escape back into QuickJS FFI.
789
+ if (faulted) {
790
+ fatal ??= mapped instanceof CodeModeError ? mapped : faultCause;
791
+ return { error: vm.null };
792
+ }
793
+ if (!(mapped instanceof CodeModeError))
794
+ throw error;
795
+ return { error: refusal(mapped) };
311
796
  }
312
- if (!Array.isArray(args)) {
797
+ // The text of a list opens with a bracket. Anything else means the
798
+ // program replaced how its arguments serialize.
799
+ if (!args.startsWith("[")) {
800
+ release();
313
801
  return {
314
- error: guestError(new CodeModeError("ARGUMENT_INVALID", `The arguments of api.${operation} did not serialize as a list`, "Do not override Array.prototype.toJSON", { context: { operation } })).dup(),
802
+ error: refusal(new CodeModeError("ARGUMENT_INVALID", `The arguments of ${namespace}.${operation} did not serialize as a list`, "Do not override Array.prototype.toJSON", { context: { operation } })),
315
803
  };
316
804
  }
317
805
  const id = nextId++;
318
- // Arguments are copied now, so later changes by the program do not reach the host.
319
- declared.set(id, { operation, args: args });
320
- return vm.newNumber(id);
806
+ let idHandle;
807
+ try {
808
+ idHandle = vm.newNumber(id);
809
+ }
810
+ catch (error) {
811
+ release();
812
+ const mapped = vmFailure(error);
813
+ if (mapped instanceof CodeModeError) {
814
+ fatal ??= mapped;
815
+ return { error: vm.null };
816
+ }
817
+ throw error;
818
+ }
819
+ // The text is taken now, so later changes by the program do not reach the host.
820
+ declared.set(id, { operation, args, onCall: declaration.start === "on-call" });
821
+ return idHandle;
321
822
  }));
322
- const start = keep(vm.newFunction("start", (idHandle) => {
323
- const id = vm.typeof(idHandle) === "number" ? vm.getNumber(idHandle) : -1;
823
+ const start = keep(vm.newFunction("start", (idHandle, resolveHandle, rejectHandle) => {
824
+ if (fatal)
825
+ return vm.undefined;
826
+ // Only the sandbox's own script calls this, once for each id `declare`
827
+ // gave it, with the two functions that settle the promise of the call.
828
+ const id = vm.getNumber(idHandle);
324
829
  const entry = declared.get(id);
325
- if (!entry) {
326
- return {
327
- error: guestError(new CodeModeError("ARGUMENT_INVALID", "Unknown operation", "Await each api call once")).dup(),
328
- };
329
- }
330
830
  declared.delete(id);
331
- const deferred = scope.manage(vm.newPromise());
332
- pending.push(async () => {
831
+ const resolve = keep(resolveHandle.dup());
832
+ const reject = keep(rejectHandle.dup());
833
+ const run = async () => {
333
834
  try {
334
835
  // Only the wait for the host is excluded from guest CPU time: credit it back
335
836
  // before QuickJS parses the result or runs the settlement.
336
837
  const before = performance.now();
337
- let value;
838
+ let json;
338
839
  try {
339
- value = await call(entry.operation, entry.args);
840
+ json = await call(entry.operation, entry.args, id);
340
841
  }
341
842
  finally {
342
843
  cpuDeadline += performance.now() - before;
343
844
  }
344
- deferred.resolve(toGuest(value));
845
+ // The program has finished: none of its code runs any more, and
846
+ // handing it a value would run some. A promise that resolves reads
847
+ // the `then` of its value, which the program may have left on a prototype.
848
+ if (finished)
849
+ return;
850
+ // The object the program receives is the one it can designate later.
851
+ drop(inGuest(glue.deliver, resolve, json, id));
345
852
  }
346
853
  catch (error) {
347
- deferred.reject(guestError(error instanceof CodeModeError ? error : new CodeModeError("OPERATION_FAILED", `api.${entry.operation} failed`, "Check the arguments, then retry once", { context: { operation: entry.operation } })));
854
+ const trap = trapped(error);
855
+ if (trap)
856
+ throw trap;
857
+ if (faulted)
858
+ throw fatal ?? error;
859
+ const failure = crossing(isWasmOom(error) ? resourceLimitFor(limits, "memory") : error) ??
860
+ operationFailed(namespace, entry.operation);
861
+ // The program did not have to await this call, so it may never see a
862
+ // rejection: the failure ends the run, before any later call is sent.
863
+ // So does a failure to hand over the result of a call the host has
864
+ // completed and cannot undo: the program must not be invited to repeat it.
865
+ if (entry.onCall || finished || options.mustDeliver?.(id)) {
866
+ fatal ??= failure;
867
+ return;
868
+ }
869
+ try {
870
+ drop(inGuest(glue.refuse, reject, ...shownAndFields(failure)));
871
+ }
872
+ catch (unbuilt) {
873
+ // The engine has no room for the error either: the run ends with that limit.
874
+ const mapped = vmFailure(unbuilt);
875
+ if (!(mapped instanceof CodeModeError))
876
+ throw unbuilt;
877
+ fatal ??= mapped;
878
+ }
348
879
  }
349
- });
350
- return deferred.handle.dup();
880
+ finally {
881
+ drop(resolve);
882
+ drop(reject);
883
+ }
884
+ };
885
+ pending.push({ id, ...entry, run });
886
+ return vm.undefined;
351
887
  }));
352
888
  vm.setProp(vm.global, "__declare", declare);
353
889
  vm.setProp(vm.global, "__start", start);
354
- vm.setProp(vm.global, "__params", toGuest(params));
355
- const evaluated = vm.evalCode(guestProgram(code), "mcpview-code-mode.js", { type: "global" });
356
- if (evaluated.error)
357
- throw fromGuest(keep(evaluated.error));
358
- const promise = keep(evaluated.value);
359
- let result;
890
+ // For limits below the mandatory 16 MiB WASM floor, reserve the surplus C
891
+ // heap now so constants, guest glue and the program all observe `memoryBytes`.
892
+ releaseArena = capInitialArena(quickjs, limits.memoryBytes);
893
+ // Each constant fits the value limit; together they may not, so only the VM's memory bounds them.
894
+ vm.setProp(vm.global, "__constants", keep(guestString(constants)));
895
+ if (tracksResults)
896
+ vm.setProp(vm.global, "__referenceKey", keep(guestString(referenceKey)));
897
+ // The sandbox's own script runs first, with the engine's intrinsics: no
898
+ // program text has been evaluated yet, not even one that closes its wrapper early.
899
+ let built;
900
+ try {
901
+ built = vm.evalCode(guestGlue(operationNames.map((name) => [name, surface.operations[name].start === "on-call"])), "mcpview-code-mode-surface.js", { type: "global" });
902
+ }
903
+ catch (error) {
904
+ throw vmFailure(error);
905
+ }
906
+ if (built.error)
907
+ throw fromGuest(keep(built.error));
908
+ const made = keep(built.value);
909
+ const surfaceObject = keep(vm.getProp(made, "surface"));
910
+ glue = {
911
+ stringify: keep(vm.getProp(made, "stringify")),
912
+ encode: keep(vm.getProp(made, "encode")),
913
+ makeError: keep(vm.getProp(made, "makeError")),
914
+ fieldsOf: keep(vm.getProp(made, "fieldsOf")),
915
+ callOf: keep(vm.getProp(made, "callOf")),
916
+ deliver: keep(vm.getProp(made, "deliver")),
917
+ refuse: keep(vm.getProp(made, "refuse")),
918
+ readProp: keep(vm.getProp(made, "readProp")),
919
+ };
920
+ /** The call whose result this very object is, when the surface reports returned results. */
921
+ function returnedCall(handle) {
922
+ if (!tracksResults || surface.returnedResult !== "reference")
923
+ return undefined;
924
+ let found;
925
+ try {
926
+ found = vm.callFunction(glue.callOf, vm.undefined, handle);
927
+ }
928
+ catch (error) {
929
+ throw vmFailure(error);
930
+ }
931
+ if (found.error) {
932
+ drop(found.error);
933
+ return undefined;
934
+ }
935
+ try {
936
+ return vm.typeof(found.value) === "number" ? vm.getNumber(found.value) : undefined;
937
+ }
938
+ finally {
939
+ drop(found.value);
940
+ }
941
+ }
942
+ let compiled;
943
+ try {
944
+ compiled = vm.evalCode(guestProgram(code, namespace), "mcpview-code-mode.js", {
945
+ type: "global",
946
+ });
947
+ }
948
+ catch (error) {
949
+ throw vmFailure(error);
950
+ }
951
+ if (compiled.error)
952
+ throw fromGuest(keep(compiled.error));
953
+ const program = keep(compiled.value);
954
+ // A program that ends the wrapper itself gains nothing: what follows is
955
+ // evaluated at top level, where the sandbox left nothing. Whatever
956
+ // function that leaves here is called in the program's place, with the
957
+ // same object, and must return a promise like the wrapper does. Anything
958
+ // else is refused with a clear error.
959
+ const notOneBody = () => new CodeModeError("RESULT_INVALID", "The program did not run as one function body", "Send only the statements of the body, without closing it");
960
+ if (vm.typeof(program) !== "function")
961
+ throw notOneBody();
962
+ let started;
963
+ try {
964
+ started = vm.callFunction(program, vm.undefined, surfaceObject);
965
+ }
966
+ catch (error) {
967
+ throw vmFailure(error);
968
+ }
969
+ if (started.error)
970
+ throw fromGuest(keep(started.error));
971
+ const promise = keep(started.value);
972
+ const first = vm.getPromiseState(promise);
973
+ if (first.type === "fulfilled") {
974
+ // For a value that is no promise, the state hands back the handle itself.
975
+ if (first.notAPromise)
976
+ throw notOneBody();
977
+ first.value.dispose();
978
+ }
979
+ else if (first.type === "rejected")
980
+ first.error.dispose();
981
+ /** The next started call that goes to the host although the program has finished. */
982
+ function nextPromisedCall() {
983
+ for (;;) {
984
+ const call = pending.shift();
985
+ if (!call || call.onCall)
986
+ return call;
987
+ dropped.push(call);
988
+ }
989
+ }
990
+ /**
991
+ * What the program returned: the JSON text of its value. One that is not
992
+ * JSON is `invalid`, and waits for what the host says of unsent calls. A
993
+ * limit, a stop or a host error met while the value is read is recorded as
994
+ * `thrown` so any `"on-call"` operation queued while reading still runs
995
+ * before the run fails (and unsent awaited calls are skipped).
996
+ */
997
+ function returned(settled) {
998
+ const call = returnedCall(settled);
999
+ if (call !== undefined)
1000
+ return { json: JSON.stringify({ [referenceKey]: call }) };
1001
+ // Nothing returned is not a returned null: the host can tell them apart.
1002
+ if (vm.typeof(settled) === "undefined")
1003
+ return { json: undefined };
1004
+ const invalid = new CodeModeError("RESULT_INVALID", `The program must return JSON within ${limits.valueLength} characters`, "Return a small JSON summary", { context: { limit: limits.valueLength } });
1005
+ try {
1006
+ return { json: jsonText(settled, () => invalid) };
1007
+ }
1008
+ catch (failure) {
1009
+ if (failure === invalid)
1010
+ return { invalid };
1011
+ if (failure instanceof CodeModeError && !faulted)
1012
+ return { thrown: failure };
1013
+ throw failure;
1014
+ }
1015
+ }
1016
+ let outcome;
360
1017
  for (;;) {
1018
+ if (isCancelled())
1019
+ throw halted();
1020
+ if (fatal)
1021
+ throw fatal;
361
1022
  const stop = halted();
362
1023
  if (stop)
363
1024
  throw stop;
364
1025
  const state = vm.getPromiseState(promise);
365
1026
  if (state.type !== "pending") {
1027
+ // The program has finished. None of its code runs any more, and no
1028
+ // call it left waiting is sent: a program cannot learn what became of
1029
+ // a call it did not wait for. A call of an operation that starts when
1030
+ // called was promised to the host when it was made: those still go,
1031
+ // in order, and a failure of one still ends the run.
1032
+ finished = true;
366
1033
  const settled = state.type === "fulfilled" ? state.value : state.error;
367
- // A call the program started (its `then` ran) is committed, like an
368
- // in-flight promise: it runs before the program completes, even when
369
- // Promise.race or a failed Promise.all moved on, or the program returned
370
- // without awaiting it. Their handlers run too.
371
- if (vm.runtime.hasPendingJob() || pending.length) {
372
- settled.dispose();
373
- if (vm.runtime.hasPendingJob()) {
374
- const job = vm.runtime.executePendingJobs(1);
375
- if (job.error)
376
- job.error.dispose();
377
- }
378
- else
379
- await pending.shift()();
380
- continue;
381
- }
382
- keep(settled);
383
- if (state.type === "rejected")
384
- throw fromGuest(settled);
385
- // Serialize once, before the final checks: `toJSON` is guest code and may start
386
- // or declare calls. Loop again so those are drained and counted like the rest.
387
- if (!result) {
388
- // A failed serialization is kept, not thrown: calls `toJSON` started still
389
- // run before the program completes, then the failure is reported.
390
- try {
391
- result = {
392
- value: vm.typeof(settled) === "undefined"
393
- ? null
394
- : readJson(settled, () => new CodeModeError("RESULT_INVALID", `The program must return JSON within ${limits.valueLength} characters`, "Return a small JSON summary", { context: { limit: limits.valueLength } })),
395
- };
1034
+ try {
1035
+ const promised = nextPromisedCall();
1036
+ if (promised) {
1037
+ await promised.run();
1038
+ continue;
396
1039
  }
397
- catch (failure) {
398
- result = { failure };
1040
+ if (!outcome) {
1041
+ // Taking what the program returned or threw reads its own objects:
1042
+ // `toJSON` or a getter is the program's code, and may make calls.
1043
+ // Loop again so those are handled like the rest.
1044
+ outcome = state.type === "rejected"
1045
+ ? { thrown: fromGuest(settled) }
1046
+ : returned(settled);
1047
+ continue;
399
1048
  }
400
- continue;
401
1049
  }
402
- // Only calls that were never started are left: nothing triggered them.
403
- const unawaited = declared.size;
404
- if (unawaited) {
405
- throw new CodeModeError("UNAWAITED_OPERATION", `The program finished with ${unawaited} api ${unawaited === 1 ? "call" : "calls"} it never awaited. They did not run`, "Put await before every api call, or pass them to Promise.all", { context: { count: unawaited } });
1050
+ finally {
1051
+ drop(settled);
1052
+ }
1053
+ if ("thrown" in outcome)
1054
+ throw outcome.thrown;
1055
+ // What the program made and did not wait for, in the order it made them.
1056
+ const unsent = [
1057
+ ...[...declared].map(([id, { operation, args }]) => ({ id, operation, args })),
1058
+ ...dropped,
1059
+ ].sort((a, b) => a.id - b.id).map(({ operation, args }) => ({ operation, args }));
1060
+ if (unsent.length) {
1061
+ if (!options.unsent)
1062
+ throw unawaitedOperation(namespace, unsent.length);
1063
+ await options.unsent(unsent);
406
1064
  }
407
- if ("failure" in result)
408
- throw result.failure;
409
- return result.value;
1065
+ if ("invalid" in outcome)
1066
+ throw outcome.invalid;
1067
+ return outcome.json;
410
1068
  }
411
1069
  if (vm.runtime.hasPendingJob()) {
412
- const job = vm.runtime.executePendingJobs(1);
1070
+ let job;
1071
+ try {
1072
+ job = vm.runtime.executePendingJobs(1);
1073
+ }
1074
+ catch (error) {
1075
+ throw vmFailure(error);
1076
+ }
413
1077
  if (job.error)
414
1078
  throw fromGuest(keep(job.error));
415
1079
  }
416
1080
  else if (pending.length) {
417
- await pending.shift()();
1081
+ await pending.shift().run();
418
1082
  }
419
1083
  else {
420
- throw new CodeModeError("GUEST_STALLED", "The program is waiting on a promise that nothing will resolve", "Only await api calls and promises the program resolves itself");
1084
+ throw new CodeModeError("GUEST_STALLED", "The program is waiting on a promise that nothing will resolve", `Only await ${namespace} calls and promises the program resolves itself`);
421
1085
  }
422
1086
  }
423
- });
1087
+ };
1088
+ let value;
1089
+ let failure;
1090
+ try {
1091
+ value = await drive();
1092
+ }
1093
+ catch (error) {
1094
+ failure = { error };
1095
+ }
1096
+ if (faultCause) {
1097
+ // After a fault the program may carry on for a moment, and the engine may
1098
+ // fail in any other way: the run still ends with the fault itself.
1099
+ failure = { error: faultCause };
1100
+ }
1101
+ else if (failure && !(failure.error instanceof CodeModeError)) {
1102
+ // An exception that is not ours came out of the engine: its state is unknown.
1103
+ faulted = true;
1104
+ if (isNativeStackOverflow(failure.error))
1105
+ failure = { error: nativeStackExhausted() };
1106
+ else if (isWasmMemoryTrap(failure.error) || isWasmOom(failure.error)) {
1107
+ failure = { error: resourceLimitFor(limits, "memory") };
1108
+ }
1109
+ }
1110
+ if (!faulted) {
1111
+ try {
1112
+ releaseArena();
1113
+ scope.dispose();
1114
+ }
1115
+ catch {
1116
+ // The engine could not release the program: QuickJS aborts when a
1117
+ // runtime it frees still holds an object, and it leaks some itself
1118
+ // (what an async function allocated after an await). The program had
1119
+ // finished and its outcome was read, so the outcome stands. The engine
1120
+ // is not to be used again.
1121
+ faulted = true;
1122
+ }
1123
+ }
1124
+ if (faulted)
1125
+ options.onEngineFault?.();
1126
+ if (failure)
1127
+ throw failure.error;
1128
+ return value;
424
1129
  }