@mcpview/compose 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +101 -1
  2. package/README.md +113 -22
  3. package/esm/src/code-mode/engine.d.ts +59 -0
  4. package/esm/src/code-mode/engine.d.ts.map +1 -0
  5. package/esm/src/code-mode/engine.js +189 -0
  6. package/esm/src/code-mode/guest-worker.d.ts +2 -5
  7. package/esm/src/code-mode/guest-worker.d.ts.map +1 -1
  8. package/esm/src/code-mode/guest-worker.js +4 -75
  9. package/esm/src/code-mode/sandbox-api.d.ts +37 -0
  10. package/esm/src/code-mode/sandbox-api.d.ts.map +1 -0
  11. package/esm/src/code-mode/sandbox-api.js +36 -0
  12. package/esm/src/code-mode/sandbox-core.d.ts +99 -21
  13. package/esm/src/code-mode/sandbox-core.d.ts.map +1 -1
  14. package/esm/src/code-mode/sandbox-core.js +926 -221
  15. package/esm/src/code-mode/sandbox-worker.d.ts +37 -0
  16. package/esm/src/code-mode/sandbox-worker.d.ts.map +1 -0
  17. package/esm/src/code-mode/sandbox-worker.js +140 -0
  18. package/esm/src/code-mode/sandbox.d.ts +142 -29
  19. package/esm/src/code-mode/sandbox.d.ts.map +1 -1
  20. package/esm/src/code-mode/sandbox.js +399 -67
  21. package/esm/src/code-mode/surface.d.ts +148 -0
  22. package/esm/src/code-mode/surface.d.ts.map +1 -0
  23. package/esm/src/code-mode/surface.js +204 -0
  24. package/esm/src/code-mode/tool.js +1 -1
  25. package/esm/src/code-mode/worker-host.d.ts +39 -11
  26. package/esm/src/code-mode/worker-host.d.ts.map +1 -1
  27. package/esm/src/code-mode/worker-host.js +100 -43
  28. package/esm/src/code-mode/worker-protocol.d.ts +45 -8
  29. package/esm/src/code-mode/worker-protocol.d.ts.map +1 -1
  30. package/esm/src/code-mode/worker-protocol.js +4 -2
  31. package/esm/src/version.d.ts +1 -1
  32. package/esm/src/version.js +1 -1
  33. package/package.json +9 -1
  34. package/script/src/code-mode/engine.d.ts +59 -0
  35. package/script/src/code-mode/engine.d.ts.map +1 -0
  36. package/script/src/code-mode/engine.js +198 -0
  37. package/script/src/code-mode/guest-worker.d.ts +2 -5
  38. package/script/src/code-mode/guest-worker.d.ts.map +1 -1
  39. package/script/src/code-mode/guest-worker.js +4 -98
  40. package/script/src/code-mode/sandbox-api.d.ts +37 -0
  41. package/script/src/code-mode/sandbox-api.d.ts.map +1 -0
  42. package/script/src/code-mode/sandbox-api.js +50 -0
  43. package/script/src/code-mode/sandbox-core.d.ts +99 -21
  44. package/script/src/code-mode/sandbox-core.d.ts.map +1 -1
  45. package/script/src/code-mode/sandbox-core.js +931 -221
  46. package/script/src/code-mode/sandbox-worker.d.ts +37 -0
  47. package/script/src/code-mode/sandbox-worker.d.ts.map +1 -0
  48. package/script/src/code-mode/sandbox-worker.js +166 -0
  49. package/script/src/code-mode/sandbox.d.ts +142 -29
  50. package/script/src/code-mode/sandbox.d.ts.map +1 -1
  51. package/script/src/code-mode/sandbox.js +429 -72
  52. package/script/src/code-mode/surface.d.ts +148 -0
  53. package/script/src/code-mode/surface.d.ts.map +1 -0
  54. package/script/src/code-mode/surface.js +211 -0
  55. package/script/src/code-mode/tool.js +1 -1
  56. package/script/src/code-mode/worker-host.d.ts +39 -11
  57. package/script/src/code-mode/worker-host.d.ts.map +1 -1
  58. package/script/src/code-mode/worker-host.js +100 -42
  59. package/script/src/code-mode/worker-protocol.d.ts +45 -8
  60. package/script/src/code-mode/worker-protocol.d.ts.map +1 -1
  61. package/script/src/code-mode/worker-protocol.js +4 -2
  62. package/script/src/version.d.ts +1 -1
  63. package/script/src/version.js +1 -1
package/CHANGELOG.md CHANGED
@@ -3,7 +3,107 @@
3
3
  All notable changes to `@mcpview/compose` (published as `@casys/mcp-compose` up to 0.9.1) will be
4
4
  documented in this file.
5
5
 
