@mcpview/compose 0.13.1 → 0.14.1
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 +118 -0
- package/README.md +53 -0
- package/esm/src/code-mode/chain.d.ts +24 -1
- package/esm/src/code-mode/chain.d.ts.map +1 -1
- package/esm/src/code-mode/chain.js +219 -86
- package/esm/src/code-mode/errors.d.ts +80 -0
- package/esm/src/code-mode/errors.d.ts.map +1 -0
- package/esm/src/code-mode/errors.js +140 -0
- package/esm/src/code-mode/guest-worker.d.ts +11 -0
- package/esm/src/code-mode/guest-worker.d.ts.map +1 -0
- package/esm/src/code-mode/guest-worker.js +80 -0
- package/esm/src/code-mode/mod.d.ts +3 -1
- package/esm/src/code-mode/mod.d.ts.map +1 -1
- package/esm/src/code-mode/mod.js +2 -0
- package/esm/src/code-mode/sandbox-core.d.ts +61 -0
- package/esm/src/code-mode/sandbox-core.d.ts.map +1 -0
- package/esm/src/code-mode/sandbox-core.js +424 -0
- package/esm/src/code-mode/sandbox.d.ts +68 -7
- package/esm/src/code-mode/sandbox.d.ts.map +1 -1
- package/esm/src/code-mode/sandbox.js +182 -120
- package/esm/src/code-mode/tool.d.ts.map +1 -1
- package/esm/src/code-mode/tool.js +2 -0
- package/esm/src/code-mode/worker-host.d.ts +82 -0
- package/esm/src/code-mode/worker-host.d.ts.map +1 -0
- package/esm/src/code-mode/worker-host.js +364 -0
- package/esm/src/code-mode/worker-protocol.d.ts +44 -0
- package/esm/src/code-mode/worker-protocol.d.ts.map +1 -0
- package/esm/src/code-mode/worker-protocol.js +7 -0
- package/esm/src/host/renderer/css/panel-controls.d.ts.map +1 -1
- package/esm/src/host/renderer/css/panel-controls.js +5 -1
- package/esm/src/host/renderer/js/card-height.d.ts +11 -1
- package/esm/src/host/renderer/js/card-height.d.ts.map +1 -1
- package/esm/src/host/renderer/js/card-height.js +57 -10
- package/esm/src/host/renderer/js/event-bus.d.ts +11 -0
- package/esm/src/host/renderer/js/event-bus.d.ts.map +1 -1
- package/esm/src/host/renderer/js/event-bus.js +49 -8
- package/esm/src/host/renderer/js/intrinsic-layout.d.ts +26 -0
- package/esm/src/host/renderer/js/intrinsic-layout.d.ts.map +1 -0
- package/esm/src/host/renderer/js/intrinsic-layout.js +44 -0
- package/esm/src/host/renderer/panel-resizing.d.ts.map +1 -1
- package/esm/src/host/renderer/panel-resizing.js +8 -0
- package/esm/src/version.d.ts +1 -1
- package/esm/src/version.js +1 -1
- package/package.json +1 -1
- package/script/src/code-mode/chain.d.ts +24 -1
- package/script/src/code-mode/chain.d.ts.map +1 -1
- package/script/src/code-mode/chain.js +218 -85
- package/script/src/code-mode/errors.d.ts +80 -0
- package/script/src/code-mode/errors.d.ts.map +1 -0
- package/script/src/code-mode/errors.js +148 -0
- package/script/src/code-mode/guest-worker.d.ts +11 -0
- package/script/src/code-mode/guest-worker.d.ts.map +1 -0
- package/script/src/code-mode/guest-worker.js +105 -0
- package/script/src/code-mode/mod.d.ts +3 -1
- package/script/src/code-mode/mod.d.ts.map +1 -1
- package/script/src/code-mode/mod.js +9 -1
- package/script/src/code-mode/sandbox-core.d.ts +61 -0
- package/script/src/code-mode/sandbox-core.d.ts.map +1 -0
- package/script/src/code-mode/sandbox-core.js +430 -0
- package/script/src/code-mode/sandbox.d.ts +68 -7
- package/script/src/code-mode/sandbox.d.ts.map +1 -1
- package/script/src/code-mode/sandbox.js +190 -122
- package/script/src/code-mode/tool.d.ts.map +1 -1
- package/script/src/code-mode/tool.js +2 -0
- package/script/src/code-mode/worker-host.d.ts +82 -0
- package/script/src/code-mode/worker-host.d.ts.map +1 -0
- package/script/src/code-mode/worker-host.js +399 -0
- package/script/src/code-mode/worker-protocol.d.ts +44 -0
- package/script/src/code-mode/worker-protocol.d.ts.map +1 -0
- package/script/src/code-mode/worker-protocol.js +8 -0
- package/script/src/host/renderer/css/panel-controls.d.ts.map +1 -1
- package/script/src/host/renderer/css/panel-controls.js +5 -1
- package/script/src/host/renderer/js/card-height.d.ts +11 -1
- package/script/src/host/renderer/js/card-height.d.ts.map +1 -1
- package/script/src/host/renderer/js/card-height.js +57 -10
- package/script/src/host/renderer/js/event-bus.d.ts +11 -0
- package/script/src/host/renderer/js/event-bus.d.ts.map +1 -1
- package/script/src/host/renderer/js/event-bus.js +50 -8
- package/script/src/host/renderer/js/intrinsic-layout.d.ts +26 -0
- package/script/src/host/renderer/js/intrinsic-layout.d.ts.map +1 -0
- package/script/src/host/renderer/js/intrinsic-layout.js +48 -0
- package/script/src/host/renderer/panel-resizing.d.ts.map +1 -1
- package/script/src/host/renderer/panel-resizing.js +8 -0
- package/script/src/version.d.ts +1 -1
- package/script/src/version.js +1 -1
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QuickJS driver for Code Mode programs. Runs identically on the main thread
|
|
3
|
+
* and inside a worker: it has no runtime-specific code and reaches the host only
|
|
4
|
+
* through the `call` function it is given.
|
|
5
|
+
*
|
|
6
|
+
* @module code-mode/sandbox-core
|
|
7
|
+
*/
|
|
8
|
+
import { Scope } from "quickjs-emscripten";
|
|
9
|
+
import { CodeModeError } from "./errors.js";
|
|
10
|
+
/** Default limits of a Code Mode program. */
|
|
11
|
+
export const CODE_MODE_LIMITS = Object.freeze({
|
|
12
|
+
cpuMs: 2_000,
|
|
13
|
+
wallMs: 30_000,
|
|
14
|
+
memoryBytes: 12 * 1024 * 1024,
|
|
15
|
+
stackBytes: 192 * 1024,
|
|
16
|
+
providerCalls: 16,
|
|
17
|
+
boardOperations: 48,
|
|
18
|
+
valueLength: 128 * 1024,
|
|
19
|
+
});
|
|
20
|
+
/** Maximum source length accepted by the code-mode execute tool. */
|
|
21
|
+
export const maxCodeLength = 16_384;
|
|
22
|
+
const PROVIDER_OPERATIONS = new Set(["listSnippets", "runSnippet"]);
|
|
23
|
+
const BOARD_OPERATIONS = new Set(["panel", "sync"]);
|
|
24
|
+
/** Serialize data crossing the QuickJS boundary within the supplied limit. */
|
|
25
|
+
export function encodeValue(value, limit = CODE_MODE_LIMITS.valueLength) {
|
|
26
|
+
const text = JSON.stringify(value);
|
|
27
|
+
if (text === undefined || text.length > limit) {
|
|
28
|
+
throw new RangeError("Expected a JSON value within the size limit.");
|
|
29
|
+
}
|
|
30
|
+
return text;
|
|
31
|
+
}
|
|
32
|
+
/** The error for a host result that exceeds the JSON limit of the boundary. */
|
|
33
|
+
export function receiptTooLarge(limit) {
|
|
34
|
+
return new CodeModeError("RECEIPT_TOO_LARGE", `The operation returned more than ${limit} characters of JSON`, "Select a smaller result", { context: { limit } });
|
|
35
|
+
}
|
|
36
|
+
/** Constant text: the message is the engine's, but a program could forge it. */
|
|
37
|
+
function resourceLimitFor(limits, limit) {
|
|
38
|
+
const memory = limit === "memory";
|
|
39
|
+
return new CodeModeError("RESOURCE_LIMIT", memory
|
|
40
|
+
? `The program used more than ${limits.memoryBytes} bytes of memory`
|
|
41
|
+
: `The program used more than ${limits.stackBytes} bytes of stack`, memory ? "Process less data per run" : "Avoid deep recursion", { context: { limit, bytes: memory ? limits.memoryBytes : limits.stackBytes } });
|
|
42
|
+
}
|
|
43
|
+
const GUEST_ERROR_FACTORY = `(() => {
|
|
44
|
+
"use strict";
|
|
45
|
+
const define = Object.defineProperty, freeze = Object.freeze, parse = JSON.parse;
|
|
46
|
+
class CodeModeError extends Error {
|
|
47
|
+
constructor(record) {
|
|
48
|
+
super(record.message);
|
|
49
|
+
define(this, "name", { value: "CodeModeError", writable: true, configurable: true });
|
|
50
|
+
this.code = record.code;
|
|
51
|
+
this.recovery = record.recovery;
|
|
52
|
+
this.context = freeze(record.context);
|
|
53
|
+
define(this, "ref", { value: record.ref });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return (json) => new CodeModeError(parse(json));
|
|
57
|
+
})()`;
|
|
58
|
+
function guestProgram(code) {
|
|
59
|
+
// Each api call is a lazy thenable: it reaches the host only when awaited,
|
|
60
|
+
// so an operation the program forgets to await never runs.
|
|
61
|
+
return `(() => {
|
|
62
|
+
const declare = globalThis.__declare, start = globalThis.__start, params = globalThis.__params;
|
|
63
|
+
delete globalThis.__declare;
|
|
64
|
+
delete globalThis.__start;
|
|
65
|
+
delete globalThis.__params;
|
|
66
|
+
const freeze = Object.freeze;
|
|
67
|
+
const lazy = (id) => {
|
|
68
|
+
let promise;
|
|
69
|
+
const run = () => (promise ??= start(id));
|
|
70
|
+
return freeze({
|
|
71
|
+
then: (onFulfilled, onRejected) => run().then(onFulfilled, onRejected),
|
|
72
|
+
catch: (onRejected) => run().catch(onRejected),
|
|
73
|
+
finally: (onFinally) => run().finally(onFinally),
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
const operation = (name) => (...args) => lazy(declare(name, args));
|
|
77
|
+
const api = freeze({
|
|
78
|
+
params,
|
|
79
|
+
listSnippets: operation("listSnippets"),
|
|
80
|
+
runSnippet: operation("runSnippet"),
|
|
81
|
+
panel: operation("panel"),
|
|
82
|
+
sync: operation("sync"),
|
|
83
|
+
});
|
|
84
|
+
return (async function(api) { "use strict";\n${code}\n})(api);
|
|
85
|
+
})()`;
|
|
86
|
+
}
|
|
87
|
+
/** Error names a program may report. Any other name is reported as `Error`. */
|
|
88
|
+
const STANDARD_ERROR_NAMES = new Set([
|
|
89
|
+
"Error",
|
|
90
|
+
"TypeError",
|
|
91
|
+
"RangeError",
|
|
92
|
+
"SyntaxError",
|
|
93
|
+
"ReferenceError",
|
|
94
|
+
"EvalError",
|
|
95
|
+
"URIError",
|
|
96
|
+
"InternalError",
|
|
97
|
+
"AggregateError",
|
|
98
|
+
"CodeModeError",
|
|
99
|
+
]);
|
|
100
|
+
/** Messages QuickJS itself uses when a program reaches its memory or stack limit. */
|
|
101
|
+
const ENGINE_LIMITS = new Map([["out of memory", "memory"], ["stack overflow", "stack"]]);
|
|
102
|
+
function cap(text, length) {
|
|
103
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
104
|
+
return flat.length > length ? `${flat.slice(0, length - 1)}…` : flat;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Run a function body in an isolated QuickJS context. Only JSON and the four
|
|
108
|
+
* `api` operations cross into the host. Failures are {@link CodeModeError}s.
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```ts
|
|
112
|
+
* const value = await runVm({
|
|
113
|
+
* quickjs: await getQuickJS(),
|
|
114
|
+
* code: "return api.params.n * 2;",
|
|
115
|
+
* params: { n: 21 },
|
|
116
|
+
* limits: CODE_MODE_LIMITS,
|
|
117
|
+
* call: () => Promise.reject(new Error("unused")),
|
|
118
|
+
* isCancelled: () => false,
|
|
119
|
+
* });
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
export function runVm(options) {
|
|
123
|
+
const { quickjs, code, params, limits, call, isCancelled } = options;
|
|
124
|
+
return Scope.withScopeAsync(async (scope) => {
|
|
125
|
+
const keep = (handle) => scope.manage(handle);
|
|
126
|
+
const vm = scope.manage(quickjs.newContext());
|
|
127
|
+
let cpuDeadline = performance.now() + limits.cpuMs;
|
|
128
|
+
let cpuExpired = false;
|
|
129
|
+
vm.runtime.setMemoryLimit(limits.memoryBytes);
|
|
130
|
+
vm.runtime.setMaxStackSize(limits.stackBytes);
|
|
131
|
+
vm.runtime.setInterruptHandler(() => {
|
|
132
|
+
if (isCancelled())
|
|
133
|
+
return true;
|
|
134
|
+
if (performance.now() >= cpuDeadline)
|
|
135
|
+
cpuExpired = true;
|
|
136
|
+
return cpuExpired;
|
|
137
|
+
});
|
|
138
|
+
function halted() {
|
|
139
|
+
if (isCancelled()) {
|
|
140
|
+
return new CodeModeError("INTERRUPTED", "The program was stopped before it finished", "Run it again if the result is still needed");
|
|
141
|
+
}
|
|
142
|
+
if (cpuExpired || performance.now() >= cpuDeadline) {
|
|
143
|
+
return new CodeModeError("TIME_LIMIT", `The program used its ${limits.cpuMs} ms of CPU time`, "Do less work per run, or split it into several execute calls", { context: { limit: "cpu", ms: limits.cpuMs } });
|
|
144
|
+
}
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
const stringify = keep(vm.unwrapResult(vm.evalCode("JSON.stringify.bind(JSON)")));
|
|
148
|
+
const parse = keep(vm.unwrapResult(vm.evalCode("JSON.parse.bind(JSON)")));
|
|
149
|
+
const makeError = keep(vm.unwrapResult(vm.evalCode(GUEST_ERROR_FACTORY)));
|
|
150
|
+
/** Errors handed to the guest, so an uncaught one maps back to the host record. */
|
|
151
|
+
const records = [];
|
|
152
|
+
const declared = new Map();
|
|
153
|
+
const pending = [];
|
|
154
|
+
let nextId = 0;
|
|
155
|
+
let providerCalls = 0;
|
|
156
|
+
let boardOperations = 0;
|
|
157
|
+
function readJson(handle, fail) {
|
|
158
|
+
const result = vm.callFunction(stringify, vm.undefined, handle);
|
|
159
|
+
if (result.error) {
|
|
160
|
+
// Serializing can exhaust the engine's own stack or memory (a recursive
|
|
161
|
+
// `toJSON`): that is the program's resource limit, not an invalid value.
|
|
162
|
+
const limit = engineLimit(result.error);
|
|
163
|
+
result.error.dispose();
|
|
164
|
+
throw halted() ?? limit ?? fail();
|
|
165
|
+
}
|
|
166
|
+
const encoded = result.value;
|
|
167
|
+
try {
|
|
168
|
+
if (vm.typeof(encoded) !== "string")
|
|
169
|
+
throw fail();
|
|
170
|
+
const text = vm.getString(encoded);
|
|
171
|
+
if (text.length > limits.valueLength)
|
|
172
|
+
throw fail();
|
|
173
|
+
return JSON.parse(text);
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
encoded.dispose();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function toGuest(value) {
|
|
180
|
+
const text = JSON.stringify(value ?? null);
|
|
181
|
+
if (text.length > limits.valueLength)
|
|
182
|
+
throw receiptTooLarge(limits.valueLength);
|
|
183
|
+
const encoded = vm.newString(text);
|
|
184
|
+
let result;
|
|
185
|
+
try {
|
|
186
|
+
result = vm.callFunction(parse, vm.undefined, encoded);
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
encoded.dispose();
|
|
190
|
+
}
|
|
191
|
+
if (result.error) {
|
|
192
|
+
// Decoding can exhaust the engine's own memory or stack: that is the
|
|
193
|
+
// program's resource limit, not a failure of the host operation.
|
|
194
|
+
const failure = fromGuest(keep(result.error));
|
|
195
|
+
if (failure.code !== "GUEST_ERROR")
|
|
196
|
+
throw failure;
|
|
197
|
+
throw new Error("The host value could not be decoded");
|
|
198
|
+
}
|
|
199
|
+
return keep(result.value);
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* A guest error object for this host error. The host keeps the handle to
|
|
203
|
+
* recognise the object later; pass `.dup()` where QuickJS takes ownership.
|
|
204
|
+
*/
|
|
205
|
+
function guestError(error) {
|
|
206
|
+
const json = vm.newString(JSON.stringify({
|
|
207
|
+
message: error.message,
|
|
208
|
+
code: error.code,
|
|
209
|
+
recovery: error.recovery,
|
|
210
|
+
context: error.context,
|
|
211
|
+
ref: records.length,
|
|
212
|
+
}));
|
|
213
|
+
try {
|
|
214
|
+
const handle = keep(vm.unwrapResult(vm.callFunction(makeError, vm.undefined, json)));
|
|
215
|
+
records.push({ error, handle });
|
|
216
|
+
return handle;
|
|
217
|
+
}
|
|
218
|
+
finally {
|
|
219
|
+
json.dispose();
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function readString(handle, key) {
|
|
223
|
+
try {
|
|
224
|
+
const value = vm.getProp(handle, key);
|
|
225
|
+
try {
|
|
226
|
+
return vm.typeof(value) === "string" ? vm.getString(value) : undefined;
|
|
227
|
+
}
|
|
228
|
+
finally {
|
|
229
|
+
value.dispose();
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/** The resource-limit error for an engine failure such as `stack overflow`, if it is one. */
|
|
237
|
+
function engineLimit(handle) {
|
|
238
|
+
if (vm.typeof(handle) !== "object" || readString(handle, "name") !== "InternalError") {
|
|
239
|
+
return undefined;
|
|
240
|
+
}
|
|
241
|
+
const limit = ENGINE_LIMITS.get(readString(handle, "message") ?? "");
|
|
242
|
+
return limit ? resourceLimitFor(limits, limit) : undefined;
|
|
243
|
+
}
|
|
244
|
+
/** Map a value thrown inside the guest to a host error. */
|
|
245
|
+
function fromGuest(handle) {
|
|
246
|
+
const stop = halted();
|
|
247
|
+
if (stop)
|
|
248
|
+
return stop;
|
|
249
|
+
let name = "Error";
|
|
250
|
+
let message = "";
|
|
251
|
+
if (vm.typeof(handle) === "object") {
|
|
252
|
+
try {
|
|
253
|
+
const refHandle = vm.getProp(handle, "ref");
|
|
254
|
+
try {
|
|
255
|
+
if (vm.typeof(refHandle) === "number") {
|
|
256
|
+
// Only the very object the host created maps back to its record.
|
|
257
|
+
const record = records[vm.getNumber(refHandle)];
|
|
258
|
+
if (record && vm.sameValue(record.handle, handle))
|
|
259
|
+
return record.error;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
refHandle.dispose();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
// A hostile getter: fall through to an untyped guest error.
|
|
268
|
+
}
|
|
269
|
+
const guestName = readString(handle, "name");
|
|
270
|
+
if (guestName && STANDARD_ERROR_NAMES.has(guestName))
|
|
271
|
+
name = guestName;
|
|
272
|
+
message = readString(handle, "message") ?? "";
|
|
273
|
+
// Reading a property runs guest getters: they may have crossed the limits.
|
|
274
|
+
const late = halted();
|
|
275
|
+
if (late)
|
|
276
|
+
return late;
|
|
277
|
+
}
|
|
278
|
+
else if (vm.typeof(handle) === "string") {
|
|
279
|
+
message = vm.getString(handle);
|
|
280
|
+
}
|
|
281
|
+
const limit = name === "InternalError" ? ENGINE_LIMITS.get(message) : undefined;
|
|
282
|
+
if (limit)
|
|
283
|
+
return resourceLimitFor(limits, limit);
|
|
284
|
+
// The guest can only see values the model may also see (it can return
|
|
285
|
+
// them), so its own error text is safe to report, capped.
|
|
286
|
+
return new CodeModeError("GUEST_ERROR", message ? `The program threw ${name}: ${cap(message, 300)}` : `The program threw ${name}`, "Fix the program and run it again", { context: { name } });
|
|
287
|
+
}
|
|
288
|
+
const declare = keep(vm.newFunction("declare", (nameHandle, argsHandle) => {
|
|
289
|
+
const operation = vm.typeof(nameHandle) === "string" ? vm.getString(nameHandle) : "";
|
|
290
|
+
const provider = PROVIDER_OPERATIONS.has(operation);
|
|
291
|
+
if (!provider && !BOARD_OPERATIONS.has(operation)) {
|
|
292
|
+
return {
|
|
293
|
+
error: guestError(new CodeModeError("ARGUMENT_INVALID", "Unknown api operation", "Use api.listSnippets, api.runSnippet, api.panel or api.sync")).dup(),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
const used = provider ? ++providerCalls : ++boardOperations;
|
|
297
|
+
const limit = provider ? limits.providerCalls : limits.boardOperations;
|
|
298
|
+
if (used > limit) {
|
|
299
|
+
return {
|
|
300
|
+
error: guestError(new CodeModeError("OPERATION_LIMIT", provider
|
|
301
|
+
? `A program can make at most ${limit} provider calls (listSnippets and runSnippet)`
|
|
302
|
+
: `A program can make at most ${limit} board operations (panel and sync)`, "Split the work into several execute calls, or save the chain and replay it", { context: { budget: provider ? "provider" : "board", limit } })).dup(),
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
let args;
|
|
306
|
+
try {
|
|
307
|
+
args = readJson(argsHandle, () => new CodeModeError("ARGUMENT_INVALID", `The arguments of api.${operation} are not JSON within ${limits.valueLength} characters`, "Pass plain JSON values", { context: { operation, limit: limits.valueLength } }));
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
return { error: guestError(error).dup() };
|
|
311
|
+
}
|
|
312
|
+
if (!Array.isArray(args)) {
|
|
313
|
+
return {
|
|
314
|
+
error: guestError(new CodeModeError("ARGUMENT_INVALID", `The arguments of api.${operation} did not serialize as a list`, "Do not override Array.prototype.toJSON", { context: { operation } })).dup(),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
const id = nextId++;
|
|
318
|
+
// Arguments are copied now, so later changes by the program do not reach the host.
|
|
319
|
+
declared.set(id, { operation, args: args });
|
|
320
|
+
return vm.newNumber(id);
|
|
321
|
+
}));
|
|
322
|
+
const start = keep(vm.newFunction("start", (idHandle) => {
|
|
323
|
+
const id = vm.typeof(idHandle) === "number" ? vm.getNumber(idHandle) : -1;
|
|
324
|
+
const entry = declared.get(id);
|
|
325
|
+
if (!entry) {
|
|
326
|
+
return {
|
|
327
|
+
error: guestError(new CodeModeError("ARGUMENT_INVALID", "Unknown operation", "Await each api call once")).dup(),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
declared.delete(id);
|
|
331
|
+
const deferred = scope.manage(vm.newPromise());
|
|
332
|
+
pending.push(async () => {
|
|
333
|
+
try {
|
|
334
|
+
// Only the wait for the host is excluded from guest CPU time: credit it back
|
|
335
|
+
// before QuickJS parses the result or runs the settlement.
|
|
336
|
+
const before = performance.now();
|
|
337
|
+
let value;
|
|
338
|
+
try {
|
|
339
|
+
value = await call(entry.operation, entry.args);
|
|
340
|
+
}
|
|
341
|
+
finally {
|
|
342
|
+
cpuDeadline += performance.now() - before;
|
|
343
|
+
}
|
|
344
|
+
deferred.resolve(toGuest(value));
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
deferred.reject(guestError(error instanceof CodeModeError ? error : new CodeModeError("OPERATION_FAILED", `api.${entry.operation} failed`, "Check the arguments, then retry once", { context: { operation: entry.operation } })));
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
return deferred.handle.dup();
|
|
351
|
+
}));
|
|
352
|
+
vm.setProp(vm.global, "__declare", declare);
|
|
353
|
+
vm.setProp(vm.global, "__start", start);
|
|
354
|
+
vm.setProp(vm.global, "__params", toGuest(params));
|
|
355
|
+
const evaluated = vm.evalCode(guestProgram(code), "mcpview-code-mode.js", { type: "global" });
|
|
356
|
+
if (evaluated.error)
|
|
357
|
+
throw fromGuest(keep(evaluated.error));
|
|
358
|
+
const promise = keep(evaluated.value);
|
|
359
|
+
let result;
|
|
360
|
+
for (;;) {
|
|
361
|
+
const stop = halted();
|
|
362
|
+
if (stop)
|
|
363
|
+
throw stop;
|
|
364
|
+
const state = vm.getPromiseState(promise);
|
|
365
|
+
if (state.type !== "pending") {
|
|
366
|
+
const settled = state.type === "fulfilled" ? state.value : state.error;
|
|
367
|
+
// A call the program started (its `then` ran) is committed, like an
|
|
368
|
+
// in-flight promise: it runs before the program completes, even when
|
|
369
|
+
// Promise.race or a failed Promise.all moved on, or the program returned
|
|
370
|
+
// without awaiting it. Their handlers run too.
|
|
371
|
+
if (vm.runtime.hasPendingJob() || pending.length) {
|
|
372
|
+
settled.dispose();
|
|
373
|
+
if (vm.runtime.hasPendingJob()) {
|
|
374
|
+
const job = vm.runtime.executePendingJobs(1);
|
|
375
|
+
if (job.error)
|
|
376
|
+
job.error.dispose();
|
|
377
|
+
}
|
|
378
|
+
else
|
|
379
|
+
await pending.shift()();
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
keep(settled);
|
|
383
|
+
if (state.type === "rejected")
|
|
384
|
+
throw fromGuest(settled);
|
|
385
|
+
// Serialize once, before the final checks: `toJSON` is guest code and may start
|
|
386
|
+
// or declare calls. Loop again so those are drained and counted like the rest.
|
|
387
|
+
if (!result) {
|
|
388
|
+
// A failed serialization is kept, not thrown: calls `toJSON` started still
|
|
389
|
+
// run before the program completes, then the failure is reported.
|
|
390
|
+
try {
|
|
391
|
+
result = {
|
|
392
|
+
value: vm.typeof(settled) === "undefined"
|
|
393
|
+
? null
|
|
394
|
+
: readJson(settled, () => new CodeModeError("RESULT_INVALID", `The program must return JSON within ${limits.valueLength} characters`, "Return a small JSON summary", { context: { limit: limits.valueLength } })),
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
catch (failure) {
|
|
398
|
+
result = { failure };
|
|
399
|
+
}
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
// Only calls that were never started are left: nothing triggered them.
|
|
403
|
+
const unawaited = declared.size;
|
|
404
|
+
if (unawaited) {
|
|
405
|
+
throw new CodeModeError("UNAWAITED_OPERATION", `The program finished with ${unawaited} api ${unawaited === 1 ? "call" : "calls"} it never awaited. They did not run`, "Put await before every api call, or pass them to Promise.all", { context: { count: unawaited } });
|
|
406
|
+
}
|
|
407
|
+
if ("failure" in result)
|
|
408
|
+
throw result.failure;
|
|
409
|
+
return result.value;
|
|
410
|
+
}
|
|
411
|
+
if (vm.runtime.hasPendingJob()) {
|
|
412
|
+
const job = vm.runtime.executePendingJobs(1);
|
|
413
|
+
if (job.error)
|
|
414
|
+
throw fromGuest(keep(job.error));
|
|
415
|
+
}
|
|
416
|
+
else if (pending.length) {
|
|
417
|
+
await pending.shift()();
|
|
418
|
+
}
|
|
419
|
+
else {
|
|
420
|
+
throw new CodeModeError("GUEST_STALLED", "The program is waiting on a promise that nothing will resolve", "Only await api calls and promises the program resolves itself");
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
}
|
|
@@ -1,10 +1,71 @@
|
|
|
1
|
-
/** Maximum source length accepted by the code-mode execute tool. */
|
|
2
|
-
export declare const maxCodeLength = 16384;
|
|
3
|
-
/** Serialize data crossing the QuickJS boundary within the supplied limit. */
|
|
4
|
-
export declare function encodeValue(value: unknown, limit?: number): string;
|
|
5
1
|
/**
|
|
6
|
-
* Run a
|
|
7
|
-
*
|
|
2
|
+
* Run a Code Mode program: QuickJS isolation, resource limits, cancellation and
|
|
3
|
+
* machine-readable errors. By default the guest runs in a worker, so a
|
|
4
|
+
* CPU-bound program cannot block the host's event loop.
|
|
5
|
+
*
|
|
6
|
+
* @module code-mode/sandbox
|
|
8
7
|
*/
|
|
9
|
-
|
|
8
|
+
import { type SandboxLimits } from "./sandbox-core.js";
|
|
9
|
+
export { CODE_MODE_LIMITS, encodeValue, maxCodeLength, type SandboxLimits, } from "./sandbox-core.js";
|
|
10
|
+
/**
|
|
11
|
+
* Where the guest runs. `worker` (default) keeps the host responsive during a
|
|
12
|
+
* CPU-bound program. `inline` runs it on the calling thread, for runtimes or
|
|
13
|
+
* bundles without workers; a guest can then block that thread for up to
|
|
14
|
+
* `cpuMs`.
|
|
15
|
+
*/
|
|
16
|
+
export type SandboxIsolation = "worker" | "inline";
|
|
17
|
+
/** Options of {@link runProgram}. */
|
|
18
|
+
export interface SandboxOptions {
|
|
19
|
+
readonly isolation?: SandboxIsolation;
|
|
20
|
+
/** Override some of {@link CODE_MODE_LIMITS}. Each value must be a positive integer; `memoryBytes` must be at least 64 KiB and `stackBytes` at least 16 KiB. */
|
|
21
|
+
readonly limits?: Partial<SandboxLimits>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Resolve and validate limits. Throws a RangeError for a value that is not a
|
|
25
|
+
* positive integer.
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolveSandboxLimits(overrides?: Partial<SandboxLimits>): SandboxLimits;
|
|
28
|
+
/**
|
|
29
|
+
* Throw `SANDBOX_UNAVAILABLE` when the isolation cannot run in this runtime.
|
|
30
|
+
* Call it at configuration time to fail before the first program.
|
|
31
|
+
*
|
|
32
|
+
* This is a partial check. Under Deno it only verifies the permission for the
|
|
33
|
+
* worker module itself; the worker also needs read access to the `code-mode`
|
|
34
|
+
* directory and to the QuickJS WASM file, which surface as `SANDBOX_FAILED` on
|
|
35
|
+
* the first run.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* assertSandboxIsolation("worker");
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function assertSandboxIsolation(isolation: SandboxIsolation): void;
|
|
43
|
+
/** Wait for `work`, but give up as soon as `signal` aborts. A late rejection of `work` is observed. */
|
|
44
|
+
export declare function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T>;
|
|
45
|
+
/** Wait for host I/O without allowing a provider that ignores cancellation to hold the VM open. */
|
|
46
|
+
export declare function waitForOperation(invoke: () => Promise<unknown>, signal: AbortSignal,
|
|
47
|
+
/** True once the caller aborted or the wall deadline passed, even if its timer could not run. */
|
|
48
|
+
stopped?: () => boolean): Promise<unknown>;
|
|
49
|
+
/**
|
|
50
|
+
* Run a function body in an isolated QuickJS context. Only JSON and explicit
|
|
51
|
+
* snippet operations cross into the host. Host operations run one at a time,
|
|
52
|
+
* when the guest awaits them; their time does not count as guest CPU.
|
|
53
|
+
*
|
|
54
|
+
* Failures are {@link CodeModeError}s, except that a caller abort rejects with
|
|
55
|
+
* the caller signal's reason. `invoke` should reject with a CodeModeError;
|
|
56
|
+
* any other rejection reaches the guest as `OPERATION_FAILED`, without its
|
|
57
|
+
* message.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* const value = await runProgram(
|
|
62
|
+
* "const r = await api.runSnippet('cad', 'plate-stl', {}); return r.value;",
|
|
63
|
+
* {},
|
|
64
|
+
* (operation, args) => myHost(operation, args),
|
|
65
|
+
* );
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
export declare function runProgram(code: string, params: Record<string, unknown>, invoke: (operation: string, args: unknown[], signal: AbortSignal,
|
|
69
|
+
/** True once the caller aborted or the wall deadline passed: check it right before any effect. */
|
|
70
|
+
stopped: () => boolean) => Promise<unknown>, callerSignal?: AbortSignal, options?: SandboxOptions): Promise<unknown>;
|
|
10
71
|
//# sourceMappingURL=sandbox.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/sandbox.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/sandbox.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,EAKL,KAAK,aAAa,EACnB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,gBAAgB,EAChB,WAAW,EACX,aAAa,EACb,KAAK,aAAa,GACnB,MAAM,mBAAmB,CAAC;AAE3B;;;;;GAKG;AACH,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAEnD,qCAAqC;AACrC,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,CAAC;IACtC,gKAAgK;IAChK,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;CAC1C;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,GAAE,OAAO,CAAC,aAAa,CAAM,GAAG,aAAa,CA0B1F;AAOD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,gBAAgB,GAAG,IAAI,CAkBxE;AAqBD,uGAAuG;AACvG,wBAAgB,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CAWjF;AAED,mGAAmG;AACnG,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,EAC9B,MAAM,EAAE,WAAW;AACnB,iGAAiG;AACjG,OAAO,GAAE,MAAM,OAA8B,GAC5C,OAAO,CAAC,OAAO,CAAC,CAYlB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,UAAU,CAC9B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,MAAM,EAAE,CACN,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,OAAO,EAAE,EACf,MAAM,EAAE,WAAW;AACnB,kGAAkG;AAClG,OAAO,EAAE,MAAM,OAAO,KACnB,OAAO,CAAC,OAAO,CAAC,EACrB,YAAY,CAAC,EAAE,WAAW,EAC1B,OAAO,GAAE,cAAmB,GAC3B,OAAO,CAAC,OAAO,CAAC,CA2FlB"}
|