@iso4/sandbox 0.0.0 → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +130 -0
- package/dist/index.d.mts +441 -0
- package/dist/index.mjs +1196 -0
- package/package.json +62 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 schplitt
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# @iso4/sandbox
|
|
2
|
+
|
|
3
|
+
Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Runs user
|
|
4
|
+
code in a separate Rust process for full crash isolation — an OOM or panic in
|
|
5
|
+
the sandbox kills only the subprocess, not your host application.
|
|
6
|
+
|
|
7
|
+
Built for the AI-agent prefix/postfix pattern: precompile host setup (globals,
|
|
8
|
+
libraries, tool bindings) once into a V8 startup snapshot, then run many
|
|
9
|
+
agent-generated code strings against the snapshot in parallel.
|
|
10
|
+
|
|
11
|
+
> **Status:** core execution works end-to-end. Not yet at 1.0.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm i @iso4/sandbox
|
|
17
|
+
# hardened fetch defaults (recommended):
|
|
18
|
+
npm i @iso4/fetch
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { createSandbox } from '@iso4/sandbox'
|
|
25
|
+
import { createSafeFetch } from '@iso4/fetch'
|
|
26
|
+
|
|
27
|
+
const sandbox = await createSandbox()
|
|
28
|
+
|
|
29
|
+
// Compile host setup once into a V8 snapshot
|
|
30
|
+
const prefix = await sandbox.precompile({
|
|
31
|
+
code: `
|
|
32
|
+
const config = { apiBase: 'https://api.example.com' }
|
|
33
|
+
globalThis.config = config
|
|
34
|
+
`,
|
|
35
|
+
globals: {
|
|
36
|
+
fetch: createSafeFetch({ policy: ({ host }) => host === 'api.example.com' }),
|
|
37
|
+
},
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
// Run agent-generated code against the snapshot — as many times as needed
|
|
41
|
+
const result = await prefix.run({
|
|
42
|
+
code: `
|
|
43
|
+
const res = await fetch(config.apiBase + '/users')
|
|
44
|
+
export default { count: res.length }
|
|
45
|
+
`,
|
|
46
|
+
limits: { cpuTimeMs: 200, wallTimeMs: 5_000, memoryMb: 64 },
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
if (result.ok) {
|
|
50
|
+
console.log(result.exports.default) // { count: 42 }
|
|
51
|
+
} else {
|
|
52
|
+
console.error(result.error.code, result.error.message)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
await sandbox.dispose()
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## How globals work
|
|
59
|
+
|
|
60
|
+
`globals` wires any non-reserved name directly into the sandbox's global
|
|
61
|
+
object as a bridge stub. The bridge is fully generic — `fetch` is not
|
|
62
|
+
special-cased:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const options = {
|
|
66
|
+
globals: {
|
|
67
|
+
searchWeb: async (query: string) => {
|
|
68
|
+
const res = await fetch(`https://api.example.com/search?q=${encodeURIComponent(query)}`)
|
|
69
|
+
return res.json()
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Functions in bridge return values are currently dropped — return plain data,
|
|
76
|
+
not class instances with methods.
|
|
77
|
+
|
|
78
|
+
## TypeScript-checked rebinding
|
|
79
|
+
|
|
80
|
+
`precompile()` infers the globals shape `G` from what you pass, and the
|
|
81
|
+
returned `Prefix<G>` only allows rebinding those names at run time:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
const prefix = await sandbox.precompile({
|
|
85
|
+
globals: { fetch: defaultFetch, myTool: defaultTool },
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
prefix.run({ globals: { fetch: perUserFetch } }) // ✅ rebind one
|
|
89
|
+
prefix.run({ globals: { unknown: handler } }) // ❌ TS error
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Resource limits
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
prefix.run({
|
|
96
|
+
code: agentCode,
|
|
97
|
+
limits: {
|
|
98
|
+
cpuTimeMs: 200, // active JS execution only (await time excluded)
|
|
99
|
+
wallTimeMs: 5_000, // hard cap including async waits
|
|
100
|
+
memoryMb: 64, // V8 heap + ArrayBuffer budget
|
|
101
|
+
maxBridgeCalls: 10, // max host-bridge calls per run (0 = unlimited)
|
|
102
|
+
maxBridgePayloadBytes: 0, // max bytes per bridge call (0 = 64 MiB framing cap)
|
|
103
|
+
},
|
|
104
|
+
})
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Result shape
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
type RunResult
|
|
111
|
+
= | { ok: true, exports: SandboxExports, stdout: string[], stderr: string[], durationMs: number }
|
|
112
|
+
| { ok: false, error: RunError, stdout: string[], stderr: string[], durationMs: number }
|
|
113
|
+
|
|
114
|
+
interface RunError { code: RunErrorCode, name: string, message: string, stack?: string }
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`run()` never throws for sandboxed failures — only for infrastructure errors
|
|
118
|
+
(subprocess crashed, binary not found). `ok: false` with an error code is the
|
|
119
|
+
normal failure path.
|
|
120
|
+
|
|
121
|
+
## Architecture
|
|
122
|
+
|
|
123
|
+
V8 runs in a separate Rust subprocess communicating over a Unix domain socket.
|
|
124
|
+
A pool of connections (one per `maxIsolates` slot) provides concurrency —
|
|
125
|
+
five concurrent `prefix.run()` calls each get their own slot and execute in
|
|
126
|
+
parallel.
|
|
127
|
+
|
|
128
|
+
## License
|
|
129
|
+
|
|
130
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* \@iso4/sandbox — public API types.
|
|
4
|
+
*
|
|
5
|
+
* Execution model: precompile a prefix once into a V8 startup snapshot,
|
|
6
|
+
* then call prefix.run({ code }) for each piece of dynamic code (e.g.
|
|
7
|
+
* agent-generated). A fresh isolate is created from the snapshot per call.
|
|
8
|
+
* Multiple concurrent callers each get their own pool slot and run in
|
|
9
|
+
* parallel. See DESIGN.md §1 and §13.
|
|
10
|
+
*/
|
|
11
|
+
interface ResourceLimits {
|
|
12
|
+
/**
|
|
13
|
+
* Hard cap on memory the isolate can use, in megabytes.
|
|
14
|
+
* Covers the V8 heap and all external `ArrayBuffer` allocations.
|
|
15
|
+
*
|
|
16
|
+
* Also determines the BridgeResponse frame read cap: the sandbox cannot
|
|
17
|
+
* receive a response larger than its own memory budget.
|
|
18
|
+
*
|
|
19
|
+
* Zero means no cap.
|
|
20
|
+
* @default 64
|
|
21
|
+
*/
|
|
22
|
+
memoryMb: number;
|
|
23
|
+
/**
|
|
24
|
+
* Maximum *active* execution time in milliseconds. Time spent waiting on
|
|
25
|
+
* host bridge calls (globals, host imports) is excluded.
|
|
26
|
+
* @default 5_000
|
|
27
|
+
*/
|
|
28
|
+
cpuTimeMs: number;
|
|
29
|
+
/**
|
|
30
|
+
* Hard wall-clock cap including async waits.
|
|
31
|
+
* @default 30_000
|
|
32
|
+
*/
|
|
33
|
+
wallTimeMs: number;
|
|
34
|
+
/**
|
|
35
|
+
* Maximum bytes the sandbox may send as arguments in a single bridge call
|
|
36
|
+
* (sandbox → host direction). Protects the host from receiving unexpectedly
|
|
37
|
+
* large payloads generated by untrusted sandbox code.
|
|
38
|
+
*
|
|
39
|
+
* Bridge responses (host → sandbox) are not separately capped here — the
|
|
40
|
+
* natural limit is `memoryMb`: the sandbox cannot hold a response larger than
|
|
41
|
+
* its own memory budget, and the framing layer enforces this automatically.
|
|
42
|
+
*
|
|
43
|
+
* Zero disables the per-call cap.
|
|
44
|
+
* @default 16 * 1024 * 1024
|
|
45
|
+
*/
|
|
46
|
+
maxBridgeCallBytes: number;
|
|
47
|
+
/**
|
|
48
|
+
* Maximum bytes allowed for the serialised export payload (all named exports
|
|
49
|
+
* combined). Exceeding this limit terminates the run with `ERR_EXPORT_TOO_LARGE`.
|
|
50
|
+
* Zero disables the cap.
|
|
51
|
+
* @default 16 * 1024 * 1024
|
|
52
|
+
*/
|
|
53
|
+
maxExportBytes: number;
|
|
54
|
+
/**
|
|
55
|
+
* Maximum bytes captured from `console.log` / `console.debug` / `console.info`
|
|
56
|
+
* combined. Lines that would push the total over the limit are silently dropped.
|
|
57
|
+
* Zero disables the cap.
|
|
58
|
+
* @default 1 * 1024 * 1024
|
|
59
|
+
*/
|
|
60
|
+
maxStdoutBytes: number;
|
|
61
|
+
/**
|
|
62
|
+
* Maximum bytes captured from `console.warn` / `console.error` combined.
|
|
63
|
+
* Lines that would push the total over the limit are silently dropped.
|
|
64
|
+
* Zero disables the cap.
|
|
65
|
+
* @default 1 * 1024 * 1024
|
|
66
|
+
*/
|
|
67
|
+
maxStderrBytes: number;
|
|
68
|
+
/**
|
|
69
|
+
* Maximum number of bridge calls (globals + host imports combined) a
|
|
70
|
+
* single run may make. Zero disables the per-run limit entirely.
|
|
71
|
+
*
|
|
72
|
+
* Protects against untrusted sandbox code making unbounded calls to host
|
|
73
|
+
* handlers (e.g. `while(true) { await myTool() }`) which consumes near-zero
|
|
74
|
+
* CPU budget but can exhaust host resources (network, DB, LLM quota).
|
|
75
|
+
*
|
|
76
|
+
* @default 10
|
|
77
|
+
*/
|
|
78
|
+
maxBridgeCalls: number;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Host-provided globals. Any name not reserved by V8 or the runtime is
|
|
82
|
+
* permitted. Each value becomes a bridge stub in the sandbox global object.
|
|
83
|
+
*
|
|
84
|
+
* Reserved names (must not be used): `console`, `URL`, `URLSearchParams`,
|
|
85
|
+
* `TextEncoder`, `TextDecoder`, `crypto`, `Event`, `AbortController`,
|
|
86
|
+
* `AbortSignal`.
|
|
87
|
+
*
|
|
88
|
+
* Common usage:
|
|
89
|
+
* ```ts
|
|
90
|
+
* globals: {
|
|
91
|
+
* fetch: myFetchHandler, // \@iso4/fetch provides createSafeFetch()
|
|
92
|
+
* myTool: async (arg) => doSomething(arg),
|
|
93
|
+
* }
|
|
94
|
+
* ```
|
|
95
|
+
*
|
|
96
|
+
* `fetch` is not special — it goes through the same bridge path as any
|
|
97
|
+
* other entry.
|
|
98
|
+
*
|
|
99
|
+
* Three value shapes are supported — see `HostGlobalValue`.
|
|
100
|
+
*/
|
|
101
|
+
type HostGlobals = Record<string, HostGlobalValue>;
|
|
102
|
+
/**
|
|
103
|
+
* The value types accepted for a named global.
|
|
104
|
+
*
|
|
105
|
+
* - `HostExportFunction` — bridge call: every sandbox invocation dispatches
|
|
106
|
+
* to the host handler.
|
|
107
|
+
* - `string` — a JS expression installed once at prefix setup:
|
|
108
|
+
* `globalThis.<name> = <expr>`. Use for pure sandbox utilities that need
|
|
109
|
+
* no host involvement.
|
|
110
|
+
* - `BridgeWithShim` — bridge call + in-sandbox result wrapper. The handler
|
|
111
|
+
* can be rebound per `prefix.run()`; the shim is compiled into the snapshot.
|
|
112
|
+
*/
|
|
113
|
+
type HostGlobalValue = HostExportFunction | string | BridgeWithShim<any>;
|
|
114
|
+
/**
|
|
115
|
+
* A global that pairs a bridge handler with an in-sandbox shim that wraps
|
|
116
|
+
* its return value. Typical use: adding `.json()` / `.text()` convenience
|
|
117
|
+
* methods to a fetch response without extra bridge round-trips.
|
|
118
|
+
*
|
|
119
|
+
* The TS layer:
|
|
120
|
+
* 1. Registers `handler` as a bridge stub under `__iso4_<name>_h`.
|
|
121
|
+
* 2. Prepends to the prefix source:
|
|
122
|
+
* ```js
|
|
123
|
+
* globalThis.<name> = async (...args) =>
|
|
124
|
+
* await (<shim>)(await __iso4_<name>_h(...args))
|
|
125
|
+
* ```
|
|
126
|
+
*
|
|
127
|
+
* The shim is a JS function expression `(result) => transformedResult` (sync
|
|
128
|
+
* or async). Sandbox built-ins (TextDecoder, JSON, …) are available in scope.
|
|
129
|
+
* The private stub `__iso4_<name>_h` stays on globalThis so the handler can
|
|
130
|
+
* be rebound per `prefix.run()` while the shim stays fixed in the snapshot.
|
|
131
|
+
*/
|
|
132
|
+
/**
|
|
133
|
+
* `H` is the specific handler function type. Carried through the type system
|
|
134
|
+
* so `RebindGlobals` can enforce that any per-run replacement has the same
|
|
135
|
+
* return type, keeping it compatible with the shim that is already compiled
|
|
136
|
+
* into the prefix snapshot.
|
|
137
|
+
*/
|
|
138
|
+
interface BridgeWithShim<H extends (...args: unknown[]) => unknown = (...args: unknown[]) => unknown> {
|
|
139
|
+
kind: "bridge-with-shim";
|
|
140
|
+
/**
|
|
141
|
+
* Bridge handler — registered as `__iso4_<name>_h` for rebinding.
|
|
142
|
+
*/
|
|
143
|
+
handler: H;
|
|
144
|
+
/**
|
|
145
|
+
* JS function expression that transforms the bridge return value.
|
|
146
|
+
* Runs in the sandbox. May be async.
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* ```ts
|
|
150
|
+
* shim: `(result) => ({
|
|
151
|
+
* ...result,
|
|
152
|
+
* ok: result.status >= 200 && result.status < 300,
|
|
153
|
+
* json: () => JSON.parse(new TextDecoder().decode(result.body)),
|
|
154
|
+
* text: () => new TextDecoder().decode(result.body),
|
|
155
|
+
* })`
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
shim: string;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* What can be supplied as a per-run override for a global declared at
|
|
162
|
+
* precompile time:
|
|
163
|
+
*
|
|
164
|
+
* - `BridgeWithShim<H>` global — only the handler `H` itself. The shim is
|
|
165
|
+
* fixed in the snapshot; rebinding must preserve the return type so the
|
|
166
|
+
* shim keeps working.
|
|
167
|
+
* - `HostExportFunction` global — any compatible `HostExportFunction`.
|
|
168
|
+
* - `string` global — cannot be rebound (compiled into the snapshot).
|
|
169
|
+
*/
|
|
170
|
+
type RebindValue<V extends HostGlobalValue> = V extends BridgeWithShim<infer H> ? H : V extends HostExportFunction ? V : never;
|
|
171
|
+
/**
|
|
172
|
+
* The per-run globals override map for a `Prefix<G>`.
|
|
173
|
+
*
|
|
174
|
+
* String-valued globals are filtered out entirely (key remapping to `never`)
|
|
175
|
+
* rather than mapped to `?: never` — they cannot be rebound because their
|
|
176
|
+
* expression is compiled into the snapshot, and they should not appear as
|
|
177
|
+
* valid keys at all.
|
|
178
|
+
*
|
|
179
|
+
* Each remaining key is optional and typed as `RebindValue<G[K]>`, which
|
|
180
|
+
* enforces the correct constraint per global kind.
|
|
181
|
+
*/
|
|
182
|
+
type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string ? never : K]?: RebindValue<G[K]> };
|
|
183
|
+
/**
|
|
184
|
+
* Resolution order: static map → dynamic resolver → ERR_MODULE_NOT_FOUND.
|
|
185
|
+
*/
|
|
186
|
+
interface ImportsConfig {
|
|
187
|
+
static?: Record<string, ImportDefinition>;
|
|
188
|
+
resolve?: (specifier: string, importer: string | null) => Promise<ImportDefinition | null> | ImportDefinition | null;
|
|
189
|
+
}
|
|
190
|
+
type ImportDefinition = SourceImport | HostImport;
|
|
191
|
+
/**
|
|
192
|
+
* Host provides ESM source; V8 compiles and caches it in-isolate.
|
|
193
|
+
*/
|
|
194
|
+
interface SourceImport {
|
|
195
|
+
kind: "source";
|
|
196
|
+
source: string;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Host provides an object; each function becomes a bridge-call stub.
|
|
200
|
+
*/
|
|
201
|
+
interface HostImport {
|
|
202
|
+
kind: "host";
|
|
203
|
+
exports: HostExports;
|
|
204
|
+
}
|
|
205
|
+
interface HostExports {
|
|
206
|
+
default?: HostExportValue;
|
|
207
|
+
[name: string]: HostExportValue | undefined;
|
|
208
|
+
}
|
|
209
|
+
type HostExportValue = HostExportData | HostExportFunction;
|
|
210
|
+
/**
|
|
211
|
+
* Represents the plain-data values that cross the bridge.
|
|
212
|
+
* Kept for `HostExports` / import system typing.
|
|
213
|
+
*/
|
|
214
|
+
type HostExportData = null | undefined | boolean | number | bigint | string | Uint8Array | HostExportData[] | {
|
|
215
|
+
[key: string]: HostExportData;
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* A host-side function exposed as a global or import export.
|
|
219
|
+
*
|
|
220
|
+
* Args and return are `unknown` — the bridge serialises/deserialises values
|
|
221
|
+
* with V8 ValueSerializer; we don't try to model that at the type level.
|
|
222
|
+
* The one invariant that matters (functions cannot cross the boundary) is
|
|
223
|
+
* enforced at runtime by the V8 layer, not here.
|
|
224
|
+
*
|
|
225
|
+
* Use specific function types for your handlers and let TypeScript infer
|
|
226
|
+
* them through `HostGlobals` and `RebindGlobals<G>`.
|
|
227
|
+
*/
|
|
228
|
+
type HostExportFunction = (...args: unknown[]) => unknown;
|
|
229
|
+
interface SandboxOptions {
|
|
230
|
+
/**
|
|
231
|
+
* Maximum number of isolates (UDS connection slots) running concurrently.
|
|
232
|
+
* The Sandbox maintains a pool of this many connections to the Rust process;
|
|
233
|
+
* each executes one run() at a time. Additional callers queue.
|
|
234
|
+
*
|
|
235
|
+
* Multiple MCP agents / concurrent callers each get their own slot and
|
|
236
|
+
* run in parallel up to this limit.
|
|
237
|
+
*
|
|
238
|
+
* Defaults to the number of logical CPUs on the host machine.
|
|
239
|
+
*/
|
|
240
|
+
maxIsolates?: number;
|
|
241
|
+
/**
|
|
242
|
+
* Override the path to the Rust V8 binary.
|
|
243
|
+
* Default: auto-detect from \@iso4/v8-* platform packages.
|
|
244
|
+
*/
|
|
245
|
+
binaryPath?: string;
|
|
246
|
+
}
|
|
247
|
+
interface Sandbox {
|
|
248
|
+
/**
|
|
249
|
+
* Execute a piece of JavaScript in a fresh V8 isolate.
|
|
250
|
+
* For repeated use with a shared context, prefer precompile() + prefix.run().
|
|
251
|
+
*/
|
|
252
|
+
run: (options: RunOptions) => Promise<RunResult>;
|
|
253
|
+
/**
|
|
254
|
+
* Pre-compile a prefix of code into a V8 startup snapshot.
|
|
255
|
+
*
|
|
256
|
+
* The type parameter `G` is inferred from the `globals` you pass and flows
|
|
257
|
+
* into the returned `Prefix<G>`. This lets TypeScript enforce at the call
|
|
258
|
+
* site that `prefix.run()` can only rebind names declared here:
|
|
259
|
+
*
|
|
260
|
+
* ```ts
|
|
261
|
+
* const prefix = await sandbox.precompile({
|
|
262
|
+
* globals: { fetch: myHandler, myTool: otherHandler },
|
|
263
|
+
* })
|
|
264
|
+
* // prefix: Prefix<{ fetch: ..., myTool: ... }>
|
|
265
|
+
*
|
|
266
|
+
* prefix.run({ globals: { fetch: newHandler } }) // ✅
|
|
267
|
+
* prefix.run({ globals: { undeclared: someHandler } }) // ❌ TS error
|
|
268
|
+
* ```
|
|
269
|
+
*
|
|
270
|
+
* Globals declared here serve as **default** implementations for all runs.
|
|
271
|
+
* `prefix.run()` may override any subset; omitted names reuse the default.
|
|
272
|
+
*/
|
|
273
|
+
precompile: <G extends HostGlobals = {}>(options: PrecompileOptions<G>) => Promise<Prefix<G>>;
|
|
274
|
+
/**
|
|
275
|
+
* Tear down the Rust process. Outstanding prefixes are invalidated.
|
|
276
|
+
*/
|
|
277
|
+
dispose: () => Promise<void>;
|
|
278
|
+
/**
|
|
279
|
+
* Enables `await using sandbox = await createSandbox()` syntax.
|
|
280
|
+
*/
|
|
281
|
+
[Symbol.asyncDispose]: () => Promise<void>;
|
|
282
|
+
readonly alive: boolean;
|
|
283
|
+
}
|
|
284
|
+
type CreateSandbox = (options?: SandboxOptions) => Promise<Sandbox>;
|
|
285
|
+
/**
|
|
286
|
+
* Options for `sandbox.precompile()`.
|
|
287
|
+
*
|
|
288
|
+
* `G` is the shape of globals this prefix declares. TypeScript infers it
|
|
289
|
+
* from the `globals` field, so the returned `Prefix<G>` is typed to allow
|
|
290
|
+
* only those names to be rebound in subsequent `prefix.run()` calls.
|
|
291
|
+
*/
|
|
292
|
+
interface PrecompileOptions<G extends HostGlobals> {
|
|
293
|
+
/**
|
|
294
|
+
* ESM source code to evaluate before snapshotting. Top-level await works.
|
|
295
|
+
*
|
|
296
|
+
* @example
|
|
297
|
+
* import { search } from 'tools:search';
|
|
298
|
+
* globalThis.search = search;
|
|
299
|
+
*/
|
|
300
|
+
code: string;
|
|
301
|
+
/**
|
|
302
|
+
* Declares the globals that sandbox code will be able to call.
|
|
303
|
+
*
|
|
304
|
+
* This defines the **bridge surface shape** — the full set of names the
|
|
305
|
+
* sandbox may invoke as globals. Names declared here:
|
|
306
|
+
*
|
|
307
|
+
* - Become bridge stubs in the V8 context on every `prefix.run()` call.
|
|
308
|
+
* - Can be rebound per-run via `prefix.run({ globals })`.
|
|
309
|
+
* - Cannot be supplemented at run time — a name not declared here will
|
|
310
|
+
* cause `ERR_UNDECLARED_BINDING` if passed to `prefix.run()`.
|
|
311
|
+
*
|
|
312
|
+
* The handlers provided here are the **default** implementations reused by
|
|
313
|
+
* any `prefix.run()` call that does not override them.
|
|
314
|
+
*/
|
|
315
|
+
globals?: G;
|
|
316
|
+
imports?: ImportsConfig;
|
|
317
|
+
/**
|
|
318
|
+
* Resource limits applied to prefix code evaluation.
|
|
319
|
+
*
|
|
320
|
+
* **Important:** limits are NOT enforced during `precompile()`. Prefix code
|
|
321
|
+
* is assumed to be developer-authored, not AI-agent-generated.
|
|
322
|
+
*
|
|
323
|
+
* **Currently a no-op placeholder.** Pass limits directly to each
|
|
324
|
+
* `prefix.run()` call.
|
|
325
|
+
*/
|
|
326
|
+
limits?: Partial<ResourceLimits>;
|
|
327
|
+
/**
|
|
328
|
+
* Optional filename for stack traces. Default: "<prefix>".
|
|
329
|
+
*/
|
|
330
|
+
filename?: string;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Handle to a precompiled prefix.
|
|
334
|
+
*
|
|
335
|
+
* `G` is the shape of globals declared at precompile time. `prefix.run()`
|
|
336
|
+
* accepts only `Partial<G>` for its `globals` field — you may override any
|
|
337
|
+
* declared global's implementation per run, but you cannot add names that
|
|
338
|
+
* were not declared at precompile time.
|
|
339
|
+
*/
|
|
340
|
+
interface Prefix<G extends HostGlobals> {
|
|
341
|
+
readonly id: string;
|
|
342
|
+
/**
|
|
343
|
+
* Execute dynamic code against this prefix's snapshot state.
|
|
344
|
+
*
|
|
345
|
+
* Globals declared at precompile time are active. You may rebind any subset
|
|
346
|
+
* of them via `options.globals`; the precompile-time handler is used for
|
|
347
|
+
* any name not overridden here.
|
|
348
|
+
*
|
|
349
|
+
* @example
|
|
350
|
+
* const result = await prefix.run({
|
|
351
|
+
* code: `export default await (${agentFn})()`,
|
|
352
|
+
* })
|
|
353
|
+
*/
|
|
354
|
+
run: (options: PrefixRunOptions<G>) => Promise<RunResult>;
|
|
355
|
+
/**
|
|
356
|
+
* Release the snapshot. Subsequent run() calls reject. Idempotent.
|
|
357
|
+
*/
|
|
358
|
+
dispose: () => Promise<void>;
|
|
359
|
+
/**
|
|
360
|
+
* Enables `await using prefix = await sandbox.precompile(...)` syntax.
|
|
361
|
+
*/
|
|
362
|
+
[Symbol.asyncDispose]: () => Promise<void>;
|
|
363
|
+
readonly alive: boolean;
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Options for `prefix.run()`.
|
|
367
|
+
*
|
|
368
|
+
* `G` is the declared-globals shape from the matching `precompile()` call.
|
|
369
|
+
* The `globals` field is typed as `Partial<G>` — only names present in `G`
|
|
370
|
+
* may be overridden. Passing any other name is a TypeScript error at compile
|
|
371
|
+
* time and `ERR_UNDECLARED_BINDING` at runtime.
|
|
372
|
+
*/
|
|
373
|
+
interface PrefixRunOptions<G extends HostGlobals> {
|
|
374
|
+
/**
|
|
375
|
+
* Dynamic ESM source code to compile and run against the prefix state.
|
|
376
|
+
*/
|
|
377
|
+
code: string;
|
|
378
|
+
/**
|
|
379
|
+
* Override implementations for a **subset** of globals declared at
|
|
380
|
+
* precompile time. Only names present in `G` are accepted (TypeScript
|
|
381
|
+
* error + runtime `ERR_UNDECLARED_BINDING` for anything else), but the
|
|
382
|
+
* function signature does not need to match the precompile-time handler
|
|
383
|
+
* exactly — any `HostExportFunction`-compatible value is accepted.
|
|
384
|
+
*/
|
|
385
|
+
globals?: RebindGlobals<G>;
|
|
386
|
+
/**
|
|
387
|
+
* Rebind host-module imports declared at precompile time.
|
|
388
|
+
* Source module imports are frozen in the snapshot and cannot be rebound.
|
|
389
|
+
* (Phase 6/7 — not yet implemented.)
|
|
390
|
+
*/
|
|
391
|
+
imports?: ImportsConfig;
|
|
392
|
+
limits?: Partial<ResourceLimits>;
|
|
393
|
+
signal?: AbortSignal;
|
|
394
|
+
filename?: string;
|
|
395
|
+
}
|
|
396
|
+
interface RunOptions {
|
|
397
|
+
code: string;
|
|
398
|
+
limits?: Partial<ResourceLimits>;
|
|
399
|
+
globals?: HostGlobals;
|
|
400
|
+
imports?: ImportsConfig;
|
|
401
|
+
signal?: AbortSignal;
|
|
402
|
+
filename?: string;
|
|
403
|
+
}
|
|
404
|
+
type RunResult = RunSuccess | RunFailure;
|
|
405
|
+
interface RunSuccess {
|
|
406
|
+
ok: true;
|
|
407
|
+
exports: SandboxExports;
|
|
408
|
+
stdout: string[];
|
|
409
|
+
stderr: string[];
|
|
410
|
+
durationMs: number;
|
|
411
|
+
}
|
|
412
|
+
interface RunFailure {
|
|
413
|
+
ok: false;
|
|
414
|
+
error: RunError;
|
|
415
|
+
stdout: string[];
|
|
416
|
+
stderr: string[];
|
|
417
|
+
durationMs: number;
|
|
418
|
+
}
|
|
419
|
+
type SandboxExports = {
|
|
420
|
+
/**
|
|
421
|
+
* Value of `export default` in user code, or `undefined`.
|
|
422
|
+
*/
|
|
423
|
+
default: unknown;
|
|
424
|
+
} & {
|
|
425
|
+
/**
|
|
426
|
+
* Named exports live directly on the export object.
|
|
427
|
+
*/
|
|
428
|
+
[name: string]: unknown;
|
|
429
|
+
};
|
|
430
|
+
interface RunError {
|
|
431
|
+
code: RunErrorCode;
|
|
432
|
+
name: string;
|
|
433
|
+
message: string;
|
|
434
|
+
stack?: string;
|
|
435
|
+
}
|
|
436
|
+
type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_EXPORT_UNRESOLVED_PROMISE" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_UNDECLARED_BINDING" | "ERR_PREFIX_DISPOSED" | "ERR_INTERNAL";
|
|
437
|
+
//#endregion
|
|
438
|
+
//#region src/index.d.ts
|
|
439
|
+
declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
|
|
440
|
+
//#endregion
|
|
441
|
+
export { type BridgeWithShim, type CreateSandbox, type HostExportData, type HostExportFunction, type HostExportValue, type HostExports, type HostGlobalValue, type HostGlobals, type HostImport, type ImportDefinition, type ImportsConfig, type PrecompileOptions, type Prefix, type PrefixRunOptions, type RebindGlobals, type RebindValue, type ResourceLimits, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, type SourceImport, createSandbox };
|