6
- ## [Unreleased]
6
+ ## [0.15.0] - 2026-12-01
7
+
8
+ ### Added
9
+
10
+ - `@mcpview/compose/code-mode/sandbox`: the Code Mode sandbox for another package's own vocabulary.
11
+ `runSandboxProgram(code, surface, invoke, signal, options)` runs a program against a
12
+ `SandboxSurface` the host declares: the name of the object the program receives, JSON constants
13
+ and a closed table of operations with named budgets. Compose's chain declares `api` and its four
14
+ operations on the same sandbox. See ADR 0007.
15
+ - Operation options: `start: "on-call"` sends a call as soon as the program makes it, and its
16
+ failure ends the run before any later call; `resultArguments: "reference"` passes an earlier
17
+ result as a `SandboxResultReference` to the call that produced it, and `returnedResult` set to
18
+ `"reference"` on the surface reports a returned result the same way. Results of such a surface are
19
+ frozen before the program receives them. The host callback receives an identifier with each call.
20
+ - `SandboxHostError(code, message, recovery)`: an error in the host's own vocabulary. The program
21
+ reads it in a `catch`; if it does not handle it, the run rejects with the host's original object.
22
+ It cannot take a code the sandbox itself throws into a program, such as `OPERATION_FAILED`.
23
+ - The `irreversible(operation, args)` option marks a call whose effect cannot be undone, such as an
24
+ approved write. The wall limit does not cut it: the wall clock stops while it runs, and a call
25
+ that arrives after the limit is not sent. Once the host has completed it, a result that cannot be
26
+ handed to the program (too large, not JSON, no memory left) ends the run, where another call gets
27
+ an error the program can catch.
28
+ - The `onUnsentCalls(calls)` option: when a program finished normally with calls it did not wait
29
+ for, the host is told which ones, in the order they were made, and decides. It returns to let the
30
+ program's value stand, or throws to fail the run with its own error.
31
+ - `SandboxResourceLimits`, `SANDBOX_RESOURCE_LIMITS` and `resolveSandboxResourceLimits`: the five
32
+ resource limits of a program (CPU time, wall time, memory, stack, value length), which the public
33
+ sandbox takes as `limits`. Call counts are the budgets of the surface; `SandboxLimits` and
34
+ `CODE_MODE_LIMITS` keep their shape for the chain.
35
+ - `@mcpview/compose/code-mode/sandbox-worker` (`serveSandboxWorker`) and the `worker` option, for a
36
+ host bundled into one file: it ships the worker as a second file, whose entry calls
37
+ `serveSandboxWorker`, names that file in the option, and copies the engine's
38
+ `emscripten-module.wasm` next to its bundle. The README says how a build script finds that file
39
+ and lists what each mistake fails with.
40
+ - The build of the npm package now runs a program from the built package as ESM and as CommonJS, and
41
+ from an esbuild bundle with its worker and its `.wasm` file, starts a worker that serves nothing,
42
+ and builds a browser-targeted bundle. CI runs it for every change.
43
+
44
+ ### Changed
45
+
46
+ - **Breaking:** once a program has finished, nothing more of it is sent. A call it started but did
47
+ not wait for (a handler attached without `await`, the loser of a `Promise.race`, the rest of a
48
+ `Promise.all` that failed early) is no longer run after the program: it is not sent, and the
49
+ program fails with `UNAWAITED_OPERATION`, like a call that was never started. Since 0.14.0 such a
50
+ call ran after the program had returned, where the program could not see whether it failed.
51
+ Migration: wait for every call, with `await`, `Promise.all`, or `Promise.allSettled` when one of
52
+ them may fail. The text of `UNAWAITED_OPERATION` now reads "did not wait for" and "were not sent".
53
+ This amends ADR 0006; see ADR 0007.
54
+ - A call refused where it is written, for arguments that are not JSON, no longer counts against its
55
+ budget: it was not made.
56
+ - An error handed to a program no longer has a `ref` property: the sandbox recognises its own errors
57
+ without writing on them. A `CodeModeError` a host operation rejects with crosses by its fields in
58
+ both isolations: when the program does not handle it, the run rejects with an equal error. With
59
+ `isolation: "inline"` it was the host's own object.
60
+ - `resolveSandboxLimits` and `resolveSandboxResourceLimits` treat a limit given as `undefined` as
61
+ not given, instead of refusing it.
62
+ - An error of the sandbox raised while a result or an argument is serialized, such as the
63
+ `OPERATION_LIMIT` of a call a `toJSON` makes over the budget, is reported as itself. It was
64
+ replaced by `RESULT_INVALID` or `ARGUMENT_INVALID`.
65
+ - A program reaches the object it receives and nothing else of the sandbox. Up to 0.14 it could read
66
+ `params` without `api.` and call the internal `declare` and `start` functions; a saved chain that
67
+ reads `params` directly must read `api.params`.
68
+ - An engine that cannot be loaded, for example because its `.wasm` file is not readable, fails the
69
+ run with `SANDBOX_UNAVAILABLE` and a recovery that names the file. It was `SANDBOX_FAILED` with
70
+ the advice to run the program again.
71
+ - The recovery texts of `OPERATION_LIMIT` and `TIME_LIMIT` say "several runs" where they named the
72
+ `execute` tool and the saved chain. The text of `OPERATION_LIMIT` for the board budget says "board
73
+ calls" where it said "board operations". Codes and contexts are unchanged.
74
+ - In a program's own stack traces its first line is now line 2 of `mcpview-code-mode.js`. It was
75
+ line 25, after the sandbox's own setup code.
76
+
77
+ ### Fixed
78
+
79
+ - Every program now runs in its own fresh WebAssembly instance, in `inline` as well as `worker`
80
+ isolation, with a bounded `WebAssembly.Memory` (and initial C-heap reservation below the 16 MiB
81
+ WASM floor) plus a guarded `_malloc`. QuickJS's Emscripten build lacks `malloc_usable_size`, which
82
+ let `ArrayBuffer`s, strings and arrays bypass `memoryBytes` up to 2 GiB and let `newString` write
83
+ at WASM address `0` when `_malloc` returned `0`, poisoning later inline runs. `memoryBytes` now
84
+ genuinely caps every allocation type, and no program state can cross to another run.
85
+ - Data nested a few thousand levels deep made the host's stack overflow inside the engine's native
86
+ JSON functions: the run ended as `SANDBOX_FAILED` and freeing the VM aborted. It now ends as
87
+ `RESOURCE_LIMIT` with `limit: "stack"`, and the faulted engine instance is abandoned.
88
+ - A program that allocated many objects after an `await` could finish correctly and still fail with
89
+ `SANDBOX_FAILED`: QuickJS leaks such objects and then aborts when the runtime is freed. The
90
+ program's value, or its own failure, now stands.
91
+ - A program that made `code`, `recovery` or `context` read-only on `Error.prototype`, put `get` or
92
+ `set` on `Object.prototype`, or replaced `Promise.prototype.then` could break error delivery or
93
+ hijack awaited operations. The sandbox's own code inside the engine now reads nothing through a
94
+ prototype the program can change.
95
+ - A program at its memory limit could freeze the host with `isolation: "inline"`, or leave a worker
96
+ thread spinning: the sandbox asked the engine to describe an error it had no room to build. Such a
97
+ program now ends with `RESOURCE_LIMIT`, and stack overflows or out-of-memory failures inside a
98
+ thrown error's getters report `RESOURCE_LIMIT` instead of `GUEST_ERROR`. Errors carry their host
99
+ fields in a private class field so QuickJS frees dropped errors immediately on refcount zero.
100
+ - A value nested a few thousand levels deep crossed with `isolation: "inline"` and crashed the
101
+ worker under Deno (`SANDBOX_FAILED`, with an uncaught error on stderr), as an argument, a result,
102
+ a returned value or a constant. Every value now crosses the worker boundary as JSON text, so both
103
+ isolations accept the same values.
104
+ - With `isolation: "inline"`, a host result that the host itself cannot serialize is
105
+ `OPERATION_FAILED`, as it already was with `isolation: "worker"`. With `isolation: "worker"`, that
106
+ error now carries the same `context.operation` as inline.
7
107
 
