@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
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ /**
3
+ * The QuickJS engine of the Code Mode sandbox.
4
+ *
5
+ * It is the engine library's default build. Its WebAssembly lives in a file
6
+ * beside the library's own module: Node and Deno read it from there, a browser
7
+ * fetches it. A host that bundles its code ships that file next to its bundle.
8
+ *
9
+ * Every program runs in its own fresh WebAssembly instance, in both `worker`
10
+ * and `inline` isolations, with a bounded `WebAssembly.Memory` and a guarded
11
+ * `_malloc`: QuickJS's Emscripten build has no `malloc_usable_size`, so
12
+ * `setMemoryLimit` alone does not cap large strings, arrays or ArrayBuffers,
13
+ * and `quickjs-emscripten`'s host helpers do not check `_malloc` for `0`.
14
+ *
15
+ * @module code-mode/engine
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.WasmOomError = void 0;
19
+ exports.isWasmOom = isWasmOom;
20
+ exports.isWasmMemoryTrap = isWasmMemoryTrap;
21
+ exports.didHitMemoryLimit = didHitMemoryLimit;
22
+ exports.newEngine = newEngine;
23
+ exports.capInitialArena = capInitialArena;
24
+ const quickjs_emscripten_1 = require("quickjs-emscripten");
25
+ const errors_js_1 = require("./errors.js");
26
+ const WASM_PAGE_BYTES = 65_536;
27
+ /** Minimum pages declared by `emscripten-module.wasm` (16 MiB). */
28
+ const MIN_WASM_PAGES = 256;
29
+ /** Maximum WASM32 linear memory Emscripten accepts (2 GiB). */
30
+ const MAX_WASM_PAGES = 32_768;
31
+ /** Static data, stack, runtime and glue overhead inside the WASM linear memory. */
32
+ const WASM_OVERHEAD_BYTES = 5_450_000;
33
+ /** Free C heap available inside the mandatory 16 MiB initial WASM memory. */
34
+ const INITIAL_ARENA_USABLE_BYTES = 10_500_000;
35
+ /**
36
+ * Thrown by our `_malloc` wrapper when Emscripten's allocator returns `0`.
37
+ * Catching it before `quickjs-emscripten` copies bytes stops host helpers from
38
+ * writing over address `0` of linear memory, leaving the VM state uncorrupted.
39
+ */
40
+ class WasmOomError extends RangeError {
41
+ constructor(bytes) {
42
+ super(`WebAssembly allocation of ${bytes} bytes failed`);
43
+ this.name = "WasmOomError";
44
+ }
45
+ }
46
+ exports.WasmOomError = WasmOomError;
47
+ /** True when our `_malloc` guard refused a host-side allocation cleanly. */
48
+ function isWasmOom(error) {
49
+ return error instanceof WasmOomError;
50
+ }
51
+ /**
52
+ * True when QuickJS trapped inside WebAssembly on an unguarded allocation
53
+ * failure. The instance's state is then unknown and must be abandoned.
54
+ */
55
+ function isWasmMemoryTrap(error) {
56
+ return error instanceof WebAssembly.RuntimeError &&
57
+ /memory access out of bounds|Aborted/i.test(error.message);
58
+ }
59
+ const arenas = new WeakMap();
60
+ /**
61
+ * True when Emscripten's linear-memory allocator failed to grow or `_malloc`
62
+ * returned `0` after arena setup. Used to tell QuickJS's out-of-memory `null`
63
+ * exception apart from an intentional `throw null` even after unwinding frees
64
+ * the program's local variables.
65
+ */
66
+ function didHitMemoryLimit(quickjs) {
67
+ return arenas.get(quickjs)?.oomObserved ?? false;
68
+ }
69
+ function wasmMaxPages(memoryBytes) {
70
+ if (memoryBytes === undefined)
71
+ return MAX_WASM_PAGES;
72
+ if (memoryBytes <= INITIAL_ARENA_USABLE_BYTES)
73
+ return MIN_WASM_PAGES;
74
+ // Emscripten grows linear memory in minimum +5% steps; headroom lets a
75
+ // program use its full limit without failing one step short.
76
+ const needed = Math.ceil(((WASM_OVERHEAD_BYTES + memoryBytes) * 1.05) / WASM_PAGE_BYTES);
77
+ return Math.min(MAX_WASM_PAGES, Math.max(MIN_WASM_PAGES, needed));
78
+ }
79
+ /**
80
+ * A new engine module, shared with nobody, whose WebAssembly linear memory is
81
+ * capped for `memoryBytes`. Rejects with `SANDBOX_UNAVAILABLE` when the engine
82
+ * cannot be loaded here: running the program again would not help, the
83
+ * deployment has to change.
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * const quickjs = await newEngine();
88
+ * const vm = quickjs.newContext();
89
+ * vm.dispose();
90
+ * ```
91
+ */
92
+ async function newEngine(memoryBytes) {
93
+ const maxPages = wasmMaxPages(memoryBytes);
94
+ const memory = new WebAssembly.Memory({ initial: MIN_WASM_PAGES, maximum: maxPages });
95
+ const state = { probing: false, oomObserved: false };
96
+ const rawGrow = memory.grow.bind(memory);
97
+ memory.grow = (delta) => {
98
+ try {
99
+ return rawGrow(delta);
100
+ }
101
+ catch (error) {
102
+ if (!state.probing)
103
+ state.oomObserved = true;
104
+ throw error;
105
+ }
106
+ };
107
+ const variant = (0, quickjs_emscripten_1.newVariant)(quickjs_emscripten_1.RELEASE_SYNC, { wasmMemory: memory });
108
+ let quickjs;
109
+ try {
110
+ quickjs = await (0, quickjs_emscripten_1.newQuickJSWASMModuleFromVariant)(variant);
111
+ }
112
+ catch {
113
+ throw new errors_js_1.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" } });
114
+ }
115
+ const mod = quickjs.module;
116
+ if (mod && typeof mod._malloc === "function" && typeof mod._free === "function") {
117
+ const rawMalloc = mod._malloc.bind(mod);
118
+ const rawFree = mod._free.bind(mod);
119
+ const arena = {
120
+ rawMalloc,
121
+ rawFree,
122
+ maxPages,
123
+ get probing() {
124
+ return state.probing;
125
+ },
126
+ set probing(value) {
127
+ state.probing = value;
128
+ },
129
+ get oomObserved() {
130
+ return state.oomObserved;
131
+ },
132
+ set oomObserved(value) {
133
+ state.oomObserved = value;
134
+ },
135
+ };
136
+ arenas.set(quickjs, arena);
137
+ mod._malloc = (bytes) => {
138
+ const ptr = rawMalloc(bytes);
139
+ if (ptr === 0 && bytes > 0) {
140
+ if (!state.probing)
141
+ state.oomObserved = true;
142
+ throw new WasmOomError(bytes);
143
+ }
144
+ return ptr;
145
+ };
146
+ }
147
+ return quickjs;
148
+ }
149
+ /**
150
+ * When `memoryBytes` is smaller than the mandatory 16 MiB initial WASM memory,
151
+ * reserve the surplus C heap so the program sees its configured limit instead
152
+ * of ~10.9 MiB. Returns an idempotent release function to call before disposal.
153
+ */
154
+ function capInitialArena(quickjs, memoryBytes) {
155
+ const arena = arenas.get(quickjs);
156
+ if (!arena || arena.maxPages !== MIN_WASM_PAGES)
157
+ return () => { };
158
+ const probe = [];
159
+ let available = 0;
160
+ arena.probing = true;
161
+ try {
162
+ for (const size of [1_048_576, 65_536, 4_096]) {
163
+ for (;;) {
164
+ const ptr = arena.rawMalloc(size);
165
+ if (ptr === 0)
166
+ break;
167
+ probe.push(ptr);
168
+ available += size;
169
+ }
170
+ }
171
+ for (const ptr of probe)
172
+ arena.rawFree(ptr);
173
+ if (available <= memoryBytes)
174
+ return () => { };
175
+ const padding = [];
176
+ let remaining = available - memoryBytes;
177
+ for (const size of [1_048_576, 65_536, 4_096, 256]) {
178
+ while (remaining >= size) {
179
+ const ptr = arena.rawMalloc(size);
180
+ if (ptr === 0)
181
+ break;
182
+ padding.push(ptr);
183
+ remaining -= size;
184
+ }
185
+ }
186
+ let released = false;
187
+ return () => {
188
+ if (released)
189
+ return;
190
+ released = true;
191
+ for (const ptr of padding)
192
+ arena.rawFree(ptr);
193
+ };
194
+ }
195
+ finally {
196
+ arena.probing = false;
197
+ }
198
+ }
@@ -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,105 +1,11 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  Object.defineProperty(exports, "__esModule", { value: true });
26
3
  /**
27
- * Worker entry for Code Mode programs. It owns one QuickJS VM, runs one
28
- * program, and asks the host for each api operation. The host terminates the
29
- * worker afterwards. Loaded by `worker-host.ts` under Deno (Web Worker) and
30
- * Node (`node:worker_threads`); keep it free of top-level await, which the
31
- * CommonJS npm build rejects.
4
+ * Compose's own worker entry for Code Mode programs, loaded by `worker-host.ts`
5
+ * by URL. It serves the sandbox with the engine Compose ships.
32
6
  *
33
7
  * @module code-mode/guest-worker
34
8
  */
