@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.
Files changed (85) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/README.md +53 -0
  3. package/esm/src/code-mode/chain.d.ts +24 -1
  4. package/esm/src/code-mode/chain.d.ts.map +1 -1
  5. package/esm/src/code-mode/chain.js +219 -86
  6. package/esm/src/code-mode/errors.d.ts +80 -0
  7. package/esm/src/code-mode/errors.d.ts.map +1 -0
  8. package/esm/src/code-mode/errors.js +140 -0
  9. package/esm/src/code-mode/guest-worker.d.ts +11 -0
  10. package/esm/src/code-mode/guest-worker.d.ts.map +1 -0
  11. package/esm/src/code-mode/guest-worker.js +80 -0
  12. package/esm/src/code-mode/mod.d.ts +3 -1
  13. package/esm/src/code-mode/mod.d.ts.map +1 -1
  14. package/esm/src/code-mode/mod.js +2 -0
  15. package/esm/src/code-mode/sandbox-core.d.ts +61 -0
  16. package/esm/src/code-mode/sandbox-core.d.ts.map +1 -0
  17. package/esm/src/code-mode/sandbox-core.js +424 -0
  18. package/esm/src/code-mode/sandbox.d.ts +68 -7
  19. package/esm/src/code-mode/sandbox.d.ts.map +1 -1
  20. package/esm/src/code-mode/sandbox.js +182 -120
  21. package/esm/src/code-mode/tool.d.ts.map +1 -1
  22. package/esm/src/code-mode/tool.js +2 -0
  23. package/esm/src/code-mode/worker-host.d.ts +82 -0
  24. package/esm/src/code-mode/worker-host.d.ts.map +1 -0
  25. package/esm/src/code-mode/worker-host.js +364 -0
  26. package/esm/src/code-mode/worker-protocol.d.ts +44 -0
  27. package/esm/src/code-mode/worker-protocol.d.ts.map +1 -0
  28. package/esm/src/code-mode/worker-protocol.js +7 -0
  29. package/esm/src/host/renderer/css/panel-controls.d.ts.map +1 -1
  30. package/esm/src/host/renderer/css/panel-controls.js +5 -1
  31. package/esm/src/host/renderer/js/card-height.d.ts +11 -1
  32. package/esm/src/host/renderer/js/card-height.d.ts.map +1 -1
  33. package/esm/src/host/renderer/js/card-height.js +57 -10
  34. package/esm/src/host/renderer/js/event-bus.d.ts +11 -0
  35. package/esm/src/host/renderer/js/event-bus.d.ts.map +1 -1
  36. package/esm/src/host/renderer/js/event-bus.js +49 -8
  37. package/esm/src/host/renderer/js/intrinsic-layout.d.ts +26 -0
  38. package/esm/src/host/renderer/js/intrinsic-layout.d.ts.map +1 -0
  39. package/esm/src/host/renderer/js/intrinsic-layout.js +44 -0
  40. package/esm/src/host/renderer/panel-resizing.d.ts.map +1 -1
  41. package/esm/src/host/renderer/panel-resizing.js +8 -0
  42. package/esm/src/version.d.ts +1 -1
  43. package/esm/src/version.js +1 -1
  44. package/package.json +1 -1
  45. package/script/src/code-mode/chain.d.ts +24 -1
  46. package/script/src/code-mode/chain.d.ts.map +1 -1
  47. package/script/src/code-mode/chain.js +218 -85
  48. package/script/src/code-mode/errors.d.ts +80 -0
  49. package/script/src/code-mode/errors.d.ts.map +1 -0
  50. package/script/src/code-mode/errors.js +148 -0
  51. package/script/src/code-mode/guest-worker.d.ts +11 -0
  52. package/script/src/code-mode/guest-worker.d.ts.map +1 -0
  53. package/script/src/code-mode/guest-worker.js +105 -0
  54. package/script/src/code-mode/mod.d.ts +3 -1
  55. package/script/src/code-mode/mod.d.ts.map +1 -1
  56. package/script/src/code-mode/mod.js +9 -1
  57. package/script/src/code-mode/sandbox-core.d.ts +61 -0
  58. package/script/src/code-mode/sandbox-core.d.ts.map +1 -0
  59. package/script/src/code-mode/sandbox-core.js +430 -0
  60. package/script/src/code-mode/sandbox.d.ts +68 -7
  61. package/script/src/code-mode/sandbox.d.ts.map +1 -1
  62. package/script/src/code-mode/sandbox.js +190 -122
  63. package/script/src/code-mode/tool.d.ts.map +1 -1
  64. package/script/src/code-mode/tool.js +2 -0
  65. package/script/src/code-mode/worker-host.d.ts +82 -0
  66. package/script/src/code-mode/worker-host.d.ts.map +1 -0
  67. package/script/src/code-mode/worker-host.js +399 -0
  68. package/script/src/code-mode/worker-protocol.d.ts +44 -0
  69. package/script/src/code-mode/worker-protocol.d.ts.map +1 -0
  70. package/script/src/code-mode/worker-protocol.js +8 -0
  71. package/script/src/host/renderer/css/panel-controls.d.ts.map +1 -1
  72. package/script/src/host/renderer/css/panel-controls.js +5 -1
  73. package/script/src/host/renderer/js/card-height.d.ts +11 -1
  74. package/script/src/host/renderer/js/card-height.d.ts.map +1 -1
  75. package/script/src/host/renderer/js/card-height.js +57 -10
  76. package/script/src/host/renderer/js/event-bus.d.ts +11 -0
  77. package/script/src/host/renderer/js/event-bus.d.ts.map +1 -1
  78. package/script/src/host/renderer/js/event-bus.js +50 -8
  79. package/script/src/host/renderer/js/intrinsic-layout.d.ts +26 -0
  80. package/script/src/host/renderer/js/intrinsic-layout.d.ts.map +1 -0
  81. package/script/src/host/renderer/js/intrinsic-layout.js +48 -0
  82. package/script/src/host/renderer/panel-resizing.d.ts.map +1 -1
  83. package/script/src/host/renderer/panel-resizing.js +8 -0
  84. package/script/src/version.d.ts +1 -1
  85. package/script/src/version.js +1 -1