8
108
  ## [0.14.1] - 2026-11-29
9
109
 
package/README.md CHANGED
@@ -127,18 +127,18 @@ cannot start the worker module. An unavailable isolation fails at configuration
127
127
  permissions: grant read access to the `code-mode` directory of the package and to the QuickJS WASM
128
128
  file shipped with `quickjs-emscripten`. Loaded from JSR, the package directory needs import access
129
129
  to `jsr.io:443` instead, which Deno grants by default. Configuration only checks the worker module
130
- itself; a missing grant for the other files fails the first run with `SANDBOX_FAILED`, so run one
131
- program at startup to verify the setup. `CODE_MODE_LIMITS` gives the defaults: 2 s of guest CPU
132
- (host calls excluded), 30 s of wall time, 12 MiB of memory, 16 provider calls (`listSnippets`,
133
- `runSnippet`) and 48 board operations (`panel`, `sync`) per program. Pass `limits` to override some
134
- of them (`memoryBytes` must be at least 64 KiB and `stackBytes` at least 16 KiB, or configuration
135
- throws a `RangeError`). `valueLength` counts UTF-16 code units of the JSON text, not UTF-8 bytes.
136
- Under Node's permission model, workers need `--allow-worker`; without it configuration fails with
137
- `SANDBOX_UNAVAILABLE` (audit mode does not count). Browsers have no worker guest: a browser-targeted
138
- bundle must use `isolation: "inline"` (the default `"worker"` fails at configuration with
139
- `SANDBOX_UNAVAILABLE`); the Node worker adapter is loaded at run time, so bundlers do not resolve
140
- `node:worker_threads`. `NODE_OPTIONS` that a worker cannot start with (such as `--input-type`) are
141
- not passed to it either.
130
+ itself: a missing grant for the modules it imports fails the first run with `SANDBOX_FAILED`, and
131
+ one for the WASM file with `SANDBOX_UNAVAILABLE`, so run one program at startup to verify the setup.
132
+ `CODE_MODE_LIMITS` gives the defaults: 2 s of guest CPU (host calls excluded), 30 s of wall time, 12
133
+ MiB of memory, 16 provider calls (`listSnippets`, `runSnippet`) and 48 board operations (`panel`,
134
+ `sync`) per program. Pass `limits` to override some of them (`memoryBytes` must be at least 64 KiB
135
+ and `stackBytes` at least 16 KiB, or configuration throws a `RangeError`). `valueLength` counts
136
+ UTF-16 code units of the JSON text, not UTF-8 bytes. Under Node's permission model, workers need
137
+ `--allow-worker`; without it configuration fails with `SANDBOX_UNAVAILABLE` (audit mode does not
138
+ count). Browsers have no worker guest: a browser-targeted bundle must use `isolation: "inline"` (the
139
+ default `"worker"` fails at configuration with `SANDBOX_UNAVAILABLE`); the Node worker adapter is
140
+ loaded at run time, so bundlers do not resolve `node:worker_threads`. `NODE_OPTIONS` that a worker
141
+ cannot start with (such as `--input-type`) are not passed to it either.
142
142
 