35
9
  require("../../_dnt.polyfills.js");
36
- const dntShim = __importStar(require("../../_dnt.shims.js"));
37
- const quickjs_emscripten_1 = require("quickjs-emscripten");
38
- const errors_js_1 = require("./errors.js");
39
- const sandbox_core_js_1 = require("./sandbox-core.js");
40
- /** The host port, or undefined when this module is loaded outside a worker. */
41
- function connect() {
42
- const deno = dntShim.dntGlobalThis.Deno;
43
- if (typeof deno?.version?.deno === "string") {
44
- const workerScope = dntShim.dntGlobalThis
45
- .WorkerGlobalScope;
46
- if (typeof workerScope !== "function" || !(dntShim.dntGlobalThis instanceof workerScope)) {
47
- return Promise.resolve(undefined);
48
- }
49
- const scope = dntShim.dntGlobalThis;
50
- return Promise.resolve({
51
- post: (message) => scope.postMessage(message),
52
- listen: (handler) => scope.addEventListener("message", (event) => handler(event.data)),
53
- });
54
- }
55
- return Promise.resolve().then(() => __importStar(require("node:worker_threads"))).then(({ parentPort }) => {
56
- if (!parentPort)
57
- return undefined;
58
- return {
59
- post: (message) => parentPort.postMessage(message),
60
- listen: (handler) => parentPort.on("message", handler),
61
- };
62
- });
63
- }
64
- void connect().then((port) => {
65
- if (!port)
66
- return;
67
- const waiting = new Map();
68
- let nextCall = 0;
69
- let started = false;
70
- port.listen((message) => {
71
- if (message.type === "reply") {
72
- const waiter = waiting.get(message.id);
73
- if (!waiter)
74
- return;
75
- waiting.delete(message.id);
76
- if (message.ok)
77
- waiter.resolve(JSON.parse(message.json));
78
- else {
79
- waiter.reject((0, errors_js_1.codeModeErrorFromFields)(message.error) ??
80
- new errors_js_1.CodeModeError("OPERATION_FAILED", "The operation failed", "Retry once"));
81
- }
82
- return;
83
- }
84
- if (message.type !== "run" || started)
85
- return;
86
- started = true;
87
- const cancel = new Int32Array(message.cancel);
88
- (0, quickjs_emscripten_1.getQuickJS)().then((quickjs) => (0, sandbox_core_js_1.runVm)({
89
- quickjs,
90
- code: message.code,
91
- params: message.params,
92
- limits: message.limits,
93
- isCancelled: () => Atomics.load(cancel, 0) === 1,
94
- call: (operation, args) => new Promise((resolve, reject) => {
95
- const id = nextCall++;
96
- waiting.set(id, { resolve, reject });
97
- port.post({ type: "call", id, operation, args });
98
- }),
99
- })).then((value) => port.post({ type: "done", value }), (error) => port.post({
100
- type: "fail",
101
- error: (error instanceof errors_js_1.CodeModeError ? error : new errors_js_1.CodeModeError("SANDBOX_FAILED", "The sandbox failed while running the program", "Run the program again")).toJSON(),
102
- }));
103
- });
104
- port.post({ type: "ready" });
105
- });
10
+ const sandbox_worker_js_1 = require("./sandbox-worker.js");
11
+ (0, sandbox_worker_js_1.serveSandboxWorker)();
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The Code Mode sandbox as another package uses it: run a program written by a
3
+ * model in an isolated QuickJS engine, against a surface the host declares.
4
+ *
5
+ * A host states the object the program receives (its name, its JSON constants
6
+ * and a closed table of operations), implements those operations in one
7
+ * callback, and gets back the program's value or a coded error. Only JSON
8
+ * crosses into the program. See ADR 0006 and ADR 0007.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { runSandboxProgram, SandboxHostError } from "@mcpview/compose/code-mode/sandbox";
13
+ *
14
+ * const total = await runSandboxProgram(
15
+ * "const order = await shop.getOrder(shop.params.id); return order.total;",
16
+ * {
17
+ * namespace: "shop",
18
+ * constants: { params: { id: 1042 } },
19
+ * operations: { getOrder: { budget: "reads" } },
20
+ * budgets: { reads: 12 },
21
+ * },
22
+ * (operation, args) => {
23
+ * if (args[0] !== 1042) {
24
+ * throw new SandboxHostError("ORDER_UNKNOWN", "No such order", "List the orders first");
25
+ * }
26
+ * return Promise.resolve({ id: 1042, total: 199.5 });
27
+ * },
28
+ * );
29
+ * ```
30
+ *
31
+ * @module code-mode/sandbox
32
+ */
33
+ import "../../_dnt.polyfills.js";
34
+ export { CODE_MODE_ERROR_CODES, CodeModeError, type CodeModeErrorCode, type CodeModeErrorContext, type CodeModeErrorEffects, type CodeModeErrorFields, formatCodeModeError, isCodeModeError, } from "./errors.js";
35
+ export { assertSandboxIsolation, resolveSandboxResourceLimits, runSandboxProgram, SANDBOX_RESOURCE_LIMITS, type SandboxInvoke, type SandboxIsolation, type SandboxOptions, type SandboxResourceLimits, type SandboxUnsentCall, } from "./sandbox.js";
36
+ export { resolveSandboxSurface, SandboxHostError, type SandboxOperation, SandboxResultReference, type SandboxSurface, } from "./surface.js";
37
+ //# sourceMappingURL=sandbox-api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox-api.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/sandbox-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,OAAO,yBAAyB,CAAC;AAGjC,OAAO,EACL,qBAAqB,EACrB,aAAa,EACb,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,mBAAmB,EACnB,eAAe,GAChB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAC5B,iBAAiB,EACjB,uBAAuB,EACvB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,KAAK,iBAAiB,GACvB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,KAAK,gBAAgB,EACrB,sBAAsB,EACtB,KAAK,cAAc,GACpB,MAAM,cAAc,CAAC"}
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SandboxResultReference = exports.SandboxHostError = exports.resolveSandboxSurface = exports.SANDBOX_RESOURCE_LIMITS = exports.runSandboxProgram = exports.resolveSandboxResourceLimits = exports.assertSandboxIsolation = exports.isCodeModeError = exports.formatCodeModeError = exports.CodeModeError = exports.CODE_MODE_ERROR_CODES = void 0;
4
+ /**
5
+ * The Code Mode sandbox as another package uses it: run a program written by a
6
+ * model in an isolated QuickJS engine, against a surface the host declares.
7
+ *
8
+ * A host states the object the program receives (its name, its JSON constants
9
+ * and a closed table of operations), implements those operations in one
10
+ * callback, and gets back the program's value or a coded error. Only JSON
11
+ * crosses into the program. See ADR 0006 and ADR 0007.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { runSandboxProgram, SandboxHostError } from "@mcpview/compose/code-mode/sandbox";
16
+ *
17
+ * const total = await runSandboxProgram(
18
+ * "const order = await shop.getOrder(shop.params.id); return order.total;",
19
+ * {
20
+ * namespace: "shop",
21
+ * constants: { params: { id: 1042 } },
22
+ * operations: { getOrder: { budget: "reads" } },
23
+ * budgets: { reads: 12 },
24
+ * },
25
+ * (operation, args) => {
26
+ * if (args[0] !== 1042) {
27
+ * throw new SandboxHostError("ORDER_UNKNOWN", "No such order", "List the orders first");
28
+ * }
29
+ * return Promise.resolve({ id: 1042, total: 199.5 });
30
+ * },
31
+ * );
32
+ * ```
33
+ *
34
+ * @module code-mode/sandbox
35
+ */
36
+ require("../../_dnt.polyfills.js");
37
+ var errors_js_1 = require("./errors.js");
38
+ Object.defineProperty(exports, "CODE_MODE_ERROR_CODES", { enumerable: true, get: function () { return errors_js_1.CODE_MODE_ERROR_CODES; } });
39
+ Object.defineProperty(exports, "CodeModeError", { enumerable: true, get: function () { return errors_js_1.CodeModeError; } });
40
+ Object.defineProperty(exports, "formatCodeModeError", { enumerable: true, get: function () { return errors_js_1.formatCodeModeError; } });
41
+ Object.defineProperty(exports, "isCodeModeError", { enumerable: true, get: function () { return errors_js_1.isCodeModeError; } });
42
+ var sandbox_js_1 = require("./sandbox.js");
43
+ Object.defineProperty(exports, "assertSandboxIsolation", { enumerable: true, get: function () { return sandbox_js_1.assertSandboxIsolation; } });
44
+ Object.defineProperty(exports, "resolveSandboxResourceLimits", { enumerable: true, get: function () { return sandbox_js_1.resolveSandboxResourceLimits; } });
45
+ Object.defineProperty(exports, "runSandboxProgram", { enumerable: true, get: function () { return sandbox_js_1.runSandboxProgram; } });
46
+ Object.defineProperty(exports, "SANDBOX_RESOURCE_LIMITS", { enumerable: true, get: function () { return sandbox_js_1.SANDBOX_RESOURCE_LIMITS; } });
47
+ var surface_js_1 = require("./surface.js");
48
+ Object.defineProperty(exports, "resolveSandboxSurface", { enumerable: true, get: function () { return surface_js_1.resolveSandboxSurface; } });
49
+ Object.defineProperty(exports, "SandboxHostError", { enumerable: true, get: function () { return surface_js_1.SandboxHostError; } });
50
+ Object.defineProperty(exports, "SandboxResultReference", { enumerable: true, get: function () { return surface_js_1.SandboxResultReference; } });
@@ -7,55 +7,133 @@
7
7
  */
