@mcpview/compose 0.14.0 → 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 +110 -1
  2. package/README.md +116 -24
  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 +402 -68
  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 +51 -11
  26. package/esm/src/code-mode/worker-host.d.ts.map +1 -1
  27. package/esm/src/code-mode/worker-host.js +114 -48
  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 +432 -73
  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 +51 -11
  57. package/script/src/code-mode/worker-host.d.ts.map +1 -1
  58. package/script/src/code-mode/worker-host.js +115 -47
  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
@@ -5,22 +5,21 @@
5
5
  *
6
6
  * @module code-mode/sandbox
7
7
  */
8
- import { getQuickJS } from "quickjs-emscripten";
8
+ import * as dntShim from "../../_dnt.shims.js";
9
+ import { newEngine } from "./engine.js";
9
10
  import { CodeModeError } from "./errors.js";
10
- import { CODE_MODE_LIMITS, encodeValue, maxCodeLength, runVm, } from "./sandbox-core.js";
11
- import { runInWorker, workerIsolationUnavailable } from "./worker-host.js";
12
- export { CODE_MODE_LIMITS, encodeValue, maxCodeLength, } from "./sandbox-core.js";
13
- /**
14
- * Resolve and validate limits. Throws a RangeError for a value that is not a
15
- * positive integer.
16
- */
17
- export function resolveSandboxLimits(overrides = {}) {
18
- const limits = { ...CODE_MODE_LIMITS, ...overrides };
11
+ import { encodeHostValue, encodeValue, HostErrorCarrier, maxCodeLength, operationFailed, runVm, SANDBOX_RESOURCE_LIMITS, sandboxFailure, unawaitedOperation, } from "./sandbox-core.js";
12
+ import { resolveSandboxSurface, SandboxHostError, SandboxResultReference, surfaceUsesReferences, } from "./surface.js";
13
+ import { runInWorker, workerIsolationUnavailable, workerNotStarted } from "./worker-host.js";
14
+ export { encodeValue, maxCodeLength, SANDBOX_RESOURCE_LIMITS, } from "./sandbox-core.js";
15
+ function assertPositiveIntegers(limits) {
19
16
  for (const [name, value] of Object.entries(limits)) {
20
17
  if (!Number.isSafeInteger(value) || value <= 0) {
21
18
  throw new RangeError(`Code Mode limit ${name} must be a positive integer.`);
22
19
  }
23
20
  }
21
+ }
22
+ function assertResourceRanges(limits) {
24
23
  for (const name of ["memoryBytes", "stackBytes"]) {
25
24
  // The QuickJS WASM setters take an i32: a larger value wraps, and 0 disables the limit.
26
25
  if (limits[name] > MAX_WASM_BYTES) {
@@ -39,6 +38,29 @@ export function resolveSandboxLimits(overrides = {}) {
39
38
  throw new RangeError(`Code Mode limit ${name} must be at most ${MAX_TIMER_DELAY_MS} ms.`);
40
39
  }
41
40
  }
41
+ }
42
+ /** The limits a host gave. One given as undefined was not given: its default stands. */
43
+ function given(overrides) {
44
+ return Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined));
45
+ }
46
+ /**
47
+ * Resolve and validate resource limits. Throws a RangeError for a name that is
48
+ * not a resource limit, or for a value out of range.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * const limits = resolveSandboxResourceLimits({ wallMs: 10_000 });
53
+ * ```
54
+ */
55
+ export function resolveSandboxResourceLimits(overrides = {}) {
56
+ for (const name of Object.keys(overrides)) {
57
+ if (!Object.hasOwn(SANDBOX_RESOURCE_LIMITS, name)) {
58
+ throw new RangeError(`${name} is not a resource limit of the sandbox. The calls a program may make are the budgets of its surface.`);
59
+ }
60
+ }
61
+ const limits = { ...SANDBOX_RESOURCE_LIMITS, ...given(overrides) };
62
+ assertPositiveIntegers(limits);
63
+ assertResourceRanges(limits);
42
64
  return Object.freeze(limits);
43
65
  }