143
143
  **Breaking change: calls dispatch in the order they are awaited.** A call reaches the provider when
144
144
  the program starts it, not where it is written. A program that stores
@@ -148,16 +148,18 @@ first; before, the provider received the write first. Await calls in the order t
148
148
  including in saved chains: edit any saved chain that relied on declaration order and save it again.
149
149
 
150
150
  Every api call is lazy: it reaches the host once the program starts it (awaits it or attaches a
151
- handler). A started call is committed like an in-flight promise and runs before the program
152
- completes, even if `Promise.race` moved on. A call the program never started never runs and the
153
- program fails with `UNAWAITED_OPERATION`; that check applies when the program returns, so a program
154
- that throws or stalls reports `GUEST_ERROR` or `GUEST_STALLED` instead. A provider call never starts
155
- after the wall limit has passed, and an exhausted CPU or wall limit wins over a guest error.
156
- Failures are `CodeModeError`s whose message reads `[execute] CODE: detail. Recovery: hint.`, so a
157
- host that forwards `error.message` keeps the code. Inside the program, a failed api call throws an
158
- `Error` with `code`, `recovery` and `context`. Once a provider call was dispatched, errors carry
159
- `effects: "possible"` and never repeat guest, provider or transport text. A program's result is
160
- serialized once at the end, and calls its `toJSON` starts are run before the program completes.
151
+ handler), in its turn, since calls run one at a time. Once the program has finished, nothing more is
152
+ sent: a call it made and did not wait for (never started, the loser of a `Promise.race`, the rest of
153
+ a `Promise.all` that failed early) does not run, and the program fails with `UNAWAITED_OPERATION`.
154
+ That check applies when the program returns, so a program that throws or stalls reports
155
+ `GUEST_ERROR` or `GUEST_STALLED` instead. A provider call never starts after the wall limit has
156
+ passed, and an exhausted CPU or wall limit wins over a guest error. Failures are `CodeModeError`s
157
+ whose message reads `[execute] CODE: detail. Recovery: hint.`, so a host that forwards
158
+ `error.message` keeps the code. Inside the program, a failed api call throws an `Error` with `code`,
159
+ `recovery` and `context`. Once a provider call was dispatched, errors carry `effects: "possible"`
160
+ and never repeat guest, provider or transport text. A program's result is serialized once at the
161
+ end; a call its `toJSON` makes then is not sent either, and counts as one the program did not wait
162
+ for.
161
163
 
162
164
  A caller abort is not a `CodeModeError`: once a provider was dispatched or a save confirmed,
163
165
  `execute` rejects with a `DOMException` (`AbortError`, or `TimeoutError` for a timeout) so a host
@@ -199,6 +201,95 @@ implemented ports in each `resolveView` result and call
199
201
  descriptor. The board's `deliver(targetReceiptId, action, data)` callback handles the action
200
202
  locally. The target view owns validation of its action data.
201
203
 