8
8
  import { type QuickJSWASMModule } from "quickjs-emscripten";
9
9
  import { CodeModeError } from "./errors.js";
10
- /** Resource limits of one program. */
11
- export interface SandboxLimits {
10
+ import { type SandboxSurface } from "./surface.js";
11
+ /**
12
+ * Resource limits of one program. How many calls it may make is not one of
13
+ * them: call counts are the budgets of its surface.
14
+ */
15
+ export interface SandboxResourceLimits {
12
16
  /** Guest CPU time. Time spent waiting for host operations is not counted. */
13
17
  readonly cpuMs: number;
14
18
  /** Wall-clock time of the whole program, host operations included. */
15
19
  readonly wallMs: number;
16
20
  readonly memoryBytes: number;
17
21
  readonly stackBytes: number;
18
- /** `listSnippets` and `runSnippet` calls: upstream, possibly side-effecting work. */
19
- readonly providerCalls: number;
20
- /** `panel` and `sync` calls: board choices kept in host memory. */
21
- readonly boardOperations: number;
22
22
  /** Maximum length, in UTF-16 code units, of the JSON text of a value crossing the sandbox boundary. */
23
23
  readonly valueLength: number;
24
24
  }
25
- /** Default limits of a Code Mode program. */
26
- export declare const CODE_MODE_LIMITS: SandboxLimits;
27
- /** Maximum source length accepted by the code-mode execute tool. */
25
+ /** Default resource limits of a program. */
26
+ export declare const SANDBOX_RESOURCE_LIMITS: SandboxResourceLimits;
27
+ /** Maximum length of a program's source, in UTF-16 code units. */
28
28
  export declare const maxCodeLength = 16384;
29
29
  /** Serialize data crossing the QuickJS boundary within the supplied limit. */
30
30
  export declare function encodeValue(value: unknown, limit?: number): string;
31
31
  /** The error for a host result that exceeds the JSON limit of the boundary. */
32
32
  export declare function receiptTooLarge(limit: number): CodeModeError;
33
+ /** The error for a host operation that rejected with nothing the program may read. */
34
+ export declare function operationFailed(namespace: string, operation: string): CodeModeError;
35
+ /**
36
+ * The JSON text of a host operation's result, as it crosses into the program.
37
+ * Throws the error the program is given instead when the value is not JSON or
38
+ * exceeds the limit. This is the host's own serialization, outside the engine:
39
+ * a getter that throws, a cycle or even the host's stack running out fails the
40
+ * operation, and is no fault of the engine.
41
+ */
42
+ export declare function encodeHostValue(namespace: string, operation: string, value: unknown, limit: number): string;
43
+ /** The error for a run the sandbox itself could not carry through. */
44
+ export declare function sandboxFailure(): CodeModeError;
45
+ /** A call a program made that never reached the host. */
46
+ export interface UnsentCall {
47
+ readonly operation: string;
48
+ /** The JSON text of the list of its arguments, taken when the call was made. */
49
+ readonly args: string;
50
+ }
51
+ /** The error for a program that finished with calls it did not wait for. */
52
+ export declare function unawaitedOperation(namespace: string, count: number): CodeModeError;
53
+ /** What a program sees of a host's own error. */
54
+ export interface HostErrorShown {
55
+ readonly code: string;
56
+ readonly message: string;
57
+ readonly recovery: string;
58
+ }
59
+ /**
60
+ * How a host's own error travels through the sandbox. The program sees
61
+ * `shown`. The run fails with this carrier, whose context names the call, so
62
+ * the host finds the original error it kept: only the object the sandbox
63
+ * handed to the program maps back to it, never one the program built.
64
+ */
65
+ export declare class HostErrorCarrier extends CodeModeError {
66
+ readonly shown: HostErrorShown;
67
+ constructor(namespace: string, operation: string, call: number, shown: HostErrorShown);
68
+ }
69
+ /**
70
+ * A surface as the driver takes it: each constant is the JSON text of its
71
+ * value. Only JSON text crosses a boundary of the sandbox, never a tree of
72
+ * objects, so no boundary adds a nesting limit of its own.
73
+ */
74
+ export interface EncodedSurface extends Omit<SandboxSurface, "constants"> {
75
+ readonly constants?: Readonly<Record<string, string>>;
76
+ }
33
77
  /** Inputs of {@link runVm}. */
34
78
  export interface RunVmOptions {
35
79
  readonly quickjs: QuickJSWASMModule;
36
80
  readonly code: string;
37
- readonly params: Record<string, unknown>;
38
- readonly limits: SandboxLimits;
39
- /** Perform one host operation. Rejections should be {@link CodeModeError}s. */
40
- call(operation: string, args: unknown[]): Promise<unknown>;
81
+ /** What the program receives. Validated again here. */
82
+ readonly surface: EncodedSurface;
83
+ readonly limits: SandboxResourceLimits;
84
+ /**
85
+ * Perform one host operation. `args` is the JSON text of the list of its
86
+ * arguments, and `id` identifies this call within the run. Resolves to the
87
+ * JSON text of the result, within `limits.valueLength`. Rejections should
88
+ * be {@link CodeModeError}s: one crosses into the program by its fields.
89
+ */
90
+ call(operation: string, args: string, id: number): Promise<string>;
91
+ /**
92
+ * The key of the record that stands for an earlier result: `{ [key]: id }`.
93
+ * Required when the surface uses references. The program never sees it, so
94
+ * it cannot write such a record itself.
95
+ */
96
+ readonly referenceKey?: string;
97
+ /**
98
+ * Called when the engine is left in a state nobody can vouch for (the host's
99
+ * stack overflowed inside it, or it could not release the program). The VM
100
+ * is then abandoned, not disposed: the caller should stop reusing the engine.
101
+ * The run still settles with its own outcome.
102
+ */
103
+ onEngineFault?(): void;
104
+ /**
105
+ * True when the host completed call `id` and its effect cannot be undone. A
106
+ * result of such a call that cannot be handed to the program ends the run:
107
+ * the program is not given a failure it could answer by calling again.
108
+ */
109
+ mustDeliver?(id: number): boolean;
110
+ /**
111
+ * Decide about the calls a program that finished normally did not wait for.
112
+ * They were not sent. Resolve to let the program's value stand; reject with
113
+ * a {@link CodeModeError} to fail the run. Without it the run fails with
114
+ * `UNAWAITED_OPERATION`.
115
+ */
116
+ unsent?(calls: UnsentCall[]): Promise<void>;
41
117
  /** Polled by the QuickJS interrupt handler and between host operations. */
42
118
  isCancelled(): boolean;
43
119
  }
44
120
  /**
45
- * Run a function body in an isolated QuickJS context. Only JSON and the four
46
- * `api` operations cross into the host. Failures are {@link CodeModeError}s.
121
+ * Run a function body in an isolated QuickJS context. Only JSON text and the
122
+ * operations its surface declares cross into the host. Resolves to the JSON
123
+ * text of what the program returned, or to undefined when it returned
124
+ * nothing. Failures are {@link CodeModeError}s.
47
125
  *
48
126
  * @example
49
127
  * ```ts
50
- * const value = await runVm({
51
- * quickjs: await getQuickJS(),
52
- * code: "return api.params.n * 2;",
53
- * params: { n: 21 },
54
- * limits: CODE_MODE_LIMITS,
128
+ * const json = await runVm({
129
+ * quickjs: await newEngine(),
130
+ * code: "return shop.params.n * 2;",
131
+ * surface: { namespace: "shop", constants: { params: '{"n":21}' }, operations: {}, budgets: {} },
132
+ * limits: SANDBOX_RESOURCE_LIMITS,
55
133
  * call: () => Promise.reject(new Error("unused")),
56
134
  * isCancelled: () => false,
57
135
  * });
58
136
  * ```
59
137
  */
60
- export declare function runVm(options: RunVmOptions): Promise<unknown>;
138
+ export declare function runVm(options: RunVmOptions): Promise<string | undefined>;
61
139
  //# sourceMappingURL=sandbox-core.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox-core.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/sandbox-core.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAsB,KAAK,iBAAiB,EAAS,MAAM,oBAAoB,CAAC;AACvF,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,sCAAsC;AACtC,MAAM,WAAW,aAAa;IAC5B,6EAA6E;IAC7E,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,sEAAsE;IACtE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,qFAAqF;IACrF,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,mEAAmE;IACnE,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,uGAAuG;IACvG,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED,6CAA6C;AAC7C,eAAO,MAAM,gBAAgB,EAAE,aAQ7B,CAAC;AAEH,oEAAoE;AACpE,eAAO,MAAM,aAAa,QAAS,CAAC;AAKpC,8EAA8E;AAC9E,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,SAA+B,GAAG,MAAM,CAMxF;AAED,+EAA+E;AAC/E,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAO5D;AAeD,+BAA+B;AAC/B,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,OAAO,EAAE,iBAAiB,CAAC;IACp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