44
66
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
@@ -50,41 +72,65 @@ const MIN_VM_BYTES = { memoryBytes: 64 * 1024, stackBytes: 16 * 1024 };
50
72
  * Call it at configuration time to fail before the first program.
51
73
  *
52
74
  * This is a partial check. Under Deno it only verifies the permission for the
53
- * worker module itself; the worker also needs read access to the `code-mode`
54
- * directory and to the QuickJS WASM file, which surface as `SANDBOX_FAILED` on
55
- * the first run.
75
+ * worker module itself; the worker also needs read access to the modules it
76
+ * imports, and a missing grant surfaces as `SANDBOX_FAILED` on the first run.
77
+ * `worker` is the module a host named in its options, when it did.
56
78
  *
57
79
  * @example
58
80
  * ```ts
59
81
  * assertSandboxIsolation("worker");
60
82
  * ```
61
83
  */
62
- export function assertSandboxIsolation(isolation) {
84
+ export function assertSandboxIsolation(isolation, worker) {
63
85
  if (isolation !== "worker" && isolation !== "inline") {
64
86
  throw new RangeError('Code Mode isolation must be "worker" or "inline".');
65
87
  }
66
- if (isolation === "inline")
88
+ if (worker !== undefined && !(worker instanceof URL)) {
89
+ throw new RangeError("The Code Mode worker option must be a URL.");
90
+ }
91
+ if (isolation === "inline") {
92
+ // A worker module that would never be started is a contradiction in the
93
+ // host's configuration, not something to ignore.
94
+ if (worker) {
95
+ throw new RangeError('The Code Mode worker option needs isolation "worker".');
96
+ }
67
97
  return;
68
- const reason = workerIsolationUnavailable();
98
+ }
99
+ const reason = workerIsolationUnavailable(dntShim.dntGlobalThis, worker);
69
100
  if (reason) {
70
101
  throw new CodeModeError("SANDBOX_UNAVAILABLE", `Worker isolation is unavailable: ${reason}`, reason.includes("--allow-worker")
71
102
  ? 'Start Node with --allow-worker, or configure isolation: "inline"'
72
- : 'Configure isolation: "inline" explicitly for this runtime', { context: { isolation } });
103
+ : reason.startsWith("Deno has no ")
104
+ ? 'Grant that Deno permission, or configure isolation: "inline"'
105
+ : 'Configure isolation: "inline" explicitly for this runtime', { context: { isolation } });
73
106
  }
74
107
  }
75
- /** A JSON copy of the params, identical in both isolations. */
76
- function jsonParams(params, limit) {
77
- let value;
78
- try {
79
- value = JSON.parse(encodeValue(params ?? {}, limit));
80
- }
81
- catch {
82
- value = undefined;
108
+ /** Refuse a source that is not a function body within the length limit. */
109
+ function assertProgramSource(code) {
110
+ if (typeof code !== "string" || !code.trim() || code.length > maxCodeLength) {
111
+ throw new CodeModeError("INVALID_INPUT", `Supply a JavaScript function body of 1 to ${maxCodeLength} characters`, "Send a shorter function body", { context: { limit: maxCodeLength } });
83
112
  }
84
- if (!value || typeof value !== "object" || Array.isArray(value)) {
85
- throw new CodeModeError("PARAMS_INVALID", `params must be a JSON object within ${limit} characters`, "Pass a smaller plain object", { context: { limit } });
113
+ }
114
+ /**
115
+ * The surface with each constant as the JSON text of its value, identical in
116
+ * both isolations. A constant that is not JSON within the value limit is a
117
+ * host configuration error: the host checks what an agent supplied before it
118
+ * declares it.
119
+ */
120
+ function withJsonConstants(surface, limit) {
121
+ const { constants: declared, ...rest } = surface;
122
+ if (!declared)
123
+ return rest;
124
+ const constants = {};
125
+ for (const [name, value] of Object.entries(declared)) {
126
+ try {
127
+ constants[name] = encodeValue(value, limit);
128
+ }
129
+ catch {
130
+ throw new RangeError(`Sandbox constant ${surface.namespace}.${name} must be JSON within ${limit} characters.`);
131
+ }
86
132
  }
87
- return value;
133
+ return { ...rest, constants };
88
134
  }
89
135
  /** Wait for `work`, but give up as soon as `signal` aborts. A late rejection of `work` is observed. */
90
136
  export function untilAborted(work, signal) {
@@ -116,93 +162,381 @@ stopped = () => signal.aborted) {
116
162
  }).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
117
163
  });