204
+ ### Running your own surface in the sandbox
205
+
206
+ The chain above gives a program `api` and four snippet operations. A server that wants the same
207
+ sandbox for its own vocabulary declares the object the program receives and implements its
208
+ operations in one callback:
209
+
210
+ ```typescript
211
+ import { runSandboxProgram, SandboxHostError } from "@mcpview/compose/code-mode/sandbox";
212
+
213
+ const total = await runSandboxProgram(
214
+ "const order = await shop.getOrder(shop.params.id); return order.total;",
215
+ {
216
+ namespace: "shop",
217
+ constants: { params: { id: 1042 } },
218
+ operations: { getOrder: { budget: "reads" } },
219
+ budgets: { reads: 12 },
220
+ },
221
+ async (operation, args) => {
222
+ const order = await findOrder(args[0]);
223
+ if (!order) {
224
+ // The program reads this code, message and recovery in its `catch`.
225
+ throw new SandboxHostError("ORDER_UNKNOWN", `No order ${args[0]}`, "List the orders first");
226
+ }
227
+ return order;
228
+ },
229
+ );
230
+ ```
231
+
232
+ Only JSON crosses into the program, and an operation the table does not declare does not exist in
233
+ it. An operation can start as soon as it is called (`start: "on-call"`) and can receive an earlier
234
+ result as a `SandboxResultReference` instead of a copy (`resultArguments: "reference"`), so the
235
+ native result stays on the host. The `irreversible` option marks a call whose effect cannot be
236
+ undone: the wall limit does not cut it, and if its result cannot be handed to the program the run
237
+ ends, instead of an error the program could catch and answer by calling again. `onUnsentCalls` hands
238
+ the host the calls a finished program did not wait for, which were not sent, and lets it decide
239
+ whether the run still succeeds. Isolation and coded errors work as for the chain. `limits` overrides
240
+ the five resource limits of `SANDBOX_RESOURCE_LIMITS` (CPU time, wall time, memory, stack, value
241
+ length); how many calls a program may make is set by the `budgets` of the surface, so a call count
242
+ passed as a limit is refused. A host error cannot take a code the sandbox itself throws into a
243
+ program, such as `OPERATION_FAILED`. A `SandboxHostError` the program does not handle comes back as
244
+ the host's own object; any other `CodeModeError` crosses by its fields, so the run rejects with an
245
+ equal error. A program that returns nothing gives `undefined`, not `null`. See
246
+ [ADR 0007](docs/decision-records/0007-host-declared-sandbox-surface.md).
247
+
248
+ A host that is bundled into one file ships two more files next to its bundle. A bundler carries
249
+ neither of them, because both are found by a URL at run time.
250
+
251
+ The first is its worker, which Compose can no longer find beside itself. The host writes the entry,
252
+ bundles it as a second file and says where it is:
253
+
254
+ ```typescript
255
+ // sandbox-worker.ts, bundled next to the main file
256
+ import { serveSandboxWorker } from "@mcpview/compose/code-mode/sandbox-worker";
257
+
258
+ serveSandboxWorker();
259
+ ```
260
+
261
+ ```typescript
262
+ await runSandboxProgram(code, surface, invoke, signal, {
263
+ worker: new URL("./sandbox-worker.mjs", import.meta.url),
264
+ });
265
+ ```
266
+
267
+ The second is the QuickJS WebAssembly file, `emscripten-module.wasm`: copy it next to the bundle,
268
+ under the same name. It serves the main file and the worker. The file belongs to the engine library,
269
+ which Compose depends on, so a build script finds it from Compose, one dependency at a time:
270
+
271
+ ```typescript
272
+ import { createRequire } from "node:module";
273
+
274
+ const fromCompose = createRequire(import.meta.resolve("@mcpview/compose/code-mode/sandbox"));
275
+ const fromEngine = createRequire(fromCompose.resolve("quickjs-emscripten"));
276
+ const wasm = fromEngine.resolve("@jitl/quickjs-wasmfile-release-sync/wasm");
277
+ ```
278
+
279
+ Each mistake has its own answer, and nothing falls back to `inline`:
280
+
281
+ | What is wrong | The run fails with |
282
+ | ------------------------------------------------ | ---------------------------------------------------- |
283
+ | The `.wasm` file is missing or unreadable | `SANDBOX_UNAVAILABLE`, `context.unavailable: engine` |
284
+ | The worker file is missing | `SANDBOX_FAILED` |
285
+ | The worker file never calls `serveSandboxWorker` | `SANDBOX_FAILED`, `context.worker: not-started` |
286
+ | `worker` is given with `isolation: "inline"` | a `RangeError`, before anything runs |
287
+
288
+ Node reports the last but one at once: a worker with nothing to do ends by itself. Deno keeps such a
289
+ worker alive, and reports it only once the wall time of the program has passed (30 s by default), so
290
+ run one program at startup. `createSnippetChain` has no `worker` option: a bundled host of the chain
291
+ still uses `isolation: "inline"`, and ships the `.wasm` file the same way.
292
+
202
293
  ## MCP SDK compatibility
203
294
 
