@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.
- package/CHANGELOG.md +101 -1
- package/README.md +113 -22
- package/esm/src/code-mode/engine.d.ts +59 -0
- package/esm/src/code-mode/engine.d.ts.map +1 -0
- package/esm/src/code-mode/engine.js +189 -0
- package/esm/src/code-mode/guest-worker.d.ts +2 -5
- package/esm/src/code-mode/guest-worker.d.ts.map +1 -1
- package/esm/src/code-mode/guest-worker.js +4 -75
- package/esm/src/code-mode/sandbox-api.d.ts +37 -0
- package/esm/src/code-mode/sandbox-api.d.ts.map +1 -0
- package/esm/src/code-mode/sandbox-api.js +36 -0
- package/esm/src/code-mode/sandbox-core.d.ts +99 -21
- package/esm/src/code-mode/sandbox-core.d.ts.map +1 -1
- package/esm/src/code-mode/sandbox-core.js +926 -221
- package/esm/src/code-mode/sandbox-worker.d.ts +37 -0
- package/esm/src/code-mode/sandbox-worker.d.ts.map +1 -0
- package/esm/src/code-mode/sandbox-worker.js +140 -0
- package/esm/src/code-mode/sandbox.d.ts +142 -29
- package/esm/src/code-mode/sandbox.d.ts.map +1 -1
- package/esm/src/code-mode/sandbox.js +399 -67
- package/esm/src/code-mode/surface.d.ts +148 -0
- package/esm/src/code-mode/surface.d.ts.map +1 -0
- package/esm/src/code-mode/surface.js +204 -0
- package/esm/src/code-mode/tool.js +1 -1
- package/esm/src/code-mode/worker-host.d.ts +39 -11
- package/esm/src/code-mode/worker-host.d.ts.map +1 -1
- package/esm/src/code-mode/worker-host.js +100 -43
- package/esm/src/code-mode/worker-protocol.d.ts +45 -8
- package/esm/src/code-mode/worker-protocol.d.ts.map +1 -1
- package/esm/src/code-mode/worker-protocol.js +4 -2
- package/esm/src/version.d.ts +1 -1
- package/esm/src/version.js +1 -1
- package/package.json +9 -1
- package/script/src/code-mode/engine.d.ts +59 -0
- package/script/src/code-mode/engine.d.ts.map +1 -0
- package/script/src/code-mode/engine.js +198 -0
- package/script/src/code-mode/guest-worker.d.ts +2 -5
- package/script/src/code-mode/guest-worker.d.ts.map +1 -1
- package/script/src/code-mode/guest-worker.js +4 -98
- package/script/src/code-mode/sandbox-api.d.ts +37 -0
- package/script/src/code-mode/sandbox-api.d.ts.map +1 -0
- package/script/src/code-mode/sandbox-api.js +50 -0
- package/script/src/code-mode/sandbox-core.d.ts +99 -21
- package/script/src/code-mode/sandbox-core.d.ts.map +1 -1
- package/script/src/code-mode/sandbox-core.js +931 -221
- package/script/src/code-mode/sandbox-worker.d.ts +37 -0
- package/script/src/code-mode/sandbox-worker.d.ts.map +1 -0
- package/script/src/code-mode/sandbox-worker.js +166 -0
- package/script/src/code-mode/sandbox.d.ts +142 -29
- package/script/src/code-mode/sandbox.d.ts.map +1 -1
- package/script/src/code-mode/sandbox.js +429 -72
- package/script/src/code-mode/surface.d.ts +148 -0
- package/script/src/code-mode/surface.d.ts.map +1 -0
- package/script/src/code-mode/surface.js +211 -0
- package/script/src/code-mode/tool.js +1 -1
- package/script/src/code-mode/worker-host.d.ts +39 -11
- package/script/src/code-mode/worker-host.d.ts.map +1 -1
- package/script/src/code-mode/worker-host.js +100 -42
- package/script/src/code-mode/worker-protocol.d.ts +45 -8
- package/script/src/code-mode/worker-protocol.d.ts.map +1 -1
- package/script/src/code-mode/worker-protocol.js +4 -2
- package/script/src/version.d.ts +1 -1
- package/script/src/version.js +1 -1
|
@@ -5,22 +5,21 @@
|
|
|
5
5
|
*
|
|
6
6
|
* @module code-mode/sandbox
|
|
7
7
|
*/
|
|
8
|
-
import
|
|
8
|
+
import * as dntShim from "../../_dnt.shims.js";
|
|
9
|
+
import { newEngine } from "./engine.js";
|
|
9
10
|
import { CodeModeError } from "./errors.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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,22 +72,31 @@ 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
|
|
54
|
-
*
|
|
55
|
-
* the
|
|
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 (
|
|
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
|
-
|
|
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"'
|
|
@@ -74,19 +105,32 @@ export function assertSandboxIsolation(isolation) {
|
|
|
74
105
|
: 'Configure isolation: "inline" explicitly for this runtime', { context: { isolation } });
|
|
75
106
|
}
|
|
76
107
|
}
|
|
77
|
-
/**
|
|
78
|
-
function
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
value = JSON.parse(encodeValue(params ?? {}, limit));
|
|
82
|
-
}
|
|
83
|
-
catch {
|
|
84
|
-
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 } });
|
|
85
112
|
}
|
|
86
|
-
|
|
87
|
-
|
|
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
|
+
}
|
|
88
132
|
}
|
|
89
|
-
return
|
|
133
|
+
return { ...rest, constants };
|
|
90
134
|
}
|
|
91
135
|
/** Wait for `work`, but give up as soon as `signal` aborts. A late rejection of `work` is observed. */
|
|
92
136
|
export function untilAborted(work, signal) {
|
|
@@ -118,93 +162,381 @@ stopped = () => signal.aborted) {
|
|
|
118
162
|
}).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
119
163
|
});
|
|
120
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
|
+
}
|
|
121
175
|
/**
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
* Failures are {@link CodeModeError}s, except that a caller abort rejects with
|
|
127
|
-
* the caller signal's reason. `invoke` should reject with a CodeModeError;
|
|
128
|
-
* any other rejection reaches the guest as `OPERATION_FAILED`, without its
|
|
129
|
-
* message.
|
|
130
|
-
*
|
|
131
|
-
* @example
|
|
132
|
-
* ```ts
|
|
133
|
-
* const value = await runProgram(
|
|
134
|
-
* "const r = await api.runSnippet('cad', 'plate-stl', {}); return r.value;",
|
|
135
|
-
* {},
|
|
136
|
-
* (operation, args) => myHost(operation, args),
|
|
137
|
-
* );
|
|
138
|
-
* ```
|
|
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.
|
|
139
179
|
*/
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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
|
+
}
|
|
143
204
|
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
+
};
|
|
148
229
|
callerSignal?.throwIfAborted();
|
|
149
230
|
const controller = new AbortController();
|
|
150
231
|
const signal = controller.signal;
|
|
151
232
|
const abort = () => controller.abort(callerSignal?.reason);
|
|
152
233
|
callerSignal?.addEventListener("abort", abort, { once: true });
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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);
|
|
156
246
|
/** True once the caller aborted or the wall deadline passed, even if the timer could not run. */
|
|
157
247
|
const stopped = () => {
|
|
158
|
-
if (!signal.aborted && performance.now() >= wallDeadline)
|
|
248
|
+
if (!wallPaused && !signal.aborted && performance.now() >= wallDeadline)
|
|
159
249
|
expire();
|
|
160
250
|
return signal.aborted;
|
|
161
251
|
};
|
|
162
|
-
|
|
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) => {
|
|
163
263
|
try {
|
|
164
|
-
|
|
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);
|
|
165
273
|
}
|
|
166
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
|
+
}
|
|
167
315
|
if (error instanceof CodeModeError)
|
|
168
316
|
throw error;
|
|
169
317
|
if (signal.aborted) {
|
|
170
|
-
throw new CodeModeError("INTERRUPTED",
|
|
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
|
+
}
|
|
171
330
|
}
|
|
172
|
-
throw new CodeModeError("OPERATION_FAILED", `api.${operation} failed`, "Check the arguments, then retry once", { context: { operation } });
|
|
173
331
|
}
|
|
174
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));
|
|
175
335
|
try {
|
|
176
336
|
if (isolation === "inline") {
|
|
177
|
-
const quickjs = await untilAborted(
|
|
337
|
+
const quickjs = await untilAborted(newEngine(limits.memoryBytes), signal);
|
|
178
338
|
signal.throwIfAborted();
|
|
179
|
-
const
|
|
339
|
+
const json = await runVm({
|
|
180
340
|
quickjs,
|
|
181
341
|
code,
|
|
182
|
-
|
|
342
|
+
surface: declared,
|
|
183
343
|
limits,
|
|
184
|
-
|
|
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,
|
|
185
349
|
// An inline guest holds the event loop, so the wall timer cannot fire: poll it.
|
|
186
350
|
isCancelled: stopped,
|
|
187
351
|
});
|
|
188
352
|
if (stopped())
|
|
189
353
|
throw signal.reason;
|
|
190
|
-
return
|
|
354
|
+
return valueOf(json);
|
|
191
355
|
}
|
|
192
|
-
const
|
|
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
|
+
});
|
|
193
370
|
if (stopped())
|
|
194
371
|
throw signal.reason;
|
|
195
|
-
return
|
|
372
|
+
return valueOf(json);
|
|
196
373
|
}
|
|
197
374
|
catch (error) {
|
|
198
375
|
if (stopped())
|
|
199
376
|
throw signal.reason;
|
|
200
|
-
|
|
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();
|
|
201
388
|
// A worker that died leaves provider calls in flight: cancel them, but keep this outcome.
|
|
202
389
|
if (failure.code === "SANDBOX_FAILED")
|
|
203
390
|
controller.abort(failure);
|
|
204
391
|
throw failure;
|
|
205
392
|
}
|
|
206
393
|
finally {
|
|
394
|
+
over = true;
|
|
207
395
|
clearTimeout(timer);
|
|
208
396
|
callerSignal?.removeEventListener("abort", abort);
|
|
209
397
|
}
|
|
210
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
|
+
}
|