@@ -1,145 +1,207 @@
1
- import { getQuickJS, Scope } from "quickjs-emscripten";
2
- /** Maximum source length accepted by the code-mode execute tool. */
3
- export const maxCodeLength = 16_384;
4
- const maxValueLength = 128 * 1024;
5
- const maxOperations = 16;
6
- /** Serialize data crossing the QuickJS boundary within the supplied limit. */
7
- export function encodeValue(value, limit = maxValueLength) {
8
- const text = JSON.stringify(value);
9
- if (text === undefined || text.length > limit) {
10
- throw new Error("Expected a JSON value within the size limit.");
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
+ : reason.startsWith("Deno has no ")
73
+ ? 'Grant that Deno permission, or configure isolation: "inline"'
74
+ : 'Configure isolation: "inline" explicitly for this runtime', { context: { isolation } });
75
+ }
76
+ }
77
+ /** A JSON copy of the params, identical in both isolations. */
78
+ function jsonParams(params, limit) {
79
+ let value;
80
+ try {
81
+ value = JSON.parse(encodeValue(params ?? {}, limit));
11
82
  }
12
- return text;
83
+ catch {
84
+ value = undefined;
85
+ }
86
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
87
+ throw new CodeModeError("PARAMS_INVALID", `params must be a JSON object within ${limit} characters`, "Pass a smaller plain object", { context: { limit } });
88
+ }
89
+ return value;
90
+ }
91
+ /** Wait for `work`, but give up as soon as `signal` aborts. A late rejection of `work` is observed. */
92
+ export function untilAborted(work, signal) {
93
+ return new Promise((resolve, reject) => {
94
+ if (signal.aborted) {
95
+ work.catch(() => { });
96
+ reject(signal.reason);
97
+ return;
98
+ }
99
+ const abort = () => reject(signal.reason);
100
+ signal.addEventListener("abort", abort, { once: true });
101
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
102
+ });
13
103
  }