118
164
  }
165
+ /** The call a record designates, if `value` is the record that stands for an earlier result. */
166
+ function designatedCall(value, referenceKey) {
167
+ if (typeof value !== "object" || value === null || Array.isArray(value))
168
+ return undefined;
169
+ const keys = Object.keys(value);
170
+ if (keys.length !== 1 || keys[0] !== referenceKey)
171
+ return undefined;
172
+ const call = value[referenceKey];
173
+ return Number.isSafeInteger(call) ? call : undefined;
174
+ }
119
175
  /**
120
- * Run a function body in an isolated QuickJS context. Only JSON and explicit
121
- * snippet operations cross into the host. Host operations run one at a time,
122
- * when the guest awaits them; their time does not count as guest CPU.
123
- *
124
- * Failures are {@link CodeModeError}s, except that a caller abort rejects with
125
- * the caller signal's reason. `invoke` should reject with a CodeModeError;
126
- * any other rejection reaches the guest as `OPERATION_FAILED`, without its
127
- * message.
128
- *
129
- * @example
130
- * ```ts
131
- * const value = await runProgram(
132
- * "const r = await api.runSnippet('cad', 'plate-stl', {}); return r.value;",
133
- * {},
134
- * (operation, args) => myHost(operation, args),
135
- * );
136
- * ```
176
+ * A copy of the arguments in which each record that stands for a result is a
177
+ * {@link SandboxResultReference}. A loop, not recursion: the program chooses
178
+ * how deep its arguments nest.
137
179
  */
