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