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