@mcpview/compose 0.13.0 → 0.14.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 +120 -0
- package/README.md +131 -2
- package/esm/_dnt.polyfills.d.ts +11 -11
- package/esm/_dnt.polyfills.d.ts.map +1 -1
- package/esm/_dnt.polyfills.js +14 -14
- package/esm/src/code-mode/board.d.ts +18 -2
- package/esm/src/code-mode/board.d.ts.map +1 -1
- package/esm/src/code-mode/board.js +74 -2
- package/esm/src/code-mode/chain.d.ts +26 -1
- package/esm/src/code-mode/chain.d.ts.map +1 -1
- package/esm/src/code-mode/chain.js +248 -89
- package/esm/src/code-mode/connections.d.ts +1 -0
- package/esm/src/code-mode/connections.d.ts.map +1 -1
- package/esm/src/code-mode/connections.js +1 -0
- 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/layout-publisher.d.ts +69 -0
- package/esm/src/code-mode/layout-publisher.d.ts.map +1 -0
- package/esm/src/code-mode/layout-publisher.js +85 -0
- package/esm/src/code-mode/layout-runs.d.ts +35 -0
- package/esm/src/code-mode/layout-runs.d.ts.map +1 -0
- package/esm/src/code-mode/layout-runs.js +130 -0
- package/esm/src/code-mode/layout.d.ts +20 -0
- package/esm/src/code-mode/layout.d.ts.map +1 -0
- package/esm/src/code-mode/layout.js +54 -0
- package/esm/src/code-mode/mod.d.ts +4 -1
- package/esm/src/code-mode/mod.d.ts.map +1 -1
- package/esm/src/code-mode/mod.js +3 -0
- package/esm/src/code-mode/panel-contexts.d.ts +25 -0
- package/esm/src/code-mode/panel-contexts.d.ts.map +1 -0
- package/esm/src/code-mode/panel-contexts.js +115 -0
- package/esm/src/code-mode/providers.d.ts +3 -0
- package/esm/src/code-mode/providers.d.ts.map +1 -1
- 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 +180 -119
- package/esm/src/code-mode/sync.d.ts +11 -0
- package/esm/src/code-mode/sync.d.ts.map +1 -0
- package/esm/src/code-mode/sync.js +42 -0
- package/esm/src/code-mode/tool.d.ts +1 -1
- package/esm/src/code-mode/tool.d.ts.map +1 -1
- package/esm/src/code-mode/tool.js +14 -0
- package/esm/src/code-mode/worker-host.d.ts +70 -0
- package/esm/src/code-mode/worker-host.d.ts.map +1 -0
- package/esm/src/code-mode/worker-host.js +355 -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/html-generator.js +2 -2
- 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-controls.d.ts +7 -0
- package/esm/src/host/renderer/panel-controls.js +1 -0
- package/esm/src/host/renderer/panel-movement.d.ts.map +1 -1
- package/esm/src/host/renderer/panel-movement.js +5 -1
- package/esm/src/host/renderer/panel-resizing.d.ts.map +1 -1
- package/esm/src/host/renderer/panel-resizing.js +36 -0
- package/esm/src/host/renderer/panel-snapshot.d.ts +11 -0
- package/esm/src/host/renderer/panel-snapshot.d.ts.map +1 -0
- package/esm/src/host/renderer/panel-snapshot.js +65 -0
- package/esm/src/version.d.ts +1 -1
- package/esm/src/version.js +1 -1
- package/package.json +9 -1
- package/script/_dnt.polyfills.d.ts +11 -11
- package/script/_dnt.polyfills.d.ts.map +1 -1
- package/script/_dnt.polyfills.js +14 -14
- package/script/src/code-mode/board.d.ts +18 -2
- package/script/src/code-mode/board.d.ts.map +1 -1
- package/script/src/code-mode/board.js +81 -2
- package/script/src/code-mode/chain.d.ts +26 -1
- package/script/src/code-mode/chain.d.ts.map +1 -1
- package/script/src/code-mode/chain.js +247 -88
- package/script/src/code-mode/connections.d.ts +1 -0
- package/script/src/code-mode/connections.d.ts.map +1 -1
- package/script/src/code-mode/connections.js +1 -0
- 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/layout-publisher.d.ts +69 -0
- package/script/src/code-mode/layout-publisher.d.ts.map +1 -0
- package/script/src/code-mode/layout-publisher.js +88 -0
- package/script/src/code-mode/layout-runs.d.ts +35 -0
- package/script/src/code-mode/layout-runs.d.ts.map +1 -0
- package/script/src/code-mode/layout-runs.js +134 -0
- package/script/src/code-mode/layout.d.ts +20 -0
- package/script/src/code-mode/layout.d.ts.map +1 -0
- package/script/src/code-mode/layout.js +57 -0
- package/script/src/code-mode/mod.d.ts +4 -1
- package/script/src/code-mode/mod.d.ts.map +1 -1
- package/script/src/code-mode/mod.js +14 -1
- package/script/src/code-mode/panel-contexts.d.ts +25 -0
- package/script/src/code-mode/panel-contexts.d.ts.map +1 -0
- package/script/src/code-mode/panel-contexts.js +118 -0
- package/script/src/code-mode/providers.d.ts +3 -0
- package/script/src/code-mode/providers.d.ts.map +1 -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 +188 -121
- package/script/src/code-mode/sync.d.ts +11 -0
- package/script/src/code-mode/sync.d.ts.map +1 -0
- package/script/src/code-mode/sync.js +51 -0
- package/script/src/code-mode/tool.d.ts +1 -1
- package/script/src/code-mode/tool.d.ts.map +1 -1
- package/script/src/code-mode/tool.js +14 -0
- package/script/src/code-mode/worker-host.d.ts +70 -0
- package/script/src/code-mode/worker-host.d.ts.map +1 -0
- package/script/src/code-mode/worker-host.js +389 -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/html-generator.js +2 -2
- 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-controls.d.ts +7 -0
- package/script/src/host/renderer/panel-controls.js +4 -1
- package/script/src/host/renderer/panel-movement.d.ts.map +1 -1
- package/script/src/host/renderer/panel-movement.js +5 -1
- package/script/src/host/renderer/panel-resizing.d.ts.map +1 -1
- package/script/src/host/renderer/panel-resizing.js +36 -0
- package/script/src/host/renderer/panel-snapshot.d.ts +11 -0
- package/script/src/host/renderer/panel-snapshot.d.ts.map +1 -0
- package/script/src/host/renderer/panel-snapshot.js +69 -0
- package/script/src/version.d.ts +1 -1
- package/script/src/version.js +1 -1
|
@@ -1,144 +1,205 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
/**
|
|
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
|
|
7
|
+
*/
|
|
8
|
+
import { getQuickJS } from "quickjs-emscripten";
|
|
9
|
+
import { CodeModeError } from "./errors.js";
|
|
10
|
+
import { CODE_MODE_LIMITS, encodeValue, maxCodeLength, runVm, } from "./sandbox-core.js";
|
|
11
|
+
import { runInWorker, workerIsolationUnavailable } from "./worker-host.js";
|
|
12
|
+
export { CODE_MODE_LIMITS, encodeValue, maxCodeLength, } from "./sandbox-core.js";
|
|
13
|
+
/**
|
|
14
|
+
* Resolve and validate limits. Throws a RangeError for a value that is not a
|
|
15
|
+
* positive integer.
|
|
16
|
+
*/
|
|
17
|
+
export function resolveSandboxLimits(overrides = {}) {
|
|
18
|
+
const limits = { ...CODE_MODE_LIMITS, ...overrides };
|
|
19
|
+
for (const [name, value] of Object.entries(limits)) {
|
|
20
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
21
|
+
throw new RangeError(`Code Mode limit ${name} must be a positive integer.`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
for (const name of ["memoryBytes", "stackBytes"]) {
|
|
25
|
+
// The QuickJS WASM setters take an i32: a larger value wraps, and 0 disables the limit.
|
|
26
|
+
if (limits[name] > MAX_WASM_BYTES) {
|
|
27
|
+
throw new RangeError(`Code Mode limit ${name} must be at most ${MAX_WASM_BYTES} bytes.`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
for (const name of ["memoryBytes", "stackBytes"]) {
|
|
31
|
+
// Below this the VM cannot even finish its own setup, and the failure carries no diagnosis.
|
|
32
|
+
if (limits[name] < MIN_VM_BYTES[name]) {
|
|
33
|
+
throw new RangeError(`Code Mode limit ${name} must be at least ${MIN_VM_BYTES[name]} bytes.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
for (const name of ["cpuMs", "wallMs"]) {
|
|
37
|
+
// Timers clamp longer delays to about 1 ms.
|
|
38
|
+
if (limits[name] > MAX_TIMER_DELAY_MS) {
|
|
39
|
+
throw new RangeError(`Code Mode limit ${name} must be at most ${MAX_TIMER_DELAY_MS} ms.`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return Object.freeze(limits);
|
|
43
|
+
}
|
|
44
|
+
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
45
|
+
const MAX_WASM_BYTES = 2_147_483_647;
|
|
46
|
+
/** About ten times what the VM needs to start, so a small limit fails at configuration. */
|
|
47
|
+
const MIN_VM_BYTES = { memoryBytes: 64 * 1024, stackBytes: 16 * 1024 };
|
|
48
|
+
/**
|
|
49
|
+
* Throw `SANDBOX_UNAVAILABLE` when the isolation cannot run in this runtime.
|
|
50
|
+
* Call it at configuration time to fail before the first program.
|
|
51
|
+
*
|
|
52
|
+
* This is a partial check. Under Deno it only verifies the permission for the
|
|
53
|
+
* worker module itself; the worker also needs read access to the `code-mode`
|
|
54
|
+
* directory and to the QuickJS WASM file, which surface as `SANDBOX_FAILED` on
|
|
55
|
+
* the first run.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* assertSandboxIsolation("worker");
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
export function assertSandboxIsolation(isolation) {
|
|
63
|
+
if (isolation !== "worker" && isolation !== "inline") {
|
|
64
|
+
throw new RangeError('Code Mode isolation must be "worker" or "inline".');
|
|
65
|
+
}
|
|
66
|
+
if (isolation === "inline")
|
|
67
|
+
return;
|
|
68
|
+
const reason = workerIsolationUnavailable();
|
|
69
|
+
if (reason) {
|
|
70
|
+
throw new CodeModeError("SANDBOX_UNAVAILABLE", `Worker isolation is unavailable: ${reason}`, reason.includes("--allow-worker")
|
|
71
|
+
? 'Start Node with --allow-worker, or configure isolation: "inline"'
|
|
72
|
+
: 'Configure isolation: "inline" explicitly for this runtime', { context: { isolation } });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** A JSON copy of the params, identical in both isolations. */
|
|
76
|
+
function jsonParams(params, limit) {
|
|
77
|
+
let value;
|
|
78
|
+
try {
|
|
79
|
+
value = JSON.parse(encodeValue(params ?? {}, limit));
|
|
11
80
|
}
|
|
12
|
-
|
|
81
|
+
catch {
|
|
82
|
+
value = undefined;
|
|
83
|
+
}
|
|
84
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
85
|
+
throw new CodeModeError("PARAMS_INVALID", `params must be a JSON object within ${limit} characters`, "Pass a smaller plain object", { context: { limit } });
|
|
86
|
+
}
|
|
87
|
+
return value;
|
|
88
|
+
}
|
|
89
|
+
/** Wait for `work`, but give up as soon as `signal` aborts. A late rejection of `work` is observed. */
|
|
90
|
+
export function untilAborted(work, signal) {
|
|
91
|
+
return new Promise((resolve, reject) => {
|
|
92
|
+
if (signal.aborted) {
|
|
93
|
+
work.catch(() => { });
|
|
94
|
+
reject(signal.reason);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const abort = () => reject(signal.reason);
|
|
98
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
99
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
100
|
+
});
|
|
13
101
|
}
|
|
14
102
|
/** Wait for host I/O without allowing a provider that ignores cancellation to hold the VM open. */
|
|
15
|
-
function waitForOperation(invoke, signal
|
|
103
|
+
export function waitForOperation(invoke, signal,
|
|
104
|
+
/** True once the caller aborted or the wall deadline passed, even if its timer could not run. */
|
|
105
|
+
stopped = () => signal.aborted) {
|
|
16
106
|
signal.throwIfAborted();
|
|
17
107
|
return new Promise((resolve, reject) => {
|
|
18
108
|
const abort = () => reject(signal.reason);
|
|
19
109
|
signal.addEventListener("abort", abort, { once: true });
|
|
20
110
|
Promise.resolve().then(() => {
|
|
21
|
-
|
|
111
|
+
// Host work may have held the event loop since admission: check the clock
|
|
112
|
+
// right before any provider work starts.
|
|
113
|
+
if (stopped())
|
|
114
|
+
throw signal.reason;
|
|
22
115
|
return invoke();
|
|
23
116
|
}).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
24
117
|
});
|
|
25
118
|
}
|
|
26
119
|
/**
|
|
27
|
-
* Run a function body in an isolated QuickJS context. Only JSON and explicit
|
|
28
|
-
* operations cross into the host.
|
|
120
|
+
* Run a function body in an isolated QuickJS context. Only JSON and explicit
|
|
121
|
+
* snippet operations cross into the host. Host operations run one at a time,
|
|
122
|
+
* when the guest awaits them; their time does not count as guest CPU.
|
|
123
|
+
*
|
|
124
|
+
* Failures are {@link CodeModeError}s, except that a caller abort rejects with
|
|
125
|
+
* the caller signal's reason. `invoke` should reject with a CodeModeError;
|
|
126
|
+
* any other rejection reaches the guest as `OPERATION_FAILED`, without its
|
|
127
|
+
* message.
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* const value = await runProgram(
|
|
132
|
+
* "const r = await api.runSnippet('cad', 'plate-stl', {}); return r.value;",
|
|
133
|
+
* {},
|
|
134
|
+
* (operation, args) => myHost(operation, args),
|
|
135
|
+
* );
|
|
136
|
+
* ```
|
|
29
137
|
*/
|
|
30
|
-
export async function runProgram(code, params, invoke, callerSignal) {
|
|
138
|
+
export async function runProgram(code, params, invoke, callerSignal, options = {}) {
|
|
31
139
|
if (typeof code !== "string" || !code.trim() || code.length > maxCodeLength) {
|
|
32
|
-
throw new
|
|
140
|
+
throw new CodeModeError("INVALID_INPUT", `Supply a JavaScript function body of 1 to ${maxCodeLength} characters`, "Send a shorter function body", { context: { limit: maxCodeLength } });
|
|
33
141
|
}
|
|
34
|
-
|
|
35
|
-
|
|
142
|
+
const isolation = options.isolation ?? "worker";
|
|
143
|
+
assertSandboxIsolation(isolation);
|
|
144
|
+
const limits = resolveSandboxLimits(options.limits);
|
|
145
|
+
const input = jsonParams(params, limits.valueLength);
|
|
36
146
|
callerSignal?.throwIfAborted();
|
|
37
147
|
const controller = new AbortController();
|
|
38
148
|
const signal = controller.signal;
|
|
39
149
|
const abort = () => controller.abort(callerSignal?.reason);
|
|
40
150
|
callerSignal?.addEventListener("abort", abort, { once: true });
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
if (text.length > maxValueLength)
|
|
60
|
-
throw new Error("JSON value exceeds the size limit.");
|
|
61
|
-
return JSON.parse(text);
|
|
62
|
-
}
|
|
63
|
-
finally {
|
|
64
|
-
encoded.dispose();
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
function decode(value) {
|
|
68
|
-
const encoded = vm.newString(encodeValue(value));
|
|
69
|
-
try {
|
|
70
|
-
return scope.manage(vm.unwrapResult(vm.callFunction(parse, vm.undefined, encoded)));
|
|
71
|
-
}
|
|
72
|
-
finally {
|
|
73
|
-
encoded.dispose();
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
const dispatch = scope.manage(vm.newFunction("dispatch", (name, args) => {
|
|
77
|
-
if (++calls > maxOperations || vm.typeof(name) !== "string") {
|
|
78
|
-
throw new Error("Snippet operation limit exceeded.");
|
|
79
|
-
}
|
|
80
|
-
const operation = vm.getString(name);
|
|
81
|
-
const arguments_ = read(args);
|
|
82
|
-
if (!Array.isArray(arguments_))
|
|
83
|
-
throw new Error("Expected snippet arguments.");
|
|
84
|
-
const deferred = scope.manage(vm.newPromise());
|
|
85
|
-
pending.push(async () => {
|
|
86
|
-
try {
|
|
87
|
-
const result = await waitForOperation(() => invoke(operation, arguments_, signal), signal);
|
|
88
|
-
signal.throwIfAborted();
|
|
89
|
-
deferred.resolve(decode(result));
|
|
90
|
-
}
|
|
91
|
-
catch (error) {
|
|
92
|
-
const message = scope.manage(vm.newString(error instanceof Error ? error.message : "Snippet failed."));
|
|
93
|
-
deferred.reject(message);
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
return deferred.handle.dup();
|
|
97
|
-
}));
|
|
98
|
-
vm.setProp(vm.global, "dispatch", dispatch);
|
|
99
|
-
vm.setProp(vm.global, "params", decode(params));
|
|
100
|
-
const promise = scope.manage(vm.unwrapResult(vm.evalCode(`(() => {
|
|
101
|
-
const call = globalThis.dispatch, params = globalThis.params;
|
|
102
|
-
delete globalThis.dispatch;
|
|
103
|
-
delete globalThis.params;
|
|
104
|
-
const api = Object.freeze({
|
|
105
|
-
params,
|
|
106
|
-
listSnippets: (...args) => call("listSnippets", args),
|
|
107
|
-
runSnippet: (...args) => call("runSnippet", args),
|
|
108
|
-
panel: (...args) => call("panel", args),
|
|
109
|
-
});
|
|
110
|
-
return (async function(api) { "use strict";\n${code}\n})(api);
|
|
111
|
-
})()`, "mcpview-code-mode.js", { type: "global" })));
|
|
112
|
-
for (;;) {
|
|
113
|
-
signal.throwIfAborted();
|
|
114
|
-
if (performance.now() >= cpuDeadline) {
|
|
115
|
-
throw new Error("JavaScript exceeded its time limit.");
|
|
116
|
-
}
|
|
117
|
-
const state = vm.getPromiseState(promise);
|
|
118
|
-
if (state.type === "fulfilled") {
|
|
119
|
-
const value = scope.manage(state.value);
|
|
120
|
-
if (pending.length) {
|
|
121
|
-
throw new Error("Await every snippet operation, including api.panel().");
|
|
122
|
-
}
|
|
123
|
-
return vm.typeof(value) === "undefined" ? null : read(value);
|
|
124
|
-
}
|
|
125
|
-
if (state.type === "rejected") {
|
|
126
|
-
const reason = scope.manage(state.error);
|
|
127
|
-
throw new Error(vm.typeof(reason) === "string" ? vm.getString(reason) : "JavaScript failed.");
|
|
128
|
-
}
|
|
129
|
-
if (vm.runtime.hasPendingJob()) {
|
|
130
|
-
vm.unwrapResult(vm.runtime.executePendingJobs(1));
|
|
131
|
-
}
|
|
132
|
-
else if (pending.length) {
|
|
133
|
-
const before = performance.now();
|
|
134
|
-
await pending.shift()();
|
|
135
|
-
cpuDeadline += performance.now() - before;
|
|
136
|
-
}
|
|
137
|
-
else {
|
|
138
|
-
throw new Error("JavaScript is waiting on an unresolved promise.");
|
|
139
|
-
}
|
|
151
|
+
const wallDeadline = performance.now() + limits.wallMs;
|
|
152
|
+
const expire = () => controller.abort(new CodeModeError("TIME_LIMIT", `The program ran for more than ${limits.wallMs} ms`, "Split the work into several execute calls", { context: { limit: "wall", ms: limits.wallMs } }));
|
|
153
|
+
const timer = setTimeout(expire, limits.wallMs);
|
|
154
|
+
/** True once the caller aborted or the wall deadline passed, even if the timer could not run. */
|
|
155
|
+
const stopped = () => {
|
|
156
|
+
if (!signal.aborted && performance.now() >= wallDeadline)
|
|
157
|
+
expire();
|
|
158
|
+
return signal.aborted;
|
|
159
|
+
};
|
|
160
|
+
const call = async (operation, args) => {
|
|
161
|
+
try {
|
|
162
|
+
return await waitForOperation(() => invoke(operation, args, signal, stopped), signal, stopped);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
if (error instanceof CodeModeError)
|
|
166
|
+
throw error;
|
|
167
|
+
if (signal.aborted) {
|
|
168
|
+
throw new CodeModeError("INTERRUPTED", `api.${operation} was interrupted`, "Run the program again if the result is still needed");
|
|
140
169
|
}
|
|
141
|
-
|
|
170
|
+
throw new CodeModeError("OPERATION_FAILED", `api.${operation} failed`, "Check the arguments, then retry once", { context: { operation } });
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
try {
|
|
174
|
+
if (isolation === "inline") {
|
|
175
|
+
const quickjs = await untilAborted(getQuickJS(), signal);
|
|
176
|
+
signal.throwIfAborted();
|
|
177
|
+
const value = await runVm({
|
|
178
|
+
quickjs,
|
|
179
|
+
code,
|
|
180
|
+
params: input,
|
|
181
|
+
limits,
|
|
182
|
+
call,
|
|
183
|
+
// An inline guest holds the event loop, so the wall timer cannot fire: poll it.
|
|
184
|
+
isCancelled: stopped,
|
|
185
|
+
});
|
|
186
|
+
if (stopped())
|
|
187
|
+
throw signal.reason;
|
|
188
|
+
return value;
|
|
189
|
+
}
|
|
190
|
+
const value = await runInWorker({ code, params: input, limits, call, signal });
|
|
191
|
+
if (stopped())
|
|
192
|
+
throw signal.reason;
|
|
193
|
+
return value;
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
if (stopped())
|
|
197
|
+
throw signal.reason;
|
|
198
|
+
const failure = error instanceof CodeModeError ? error : new CodeModeError("SANDBOX_FAILED", "The sandbox failed while running the program", "Run the program again");
|
|
199
|
+
// A worker that died leaves provider calls in flight: cancel them, but keep this outcome.
|
|
200
|
+
if (failure.code === "SANDBOX_FAILED")
|
|
201
|
+
controller.abort(failure);
|
|
202
|
+
throw failure;
|
|
142
203
|
}
|
|
143
204
|
finally {
|
|
144
205
|
clearTimeout(timer);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ViewComponentEventPorts } from "../core/types/components.js";
|
|
2
|
+
import type { UiSyncRule } from "../core/types/sync-rules.js";
|
|
3
|
+
/** App-only metadata for explicit, receipt-scoped Compose rules. */
|
|
4
|
+
export declare const SNIPPET_SYNC_META_KEY = "io.mcpview/snippet-sync";
|
|
5
|
+
export declare function isPortName(value: unknown): value is string;
|
|
6
|
+
export declare function snippetPorts(events: Readonly<Record<string, ViewComponentEventPorts>> | undefined, name: string): ViewComponentEventPorts | undefined;
|
|
7
|
+
export declare function readSnippetEventPorts(value: unknown): ViewComponentEventPorts | undefined;
|
|
8
|
+
export declare function parseSnippetSyncRule(value: unknown): UiSyncRule | undefined;
|
|
9
|
+
export declare function supportsSnippetSync(rule: UiSyncRule, panels: ReadonlyMap<string, ViewComponentEventPorts | undefined>): boolean;
|
|
10
|
+
export declare function snippetSyncKey({ from, event, to, action }: UiSyncRule): string;
|
|
11
|
+
//# sourceMappingURL=sync.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/sync.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAC3E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAE9D,oEAAoE;AACpE,eAAO,MAAM,qBAAqB,4BAA4B,CAAC;AAE/D,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAG1D;AAED,wBAAgB,YAAY,CAC1B,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAAC,CAAC,GAAG,SAAS,EACrE,IAAI,EAAE,MAAM,GACX,uBAAuB,GAAG,SAAS,CAGrC;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,GAAG,SAAS,CAQzF;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU,GAAG,SAAS,CAW3E;AAED,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,UAAU,EAChB,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,uBAAuB,GAAG,SAAS,CAAC,GAC/D,OAAO,CAIT;AAED,wBAAgB,cAAc,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,UAAU,GAAG,MAAM,CAE9E"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { validateSyncRules } from "../core/sync/validator.js";
|
|
2
|
+
/** App-only metadata for explicit, receipt-scoped Compose rules. */
|
|
3
|
+
export const SNIPPET_SYNC_META_KEY = "io.mcpview/snippet-sync";
|
|
4
|
+
export function isPortName(value) {
|
|
5
|
+
return typeof value === "string" && value.length > 0 && value.length <= 120 &&
|
|
6
|
+
value.trim() === value && value !== "*";
|
|
7
|
+
}
|
|
8
|
+
export function snippetPorts(events, name) {
|
|
9
|
+
if (!events || !Object.hasOwn(events, name))
|
|
10
|
+
return;
|
|
11
|
+
return readSnippetEventPorts(events[name]);
|
|
12
|
+
}
|
|
13
|
+
export function readSnippetEventPorts(value) {
|
|
14
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
15
|
+
return;
|
|
16
|
+
const ports = value;
|
|
17
|
+
const names = (values) => Array.isArray(values) ? [...new Set(values.filter(isPortName))] : [];
|
|
18
|
+
const emits = names(ports.emits);
|
|
19
|
+
const accepts = names(ports.accepts);
|
|
20
|
+
if (emits.length || accepts.length)
|
|
21
|
+
return { emits, accepts };
|
|
22
|
+
}
|
|
23
|
+
export function parseSnippetSyncRule(value) {
|
|
24
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
25
|
+
return;
|
|
26
|
+
const fields = ["from", "event", "to", "action"];
|
|
27
|
+
if (Object.keys(value).length !== fields.length || !fields.every((key) => Object.hasOwn(value, key))) {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const { from, event, to, action } = value;
|
|
31
|
+
if (!isPortName(from) || !isPortName(event) || !isPortName(to) || !isPortName(action))
|
|
32
|
+
return;
|
|
33
|
+
return { from, event, to, action };
|
|
34
|
+
}
|
|
35
|
+
export function supportsSnippetSync(rule, panels) {
|
|
36
|
+
return validateSyncRules([rule], [rule.from, rule.to].filter((id) => panels.has(id))).valid &&
|
|
37
|
+
panels.get(rule.from)?.emits?.includes(rule.event) === true &&
|
|
38
|
+
panels.get(rule.to)?.accepts?.includes(rule.action) === true;
|
|
39
|
+
}
|
|
40
|
+
export function snippetSyncKey({ from, event, to, action }) {
|
|
41
|
+
return JSON.stringify([from, event, to, action]);
|
|
42
|
+
}
|
|
@@ -3,7 +3,7 @@ import type { SnippetProvider } from "./providers.js";
|
|
|
3
3
|
/** Configure the single model-facing tool and its MCP Apps board resource. */
|
|
4
4
|
export interface SnippetExecuteToolOptions {
|
|
5
5
|
readonly resourceUri: string;
|
|
6
|
-
readonly providers: ReadonlyMap<string, Pick<SnippetProvider, "names">>;
|
|
6
|
+
readonly providers: ReadonlyMap<string, Pick<SnippetProvider, "names" | "events">>;
|
|
7
7
|
/** Enable this when the chain uses a catalog and the host supplies a trusted scope. */
|
|
8
8
|
readonly savedChains?: boolean;
|
|
9
9
|
readonly annotations?: MCPTool["annotations"];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/tool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/tool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAItD,8EAA8E;AAC9E,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC;IACnF,uFAAuF;IACvF,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAC/B,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;CAC/C;AAED,0EAA0E;AAC1E,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAoEpF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { snippetPorts } from "./sync.js";
|
|
1
2
|
import { maxCodeLength } from "./sandbox.js";
|
|
2
3
|
/** Build the tool declaration for registration with an MCPView server. */
|
|
3
4
|
export function createSnippetExecuteTool(options) {
|
|
@@ -6,6 +7,10 @@ export function createSnippetExecuteTool(options) {
|
|
|
6
7
|
throw new Error("Supply a ui:// resource URI for the board.");
|
|
7
8
|
}
|
|
8
9
|
const available = [...options.providers.keys()];
|
|
10
|
+
const eventPorts = [...options.providers].flatMap(([provider, config]) => config.names.flatMap((snippet) => {
|
|
11
|
+
const ports = snippetPorts(config.events, snippet);
|
|
12
|
+
return ports ? [{ provider, snippet, ...ports }] : [];
|
|
13
|
+
}));
|
|
9
14
|
return {
|
|
10
15
|
name: "execute",
|
|
11
16
|
description: [
|
|
@@ -14,6 +19,15 @@ export function createSnippetExecuteTool(options) {
|
|
|
14
19
|
"Configured provider aliases: " + JSON.stringify(available) + ".",
|
|
15
20
|
"await api.runSnippet(provider, name, input) returns a receipt {id, value}.",
|
|
16
21
|
"Pass values between calls. Use await api.panel(receipt.id, optionalTitle) for each result to display, in display order. Return a JSON summary.",
|
|
22
|
+
"Await every api call (or pass them to Promise.all): a call that is never awaited does not run.",
|
|
23
|
+
"A failed api call throws an Error with code, recovery and context; tool errors read [execute] CODE: detail. Recovery: hint.",
|
|
24
|
+
...(eventPorts.length
|
|
25
|
+
? [
|
|
26
|
+
"After selecting both panels, use await api.sync({from: source.id, event, to: target.id, action}) to route a UI event between them.",
|
|
27
|
+
"Use the source's declared emits and the target's declared accepts. Available panel event ports: " +
|
|
28
|
+
JSON.stringify(eventPorts) + ".",
|
|
29
|
+
]
|
|
30
|
+
: []),
|
|
17
31
|
...(options.savedChains
|
|
18
32
|
? [
|
|
19
33
|
"Use saveAs to save a successful chain, listSaved to list your saved chains, or replay with the saved name and new params.",
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { CodeModeError } from "./errors.js";
|
|
2
|
+
import { type SandboxLimits } from "./sandbox-core.js";
|
|
3
|
+
import type { HostMessage } from "./worker-protocol.js";
|
|
4
|
+
/**
|
|
5
|
+
* Why worker isolation cannot run here, or undefined when it can. `scope` is the
|
|
6
|
+
* global object to inspect.
|
|
7
|
+
*/
|
|
8
|
+
export declare function workerIsolationUnavailable(scope?: object): string | undefined;
|
|
9
|
+
/** The part of `process` that tells whether Node's permission model allows workers. */
|
|
10
|
+
export interface NodeProcessLike {
|
|
11
|
+
readonly permission?: {
|
|
12
|
+
has?(scope: string): boolean;
|
|
13
|
+
};
|
|
14
|
+
readonly execArgv?: readonly string[];
|
|
15
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Why Node's enforced permission model forbids workers, or undefined. Audit mode
|
|
19
|
+
* (`--permission-audit`) reports a missing grant but still creates the worker, so it
|
|
20
|
+
* does not count.
|
|
21
|
+
*/
|
|
22
|
+
export declare function nodeWorkerPermission(process: NodeProcessLike | undefined): string | undefined;
|
|
23
|
+
/** The part of the host's Node options that a Code Mode worker can start with. */
|
|
24
|
+
export declare function nodeWorkerExecArgv(execArgv: readonly string[]): string[];
|
|
25
|
+
/**
|
|
26
|
+
* The host's `NODE_OPTIONS` reduced to what a Code Mode worker can start with. A
|
|
27
|
+
* worker inherits the environment by default, so `--input-type` or
|
|
28
|
+
* `--max-old-space-size` there would break it just like in `execArgv`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function nodeWorkerNodeOptions(options: string | undefined): string;
|
|
31
|
+
/**
|
|
32
|
+
* Split `NODE_OPTIONS` the way Node does: whitespace separates options, double
|
|
33
|
+
* quotes group (and are dropped), and inside quotes a backslash escapes the next
|
|
34
|
+
* character.
|
|
35
|
+
*/
|
|
36
|
+
export declare function parseNodeOptions(options: string): string[];
|
|
37
|
+
/** The host's environment with `NODE_OPTIONS` reduced for a worker. */
|
|
38
|
+
export declare function nodeWorkerEnv(env: Readonly<Record<string, string | undefined>>): Record<string, string | undefined>;
|
|
39
|
+
/**
|
|
40
|
+
* The reply for one host operation. The JSON text is bounded here, before it is
|
|
41
|
+
* posted, so an oversized result never crosses the worker boundary (no parse and
|
|
42
|
+
* no structured clone). The guest decodes the text.
|
|
43
|
+
*/
|
|
44
|
+
export declare function encodeReply(id: number, operation: string, value: unknown, valueLength: number): HostMessage;
|
|
45
|
+
/** Inputs of {@link runInWorker}. */
|
|
46
|
+
export interface WorkerRunInput {
|
|
47
|
+
readonly code: string;
|
|
48
|
+
readonly params: Record<string, unknown>;
|
|
49
|
+
readonly limits: SandboxLimits;
|
|
50
|
+
/** Host operation for the guest. Rejections should be {@link CodeModeError}s. */
|
|
51
|
+
call(operation: string, args: unknown[]): Promise<unknown>;
|
|
52
|
+
/** Aborting stops the guest at its next interrupt check. */
|
|
53
|
+
readonly signal: AbortSignal;
|
|
54
|
+
}
|
|
55
|
+
/** The error for a worker that could not be created at all. */
|
|
56
|
+
export declare function workerSpawnFailure(error: unknown): CodeModeError;
|
|
57
|
+
/**
|
|
58
|
+
* Run one program in a fresh worker and settle once with its value or a
|
|
59
|
+
* {@link CodeModeError}. The worker is always terminated afterwards.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* const value = await runInWorker({
|
|
64
|
+
* code: "return 1 + 1;", params: {}, limits: CODE_MODE_LIMITS,
|
|
65
|
+
* call: () => Promise.reject(new Error("unused")), signal: new AbortController().signal,
|
|
66
|
+
* });
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export declare function runInWorker(input: WorkerRunInput): Promise<unknown>;
|
|
70
|
+
//# sourceMappingURL=worker-host.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-host.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/worker-host.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAA2B,MAAM,aAAa,CAAC;AACrE,OAAO,EAAmB,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAgB,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAoBtE;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,GAAE,MAA8B,GAAG,MAAM,GAAG,SAAS,CAUpG;AAED,uFAAuF;AACvF,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE;QAAE,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;IACvD,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;CAC7D;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,eAAe,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAc7F;AA4CD,kFAAkF;AAClF,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAYxE;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAEzE;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAuB1D;AAOD,uEAAuE;AACvE,wBAAgB,aAAa,CAC3B,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,GAChD,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAIpC;AAyDD;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,EAAE,EAAE,MAAM,EACV,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,OAAO,EACd,WAAW,EAAE,MAAM,GAClB,WAAW,CAwBb;AAED,qCAAqC;AACrC,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzC,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,iFAAiF;IACjF,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC3D,4DAA4D;IAC5D,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;CAC9B;AAED,+DAA+D;AAC/D,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,CAWhE;AAUD;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAmHnE"}
|