@iso4/sandbox 0.4.2 → 0.5.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.
package/dist/index.d.mts CHANGED
@@ -2,9 +2,12 @@
2
2
  /**
3
3
  * \@iso4/sandbox — public API types.
4
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.
5
+ * Execution model: prepare a prefix once (validated and cached by the
6
+ * runtime), then run many dynamic postfixes against it (typically
7
+ * agent-generated) with `prefix.execute({ code })` or invoke one of its
8
+ * exports with `prefix.call({ export, args })`. Prefix runs are served by
9
+ * resident warm instances, which skip isolate boot and prefix evaluation on
10
+ * reuse; a one-off `sandbox.run({ code })` always gets a fresh isolate.
8
11
  * Multiple concurrent callers each get their own pool slot and run in
9
12
  * parallel. See DESIGN.md §1 and §13.
10
13
  */
@@ -20,18 +23,62 @@
20
23
  * A field set to `0` is not the same as leaving it unset: `0` explicitly
21
24
  * disables that limit, whereas unset yields the runtime default.
22
25
  */
23
- interface ResourceLimits {
26
+ /**
27
+ * The two heap lines a REUSED isolate is held to, when the managed default
28
+ * is not what you want. One-off `run()` isolates are never reused and take a
29
+ * plain `memoryMb` number, enforced exactly.
30
+ *
31
+ * - `hard` **terminates**: V8's heap cap. Crossing it kills whatever JS is
32
+ * executing, taints the instance, and fails its co-resident runs with
33
+ * `ERR_INSTANCE_RESET`. This is the ceiling the container reserves against
34
+ * its admission line.
35
+ * - `soft` **retires**: a warm instance whose heap sits above it at two
36
+ * consecutive finishes takes no further runs and is dropped once the runs
37
+ * it is already serving complete. No run fails and nothing is terminated —
38
+ * it is how a prefix that accumulates memory across reuse gets replaced
39
+ * instead of eventually killing a run. Omit it for a hard line only.
40
+ *
41
+ * A plain `memoryMb: number` is the managed form of this: the number is the
42
+ * soft line and the hard line sits a headroom band above it (`+sqrt(8 × n)`
43
+ * MB, so 128 → 160). Write the object when you want the exact numbers.
44
+ */
45
+ interface MemoryLimit {
46
+ /**
47
+ * The retirement line, in megabytes. Omit for no soft line (a `hard`-only
48
+ * cap behaves exactly like the pre-#169 `memoryMb`). Must be an integer
49
+ * ≥ 1 and below `hard`.
50
+ */
51
+ soft?: number;
24
52
  /**
25
- * Hard cap on memory the isolate can use, in megabytes.
26
- * Covers the V8 heap and all external `ArrayBuffer` allocations.
53
+ * The terminating cap, in megabytes. Must be an integer ≥ 1 — `0` is not
54
+ * accepted here, because an uncapped isolate has no line to enforce and a
55
+ * runaway allocation would take the whole runtime process down with a
56
+ * fatal OOM. Write `memoryMb: 0` for uncapped.
57
+ */
58
+ hard: number;
59
+ }
60
+ /**
61
+ * Limits for a one-off `sandbox.run()`, which always gets a fresh isolate —
62
+ * so unlike prefix runs (whose isolates are shared and reused, cap set at
63
+ * `prepare({ memoryMb })` or the sandbox default) it may cap its own heap.
64
+ */
65
+ interface OneOffResourceLimits extends ResourceLimits {
66
+ /**
67
+ * Hard cap on this run's isolate memory, in megabytes — V8 heap plus
68
+ * external `ArrayBuffer`s. Enforced exactly: this run dies at this number.
27
69
  *
28
- * Also determines the BridgeResponse frame read cap: the sandbox cannot
29
- * receive a response larger than its own memory budget.
70
+ * A one-off always gets a fresh isolate, so — unlike a prefix's reused
71
+ * instances — there is nothing to retire and no headroom band. The number
72
+ * you write is the number that terminates. A plain number only, for the
73
+ * same reason: {@link MemoryLimit}'s soft line would be inert here.
30
74
  *
31
- * Zero means no cap.
32
- * @default 64
75
+ * `0` = uncapped (admitted against the memory budget instead of the 90%
76
+ * line — see `memoryBudgetMb`). Must be an integer ≥ 0.
77
+ * @default the sandbox-level `memoryMb` (128)
33
78
  */
34
79
  memoryMb?: number;
80
+ }
81
+ interface ResourceLimits {
35
82
  /**
36
83
  * Maximum *active* execution time in milliseconds. Time spent waiting on
37
84
  * host bridge calls (globals, host imports) is excluded.
@@ -39,7 +86,8 @@ interface ResourceLimits {
39
86
  */
40
87
  cpuTimeMs?: number;
41
88
  /**
42
- * Hard wall-clock cap including async waits.
89
+ * Cap on the run's own logic time — execution + async waits (the result's
90
+ * `wallTimeMs`). Engine time for co-resident runs doesn't count.
43
91
  * @default 30_000
44
92
  */
45
93
  wallTimeMs?: number;
@@ -51,17 +99,21 @@ interface ResourceLimits {
51
99
  * A violation terminates the run immediately with
52
100
  * `ERR_BRIDGE_PAYLOAD_TOO_LARGE`; sandbox code cannot catch it.
53
101
  *
54
- * Bridge responses (host → sandbox) are not separately capped here — the
55
- * natural limit is `memoryMb`: the sandbox cannot hold a response larger than
56
- * its own memory budget, and the framing layer enforces this automatically.
102
+ * Bridge responses (host → sandbox) are not separately capped here. The
103
+ * binding limit is the host framing ceiling of 64 MiB, below the runtime's own
104
+ * inbound allowance of `memoryMb`: a handler returning more than that cannot
105
+ * be encoded, and the sandbox receives `ERR_HOST_BRIDGE` for that call rather
106
+ * than the value. Cap large handler return values yourself if you want a
107
+ * cleaner failure.
57
108
  *
58
109
  * Zero disables the per-call cap.
59
110
  * @default 16 * 1024 * 1024
60
111
  */
61
112
  maxBridgeCallBytes?: number;
62
113
  /**
63
- * Maximum bytes allowed for the serialised export payload (all named exports
64
- * combined). Exceeding this limit terminates the run with `ERR_EXPORT_TOO_LARGE`.
114
+ * Maximum bytes allowed for the serialised export payload — one V8
115
+ * serialization blob holding all exports combined. Exceeding this limit
116
+ * terminates the run with `ERR_EXPORT_TOO_LARGE`.
65
117
  * Zero disables the cap.
66
118
  * @default 16 * 1024 * 1024
67
119
  */
@@ -95,14 +147,25 @@ interface ResourceLimits {
95
147
  * @default 10
96
148
  */
97
149
  maxBridgeCalls?: number;
150
+ /**
151
+ * Wall budget in milliseconds for `waitUntil` background work after the
152
+ * run's value has been delivered. One budget for the whole registered
153
+ * set, started when the result ships. Grace work additionally gets a fresh
154
+ * CPU allotment sized like `cpuTimeMs`. `0` disables the grace phase
155
+ * entirely: registered work dies when the value settles.
156
+ * @default 30_000
157
+ */
158
+ graceMs?: number;
98
159
  }
99
160
  /**
100
161
  * Host-provided globals. Any name not reserved by V8 or the runtime is
101
162
  * permitted. Each value becomes a bridge stub in the sandbox global object.
102
163
  *
103
- * Reserved names (must not be used): `console`, `URL`, `URLSearchParams`,
104
- * `TextEncoder`, `TextDecoder`, `crypto`, `Event`, `AbortController`,
105
- * `AbortSignal`.
164
+ * Reserved names (rejected with `ERR_RESERVED_NAME`): `console`,
165
+ * `waitUntil`, `setTimeout`, `clearTimeout`, `Headers`, `Request`,
166
+ * `Response`, `TextEncoder`, `TextDecoder`, `URL`, `URLSearchParams`. These
167
+ * are owned by the runtime; shadowing `Response` would silently break
168
+ * serialization.
106
169
  *
107
170
  * Common usage:
108
171
  * ```ts
@@ -122,23 +185,75 @@ type HostGlobals = Record<string, HostGlobalValue>;
122
185
  * The value types accepted for a named global.
123
186
  *
124
187
  * - `HostExportFunction` — bridge call: every sandbox invocation dispatches
125
- * to the host handler.
188
+ * to the host handler. Shorthand for `BridgeGlobal` with the defaults.
126
189
  * - `string` — a JS expression the runtime evaluates once and installs as
127
190
  * `globalThis.<name>`. Use for pure sandbox utilities that need no host
128
191
  * involvement. The expression is evaluated by Rust as its own script, so it
129
- * never shifts the line numbers of user code.
192
+ * never shifts the line numbers of user code. Shorthand for `StringGlobal`
193
+ * with the defaults.
194
+ * - `BridgeGlobal` / `StringGlobal` — the same two as object forms, for when
195
+ * an option (`enumerable`) is needed.
130
196
  * - `DataGlobal` — a plain constant carried as data and installed natively;
131
197
  * no code text, no host involvement.
132
198
  * - `BridgeWithShim` — bridge call + in-sandbox result wrapper. The handler
133
- * can be rebound per `prefix.run()`; the shim is compiled into the snapshot.
199
+ * can be rebound per `prefix.run()`; the shim is part of the prefix state.
200
+ *
201
+ * Every **object** form accepts `enumerable?: boolean` (default `true`).
202
+ * The bare-function and bare-string shorthands are always enumerable.
134
203
  */
135
- type HostGlobalValue = HostExportFunction | string | BridgeWithShim<any> | DataGlobal;
204
+ type HostGlobalValue = HostExportFunction | string | BridgeWithShim<any> | DataGlobal | BridgeGlobal<any> | StringGlobal;
205
+ /**
206
+ * Shared option of every object-form global.
207
+ *
208
+ * `enumerable: false` keeps the name out of `for...in`, `Object.keys`, and
209
+ * spreads of `globalThis`, so enumeration-driven sandbox code (serializers,
210
+ * "copy the environment" patterns) never sweeps it up. This is hygiene, not
211
+ * secrecy: the property still appears in `Object.getOwnPropertyNames` (a
212
+ * language-level fact, identical in every engine), and code that knows the
213
+ * name can still call it. A capability that must be undiscoverable belongs in
214
+ * `imports`, which nothing can enumerate.
215
+ */
216
+ interface GlobalOptions {
217
+ /**
218
+ * Whether the installed global shows up in enumeration. Defaults to `true`,
219
+ * matching how browsers keep `fetch` enumerable on `window`.
220
+ */
221
+ enumerable?: boolean;
222
+ }
223
+ /**
224
+ * Object form of the bare-function bridge global, for when options are
225
+ * needed. `handler` is exactly the function the shorthand would be.
226
+ *
227
+ * ```ts
228
+ * globals: { myTool: { kind: 'bridge', handler: async (q) => search(q), enumerable: false } }
229
+ * ```
230
+ */
231
+ interface BridgeGlobal<H extends HostExportFunction = HostExportFunction> extends GlobalOptions {
232
+ kind: "bridge";
233
+ /**
234
+ * Bridge handler — every sandbox invocation dispatches to it. Can be
235
+ * rebound per `prefix.run()` like a shorthand bridge global.
236
+ */
237
+ handler: H;
238
+ }
239
+ /**
240
+ * Object form of the bare-string expression global, for when options are
241
+ * needed. `expr` is exactly the expression the shorthand would be.
242
+ */
243
+ interface StringGlobal extends GlobalOptions {
244
+ kind: "string";
245
+ /**
246
+ * JS expression the runtime evaluates once and installs under the name.
247
+ */
248
+ expr: string;
249
+ }
136
250
  /**
137
251
  * A plain **constant** global — a data value installed directly on the sandbox
138
252
  * global object, with no host involvement and no code text anywhere.
139
253
  *
140
- * The value crosses the wire as a `WireValue` and Rust materialises it natively
141
- * with `wire_to_v8_value` (the same path host-module data leaves take):
254
+ * The value crosses the wire as a V8 serialization blob and Rust materialises
255
+ * it natively with `blob::deserialize_value` (the same path host-module data
256
+ * leaves take):
142
257
  *
143
258
  * ```ts
144
259
  * globals: { config: { kind: 'data', value: userConfig } }
@@ -149,9 +264,14 @@ type HostGlobalValue = HostExportFunction | string | BridgeWithShim<any> | DataG
149
264
  * Like string globals, a data global is a constant — it cannot be rebound per
150
265
  * `prefix.run()`.
151
266
  */
152
- interface DataGlobal {
267
+ interface DataGlobal extends GlobalOptions {
153
268
  kind: "data";
154
- value: HostExportData;
269
+ /**
270
+ * Any `HostExportData`, or a `Request`/`Response`/`Headers` — including nested
271
+ * inside a plain object or array, which the runtime rebuilds as real instances
272
+ * (`docs/protocol.md` §4.4).
273
+ */
274
+ value: HostExportData | Request | Response | Headers;
155
275
  }
156
276
  /**
157
277
  * A global that pairs a bridge handler with an in-sandbox shim that wraps
@@ -169,15 +289,15 @@ interface DataGlobal {
169
289
  * The shim is a JS function expression `(result) => transformedResult` (sync
170
290
  * or async). Sandbox built-ins (TextDecoder, JSON, …) are available in scope.
171
291
  * The private stub `__iso4_<name>_h` stays on globalThis so the handler can
172
- * be rebound per `prefix.run()` while the shim stays fixed in the snapshot.
292
+ * be rebound per `prefix.run()` while the shim itself stays fixed.
173
293
  */
174
294
  /**
175
295
  * `H` is the specific handler function type. Carried through the type system
176
296
  * so `RebindGlobals` can enforce that any per-run replacement has the same
177
297
  * return type, keeping it compatible with the shim that is already compiled
178
- * into the prefix snapshot.
298
+ * into the prefix state.
179
299
  */
180
- interface BridgeWithShim<H extends (...args: unknown[]) => unknown = (...args: unknown[]) => unknown> {
300
+ interface BridgeWithShim<H extends (...args: unknown[]) => unknown = (...args: unknown[]) => unknown> extends GlobalOptions {
181
301
  kind: "bridge-with-shim";
182
302
  /**
183
303
  * Bridge handler — registered as `__iso4_<name>_h` for rebinding.
@@ -204,24 +324,24 @@ interface BridgeWithShim<H extends (...args: unknown[]) => unknown = (...args: u
204
324
  * precompile time:
205
325
  *
206
326
  * - `BridgeWithShim<H>` global — only the handler `H` itself. The shim is
207
- * fixed in the snapshot; rebinding must preserve the return type so the
327
+ * fixed with the prefix; rebinding must preserve the return type so the
208
328
  * shim keeps working.
209
329
  * - `HostExportFunction` global — any compatible `HostExportFunction`.
210
- * - `string` global — cannot be rebound (compiled into the snapshot).
330
+ * - `string` global — cannot be rebound (fixed at prepare() time).
211
331
  */
212
- type RebindValue<V extends HostGlobalValue> = V extends BridgeWithShim<infer H> ? H : V extends HostExportFunction ? V : never;
332
+ type RebindValue<V extends HostGlobalValue> = V extends BridgeWithShim<infer H> ? H : V extends BridgeGlobal<infer H> ? H : V extends HostExportFunction ? V : never;
213
333
  /**
214
334
  * The per-run globals override map for a `Prefix<G>`.
215
335
  *
216
336
  * String-valued and `DataGlobal` (constant) globals are filtered out entirely
217
337
  * (key remapping to `never`) rather than mapped to `?: never` — they cannot be
218
- * rebound because their value is compiled into the snapshot, and they should
338
+ * rebound because their value is fixed at prepare() time, and they should
219
339
  * not appear as valid keys at all.
220
340
  *
221
341
  * Each remaining key is optional and typed as `RebindValue<G[K]>`, which
222
342
  * enforces the correct constraint per global kind.
223
343
  */
224
- type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string | DataGlobal ? never : K]?: RebindValue<G[K]> };
344
+ type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string | DataGlobal | StringGlobal ? never : K]?: RebindValue<G[K]> };
225
345
  /**
226
346
  * Top-level `imports` shape. Keys are import specifiers; values are either
227
347
  * a source string or a host-module description object.
@@ -239,16 +359,17 @@ type ImportValue = string | HostModuleObject;
239
359
  /**
240
360
  * A host-module description object. Each property is either:
241
361
  *
242
- * - A function — becomes an async bridge stub in the generated module.
243
- * - A plain data value (primitive, plain object/array, `BigInt`,
244
- * `Uint8Array`) — becomes a JS literal in the generated module.
362
+ * - A function — the runtime builds an async bridge trampoline for it.
363
+ * - A data value (anything in {@link HostExportData}) — materialised in the
364
+ * isolate from its V8 serialization blob.
245
365
  * - A nested object that itself contains a mix of functions and data —
246
366
  * walked recursively.
247
367
  *
248
- * `Date`, `Map`, `Set`, circular references, class instances with
249
- * prototype methods, and stateful handles (streams, sockets) are rejected
250
- * at registration with a clear error. The supported set deliberately
251
- * matches what the wire codec can carry back out of the sandbox.
368
+ * Class instances with prototype methods and stateful handles (streams,
369
+ * sockets) are rejected at registration with a clear error naming the exact
370
+ * path: V8's format would carry them, but only as their own enumerable
371
+ * properties, so the methods you meant to send would vanish silently. Copy
372
+ * what you mean to send into a plain object.
252
373
  */
253
374
  interface HostModuleObject {
254
375
  [name: string]: HostModuleValue;
@@ -258,10 +379,27 @@ interface HostModuleObject {
258
379
  */
259
380
  type HostModuleValue = HostExportFunction | HostExportData | HostModuleObject;
260
381
  /**
261
- * The set of plain-data values supported as data leaves in the host-module
262
- * shape. The JS-literal emitter knows how to emit each of these.
382
+ * The set of data values that can cross the sandbox boundary.
383
+ *
384
+ * This mirrors what V8's serialization format can represent, so every value
385
+ * here arrives on the other side as a **real instance** — a `Date` is a `Date`,
386
+ * a `Map` is a `Map`, a `Float64Array` keeps its element type. Cyclic and
387
+ * shared references are preserved, including object identity.
388
+ *
389
+ * What is *not* here cannot cross and is rejected loudly: functions (except as
390
+ * declared function leaves), `Promise`, `Symbol`, `WeakMap`, `WeakSet`, and
391
+ * `Proxy`. Class instances are also excluded — V8 would carry one, but only as
392
+ * its own enumerable properties, silently dropping its prototype and methods.
393
+ *
394
+ * Two notes for hosts:
395
+ *
396
+ * - Node `Buffer` is a `Uint8Array` subclass, so it crosses fine, but it
397
+ * arrives as a plain `Uint8Array` (data preserved, subclass identity not).
398
+ * - A `subarray` window carries only the bytes in its window.
399
+ *
400
+ * @see `docs/protocol.md` §4.2 for the full table, both directions.
263
401
  */
264
- type HostExportData = null | undefined | boolean | number | bigint | string | Uint8Array | HostExportData[] | {
402
+ type HostExportData = null | undefined | boolean | number | bigint | string | Date | RegExp | Error | Map<HostExportData, HostExportData> | Set<HostExportData> | ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array | HostExportData[] | {
265
403
  [key: string]: HostExportData;
266
404
  };
267
405
  /**
@@ -281,7 +419,7 @@ type HostExportFunction = (...args: unknown[]) => unknown;
281
419
  *
282
420
  * Mirrors `RebindGlobals<G>` over the recursive host-module shape:
283
421
  *
284
- * - **Source imports** (string values) are compiled into the snapshot and
422
+ * - **Source imports** (string values) are fixed at prepare() time and
285
423
  * cannot be rebound — their keys are excluded from the result.
286
424
  * - **Host imports** (object values) are walked recursively. Only function
287
425
  * leaves survive; data leaves are excluded because their values are
@@ -306,30 +444,252 @@ type RebindImports<M extends Record<string, ImportValue>> = Record<string, Impor
306
444
  type RebindHostModule<T> = T extends HostExportFunction ? T : T extends HostModuleObject ? { [K in keyof T as T[K] extends HostExportFunction ? K : T[K] extends HostModuleObject ? K : never]?: T[K] extends HostExportFunction ? T[K] : T[K] extends HostModuleObject ? RebindHostModule<T[K]> : never } : never;
307
445
  interface SandboxOptions {
308
446
  /**
309
- * Maximum number of isolates (UDS connection slots) running concurrently.
310
- * The Sandbox maintains a pool of this many connections to the Rust process;
311
- * each executes one run() at a time. Additional callers queue.
447
+ * Maximum number of runs executing at once. Additional callers queue FIFO
448
+ * until a run finishes; a queued caller's `AbortSignal` is honoured while
449
+ * it waits, so `AbortSignal.timeout()` composes as a queue-wait bound —
450
+ * there is no separate timeout option.
451
+ *
452
+ * This is an admission number, not a socket count: connections to the
453
+ * runtime process open on demand as runs need them and are reused for the
454
+ * process lifetime (`SandboxStats.openConnections` reports the live
455
+ * count). Multiple MCP agents / concurrent callers run in parallel up to
456
+ * this limit.
457
+ *
458
+ * Overridable in both directions: lowering it leaves cores to the host
459
+ * app; raising it above the core count pays only for workloads that spend
460
+ * their time suspended on host calls rather than computing.
461
+ *
462
+ * This caps *concurrent runs* only. How many isolates stay resident
463
+ * (warm instances included) is the memory budget's job — see
464
+ * `memoryBudgetMb`. There is no instance-count cap of any kind, so
465
+ * idle warm instances may outnumber the running count here, or fall below
466
+ * it under memory pressure.
467
+ *
468
+ * Must be an integer ≥ 1 — anything else throws at `createSandbox()`
469
+ * (`0` would queue every run forever).
470
+ *
471
+ * Defaults to `os.availableParallelism()`, bounded by memory: when that
472
+ * many worst-case heaps (`memoryMb` each) would not fit inside the
473
+ * memory budget, the default becomes `budget / memoryMb` instead (at
474
+ * least 1) — the cores default must not promise more concurrent heaps
475
+ * than the container can hold. With `memoryMb: 0` or `memoryBudgetMb: 0`
476
+ * there is nothing to bound with and the default stays the core count.
477
+ */
478
+ maxConcurrentRuns?: number;
479
+ /**
480
+ * How many callers may wait for a run slot before new ones are shed.
481
+ * Past the bound, a run fails immediately with `ERR_QUEUE_FULL` instead
482
+ * of joining the queue: every queued caller holds memory (its serialized
483
+ * arguments included), so an unbounded queue turns sustained overload
484
+ * into a host out-of-memory crash. A hammered sandbox should fail some
485
+ * requests cleanly and keep answering the rest.
486
+ *
487
+ * `0` is valid: no queue at all — every run past `maxConcurrentRuns`
488
+ * fails immediately. Must be an integer ≥ 0.
489
+ *
490
+ * This bounds queue *depth*; the wait *time* of an individual queued
491
+ * caller is still bounded only by its own `AbortSignal`
492
+ * (`AbortSignal.timeout()` composes — there is no timeout knob).
493
+ *
494
+ * Defaults to `100 × maxConcurrentRuns`.
495
+ */
496
+ maxQueuedRuns?: number;
497
+ /**
498
+ * Default hard cap on memory each isolate can use, in megabytes. Covers
499
+ * the V8 heap and all external `ArrayBuffer` allocations; also determines
500
+ * the BridgeResponse frame read cap (the sandbox cannot receive a
501
+ * response larger than its own memory budget).
502
+ *
503
+ * This is the DEFAULT: `prepare({ memoryMb })` overrides it per prefix,
504
+ * and `run({ limits: { memoryMb } })` per one-off run (fresh isolate).
505
+ * What stays impossible is a per-run value on a warm instance — the cap
506
+ * is baked into the isolate at creation and instances are shared across
507
+ * runs of their prefix, which is why prefix `execute()`/`call()` limits
508
+ * reject it. Memory accumulates across calls on a warm instance —
509
+ * hitting the cap taints the instance and the next call cold-starts.
510
+ *
511
+ * A plain number is the MANAGED form for a prefix's reused instances: it
512
+ * is the retirement line, and the terminating cap sits a headroom band
513
+ * above it (`+sqrt(8 × n)` MB, so `128` terminates at 160). An instance
514
+ * over the number at two consecutive finishes is retired without failing
515
+ * anything; only a runaway allocation reaches the terminating cap. Pass a
516
+ * {@link MemoryLimit} to set the two lines yourself, or `{ hard }` alone
517
+ * for a single terminating cap and no retirement.
312
518
  *
313
- * Multiple MCP agents / concurrent callers each get their own slot and
314
- * run in parallel up to this limit.
519
+ * One-off `run()` isolates take the same number as a plain hard cap — no
520
+ * band, no retirement, since a fresh isolate is never reused. So `128`
521
+ * means "retire a prefix instance at 128, kill it at 160" and "kill a
522
+ * one-off at 128".
315
523
  *
316
- * Defaults to the number of logical CPUs on the host machine.
524
+ * Zero means no cap (such runs are admitted against the memory budget
525
+ * instead of the 90% admission line). Must be an integer ≥ 0.
526
+ * @default 128
317
527
  */
318
- maxIsolates?: number;
528
+ memoryMb?: number | MemoryLimit;
529
+ /**
530
+ * The runtime's memory budget (the shedding mark), in megabytes. The
531
+ * runtime watches measured GLOBAL container memory against it — the
532
+ * cgroup's working set, Node host included, the number the container's
533
+ * OOM killer acts on (where no cgroup exists, e.g. macOS, it falls back
534
+ * to the runtime child's own RSS). At/above the mark it evicts idle warm
535
+ * instances by `heapUsed × idleTime` score (highest first) AND stops
536
+ * pooling new instances — prefix runs without an idle instance execute
537
+ * on cold one-off isolates — until usage falls back to 80 % of the mark
538
+ * (hysteresis, so eviction doesn't flap). Reusing an already-warm
539
+ * instance stays allowed under pressure; it adds no memory. Correctness
540
+ * never depends on warmth; the only observable cost of eviction is
541
+ * cold-start latency. There is no instance-count cap — concurrency is
542
+ * bounded by `maxConcurrentRuns`, memory by this mark.
543
+ *
544
+ * Above the budget sits one more, non-configurable line: the runtime
545
+ * never CREATES an isolate when measured usage plus the run's own
546
+ * `memoryMb` would cross 90 % of the container limit (minus a 256 MB
547
+ * host reserve) — such a run fails with `ERR_CAPACITY` instead, so the
548
+ * newest admission can never be what tips the container into an OOM
549
+ * kill. Runs with `memoryMb: 0` (uncapped) are refused already from the
550
+ * budget mark — their worst case has no arithmetic.
551
+ *
552
+ * `0` disables the budget entirely (nothing bounds warmth then except
553
+ * `dispose()`, and uncapped runs are never refused). Independent of
554
+ * `memoryMb`: usage is measured, not derived from per-isolate caps.
555
+ *
556
+ * Default: 80 % of what remains of the container limit after a 256 MB
557
+ * reserve for the Node host — container/cgroup-aware via
558
+ * `process.constrainedMemory()`, falling back to `os.totalmem()`.
559
+ * Services with a large host-side footprint should set this lower.
560
+ * On a host too small for that subtraction the default floors at 64 MB
561
+ * (with a warning on stderr) rather than reaching 0 and disabling the
562
+ * mark: memory-starved hosts get aggressive eviction, never no protection.
563
+ * The floor applies to the default only — an explicit `0` still opts out.
564
+ * Explicit values are clamped to `Number.MAX_SAFE_INTEGER` bytes (above
565
+ * that the byte math stops being exact) and a negative value to `0`; a
566
+ * non-finite one throws.
567
+ */
568
+ memoryBudgetMb?: number;
319
569
  /**
320
570
  * Override the path to the Rust V8 binary.
321
571
  * Default: auto-detect from \@iso4/v8-* platform packages.
322
572
  */
323
573
  binaryPath?: string;
324
574
  }
575
+ /**
576
+ * A point-in-time capacity/usage snapshot from `sandbox.stats()`.
577
+ * The runtime-side numbers are mutually consistent (taken under one
578
+ * registry lock); `queueDepth` is a separate host-side read taken after
579
+ * the round trip. All of it is stale the moment it returns —
580
+ * diagnostics, not synchronization.
581
+ */
582
+ interface SandboxStats {
583
+ /**
584
+ * Runs executing right now: one-off `run()`s plus prefix runs on warm
585
+ * instances. Since #77 several prefix runs may share one instance, so
586
+ * this can exceed the busy-instance count.
587
+ */
588
+ activeRuns: number;
589
+ /**
590
+ * Callers queued for a free run slot (`maxConcurrentRuns` runs are
591
+ * already executing).
592
+ */
593
+ queueDepth: number;
594
+ /**
595
+ * Host-side count of runtime connections as the pool tracks them (the
596
+ * dedicated `stats()` control connection not included). Runs are
597
+ * multiplexed onto shared connections — several concurrent runs per
598
+ * connection, another opened only when all are at the internal
599
+ * per-connection cap — and connections are kept for the process lifetime,
600
+ * so this rises to roughly the concurrency high-water mark divided by the
601
+ * cap and stays there. Capacity is `maxConcurrentRuns`, an admission
602
+ * number decoupled from sockets. It is a ledger, not a per-read socket
603
+ * probe: a connection that died stays counted until the next run
604
+ * observes and replaces it.
605
+ */
606
+ openConnections: number;
607
+ /**
608
+ * Resident warm instances — busy plus idle. Bounded by memory (the RSS
609
+ * mark), not by a count.
610
+ */
611
+ warmInstances: number;
612
+ /**
613
+ * Idle warm instances ready to serve their prefix without a cold start.
614
+ */
615
+ idleInstances: number;
616
+ /**
617
+ * Summed heap of the idle instances in bytes, each measured after its
618
+ * last call (a busy instance's current heap is unknown mid-call).
619
+ */
620
+ idleHeapBytes: number;
621
+ /**
622
+ * The memory mark the runtime sheds against, in bytes —
623
+ * `memoryBudgetMb` as the runtime received it. 0 = watermarks disabled.
624
+ * Utilization is `usageBytes / budgetBytes`.
625
+ */
626
+ budgetBytes: number;
627
+ /**
628
+ * The runtime process's own resident set size in bytes at snapshot time
629
+ * — the child's share of the container, for diagnostics. 0 when the
630
+ * platform offers no reader.
631
+ */
632
+ rssBytes: number;
633
+ /**
634
+ * Measured global container memory in bytes at snapshot time — the
635
+ * signal both capacity lines act on (cgroup working set including the
636
+ * Node host; equals the child's RSS where no cgroup exists; 0 when
637
+ * neither is readable).
638
+ */
639
+ usageBytes: number;
640
+ /**
641
+ * The isolate admission line in bytes: 90 % of the container limit minus
642
+ * the host reserve. A run needing a new isolate whose `memoryMb` would
643
+ * not fit under it fails with `ERR_CAPACITY`. 0 = no container limit
644
+ * readable, line disabled.
645
+ */
646
+ hardLineBytes: number;
647
+ /**
648
+ * True while the runtime is shedding: usage reached the budget and
649
+ * has not yet fallen back to 80 % of it. While shedding, idle instances
650
+ * are evicted by score and new warm admissions stop (prefix runs without
651
+ * an idle instance degrade to cold one-off isolates).
652
+ */
653
+ underPressure: boolean;
654
+ /**
655
+ * Per-prefix instance counts, keyed by prefix id — saturation of a single
656
+ * hot prefix is diagnosable here.
657
+ */
658
+ prefixes: Record<string, {
659
+ idle: number;
660
+ busy: number;
661
+ }>;
662
+ }
325
663
  interface Sandbox {
326
664
  /**
327
665
  * Execute a piece of JavaScript in a fresh V8 isolate.
328
- * For repeated use with a shared context, prefer precompile() + prefix.run().
666
+ * For repeated use with a shared context, prefer prepare() + prefix.execute().
667
+ *
668
+ * With `call`, the freshly evaluated module's export at `call.export` is
669
+ * invoked and the result carries its return `value` instead of `exports`:
670
+ *
671
+ * ```ts
672
+ * await sandbox.run({
673
+ * code: `export default { async fetch(request) { return new Response('hi') } }`,
674
+ * call: { export: 'default.fetch', args: [request] },
675
+ * })
676
+ * ```
329
677
  */
330
- run: (options: RunOptions) => Promise<RunResult>;
678
+ run: {
679
+ (options: RunCallOptions): Promise<CallResult>;
680
+ (options: RunOptions): Promise<RunResult>;
681
+ };
331
682
  /**
332
- * Pre-compile a prefix of code into a V8 startup snapshot.
683
+ * Load a module once and read its serializable exports — the
684
+ * deploy/registration path (IaC-style declaration exports read when a
685
+ * function is created, never per request). Builds no prefix and retains
686
+ * nothing. Function exports are skipped and reported, so a module that
687
+ * also exports handlers reads cleanly. Rejects on compile/runtime errors,
688
+ * like `prepare()`.
689
+ */
690
+ readExports: (options: ReadExportsOptions) => Promise<ReadExportsResult>;
691
+ /**
692
+ * Validate and prepare a prefix of code for repeated runs.
333
693
  *
334
694
  * The type parameter `G` is inferred from the `globals` you pass and flows
335
695
  * into the returned `Prefix<G>`. This lets TypeScript enforce at the call
@@ -358,6 +718,13 @@ interface Sandbox {
358
718
  */
359
719
  precompile: <G extends HostGlobals = {}, M extends Imports = {}>(options: PrecompileOptions<G, M>) => Promise<Prefix<G, M>>;
360
720
  /**
721
+ * A point-in-time capacity/usage snapshot: active runs, queue
722
+ * depth, warm-instance counts and their measured memory. Served over a
723
+ * dedicated control connection, so it answers even while every run slot
724
+ * is busy. See {@link SandboxStats}.
725
+ */
726
+ stats: () => Promise<SandboxStats>;
727
+ /**
361
728
  * Tear down the Rust process. Outstanding prefixes are invalidated.
362
729
  */
363
730
  dispose: () => Promise<void>;
@@ -377,7 +744,7 @@ type CreateSandbox = (options?: SandboxOptions) => Promise<Sandbox>;
377
744
  */
378
745
  interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
379
746
  /**
380
- * ESM source code to evaluate before snapshotting. Top-level await works.
747
+ * ESM prefix source, evaluated at the start of every run. Top-level await works.
381
748
  *
382
749
  * @example
383
750
  * import { search } from 'tools:search';
@@ -385,6 +752,22 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
385
752
  */
386
753
  code: string;
387
754
  /**
755
+ * Cap on isolate memory for THIS prefix, in megabytes — V8 heap plus
756
+ * external `ArrayBuffer`s, baked into every instance serving it (e.g.
757
+ * 256 MB edge functions beside 32 MB codemode functions in one sandbox).
758
+ * Per-prefix and per-one-off are the only granularities: a per-run value
759
+ * on a warm instance stays impossible — the cap is fixed at isolate
760
+ * creation and instances are shared across runs.
761
+ *
762
+ * A plain number is the managed form (retirement line + headroom band);
763
+ * pass a {@link MemoryLimit} for exact lines. This is the granularity the
764
+ * soft line is really for: prefix instances are the ones that get reused
765
+ * long enough to accumulate. `0` = uncapped (admitted against the memory
766
+ * budget instead of the 90% line). Must be an integer ≥ 0.
767
+ * @default the sandbox-level `memoryMb` (128)
768
+ */
769
+ memoryMb?: number | MemoryLimit;
770
+ /**
388
771
  * Declares the globals that sandbox code will be able to call.
389
772
  *
390
773
  * This defines the **bridge surface shape** — the full set of names the
@@ -409,11 +792,12 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
409
792
  /**
410
793
  * Resource limits applied to prefix code evaluation.
411
794
  *
412
- * **Important:** limits are NOT enforced during `precompile()`. Prefix code
413
- * is assumed to be developer-authored, not AI-agent-generated.
414
- *
415
795
  * **Currently a no-op placeholder.** Pass limits directly to each
416
- * `prefix.run()` call.
796
+ * `prefix.run()` call. The one budget that DOES apply here is not
797
+ * configurable: prefix evaluation runs under the fixed warm-up budget
798
+ * (1 s wall / 1 s CPU) — a prefix that cannot evaluate inside it is
799
+ * rejected with `ERR_WARMUP_LIMIT` at `prepare()` time, because it could
800
+ * never cold-start a warm instance either.
417
801
  */
418
802
  limits?: ResourceLimits;
419
803
  /**
@@ -428,11 +812,25 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
428
812
  * accepts only `Partial<G>` for its `globals` field — you may override any
429
813
  * declared global's implementation per run, but you cannot add names that
430
814
  * were not declared at precompile time.
815
+ *
816
+ * **Warm instances.** Runs on a prefix are served by resident
817
+ * isolates: the first run cold-starts one (prefix evaluated once, under the
818
+ * fixed warm-up budget), later runs reuse it and skip isolate boot and
819
+ * prefix re-evaluation. Warmth is a cache, never a guarantee — module-scope
820
+ * state MAY survive between runs on one instance, but any instance can be
821
+ * evicted at any moment (a CPU/memory limit firing mid-execution, an abort
822
+ * landing on running code, memory pressure,
823
+ * `dispose()`), and concurrent runs of one prefix are served by separate
824
+ * instances that share no state. Do not rely on carryover, and do not rely
825
+ * on per-run isolation within a prefix either: keep durable state outside
826
+ * the sandbox, and do per-request setup inside the handler — lazy init
827
+ * (`conn ??= await setup()`) runs under that call's budget and re-runs
828
+ * correctly after any eviction.
431
829
  */
432
830
  interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
433
831
  readonly id: string;
434
832
  /**
435
- * Execute dynamic code against this prefix's snapshot state.
833
+ * Execute dynamic code against this prefix's declared state.
436
834
  *
437
835
  * Globals declared at precompile time are active. You may rebind any subset
438
836
  * of them via `options.globals`; the precompile-time handler is used for
@@ -451,7 +849,22 @@ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
451
849
  */
452
850
  run: (options: PrefixRunOptions<G, M>) => Promise<RunResult>;
453
851
  /**
454
- * Release the snapshot. Subsequent run() calls reject. Idempotent.
852
+ * Call a function exported by this prefix's module — nothing is compiled
853
+ * per request. On a warm instance the prefix is not even re-evaluated:
854
+ * `export` resolves against the retained module and the result carries
855
+ * the function's return value:
856
+ *
857
+ * ```ts
858
+ * const prefix = await sandbox.prepare({ code: bundle })
859
+ * const result = await prefix.call({ export: 'default.fetch', args: [request] })
860
+ * ```
861
+ *
862
+ * `globals` / `imports` rebind per call exactly as they do for
863
+ * {@link Prefix.execute}.
864
+ */
865
+ call: (options: PrefixCallOptions<G, M>) => Promise<CallResult>;
866
+ /**
867
+ * Release the prepared prefix. Subsequent run() calls reject. Idempotent.
455
868
  */
456
869
  dispose: () => Promise<void>;
457
870
  /**
@@ -483,25 +896,169 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
483
896
  globals?: RebindGlobals<G>;
484
897
  /**
485
898
  * Rebind host-module function exports declared at precompile time.
486
- * Source module imports are frozen in the snapshot and cannot be rebound;
899
+ * Source module imports are frozen at prepare() time and cannot be rebound;
487
900
  * data exports are baked into the synthetic module. TypeScript enforces
488
- * this at the type level via `RebindImports<M>`; the runtime rejects
489
- * anything that slips through with `ERR_UNDECLARED_BINDING`.
901
+ * this at the type level via `RebindImports<M>`; anything that slips
902
+ * through is rejected at runtime — `ERR_UNDECLARED_BINDING` for locations
903
+ * never declared, `ERR_FROZEN_BINDING` for source modules and data leaves,
904
+ * `ERR_INVALID_REBIND` for a non-function override value.
490
905
  */
491
906
  imports?: RebindImports<M>;
492
907
  limits?: ResourceLimits;
908
+ /**
909
+ * Abort the run. Firing this is always SOFT: while queued the caller is
910
+ * dequeued; a running run is abandoned at its next execution boundary —
911
+ * nothing is interrupted mid-execution, the warm instance survives, and
912
+ * co-resident runs are untouched. The result resolves with
913
+ * `status: 'aborted'` carrying the runtime's real partial telemetry.
914
+ *
915
+ * A soft abort cannot reach code that never yields: a synchronous loop
916
+ * with no `cpuTimeMs` cap keeps its thread until a hard abort
917
+ * ({@link hardAbortSignal}) or dispose. Bound such code with `cpuTimeMs`.
918
+ */
493
919
  signal?: AbortSignal;
920
+ /**
921
+ * HARD abort — the opt-in escalation. Firing this interrupts the run
922
+ * wherever it is: executing JS is terminated immediately, and when that
923
+ * lands mid-execution the shared instance is discarded and co-resident
924
+ * runs fail with `ERR_INSTANCE_RESET` (cause `abort`). On a run that is
925
+ * queued or suspended it degrades to the same clean abandon as `signal`,
926
+ * so firing it is never worse than a soft abort. Typical use: fire
927
+ * `signal` first, then this after your own patience runs out.
928
+ */
929
+ hardAbortSignal?: AbortSignal;
494
930
  filename?: string;
495
931
  }
932
+ /**
933
+ * Options for `prefix.call()` — a {@link CallTarget} plus the same per-call
934
+ * rebinding surface as {@link PrefixRunOptions}, minus `code`: a call frame
935
+ * carries a postfix *or* a call, never both.
936
+ */
937
+ interface PrefixCallOptions<G extends HostGlobals, M extends Imports> extends CallTarget {
938
+ /**
939
+ * Override implementations for a subset of globals declared at
940
+ * prepare() time — same rules as {@link PrefixRunOptions.globals}.
941
+ */
942
+ globals?: RebindGlobals<G>;
943
+ /**
944
+ * Rebind host-module function exports declared at prepare() time — same
945
+ * rules as {@link PrefixRunOptions.imports}.
946
+ */
947
+ imports?: RebindImports<M>;
948
+ limits?: ResourceLimits;
949
+ /**
950
+ * Abort the run. Firing this is always SOFT: while queued the caller is
951
+ * dequeued; a running run is abandoned at its next execution boundary —
952
+ * nothing is interrupted mid-execution, the warm instance survives, and
953
+ * co-resident runs are untouched. The result resolves with
954
+ * `status: 'aborted'` carrying the runtime's real partial telemetry.
955
+ *
956
+ * A soft abort cannot reach code that never yields: a synchronous loop
957
+ * with no `cpuTimeMs` cap keeps its thread until a hard abort
958
+ * ({@link hardAbortSignal}) or dispose. Bound such code with `cpuTimeMs`.
959
+ */
960
+ signal?: AbortSignal;
961
+ /**
962
+ * HARD abort — the opt-in escalation. Firing this interrupts the run
963
+ * wherever it is: executing JS is terminated immediately, and when that
964
+ * lands mid-execution the shared instance is discarded and co-resident
965
+ * runs fail with `ERR_INSTANCE_RESET` (cause `abort`). On a run that is
966
+ * queued or suspended it degrades to the same clean abandon as `signal`,
967
+ * so firing it is never worse than a soft abort. Typical use: fire
968
+ * `signal` first, then this after your own patience runs out.
969
+ */
970
+ hardAbortSignal?: AbortSignal;
971
+ }
972
+ /**
973
+ * Addresses a function that lives inside the sandbox, **relative to the
974
+ * module's exports** — never `globalThis`. Either a top-level exported
975
+ * function (`"handler"`) or a method on an exported object
976
+ * (`"default.fetch"`).
977
+ *
978
+ * The receiver (`this`) is the object the final path segment was read from —
979
+ * plain `a.b.c()` semantics — so `export default { fetch() { this.… } }` and
980
+ * `export default new Worker()` (prototype methods included) both work.
981
+ * A path that does not resolve, or resolves to something that is not
982
+ * callable, fails the run with `ERR_CALL_TARGET_NOT_FOUND`.
983
+ */
984
+ interface CallTarget {
985
+ /**
986
+ * Dot-separated export path, e.g. `"default.fetch"` or `"handler"`.
987
+ */
988
+ export: string;
989
+ /**
990
+ * Arguments for the call. They cross the boundary as **one** V8
991
+ * serialization blob holding the array (identity between arguments
992
+ * preserved), so anything in {@link HostExportData} is accepted — plus
993
+ * `Request` / `Response` / `Headers` at any depth, which arrive in the
994
+ * sandbox as real instances. Defaults to `[]`.
995
+ */
996
+ args?: unknown[];
997
+ }
496
998
  interface RunOptions {
497
999
  code: string;
498
- limits?: ResourceLimits;
1000
+ limits?: OneOffResourceLimits;
499
1001
  globals?: HostGlobals;
500
1002
  imports?: Imports;
1003
+ /**
1004
+ * Abort the run. Firing this is always SOFT: while queued the caller is
1005
+ * dequeued; a running run is abandoned at its next execution boundary —
1006
+ * nothing is interrupted mid-execution, the warm instance survives, and
1007
+ * co-resident runs are untouched. The result resolves with
1008
+ * `status: 'aborted'` carrying the runtime's real partial telemetry.
1009
+ *
1010
+ * A soft abort cannot reach code that never yields: a synchronous loop
1011
+ * with no `cpuTimeMs` cap keeps its thread until a hard abort
1012
+ * ({@link hardAbortSignal}) or dispose. Bound such code with `cpuTimeMs`.
1013
+ */
501
1014
  signal?: AbortSignal;
1015
+ /**
1016
+ * HARD abort — the opt-in escalation. Firing this interrupts the run
1017
+ * wherever it is: executing JS is terminated immediately, and when that
1018
+ * lands mid-execution the shared instance is discarded and co-resident
1019
+ * runs fail with `ERR_INSTANCE_RESET` (cause `abort`). On a run that is
1020
+ * queued or suspended it degrades to the same clean abandon as `signal`,
1021
+ * so firing it is never worse than a soft abort. Typical use: fire
1022
+ * `signal` first, then this after your own patience runs out.
1023
+ */
1024
+ hardAbortSignal?: AbortSignal;
502
1025
  filename?: string;
503
1026
  }
504
1027
  /**
1028
+ * `run()` options with a call: the module is evaluated, then
1029
+ * `call.export` is resolved against its freshly evaluated exports and
1030
+ * invoked. The result carries the function's return {@link CallSuccess.value}
1031
+ * instead of `exports` — never both.
1032
+ */
1033
+ interface RunCallOptions extends RunOptions {
1034
+ call: CallTarget;
1035
+ }
1036
+ /**
1037
+ * Options for `sandbox.readExports()` — the deploy/registration path: load a
1038
+ * module once and read its declaration exports (IaC-style limits, connection
1039
+ * requirements, …). Function-valued exports are absent and reported in
1040
+ * {@link ReadExportsResult.skippedExports}, so reading the declarations of a
1041
+ * module that also exports handlers is not an error.
1042
+ */
1043
+ interface ReadExportsOptions {
1044
+ code: string;
1045
+ limits?: ResourceLimits;
1046
+ filename?: string;
1047
+ }
1048
+ /**
1049
+ * What `sandbox.readExports()` resolves to. Unlike `run()`, failures reject
1050
+ * the returned promise (like `prepare()`), since the deploy path treats a
1051
+ * broken module as exceptional rather than as a result variant.
1052
+ */
1053
+ interface ReadExportsResult {
1054
+ exports: SandboxExports;
1055
+ /**
1056
+ * Export names absent from `exports` because their value cannot cross the
1057
+ * boundary — see {@link RunSuccess.skippedExports}.
1058
+ */
1059
+ skippedExports: string[];
1060
+ }
1061
+ /**
505
1062
  * Why a run was aborted — whatever value was passed to the aborting
506
1063
  * `AbortController.abort(reason)` (or left `undefined`). Opaque to iso4 and
507
1064
  * surfaced verbatim on {@link RunAborted.reason}; a consumer built on top
@@ -510,6 +1067,67 @@ interface RunOptions {
510
1067
  type AbortReason = unknown;
511
1068
  type RunResult = RunSuccess | RunFailure | RunAborted;
512
1069
  /**
1070
+ * Result of a run that carried a {@link CallTarget}: on success the called
1071
+ * function's return value replaces `exports` — never both. Failures and
1072
+ * aborts are shared with {@link RunResult}.
1073
+ */
1074
+ type CallResult = CallSuccess | RunFailure | RunAborted;
1075
+ /**
1076
+ * The success arm of a {@link CallResult}. Logs, timings, and bridge records
1077
+ * are identical to {@link RunSuccess}; only the value slot differs.
1078
+ */
1079
+ interface CallSuccess {
1080
+ status: "completed";
1081
+ ok: true;
1082
+ /**
1083
+ * The called function's return value — awaited first when the function
1084
+ * returned a Promise. Anything V8's serialization format carries arrives
1085
+ * as a real instance, including a `Response`.
1086
+ *
1087
+ * A `Response`/`Request` whose body STREAMS (sandbox code returned
1088
+ * `new Response(asyncIterable)` or passed `request.body` through)
1089
+ * arrives with a real `ReadableStream` body: read it or cancel it. Your
1090
+ * reads drive the sandbox's production under flow control (a slow
1091
+ * reader pauses the source); a stream neither read nor cancelled for
1092
+ * 10 seconds is dropped by the runtime and later reads reject. Body
1093
+ * failures after this result was delivered reject the read, never
1094
+ * change this result — the same split as a `fetch` body dying
1095
+ * mid-transfer.
1096
+ */
1097
+ value: unknown;
1098
+ stdout: string[];
1099
+ stderr: string[];
1100
+ /**
1101
+ * Complete wall-clock from dispatch to the processed conclusion — async
1102
+ * waits, engine time for co-resident runs, machinery: everything. May
1103
+ * exceed the `wallTimeMs` limit, which counts {@link wallTimeMs} instead.
1104
+ */
1105
+ durationMs: number;
1106
+ /**
1107
+ * The call's own logic time: execution plus async waits, each wait counted
1108
+ * until its answer arrived — engine time is excluded and visible as
1109
+ * `durationMs - wallTimeMs`. This is the number `limits.wallTimeMs` caps.
1110
+ * `cpuTimeMs ≤ wallTimeMs ≤ durationMs`.
1111
+ */
1112
+ wallTimeMs: number;
1113
+ /**
1114
+ * Active V8 execution only; bridge waits excluded (itemized in `bridgeCalls`).
1115
+ */
1116
+ cpuTimeMs: number;
1117
+ bridgeCalls: BridgeCallEntry[];
1118
+ /**
1119
+ * `used_heap_size` of the isolate that served this call, measured after
1120
+ * the call settled. Reported for prefix calls (warm instances);
1121
+ * `undefined` for one-off `sandbox.run({ call })`.
1122
+ */
1123
+ heapUsedBytes?: number;
1124
+ /**
1125
+ * Present when the call registered background work with `waitUntil` —
1126
+ * see {@link RunSuccess.waitUntil}. Never rejects.
1127
+ */
1128
+ waitUntil?: Promise<WaitUntilResult>;
1129
+ }
1130
+ /**
513
1131
  * Metadata for a single bridge call attempt, recorded by the Rust runtime on
514
1132
  * the run's own clock. No payloads — names, timing, and sizes only — so
515
1133
  * recording is cheap enough to stay always-on. Unbounded: every attempt gets
@@ -560,6 +1178,52 @@ interface BridgeCallEntry {
560
1178
  blocked: boolean;
561
1179
  }
562
1180
  /**
1181
+ * Outcome of a run's `waitUntil` grace phase, delivered through
1182
+ * {@link RunSuccess.waitUntil} / {@link CallSuccess.waitUntil}. The promise
1183
+ * always **resolves** (never rejects), so ignoring it — the intended common
1184
+ * case — produces no unhandled-rejection noise.
1185
+ */
1186
+ interface WaitUntilResult {
1187
+ /**
1188
+ * `settled`: every registered promise finished within the grace budget.
1189
+ * `truncated`: the budget (or a host abort) cut the work short.
1190
+ * `failed`: at least one registered promise rejected — a normal outcome,
1191
+ * the code finished via its error path; the rest were still driven.
1192
+ */
1193
+ status: "settled" | "truncated" | "failed";
1194
+ /**
1195
+ * Complete wall time of the grace phase (after the result shipped), ms.
1196
+ */
1197
+ durationMs: number;
1198
+ /**
1199
+ * The grace phase's own logic time — same rule as
1200
+ * {@link RunSuccess.wallTimeMs}, metered separately from the run's.
1201
+ */
1202
+ wallTimeMs: number;
1203
+ /**
1204
+ * Active V8 execution time during the grace phase, ms.
1205
+ */
1206
+ cpuTimeMs: number;
1207
+ /**
1208
+ * Console lines written during the grace phase — the run's own lines
1209
+ * arrived on the result itself.
1210
+ */
1211
+ stdout: string[];
1212
+ stderr: string[];
1213
+ /**
1214
+ * Bridge calls attempted during the grace phase.
1215
+ */
1216
+ bridgeCalls: BridgeCallEntry[];
1217
+ /**
1218
+ * The first rejection when `status === 'failed'`, or the fatal error that
1219
+ * ended a truncated phase, when one exists.
1220
+ */
1221
+ error?: {
1222
+ name: string;
1223
+ message: string;
1224
+ };
1225
+ }
1226
+ /**
563
1227
  * `status` is the primary discriminant across all three outcomes; `ok` is kept
564
1228
  * as a convenience alias for `status === 'completed'`, so the common guard
565
1229
  * stays `if (result.ok)`. Reach for `switch (result.status)` when a deliberate
@@ -569,17 +1233,53 @@ interface RunSuccess {
569
1233
  status: "completed";
570
1234
  ok: true;
571
1235
  exports: SandboxExports;
1236
+ /**
1237
+ * Export names absent from `exports` because their value cannot cross the
1238
+ * boundary — a function (`export default { fetch }`), a Promise, or a value
1239
+ * whose serialization failed. Skipping is never fatal; the names are
1240
+ * reported here so nothing is silently hidden.
1241
+ *
1242
+ * A Promise is skipped **whatever its state**: the export path never awaits,
1243
+ * so `export default Promise.resolve(42)` is dropped exactly like a pending
1244
+ * one. Export the value instead — `export default await something()` — which
1245
+ * works because the module's own evaluation settles before the runtime reads
1246
+ * the namespace. `prefix.call()` is the opposite: it awaits a returned
1247
+ * Promise and resolves to its value.
1248
+ */
1249
+ skippedExports: string[];
1250
+ /**
1251
+ * Lines this run wrote to `console.log` / `.debug` / `.info`, capped by
1252
+ * `limits.maxStdoutBytes`. Prefix code shares the same console: when a run
1253
+ * cold-starts a warm instance, what the prefix logged while evaluating
1254
+ * arrives here once, on that run's result, ahead of the run's own lines.
1255
+ *
1256
+ * Only `log`/`debug`/`info`/`warn`/`error` are captured. The rest of the
1257
+ * sandbox's `console` is callable but emits nothing — see
1258
+ * `docs/conformance.md`.
1259
+ */
572
1260
  stdout: string[];
1261
+ /**
1262
+ * Same as {@link RunSuccess.stdout}, for `console.warn` / `.error`.
1263
+ */
573
1264
  stderr: string[];
574
1265
  /**
575
- * Wall-clock time of the run (start of execution to result), measured in
576
- * the runtime. Milliseconds with microsecond resolution.
1266
+ * Complete wall-clock time of the run (dispatch to the processed
1267
+ * conclusion), measured in the runtime — async waits, engine time for
1268
+ * co-resident runs, machinery: everything. May exceed the `wallTimeMs`
1269
+ * limit, which counts {@link wallTimeMs} instead. Milliseconds with
1270
+ * microsecond resolution.
577
1271
  */
578
1272
  durationMs: number;
579
1273
  /**
1274
+ * The run's own logic time: execution plus async waits, each wait counted
1275
+ * until its answer arrived — engine time is excluded and visible as
1276
+ * `durationMs - wallTimeMs`. This is the number `limits.wallTimeMs` caps.
1277
+ * `cpuTimeMs ≤ wallTimeMs ≤ durationMs`.
1278
+ */
1279
+ wallTimeMs: number;
1280
+ /**
580
1281
  * Active V8 execution time — time spent waiting on host bridge calls is
581
- * excluded. Milliseconds with microsecond resolution. The remainder
582
- * (`durationMs - cpuTimeMs`) is bridge waits plus scheduling.
1282
+ * excluded. Milliseconds with microsecond resolution.
583
1283
  */
584
1284
  cpuTimeMs: number;
585
1285
  /**
@@ -588,6 +1288,21 @@ interface RunSuccess {
588
1288
  * Recorded by the Rust runtime.
589
1289
  */
590
1290
  bridgeCalls: BridgeCallEntry[];
1291
+ /**
1292
+ * `used_heap_size` of the isolate that served this run, measured after the
1293
+ * run settled. Reported for prefix runs — warm instances keep their
1294
+ * heap between calls, and this number feeds eviction. `undefined` for
1295
+ * one-off `sandbox.run()` runs, whose isolate is disposed with the run.
1296
+ */
1297
+ heapUsedBytes?: number;
1298
+ /**
1299
+ * Present when the run registered background work with `waitUntil`:
1300
+ * the value in this result was delivered early, the work keeps running
1301
+ * runtime-side, and this promise resolves with the grace phase's outcome
1302
+ * once it ends. `undefined` for every run that registered nothing. Safe to
1303
+ * ignore — it never rejects.
1304
+ */
1305
+ waitUntil?: Promise<WaitUntilResult>;
591
1306
  }
592
1307
  interface RunFailure {
593
1308
  status: "failed";
@@ -596,8 +1311,19 @@ interface RunFailure {
596
1311
  stdout: string[];
597
1312
  stderr: string[];
598
1313
  durationMs: number;
1314
+ /**
1315
+ * See {@link RunSuccess.wallTimeMs}.
1316
+ */
1317
+ wallTimeMs: number;
599
1318
  cpuTimeMs: number;
600
1319
  bridgeCalls: BridgeCallEntry[];
1320
+ /**
1321
+ * `used_heap_size` of the isolate that served this run, measured after the
1322
+ * run settled. Reported for prefix runs — warm instances keep their
1323
+ * heap between calls, and this number feeds eviction. `undefined` for
1324
+ * one-off `sandbox.run()` runs, whose isolate is disposed with the run.
1325
+ */
1326
+ heapUsedBytes?: number;
601
1327
  }
602
1328
  /**
603
1329
  * The run was stopped by an abort — a pre-aborted or mid-run `signal` passed to
@@ -614,10 +1340,14 @@ interface RunAborted {
614
1340
  stdout: string[];
615
1341
  stderr: string[];
616
1342
  durationMs: number;
1343
+ /**
1344
+ * See {@link RunSuccess.wallTimeMs}.
1345
+ */
1346
+ wallTimeMs: number;
617
1347
  cpuTimeMs: number;
618
1348
  /**
619
1349
  * Bridge calls recorded before the abort landed. Populated when the runtime
620
- * terminates gracefully (#36) — the common case, where the run was suspended
1350
+ * terminates gracefully — the common case, where the run was suspended
621
1351
  * awaiting a bridge response. Empty (and `durationMs`/`cpuTimeMs` zero) only
622
1352
  * when graceful termination falls back to socket teardown — e.g. a run
623
1353
  * aborted while stuck in a tight synchronous loop, or a signal already
@@ -654,10 +1384,26 @@ interface RunError {
654
1384
  * value is an object with serializable own properties.
655
1385
  */
656
1386
  fields?: Record<string, unknown>;
1387
+ /**
1388
+ * Present only for `ERR_INSTANCE_RESET`: what interrupted the co-resident
1389
+ * run that took the shared instance down with it.
1390
+ */
1391
+ resetCause?: ResetCause;
1392
+ /**
1393
+ * Present only for `ERR_INSTANCE_RESET`: the wire run id of the run whose
1394
+ * interruption reset the instance — an opaque number, but stable across
1395
+ * the victims of one reset, so they can be correlated.
1396
+ */
1397
+ culpritRunId?: number;
657
1398
  }
658
- 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";
1399
+ /**
1400
+ * Why a shared instance was reset under an innocent victim — see
1401
+ * `RunError.resetCause`.
1402
+ */
1403
+ type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
1404
+ 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_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY" | "ERR_QUEUE_FULL" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PREFIX_DISPOSED" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
659
1405
  //#endregion
660
1406
  //#region src/index.d.ts
661
1407
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
662
1408
  //#endregion
663
- export { type BridgeCallEntry, type BridgeWithShim, type CreateSandbox, type DataGlobal, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type PrecompileOptions, type Prefix, type PrefixRunOptions, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResourceLimits, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, createSandbox };
1409
+ export { type BridgeCallEntry, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type StringGlobal, type WaitUntilResult, createSandbox };