@iso4/sandbox 0.4.2 → 0.5.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/README.md CHANGED
@@ -4,11 +4,14 @@ Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Runs user
4
4
  code in a separate Rust process for full crash isolation — an OOM or panic in
5
5
  the sandbox kills only the subprocess, not your host application.
6
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.
7
+ Built for the AI-agent prefix/postfix pattern: prepare host setup (globals,
8
+ libraries, tool bindings) once, then run many agent-generated code strings
9
+ against it in parallel. Every run gets its own limits, guards, and bridge
10
+ bindings; one-off `sandbox.run()` always gets a fresh isolate, while prefix
11
+ runs reuse resident warm instances when one is free (see below).
10
12
 
11
- > **Status:** core execution works end-to-end. Not yet at 1.0.
13
+ > **Status:** core execution works end-to-end. Not yet at 1.0 — every API,
14
+ > option, and observability surface (including `stats()`) may still change.
12
15
 
13
16
  ## Install
14
17
 
@@ -24,9 +27,9 @@ npm i @iso4/fetch
24
27
  import { createSandbox } from '@iso4/sandbox'
25
28
  import { createSafeFetch } from '@iso4/fetch'
26
29
 
27
- const sandbox = await createSandbox()
30
+ const sandbox = await createSandbox({ memoryMb: 128 }) // per-isolate heap cap
28
31
 