204
295
  Compose uses MCP Apps 2.x and the split MCP SDK 2.x packages. Integrations importing SDK types or
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The QuickJS engine of the Code Mode sandbox.
3
+ *
4
+ * It is the engine library's default build. Its WebAssembly lives in a file
5
+ * beside the library's own module: Node and Deno read it from there, a browser
6
+ * fetches it. A host that bundles its code ships that file next to its bundle.
7
+ *
8
+ * Every program runs in its own fresh WebAssembly instance, in both `worker`
9
+ * and `inline` isolations, with a bounded `WebAssembly.Memory` and a guarded
10
+ * `_malloc`: QuickJS's Emscripten build has no `malloc_usable_size`, so
11
+ * `setMemoryLimit` alone does not cap large strings, arrays or ArrayBuffers,
12
+ * and `quickjs-emscripten`'s host helpers do not check `_malloc` for `0`.
13
+ *
14
+ * @module code-mode/engine
15
+ */
16
+ import { type QuickJSWASMModule } from "quickjs-emscripten";
17
+ /**
18
+ * Thrown by our `_malloc` wrapper when Emscripten's allocator returns `0`.
19
+ * Catching it before `quickjs-emscripten` copies bytes stops host helpers from
20
+ * writing over address `0` of linear memory, leaving the VM state uncorrupted.
21
+ */
22
+ export declare class WasmOomError extends RangeError {
23
+ constructor(bytes: number);
24
+ }
25
+ /** True when our `_malloc` guard refused a host-side allocation cleanly. */
26
+ export declare function isWasmOom(error: unknown): boolean;
27
+ /**
28
+ * True when QuickJS trapped inside WebAssembly on an unguarded allocation
29
+ * failure. The instance's state is then unknown and must be abandoned.
30
+ */
31
+ export declare function isWasmMemoryTrap(error: unknown): boolean;
32
+ /**
33
+ * True when Emscripten's linear-memory allocator failed to grow or `_malloc`
34
+ * returned `0` after arena setup. Used to tell QuickJS's out-of-memory `null`
35
+ * exception apart from an intentional `throw null` even after unwinding frees
36
+ * the program's local variables.
37
+ */
38
+ export declare function didHitMemoryLimit(quickjs: QuickJSWASMModule): boolean;
39
+ /**
40
+ * A new engine module, shared with nobody, whose WebAssembly linear memory is
41
+ * capped for `memoryBytes`. Rejects with `SANDBOX_UNAVAILABLE` when the engine
42
+ * cannot be loaded here: running the program again would not help, the
43
+ * deployment has to change.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const quickjs = await newEngine();
48
+ * const vm = quickjs.newContext();
49
+ * vm.dispose();
50
+ * ```
51
+ */
52
+ export declare function newEngine(memoryBytes?: number): Promise<QuickJSWASMModule>;
53
+ /**
54
+ * When `memoryBytes` is smaller than the mandatory 16 MiB initial WASM memory,
55
+ * reserve the surplus C heap so the program sees its configured limit instead
56
+ * of ~10.9 MiB. Returns an idempotent release function to call before disposal.
57
+ */
58
+ export declare function capInitialArena(quickjs: QuickJSWASMModule, memoryBytes: number): () => void;
59
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAGL,KAAK,iBAAiB,EAEvB,MAAM,oBAAoB,CAAC;AAa5B;;;;GAIG;AACH,qBAAa,YAAa,SAAQ,UAAU;gBAC9B,KAAK,EAAE,MAAM;CAI1B;AAED,4EAA4E;AAC5E,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAEjD;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAGxD;AAiBD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAErE;AAWD;;;;;;;;;;;;GAYG;AACH,wBAAsB,SAAS,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAyDhF;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,IAAI,CAqC3F"}
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The QuickJS engine of the Code Mode sandbox.
3
+ *
4
+ * It is the engine library's default build. Its WebAssembly lives in a file
5
+ * beside the library's own module: Node and Deno read it from there, a browser
6
+ * fetches it. A host that bundles its code ships that file next to its bundle.
7
+ *
8
+ * Every program runs in its own fresh WebAssembly instance, in both `worker`
9
+ * and `inline` isolations, with a bounded `WebAssembly.Memory` and a guarded
10
+ * `_malloc`: QuickJS's Emscripten build has no `malloc_usable_size`, so
11
+ * `setMemoryLimit` alone does not cap large strings, arrays or ArrayBuffers,
12
+ * and `quickjs-emscripten`'s host helpers do not check `_malloc` for `0`.
13
+ *
14
+ * @module code-mode/engine
15
+ */
16
+ import { newQuickJSWASMModuleFromVariant, newVariant, RELEASE_SYNC, } from "quickjs-emscripten";
17
+ import { CodeModeError } from "./errors.js";
18
+ const WASM_PAGE_BYTES = 65_536;
19
+ /** Minimum pages declared by `emscripten-module.wasm` (16 MiB). */
20
+ const MIN_WASM_PAGES = 256;
21
+ /** Maximum WASM32 linear memory Emscripten accepts (2 GiB). */
22
+ const MAX_WASM_PAGES = 32_768;
23
+ /** Static data, stack, runtime and glue overhead inside the WASM linear memory. */
24
+ const WASM_OVERHEAD_BYTES = 5_450_000;
25
+ /** Free C heap available inside the mandatory 16 MiB initial WASM memory. */
26
+ const INITIAL_ARENA_USABLE_BYTES = 10_500_000;
27
+ /**
28
+ * Thrown by our `_malloc` wrapper when Emscripten's allocator returns `0`.
29
+ * Catching it before `quickjs-emscripten` copies bytes stops host helpers from
30
+ * writing over address `0` of linear memory, leaving the VM state uncorrupted.
31
+ */
32
+ export class WasmOomError extends RangeError {
33
+ constructor(bytes) {
34
+ super(`WebAssembly allocation of ${bytes} bytes failed`);
35
+ this.name = "WasmOomError";
36
+ }
37
+ }
38
+ /** True when our `_malloc` guard refused a host-side allocation cleanly. */
39
+ export function isWasmOom(error) {
40
+ return error instanceof WasmOomError;
41
+ }
42
+ /**
43
+ * True when QuickJS trapped inside WebAssembly on an unguarded allocation
44
+ * failure. The instance's state is then unknown and must be abandoned.
45
+ */
46
+ export function isWasmMemoryTrap(error) {
47
+ return error instanceof WebAssembly.RuntimeError &&
48
+ /memory access out of bounds|Aborted/i.test(error.message);
49
+ }
50
+ const arenas = new WeakMap();
51
+ /**
52
+ * True when Emscripten's linear-memory allocator failed to grow or `_malloc`
53
+ * returned `0` after arena setup. Used to tell QuickJS's out-of-memory `null`
54
+ * exception apart from an intentional `throw null` even after unwinding frees
55
+ * the program's local variables.
56
+ */
57
+ export function didHitMemoryLimit(quickjs) {
58
+ return arenas.get(quickjs)?.oomObserved ?? false;
59
+ }
60
+ function wasmMaxPages(memoryBytes) {
61
+ if (memoryBytes === undefined)
62
+ return MAX_WASM_PAGES;
63
+ if (memoryBytes <= INITIAL_ARENA_USABLE_BYTES)
64
+ return MIN_WASM_PAGES;
65
+ // Emscripten grows linear memory in minimum +5% steps; headroom lets a
66
+ // program use its full limit without failing one step short.
67
+ const needed = Math.ceil(((WASM_OVERHEAD_BYTES + memoryBytes) * 1.05) / WASM_PAGE_BYTES);
68
+ return Math.min(MAX_WASM_PAGES, Math.max(MIN_WASM_PAGES, needed));
69
+ }
70
+ /**
71
+ * A new engine module, shared with nobody, whose WebAssembly linear memory is
72
+ * capped for `memoryBytes`. Rejects with `SANDBOX_UNAVAILABLE` when the engine
73
+ * cannot be loaded here: running the program again would not help, the
74
+ * deployment has to change.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const quickjs = await newEngine();
79
+ * const vm = quickjs.newContext();
80
+ * vm.dispose();
81
+ * ```
82
+ */
83
+ export async function newEngine(memoryBytes) {
84
+ const maxPages = wasmMaxPages(memoryBytes);
85
+ const memory = new WebAssembly.Memory({ initial: MIN_WASM_PAGES, maximum: maxPages });
86
+ const state = { probing: false, oomObserved: false };
87
+ const rawGrow = memory.grow.bind(memory);
88
+ memory.grow = (delta) => {
89
+ try {
90
+ return rawGrow(delta);
91
+ }
92
+ catch (error) {
93
+ if (!state.probing)
94
+ state.oomObserved = true;
95
+ throw error;
96
+ }
97
+ };
98
+ const variant = newVariant(RELEASE_SYNC, { wasmMemory: memory });
99
+ let quickjs;
100
+ try {
101
+ quickjs = await newQuickJSWASMModuleFromVariant(variant);
102
+ }
103
+ catch {
104
+ throw new CodeModeError("SANDBOX_UNAVAILABLE", "The QuickJS engine could not be loaded", "Make the engine's WebAssembly file readable: under Deno, grant read access to it; in a bundle, ship emscripten-module.wasm next to the bundle", { context: { unavailable: "engine" } });
105
+ }
106
+ const mod = quickjs.module;
107
+ if (mod && typeof mod._malloc === "function" && typeof mod._free === "function") {
108
+ const rawMalloc = mod._malloc.bind(mod);
109
+ const rawFree = mod._free.bind(mod);
110
+ const arena = {
111
+ rawMalloc,
112
+ rawFree,
113
+ maxPages,
114
+ get probing() {
115
+ return state.probing;
116
+ },
117
+ set probing(value) {
118
+ state.probing = value;
119
+ },
120
+ get oomObserved() {
121
+ return state.oomObserved;
122
+ },
123
+ set oomObserved(value) {
124
+ state.oomObserved = value;
125
+ },
126
+ };
127
+ arenas.set(quickjs, arena);
128
+ mod._malloc = (bytes) => {
129
+ const ptr = rawMalloc(bytes);
130
+ if (ptr === 0 && bytes > 0) {
131
+ if (!state.probing)
132
+ state.oomObserved = true;
133
+ throw new WasmOomError(bytes);
134
+ }
135
+ return ptr;
136
+ };
137
+ }
138
+ return quickjs;
139
+ }
140
+ /**
141
+ * When `memoryBytes` is smaller than the mandatory 16 MiB initial WASM memory,
142
+ * reserve the surplus C heap so the program sees its configured limit instead
143
+ * of ~10.9 MiB. Returns an idempotent release function to call before disposal.
144
+ */
145
+ export function capInitialArena(quickjs, memoryBytes) {
146
+ const arena = arenas.get(quickjs);
147
+ if (!arena || arena.maxPages !== MIN_WASM_PAGES)
148
+ return () => { };
149
+ const probe = [];
150
+ let available = 0;
151
+ arena.probing = true;
152
+ try {
153
+ for (const size of [1_048_576, 65_536, 4_096]) {
154
+ for (;;) {
155
+ const ptr = arena.rawMalloc(size);
156
+ if (ptr === 0)
157
+ break;
158
+ probe.push(ptr);
159
+ available += size;
160
+ }
161
+ }
162
+ for (const ptr of probe)
163
+ arena.rawFree(ptr);
164
+ if (available <= memoryBytes)
165
+ return () => { };
166
+ const padding = [];
167
+ let remaining = available - memoryBytes;
168
+ for (const size of [1_048_576, 65_536, 4_096, 256]) {
169
+ while (remaining >= size) {
170
+ const ptr = arena.rawMalloc(size);
171
+ if (ptr === 0)
172
+ break;
173
+ padding.push(ptr);
174
+ remaining -= size;
175
+ }
176
+ }
177
+ let released = false;
178
+ return () => {
179
+ if (released)
180
+ return;
181
+ released = true;
182
+ for (const ptr of padding)
183
+ arena.rawFree(ptr);
184
+ };
185
+ }
186
+ finally {
187
+ arena.probing = false;
188
+ }
189
+ }
@@ -1,9 +1,6 @@
1
1
  /**
2
- * Worker entry for Code Mode programs. It owns one QuickJS VM, runs one
3
- * program, and asks the host for each api operation. The host terminates the
4
- * worker afterwards. Loaded by `worker-host.ts` under Deno (Web Worker) and
5
- * Node (`node:worker_threads`); keep it free of top-level await, which the
6
- * CommonJS npm build rejects.
2
+ * Compose's own worker entry for Code Mode programs, loaded by `worker-host.ts`
3
+ * by URL. It serves the sandbox with the engine Compose ships.
7
4
  *
8
5
  * @module code-mode/guest-worker
9
6
  */
