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