14
104
  /** Wait for host I/O without allowing a provider that ignores cancellation to hold the VM open. */
15
- function waitForOperation(invoke, signal) {
105
+ export function waitForOperation(invoke, signal,
106
+ /** True once the caller aborted or the wall deadline passed, even if its timer could not run. */
107
+ stopped = () => signal.aborted) {
16
108
  signal.throwIfAborted();
17
109
  return new Promise((resolve, reject) => {
18
110
  const abort = () => reject(signal.reason);
19
111
  signal.addEventListener("abort", abort, { once: true });
20
112
  Promise.resolve().then(() => {
21
- signal.throwIfAborted();
113
+ // Host work may have held the event loop since admission: check the clock
114
+ // right before any provider work starts.
115
+ if (stopped())
116
+ throw signal.reason;
22
117
  return invoke();
23
118
  }).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
24
119
  });
25
120
  }
26
121
  /**
27
- * Run a function body in an isolated QuickJS context. Only JSON and explicit snippet
28
- * operations cross into the host. Execute host requests when the guest yields.
122
+ * Run a function body in an isolated QuickJS context. Only JSON and explicit
123
+ * snippet operations cross into the host. Host operations run one at a time,
124
+ * when the guest awaits them; their time does not count as guest CPU.
125
+ *
126
+ * Failures are {@link CodeModeError}s, except that a caller abort rejects with
127
+ * the caller signal's reason. `invoke` should reject with a CodeModeError;
128
+ * any other rejection reaches the guest as `OPERATION_FAILED`, without its
129
+ * message.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * const value = await runProgram(
134
+ * "const r = await api.runSnippet('cad', 'plate-stl', {}); return r.value;",
135
+ * {},
136
+ * (operation, args) => myHost(operation, args),
137
+ * );
138
+ * ```
29
139
  */
30
- export async function runProgram(code, params, invoke, callerSignal) {
140
+ export async function runProgram(code, params, invoke, callerSignal, options = {}) {
31
141
  if (typeof code !== "string" || !code.trim() || code.length > maxCodeLength) {
32
- throw new Error("Supply a JavaScript function body of at most 16 KiB.");
142
+ throw new CodeModeError("INVALID_INPUT", `Supply a JavaScript function body of 1 to ${maxCodeLength} characters`, "Send a shorter function body", { context: { limit: maxCodeLength } });
33
143
  }
34
- callerSignal?.throwIfAborted();
35
- const wasm = await getQuickJS();
144
+ const isolation = options.isolation ?? "worker";
145
+ assertSandboxIsolation(isolation);
146
+ const limits = resolveSandboxLimits(options.limits);
147
+ const input = jsonParams(params, limits.valueLength);
36
148
  callerSignal?.throwIfAborted();
37
149
  const controller = new AbortController();
38
150
  const signal = controller.signal;
39
151
  const abort = () => controller.abort(callerSignal?.reason);
40
152
  callerSignal?.addEventListener("abort", abort, { once: true });
41
- const timer = setTimeout(() => controller.abort(new Error("JavaScript exceeded its time limit.")), 30_000);
42
- try {
43
- return await Scope.withScopeAsync(async (scope) => {
44
- const vm = scope.manage(wasm.newContext());
45
- let cpuDeadline = performance.now() + 2000;
46
- vm.runtime.setMemoryLimit(12 * 1024 * 1024);
47
- vm.runtime.setMaxStackSize(192 * 1024);
48
- vm.runtime.setInterruptHandler(() => signal.aborted || performance.now() >= cpuDeadline);
49
- const stringify = scope.manage(vm.unwrapResult(vm.evalCode("JSON.stringify.bind(JSON)")));
50
- const parse = scope.manage(vm.unwrapResult(vm.evalCode("JSON.parse.bind(JSON)")));
51
- const pending = [];
52
- let calls = 0;
53
- function read(handle) {
54
- const encoded = vm.unwrapResult(vm.callFunction(stringify, vm.undefined, handle));
55
- try {
56
- if (vm.typeof(encoded) !== "string")
57
- throw new Error("Expected a JSON value.");
58
- const text = vm.getString(encoded);
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
- sync: (...args) => call("sync", args),
110
- });
111
- return (async function(api) { "use strict";\n${code}\n})(api);
112
- })()`, "mcpview-code-mode.js", { type: "global" })));
113
- for (;;) {
114
- signal.throwIfAborted();
115
- if (performance.now() >= cpuDeadline) {
116
- throw new Error("JavaScript exceeded its time limit.");
117
- }
118
- const state = vm.getPromiseState(promise);
119
- if (state.type === "fulfilled") {
120
- const value = scope.manage(state.value);
121
- if (pending.length) {
122
- throw new Error("Await every snippet operation, including api.panel() and api.sync().");
123
- }
124
- return vm.typeof(value) === "undefined" ? null : read(value);
125
- }
126
- if (state.type === "rejected") {
127
- const reason = scope.manage(state.error);
128
- throw new Error(vm.typeof(reason) === "string" ? vm.getString(reason) : "JavaScript failed.");
129
- }
130
- if (vm.runtime.hasPendingJob()) {
131
- vm.unwrapResult(vm.runtime.executePendingJobs(1));
132
- }
133
- else if (pending.length) {
134
- const before = performance.now();
135
- await pending.shift()();
136
- cpuDeadline += performance.now() - before;
137
- }
138
- else {
139
- throw new Error("JavaScript is waiting on an unresolved promise.");
140
- }
153
+ const wallDeadline = performance.now() + limits.wallMs;
154
+ 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 } }));
155
+ const timer = setTimeout(expire, limits.wallMs);
156
+ /** True once the caller aborted or the wall deadline passed, even if the timer could not run. */
157
+ const stopped = () => {
158
+ if (!signal.aborted && performance.now() >= wallDeadline)
159
+ expire();
160
+ return signal.aborted;
161
+ };
162
+ const call = async (operation, args) => {
163
+ try {
164
+ return await waitForOperation(() => invoke(operation, args, signal, stopped), signal, stopped);
165
+ }
166
+ catch (error) {
167
+ if (error instanceof CodeModeError)
168
+ throw error;
169
+ if (signal.aborted) {
170
+ throw new CodeModeError("INTERRUPTED", `api.${operation} was interrupted`, "Run the program again if the result is still needed");
141
171
  }
142
- });
172
+ throw new CodeModeError("OPERATION_FAILED", `api.${operation} failed`, "Check the arguments, then retry once", { context: { operation } });
173
+ }
174
+ };
175
+ try {
176
+ if (isolation === "inline") {
177
+ const quickjs = await untilAborted(getQuickJS(), signal);
178
+ signal.throwIfAborted();
179
+ const value = await runVm({
180
+ quickjs,
181
+ code,
182
+ params: input,
183
+ limits,
184
+ call,
185
+ // An inline guest holds the event loop, so the wall timer cannot fire: poll it.
186
+ isCancelled: stopped,
187
+ });
188
+ if (stopped())
189
+ throw signal.reason;
190
+ return value;
191
+ }
192
+ const value = await runInWorker({ code, params: input, limits, call, signal });
193
+ if (stopped())
194
+ throw signal.reason;
195
+ return value;
196
+ }
197
+ catch (error) {
198
+ if (stopped())
199
+ throw signal.reason;
200
+ const failure = error instanceof CodeModeError ? error : new CodeModeError("SANDBOX_FAILED", "The sandbox failed while running the program", "Run the program again");
201
+ // A worker that died leaves provider calls in flight: cancel them, but keep this outcome.
202
+ if (failure.code === "SANDBOX_FAILED")
203
+ controller.abort(failure);
204
+ throw failure;
143
205
  }
144
206
  finally {
145
207
  clearTimeout(timer);
@@ -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;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,CAkEpF"}
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"}
@@ -19,6 +19,8 @@ export function createSnippetExecuteTool(options) {
19
19
  "Configured provider aliases: " + JSON.stringify(available) + ".",
20
20
  "await api.runSnippet(provider, name, input) returns a receipt {id, value}.",
21
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.",
22
24
  ...(eventPorts.length
23
25
  ? [
24
26
  "After selecting both panels, use await api.sync({from: source.id, event, to: target.id, action}) to route a UI event between them.",
@@ -0,0 +1,82 @@
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
+ /**
24
+ * The permission Deno needs to load the guest module, or undefined for schemes it does
25
+ * not gate. An import query must name the port: a bare `jsr.io` asks about every port
26
+ * and reads "prompt", although Deno grants `jsr.io:443` by default.
27
+ */
28
+ export declare function guestModulePermission(url: URL): {
29
+ name: "read";
30
+ path: URL;
31
+ } | {
32
+ name: "import";
33
+ host: string;
34
+ } | undefined;
35
+ /** The part of the host's Node options that a Code Mode worker can start with. */
36
+ export declare function nodeWorkerExecArgv(execArgv: readonly string[]): string[];
37
+ /**
38
+ * The host's `NODE_OPTIONS` reduced to what a Code Mode worker can start with. A
39
+ * worker inherits the environment by default, so `--input-type` or
40
+ * `--max-old-space-size` there would break it just like in `execArgv`.
41
+ */
42
+ export declare function nodeWorkerNodeOptions(options: string | undefined): string;
43
+ /**
44
+ * Split `NODE_OPTIONS` the way Node does: whitespace separates options, double
45
+ * quotes group (and are dropped), and inside quotes a backslash escapes the next
46
+ * character.
47
+ */
48
+ export declare function parseNodeOptions(options: string): string[];
49
+ /** The host's environment with `NODE_OPTIONS` reduced for a worker. */
50
+ export declare function nodeWorkerEnv(env: Readonly<Record<string, string | undefined>>): Record<string, string | undefined>;
51
+ /**
52
+ * The reply for one host operation. The JSON text is bounded here, before it is
53
+ * posted, so an oversized result never crosses the worker boundary (no parse and
54
+ * no structured clone). The guest decodes the text.
55
+ */
56
+ export declare function encodeReply(id: number, operation: string, value: unknown, valueLength: number): HostMessage;
57
+ /** Inputs of {@link runInWorker}. */
58
+ export interface WorkerRunInput {
59
+ readonly code: string;
60
+ readonly params: Record<string, unknown>;
61
+ readonly limits: SandboxLimits;
62
+ /** Host operation for the guest. Rejections should be {@link CodeModeError}s. */
63
+ call(operation: string, args: unknown[]): Promise<unknown>;
64
+ /** Aborting stops the guest at its next interrupt check. */
65
+ readonly signal: AbortSignal;
66
+ }
67
+ /** The error for a worker that could not be created at all. */
68
+ export declare function workerSpawnFailure(error: unknown): CodeModeError;
69
+ /**
70
+ * Run one program in a fresh worker and settle once with its value or a
71
+ * {@link CodeModeError}. The worker is always terminated afterwards.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * const value = await runInWorker({
76
+ * code: "return 1 + 1;", params: {}, limits: CODE_MODE_LIMITS,
77
+ * call: () => Promise.reject(new Error("unused")), signal: new AbortController().signal,
78
+ * });
79
+ * ```
80
+ */
81
+ export declare function runInWorker(input: WorkerRunInput): Promise<unknown>;
82
+ //# 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,CA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