@@ -1 +1 @@
1
- {"version":3,"file":"guest-worker.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/guest-worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,yBAAyB,CAAC"}
1
+ {"version":3,"file":"guest-worker.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/guest-worker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,yBAAyB,CAAC"}
@@ -1,80 +1,9 @@
1
1
  /**
2
- * Worker entry for Code Mode programs. It owns one QuickJS VM, runs one
3
- * program, and asks the host for each api operation. The host terminates the
4
- * worker afterwards. Loaded by `worker-host.ts` under Deno (Web Worker) and
5
- * Node (`node:worker_threads`); keep it free of top-level await, which the
6
- * CommonJS npm build rejects.
2
+ * Compose's own worker entry for Code Mode programs, loaded by `worker-host.ts`
3
+ * by URL. It serves the sandbox with the engine Compose ships.
7
4
  *
8
5
  * @module code-mode/guest-worker
9
6
  */
10
7
  import "../../_dnt.polyfills.js";
11
- import * as dntShim from "../../_dnt.shims.js";
12
- import { getQuickJS } from "quickjs-emscripten";
13
- import { CodeModeError, codeModeErrorFromFields } from "./errors.js";
14
- import { runVm } from "./sandbox-core.js";
15
- /** The host port, or undefined when this module is loaded outside a worker. */
16
- function connect() {
17
- const deno = dntShim.dntGlobalThis.Deno;
18
- if (typeof deno?.version?.deno === "string") {
19
- const workerScope = dntShim.dntGlobalThis
20
- .WorkerGlobalScope;
21
- if (typeof workerScope !== "function" || !(dntShim.dntGlobalThis instanceof workerScope)) {
22
- return Promise.resolve(undefined);
23
- }
24
- const scope = dntShim.dntGlobalThis;
25
- return Promise.resolve({
26
- post: (message) => scope.postMessage(message),
27
- listen: (handler) => scope.addEventListener("message", (event) => handler(event.data)),
28
- });
29
- }
30
- return import("node:worker_threads").then(({ parentPort }) => {
31
- if (!parentPort)
32
- return undefined;
33
- return {
34
- post: (message) => parentPort.postMessage(message),
35
- listen: (handler) => parentPort.on("message", handler),
36
- };
37
- });
38
- }
39
- void connect().then((port) => {
40
- if (!port)
41
- return;
42
- const waiting = new Map();
43
- let nextCall = 0;
44
- let started = false;
45
- port.listen((message) => {
46
- if (message.type === "reply") {
47
- const waiter = waiting.get(message.id);
48
- if (!waiter)
49
- return;
50
- waiting.delete(message.id);
51
- if (message.ok)
52
- waiter.resolve(JSON.parse(message.json));
53
- else {
54
- waiter.reject(codeModeErrorFromFields(message.error) ??
55
- new CodeModeError("OPERATION_FAILED", "The operation failed", "Retry once"));
56
- }
57
- return;
58
- }
59
- if (message.type !== "run" || started)
60
- return;
61
- started = true;
62
- const cancel = new Int32Array(message.cancel);
63
- getQuickJS().then((quickjs) => runVm({
64
- quickjs,
65
- code: message.code,
66
- params: message.params,
67
- limits: message.limits,
68
- isCancelled: () => Atomics.load(cancel, 0) === 1,
69
- call: (operation, args) => new Promise((resolve, reject) => {
70
- const id = nextCall++;
71
- waiting.set(id, { resolve, reject });
72
- port.post({ type: "call", id, operation, args });
73
- }),
74
- })).then((value) => port.post({ type: "done", value }), (error) => port.post({
75
- type: "fail",
76
- error: (error instanceof CodeModeError ? error : new CodeModeError("SANDBOX_FAILED", "The sandbox failed while running the program", "Run the program again")).toJSON(),
77
- }));
78
- });
79
- port.post({ type: "ready" });
80
- });
8
+ import { serveSandboxWorker } from "./sandbox-worker.js";
9
+ serveSandboxWorker();