29
- // Compile host setup once into a V8 snapshot
32
+ // Validate and prepare host setup once
30
33
  const prefix = await sandbox.prepare({
31
34
  code: `
32
35
  const config = { apiBase: 'https://api.example.com' }
@@ -37,13 +40,13 @@ const prefix = await sandbox.prepare({
37
40
  },
38
41
  })
39
42
 
40
- // Run agent-generated code against the snapshot — as many times as needed
43
+ // Run agent-generated code against the prefix — as many times as needed
41
44
  const result = await prefix.execute({
42
45
  code: `
43
46
  const res = await fetch(config.apiBase + '/users')
44
47
  export default { count: res.length }
45
48
  `,
46
- limits: { cpuTimeMs: 200, wallTimeMs: 5_000, memoryMb: 64 },
49
+ limits: { cpuTimeMs: 200, wallTimeMs: 5_000 }, // heap cap: prepare({ memoryMb }) or the sandbox default
47
50
  })
48
51
 
49
52
  if (result.ok) {
@@ -101,13 +104,95 @@ prefix.execute({
101
104
  limits: {
102
105
  cpuTimeMs: 200, // active JS execution only (await time excluded)
103
106
  wallTimeMs: 5_000, // hard cap including async waits
104
- memoryMb: 64, // V8 heap + ArrayBuffer budget
107
+ // memoryMb: per prefix via prepare({ memoryMb }) or the sandbox default —
108
+ // never per prefix-run, the cap is baked into the shared warm isolates.
109
+ // One-off sandbox.run() may set limits.memoryMb (fresh isolate anyway).
105
110
  maxBridgeCalls: 10, // max host-bridge calls per run (0 = unlimited)
106
- maxBridgePayloadBytes: 0, // max bytes per bridge call (0 = 64 MiB framing cap)
111
+ maxBridgeCallBytes: 0, // max bytes per bridge call (0 = 64 MiB framing cap)
112
+ maxExportBytes: 0, // max bytes of encoded exports (0 = unlimited)
113
+ maxStdoutBytes: 0, // per-run console capture caps (0 = unlimited)
114
+ maxStderrBytes: 0,
107
115
  },
108
116
  })
109
117
  ```
110
118
 
119
+ ## Warm instances and the memory budget
120
+
121
+ Runs against a prepared prefix are served by **warm instances**: resident
122
+ isolates with the prefix already evaluated, so boot and prefix evaluation
123
+ are paid once instead of per run. Automatic — no flag, no separate API.
124
+
125
+ Warmth is a cache, never a guarantee. An instance can vanish between any
126
+ two calls (memory pressure, `dispose()`), and a run interrupted
127
+ **mid-execution** — a CPU or memory limit firing, or an abort landing on
128
+ actively running code — costs its instance: the next call cold-starts
129
+ clean. Failures that arrive while a run is _waiting_ (a wall timeout during
130
+ a host call, an abort of a suspended run, a dropped connection) fail that
131
+ run alone and the instance keeps serving, state intact. Don't rely on state
132
+ carrying over either way: `globalThis` writes and patched builtins stay
133
+ visible to later runs until eviction silently wipes them. Keep durable
134
+ state in a database and do expensive setup lazily in the handler
135
+ (`conn ??= await connect()`).
136
+
137
+ Carryover is not an isolation boundary. Because a warm instance is reused
138
+ across runs of the same prefix, one run can change what a later run sees —
139
+ including reassigning the runtime's own globals (`Response`, `fetch`, …) or
140
+ patching prototypes, which then affects that later run. This is intended and
141
+ matches a shared-isolate worker: run one prefix only for callers that trust
142
+ each other, and give mutually-distrusting workloads separate prefixes.
143
+
144
+ Instances of one prefix share no state with each other; today each serves
145
+ one call at a time, so concurrency means more instances (the engine can
146
+ already interleave several runs on one instance — that switches on with
147
+ wire multiplexing). Top-level names never collide across runs
148
+ (each run is its own module). A prefix that can't finish evaluating under
149
+ the fixed warm-up budget is rejected by `prepare()` with
150
+ `ERR_WARMUP_LIMIT`. `console.*` from prefix evaluation arrives on the
151
+ cold-starting call's result.
152
+
153
+ Residency is bounded by memory, not by a count:
154
+
155
+ ```ts
156
+ const sandbox = await createSandbox({
157
+ memoryMb: 128, // default heap cap per isolate (override per prefix at prepare())
158
+ memoryBudgetMb: 2048, // RSS mark for the whole runtime process (0 = off)
159
+ })
160
+ ```
161
+
162
+ `memoryMb` means two different things depending on whether the isolate is
163
+ reused.
164
+
165
+ **On a prefix**, the number is the retirement line: an instance whose heap sits
166
+ above it when two runs in a row finish takes no new runs and drops once the
167
+ runs it is already serving complete. Nothing fails. The terminating line sits a
168
+ headroom band above it (`round(sqrt(8 × memoryMb))` MB, so 128 → 160); crossing
169
+ _that_ kills the run and fails its co-residents, and only a runaway allocation
170
+ gets there. The band is what lets a grown instance be replaced instead of
171
+ killing a run at the number — an optimization for reuse.
172
+
173
+ ```ts
174
+ await sandbox.prepare({ code, memoryMb: { soft: 96, hard: 256 } }) // exact lines
175
+ await sandbox.prepare({ code, memoryMb: { hard: 128 } }) // terminate at 128, never retire
176
+ ```
177
+
178
+ **On a one-off `run()`**, the number is enforced exactly — `memoryMb: 128`
179
+ dies at 128. A fresh isolate is never reused, so there is nothing to retire
180
+ and no band. It takes a plain number for the same reason: a soft line would
181
+ be inert.
182
+
183
+ The runtime watches its own process RSS. At or above `memoryBudgetMb` it
184
+ evicts idle instances (largest heap × longest idle first) and stops adding new
185
+ warm ones — prefix runs then execute on cold one-off isolates — until RSS falls
186
+ back to 80 % of the mark. `maxConcurrentRuns` caps concurrent runs; this caps
187
+ memory.
188
+ The default is derived from the memory available to the process
189
+ (container-aware), so most hosts never set it.
190
+
191
+ `sandbox.stats()` reports the live picture — active runs, queue depth, warm and
192
+ idle instance counts, summed idle heap, `budgetBytes` / `rssBytes`, whether the
193
+ runtime is currently `underPressure`, and per-prefix counts. It answers on a
194
+ dedicated connection, so it works even when every run slot is busy.
195
+
111
196
  ## Async context (`AsyncLocalStorage`)
112
197
 
113
198
  Run/postfix code can import a minimal, Node-compatible `AsyncLocalStorage` to
@@ -132,13 +217,49 @@ V8's continuation-preserved embedder data; no promise hooks, so it's free
132
217
  unless used. Not available in `prepare()` (prefix) code — it's for the
133
218
  postfix. See DESIGN.md §16.
134
219
 
220
+ ## Calling into the sandbox
221
+
222
+ Invoke a function the module exports — `export default { fetch }` or any
223
+ named export — with real typed arguments. On a prepared prefix nothing is
224
+ compiled per request:
225
+
226
+ ```ts
227
+ const prefix = await sandbox.prepare({ code: workerBundle })
228
+
229
+ const result = await prefix.call({
230
+ export: 'default.fetch',
231
+ args: [new Request('https://example.com/', { method: 'POST', body: 'hi' })],
232
+ })
233
+ if (result.ok) {
234
+ const response = result.value as Response // a real Response instance
235
+ }
236
+ ```
237
+
238
+ `sandbox.run({ code, call })` does the same against a freshly evaluated
239
+ module. With `call` the success result carries the function's return `value`
240
+ instead of `exports` — never both. The receiver is the exported object
241
+ (`this` works); prototype methods resolve (`export default new Worker()`),
242
+ and a path that does not reach a callable fails with
243
+ `ERR_CALL_TARGET_NOT_FOUND`. `prefix.call()` accepts the same per-call
244
+ `globals` / `imports` rebinds as `prefix.execute()`.
245
+
246
+ Non-serializable **exports** no longer fail a plain run: they are absent from
247
+ `exports` and reported in `skippedExports`, so a module that exports handlers
248
+ still reads cleanly. `sandbox.readExports({ code })` wraps that for the
249
+ deploy path — load once, read the declaration exports, and get the skipped
250
+ handler names back.
251
+
135
252
  ## Result shape
136
253
 
137
254
  ```ts
138
255
  type RunResult
139
- = | { ok: true, exports: SandboxExports, stdout: string[], stderr: string[], durationMs: number, cpuTimeMs: number, bridgeCalls: BridgeCallEntry[] }
256
+ = | { ok: true, exports: SandboxExports, skippedExports: string[], stdout: string[], stderr: string[], durationMs: number, cpuTimeMs: number, bridgeCalls: BridgeCallEntry[] }
140
257
  | { ok: false, error: RunError, stdout: string[], stderr: string[], durationMs: number, cpuTimeMs: number, bridgeCalls: BridgeCallEntry[] }
141
258
 
259
+ // prefix.call() / run({ code, call }) resolve to a CallResult instead:
260
+ // the success arm carries `value` (the function's return value) in place of
261
+ // `exports` + `skippedExports`; failure/aborted arms are shared.
262
+
142
263
  // durationMs — wall-clock time of the run; cpuTimeMs — active V8 execution
143
264
  // time (bridge waits excluded). Both measured in the runtime, µs resolution.
144
265
 
@@ -158,6 +279,8 @@ interface RunError {
158
279
  message: string
159
280
  stack?: string
160
281
  fields?: Record<string, unknown> // all other own-enumerable props of the thrown error
282
+ resetCause?: 'cpu' | 'memory' | 'wall' | 'abort' | 'internal' // ERR_INSTANCE_RESET only
283
+ culpritRunId?: number // ERR_INSTANCE_RESET only: the run whose interruption reset the instance
161
284
  }
162
285
  ```
163
286
 
@@ -165,6 +288,12 @@ interface RunError {
165
288
  (subprocess crashed, binary not found). `ok: false` with an error code is the
166
289
  normal failure path.
167
290
 
291
+ One code is about a _neighbor_, not your own run: `ERR_INSTANCE_RESET` means a
292
+ run sharing the same warm instance had to be terminated mid-execution
293
+ (`resetCause` says why, `culpritRunId` names it), so this run — in flight on
294
+ the now-untrusted instance — was failed with its real partial telemetry. It is
295
+ never retried automatically, because it may already have had side effects.
296
+
168
297
  Thrown errors keep their identity across the bridge, in both directions:
169
298
 
170
299
  - **Sandbox → host**: an uncaught sandbox throw surfaces as `ERR_USER_CODE`
@@ -179,11 +308,22 @@ Thrown errors keep their identity across the bridge, in both directions:
179
308
  the run with `ERR_HOST_BRIDGE`. The **host stack never crosses** into the
180
309
  sandbox.
181
310
 
311
+ > Every own property you attach to a host-thrown error is visible to sandbox
312
+ > code (the auto-populated stack is the one exception). Sandbox code is
313
+ > untrusted, and this includes properties a third-party SDK attaches to its own
314
+ > error objects — so if an error may carry request context or credentials
315
+ > (an SDK's `config`/`request`/`response`), throw a clean `Error` from your
316
+ > handler instead of re-throwing it wholesale. Sanitising is the handler's job,
317
+ > the same as with any value you return.
318
+
182
319
  ## Architecture
183
320
 
184
321
  V8 runs in a separate Rust subprocess communicating over a Unix domain socket.
185
- A pool of connections (one per `maxIsolates` slot) provides concurrency —
186
- five concurrent `prefix.execute()` calls each get their own slot and execute in
322
+ A slot pool admits up to `maxConcurrentRuns` runs at once (the rest queue
323
+ FIFO — an `AbortSignal`, e.g. `AbortSignal.timeout()`, bounds the wait);
324
+ connections to the subprocess open on demand and are reused, and `stats()`
325
+ reports the live count as `openConnections`. Five concurrent
326
+ `prefix.execute()` calls each get their own run slot and execute in
187
327
  parallel.
188
328
 
189
329
  ## License