138
- export async function runProgram(code, params, invoke, callerSignal, options = {}) {
139
- if (typeof code !== "string" || !code.trim() || code.length > maxCodeLength) {
140
- throw new CodeModeError("INVALID_INPUT", `Supply a JavaScript function body of 1 to ${maxCodeLength} characters`, "Send a shorter function body", { context: { limit: maxCodeLength } });
180
+ function withReferences(args, referenceKey) {
181
+ const root = [];
182
+ const pending = [[args, root]];
183
+ while (pending.length > 0) {
184
+ const [source, copy] = pending.pop();
185
+ for (const [key, item] of Object.entries(source)) {
186
+ let value = item;
187
+ if (typeof item === "object" && item !== null) {
188
+ const call = designatedCall(item, referenceKey);
189
+ if (call !== undefined)
190
+ value = new SandboxResultReference(call);
191
+ else {
192
+ value = Array.isArray(item) ? [] : {};
193
+ pending.push([item, value]);
194
+ }
195
+ }
196
+ // A plain assignment to `__proto__` would set the prototype and drop the value.
197
+ Object.defineProperty(copy, key, {
198
+ value,
199
+ enumerable: true,
200
+ writable: true,
201
+ configurable: true,
202
+ });
203
+ }
141
204
  }
142
- const isolation = options.isolation ?? "worker";
143
- assertSandboxIsolation(isolation);
144
- const limits = resolveSandboxLimits(options.limits);
145
- const input = jsonParams(params, limits.valueLength);
205
+ return root;
206
+ }
207
+ /** The list of arguments of a call, from the JSON text the guest handed over. */
208
+ function argumentsOf(json) {
209
+ const args = JSON.parse(json);
210
+ if (!Array.isArray(args))
211
+ throw new TypeError("The arguments of a call must be a list.");
212
+ return args;
213
+ }
214
+ async function execute(run, invoke, callerSignal) {
215
+ const { code, surface: declared, limits, isolation } = run;
216
+ const namespace = declared.namespace;
217
+ // Fresh for each run and never shown to the program, which therefore cannot
218
+ // write a record that designates a result: only the sandbox does.
219
+ const referenceKey = surfaceUsesReferences(declared)
220
+ ? `mcpview-result-${crypto.randomUUID()}`
221
+ : undefined;
222
+ /** The value of the run: a program that returned a result itself yields its reference. */
223
+ const outcome = (value) => {
224
+ if (referenceKey === undefined || declared.returnedResult !== "reference")
225
+ return value;
226
+ const call = designatedCall(value, referenceKey);
227
+ return call === undefined ? value : new SandboxResultReference(call);
228
+ };
146
229
  callerSignal?.throwIfAborted();
147
230
  const controller = new AbortController();
148
231
  const signal = controller.signal;
149
232
  const abort = () => controller.abort(callerSignal?.reason);
150
233
  callerSignal?.addEventListener("abort", abort, { once: true });
151
- const wallDeadline = performance.now() + limits.wallMs;
152
- const expire = () => controller.abort(new CodeModeError("TIME_LIMIT", `The program ran for more than ${limits.wallMs} ms`, "Split the work into several execute calls", { context: { limit: "wall", ms: limits.wallMs } }));
153
- const timer = setTimeout(expire, limits.wallMs);
234
+ let wallDeadline = performance.now() + limits.wallMs;
235
+ /** True while an irreversible call runs: the wall clock is stopped. */
236
+ let wallPaused = false;
237
+ /** False until there is a guest to run the program: at once inline, once it reported in a worker. */
238
+ let guestStarted = isolation === "inline";
239
+ /** The host's own errors, by the call that rejected with them. */
240
+ const hostErrors = new Map();
241
+ const expire = () => controller.abort(guestStarted
242
+ ? new CodeModeError("TIME_LIMIT", `The program ran for more than ${limits.wallMs} ms`, "Split the work into several runs", { context: { limit: "wall", ms: limits.wallMs } })
243
+ // No program ran: the time went into a worker that never reported.
244
+ : workerNotStarted(limits.wallMs));
245
+ let timer = setTimeout(expire, limits.wallMs);
154
246
  /** True once the caller aborted or the wall deadline passed, even if the timer could not run. */
155
247
  const stopped = () => {
156
- if (!signal.aborted && performance.now() >= wallDeadline)
248
+ if (!wallPaused && !signal.aborted && performance.now() >= wallDeadline)
157
249
  expire();
158
250
  return signal.aborted;
159
251
  };
160
- const call = async (operation, args) => {
252
+ /** The arguments of a call as the host receives them: references where the operation asked for them. */
253
+ const asReceived = (operation, args) => referenceKey !== undefined && declared.operations[operation]?.resultArguments === "reference"
254
+ ? withReferences(args, referenceKey)
255
+ : args;
256
+ /** Irreversible calls the host completed: their result must reach the program. */
257
+ const done = new Set();
258
+ const mustDeliver = (id) => done.has(id);
259
+ /** What the host threw when it refused the calls a program left unsent. */
260
+ let refusal;
261
+ const judge = run.onUnsentCalls;
262
+ const unsent = judge && (async (calls) => {
161
263
  try {
162
- return await waitForOperation(() => invoke(operation, args, signal, stopped), signal, stopped);
264
+ // A run that was aborted asks the host nothing more.
265
+ signal.throwIfAborted();
266
+ const received = calls.map(({ operation, args }) => ({
267
+ operation,
268
+ args: asReceived(operation, argumentsOf(args)),
269
+ }));
270
+ // The host may take its time, but no longer than any of its calls: the
271
+ // wall limit and the caller's abort end the wait.
272
+ await untilAborted(Promise.resolve(received).then(judge), signal);
163
273
  }
164
274
  catch (error) {
275
+ // The guest's run ends here; the caller gets what the host threw. An
276
+ // abort is not the host's answer: the run ends with the abort's reason.
277
+ if (!signal.aborted)
278
+ refusal = { error };
279
+ throw unawaitedOperation(namespace, calls.length);
280
+ }
281
+ });
282
+ /** True once the run has settled: nothing is scheduled on its behalf any more. */
283
+ let over = false;
284
+ const call = async (operation, args, id) => {
285
+ /** When the wall clock was stopped for this call, if it was. */
286
+ let pausedAt;
287
+ try {
288
+ const received = asReceived(operation, argumentsOf(args));
289
+ const irreversible = run.irreversible?.(operation, received) === true;
290
+ // The clock is read before it is stopped: a call that arrives after the
291
+ // wall limit is not sent, irreversible or not, and the time the host
292
+ // took to say which it is belongs to the program.
293
+ if (stopped())
294
+ throw signal.reason;
295
+ if (irreversible) {
296
+ pausedAt = performance.now();
297
+ wallPaused = true;
298
+ clearTimeout(timer);
299
+ }
300
+ const value = await waitForOperation(() => invoke(operation, received, signal, stopped, id), signal, stopped);
301
+ if (irreversible)
302
+ done.add(id);
303
+ return value;
304
+ }
305
+ catch (error) {
306
+ if (error instanceof SandboxHostError) {
307
+ // The program is shown the host's words; the host keeps its object.
308
+ hostErrors.set(id, error);
309
+ throw new HostErrorCarrier(namespace, operation, id, {
310
+ code: error.code,
311
+ message: error.message,
312
+ recovery: error.recovery,
313
+ });
314
+ }
165
315
  if (error instanceof CodeModeError)
166
316
  throw error;
167
317
  if (signal.aborted) {
168
- throw new CodeModeError("INTERRUPTED", `api.${operation} was interrupted`, "Run the program again if the result is still needed");
318
+ throw new CodeModeError("INTERRUPTED", `${namespace}.${operation} was interrupted`, "Run the program again if the result is still needed");
319
+ }
320
+ throw operationFailed(namespace, operation);
321
+ }
322
+ finally {
323
+ if (pausedAt !== undefined) {
324
+ // The time of the call is set aside, then the clock starts again.
325
+ wallPaused = false;
326
+ wallDeadline += performance.now() - pausedAt;
327
+ if (!signal.aborted && !over) {
328
+ timer = setTimeout(expire, Math.max(0, wallDeadline - performance.now()));
329
+ }
169
330
  }
170
- throw new CodeModeError("OPERATION_FAILED", `api.${operation} failed`, "Check the arguments, then retry once", { context: { operation } });
171
331
  }
172
332
  };
333
+ /** The value of a finished run, from the JSON text the guest handed over. */
334
+ const valueOf = (json) => outcome(json === undefined ? undefined : JSON.parse(json));
173
335
  try {
174
336
  if (isolation === "inline") {
175
- const quickjs = await untilAborted(getQuickJS(), signal);
337
+ const quickjs = await untilAborted(newEngine(limits.memoryBytes), signal);
176
338
  signal.throwIfAborted();
177
- const value = await runVm({
339
+ const json = await runVm({
178
340
  quickjs,
179
341
  code,
180
- params: input,
342
+ surface: declared,
181
343
  limits,
182
- call,
344
+ // The same rule as the worker path: one function decides what crosses.
345
+ call: async (operation, args, id) => encodeHostValue(namespace, operation, await call(operation, args, id), limits.valueLength),
346
+ referenceKey,
347
+ unsent,
348
+ mustDeliver,
183
349
  // An inline guest holds the event loop, so the wall timer cannot fire: poll it.
184
350
  isCancelled: stopped,
185
351
  });
186
352
  if (stopped())
187
353
  throw signal.reason;
188
- return value;
354
+ return valueOf(json);
189
355
  }
190
- const value = await runInWorker({ code, params: input, limits, call, signal });
356
+ const json = await runInWorker({
357
+ code,
358
+ surface: declared,
359
+ limits,
360
+ call,
361
+ referenceKey,
362
+ worker: run.worker,
363
+ unsent,
364
+ mustDeliver,
365
+ started: () => {
366
+ guestStarted = true;
367
+ },
368
+ signal,
369
+ });
191
370
  if (stopped())
192
371
  throw signal.reason;
193
- return value;
372
+ return valueOf(json);
194
373
  }
195
374
  catch (error) {
196
375
  if (stopped())
197
376
  throw signal.reason;
198
- const failure = error instanceof CodeModeError ? error : new CodeModeError("SANDBOX_FAILED", "The sandbox failed while running the program", "Run the program again");
377
+ if (refusal)
378
+ throw refusal.error;
379
+ // A host error the program did not handle is the run's own failure: the
380
+ // context of the carrier names the call, and the host kept the object.
381
+ const hostError = error instanceof CodeModeError &&
382
+ typeof error.context.hostError === "number"
383
+ ? hostErrors.get(error.context.hostError)
384
+ : undefined;
385
+ if (hostError)
386
+ throw hostError;
387
+ const failure = error instanceof CodeModeError ? error : sandboxFailure();
199
388
  // A worker that died leaves provider calls in flight: cancel them, but keep this outcome.
200
389
  if (failure.code === "SANDBOX_FAILED")
201
390
  controller.abort(failure);
202
391
  throw failure;
203
392
  }
204
393
  finally {
394
+ over = true;
205
395
  clearTimeout(timer);
206
396
  callerSignal?.removeEventListener("abort", abort);
207
397
  }
208
398
  }
399
+ /**
400
+ * Run a function body in an isolated QuickJS context, against the surface the
401
+ * host declares. Only JSON and the declared operations cross into the host.
402
+ * Host operations run one at a time, in the order the program started them: an
403
+ * operation starts when the program awaits its call, or as soon as it is
404
+ * called if it is declared `start: "on-call"`. Their time does not count as
405
+ * guest CPU.
406
+ *
407
+ * Once the program has finished, none of its code runs and no call it left
408
+ * waiting is sent. If it finished normally with such calls, the host decides
409
+ * through `onUnsentCalls`; without it the run fails with `UNAWAITED_OPERATION`.
410
+ * Only a call of an `"on-call"` operation, which the program did not have to
411
+ * wait for, is still delivered.
412
+ *
413
+ * The promise rejects with:
414
+ * - a RangeError, before anything runs, for what the host itself got wrong: an
415
+ * option, a limit, the surface, or a constant that is not JSON;
416
+ * - the caller signal's reason, when the caller aborts;
417
+ * - the host's own {@link SandboxHostError}, when an operation rejected with
418
+ * one and the program did not handle it;
419
+ * - a {@link CodeModeError} in every other case.
420
+ *
421
+ * An operation that rejects with a `CodeModeError` or a `SandboxHostError`
422
+ * shows it to the program. Any other rejection reaches the program as
423
+ * `OPERATION_FAILED`, without its message.
424
+ *
425
+ * The promise resolves with the JSON value the program returned, and with
426
+ * `undefined` when it returned nothing: a forgotten `return` is not a `null`.
427
+ *
428
+ * @example
429
+ * ```ts
430
+ * const total = await runSandboxProgram(
431
+ * "const order = await shop.getOrder(shop.params.id); return order.total;",
432
+ * {
433
+ * namespace: "shop",
434
+ * constants: { params: { id: 1042 } },
435
+ * operations: { getOrder: { budget: "reads" } },
436
+ * budgets: { reads: 12 },
437
+ * },
438
+ * (operation, args) => myHost(operation, args),
439
+ * );
440
+ * ```
441
+ */
442
+ export async function runSandboxProgram(code, surface, invoke, callerSignal, options = {}) {
443
+ assertProgramSource(code);
444
+ const isolation = options.isolation ?? "worker";
445
+ assertSandboxIsolation(isolation, options.worker);
446
+ for (const name of ["irreversible", "onUnsentCalls"]) {
447
+ if (options[name] !== undefined && typeof options[name] !== "function") {
448
+ throw new RangeError(`The Code Mode ${name} option must be a function.`);
449
+ }
450
+ }
451
+ const limits = resolveSandboxResourceLimits(options.limits);
452
+ return await execute({
453
+ code,
454
+ surface: withJsonConstants(resolveSandboxSurface(surface), limits.valueLength),
455
+ limits,
456
+ isolation,
457
+ worker: options.worker,
458
+ irreversible: options.irreversible,
459
+ onUnsentCalls: options.onUnsentCalls,
460
+ }, invoke, callerSignal);
461
+ }
462
+ /** Default limits of a program of Compose's chain. */
463
+ export const CODE_MODE_LIMITS = Object.freeze({
464
+ cpuMs: SANDBOX_RESOURCE_LIMITS.cpuMs,
465
+ wallMs: SANDBOX_RESOURCE_LIMITS.wallMs,
466
+ memoryBytes: SANDBOX_RESOURCE_LIMITS.memoryBytes,
467
+ stackBytes: SANDBOX_RESOURCE_LIMITS.stackBytes,
468
+ providerCalls: 16,
469
+ boardOperations: 48,
470
+ valueLength: SANDBOX_RESOURCE_LIMITS.valueLength,
471
+ });
472
+ /**
473
+ * Resolve and validate the limits of Compose's chain. Throws a RangeError for
474
+ * a value that is not a positive integer, or out of range.
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * const limits = resolveSandboxLimits({ providerCalls: 4 });
479
+ * ```
480
+ */
481
+ export function resolveSandboxLimits(overrides = {}) {
482
+ const limits = { ...CODE_MODE_LIMITS, ...given(overrides) };
483
+ assertPositiveIntegers(limits);
484
+ assertResourceRanges(limits);
485
+ return Object.freeze(limits);
486
+ }
487
+ /** What Compose's own chain exposes to a program: the four operations of ADR 0006. */
488
+ function snippetSurface(params, providerCalls, boardOperations) {
489
+ return {
490
+ namespace: "api",
491
+ constants: { params },
492
+ operations: {
493
+ listSnippets: { budget: "provider" },
494
+ runSnippet: { budget: "provider" },
495
+ panel: { budget: "board" },
496
+ sync: { budget: "board" },
497
+ },
498
+ budgets: { provider: providerCalls, board: boardOperations },
499
+ };
500
+ }
501
+ /** A JSON copy of the params, identical in both isolations. */
502
+ function jsonParams(params, limit) {
503
+ let value;
504
+ try {
505
+ value = JSON.parse(encodeValue(params ?? {}, limit));
506
+ }
507
+ catch {
508
+ value = undefined;
509
+ }
510
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
511
+ throw new CodeModeError("PARAMS_INVALID", `params must be a JSON object within ${limit} characters`, "Pass a smaller plain object", { context: { limit } });
512
+ }
513
+ return value;
514
+ }
515
+ /**
516
+ * Run a program against Compose's own surface: `api.params` and the four
517
+ * snippet operations of ADR 0006. See {@link runSandboxProgram} for the rules.
518
+ *
519
+ * @example
520
+ * ```ts
521
+ * const value = await runProgram(
522
+ * "const r = await api.runSnippet('cad', 'plate-stl', {}); return r.value;",
523
+ * {},
524
+ * (operation, args) => myHost(operation, args),
525
+ * );
526
+ * ```
527
+ */
528
+ export async function runProgram(code, params, invoke, callerSignal, options = {}) {
529
+ assertProgramSource(code);
530
+ const isolation = options.isolation ?? "worker";
531
+ assertSandboxIsolation(isolation);
532
+ const { providerCalls, boardOperations, ...limits } = resolveSandboxLimits(options.limits);
533
+ const input = jsonParams(params, limits.valueLength);
534
+ const value = await execute({
535
+ code,
536
+ surface: withJsonConstants(resolveSandboxSurface(snippetSurface(input, providerCalls, boardOperations)), limits.valueLength),
537
+ limits,
538
+ isolation,
539
+ }, invoke, callerSignal);
540
+ // The chain reports a program that returned nothing as null, as it always did.
541
+ return value === undefined ? null : value;
542
+ }