@iso4/sandbox 0.3.1 → 0.4.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
@@ -27,7 +27,7 @@ import { createSafeFetch } from '@iso4/fetch'
27
27
  const sandbox = await createSandbox()
28
28
 
29
29
  // Compile host setup once into a V8 snapshot
30
- const prefix = await sandbox.precompile({
30
+ const prefix = await sandbox.prepare({
31
31
  code: `
32
32
  const config = { apiBase: 'https://api.example.com' }
33
33
  globalThis.config = config
@@ -38,7 +38,7 @@ const prefix = await sandbox.precompile({
38
38
  })
39
39
 
40
40
  // Run agent-generated code against the snapshot — as many times as needed
41
- const result = await prefix.run({
41
+ const result = await prefix.execute({
42
42
  code: `
43
43
  const res = await fetch(config.apiBase + '/users')
44
44
  export default { count: res.length }
@@ -55,6 +55,10 @@ if (result.ok) {
55
55
  await sandbox.dispose()
56
56
  ```
57
57
 
58
+ > `sandbox.prepare()` and `prefix.execute()` are the current names. The former
59
+ > names — `sandbox.precompile()` and `prefix.run()` — remain as deprecated
60
+ > aliases with identical behavior and will be removed in a future major.
61
+
58
62
  ## How globals work
59
63
 
60
64
  `globals` wires any non-reserved name directly into the sandbox's global
@@ -77,22 +81,22 @@ not class instances with methods.
77
81
 
78
82
  ## TypeScript-checked rebinding
79
83
 
80
- `precompile()` infers the globals shape `G` from what you pass, and the
84
+ `prepare()` infers the globals shape `G` from what you pass, and the
81
85
  returned `Prefix<G>` only allows rebinding those names at run time:
82
86
 
83
87
  ```ts
84
- const prefix = await sandbox.precompile({
88
+ const prefix = await sandbox.prepare({
85
89
  globals: { fetch: defaultFetch, myTool: defaultTool },
86
90
  })
87
91
 
88
- prefix.run({ globals: { fetch: perUserFetch } }) // ✅ rebind one
89
- prefix.run({ globals: { unknown: handler } }) // ❌ TS error
92
+ prefix.execute({ globals: { fetch: perUserFetch } }) // ✅ rebind one
93
+ prefix.execute({ globals: { unknown: handler } }) // ❌ TS error
90
94
  ```
91
95
 
92
96
  ## Resource limits
93
97
 
94
98
  ```ts
95
- prefix.run({
99
+ prefix.execute({
96
100
  code: agentCode,
97
101
  limits: {
98
102
  cpuTimeMs: 200, // active JS execution only (await time excluded)
@@ -111,7 +115,7 @@ carry an ambient value across `await` points — concurrency-safe, unlike a
111
115
  module variable:
112
116
 
113
117
  ```ts
114
- prefix.run({
118
+ prefix.execute({
115
119
  code: `
116
120
  import { AsyncLocalStorage } from 'node:async_hooks'
117
121
  const als = new AsyncLocalStorage()
@@ -125,15 +129,28 @@ prefix.run({
125
129
 
126
130
  Only `run(store, callback, ...args)` and `getStore()` are provided. Built on
127
131
  V8's continuation-preserved embedder data; no promise hooks, so it's free
128
- unless used. Not available in `precompile()` (prefix) code — it's for the
132
+ unless used. Not available in `prepare()` (prefix) code — it's for the
129
133
  postfix. See DESIGN.md §16.
130
134
 
131
135
  ## Result shape
132
136
 
133
137
  ```ts
134
138
  type RunResult
135
- = | { ok: true, exports: SandboxExports, stdout: string[], stderr: string[], durationMs: number }
136
- | { ok: false, error: RunError, stdout: string[], stderr: string[], durationMs: number }
139
+ = | { ok: true, exports: SandboxExports, stdout: string[], stderr: string[], durationMs: number, cpuTimeMs: number, bridgeCalls: BridgeCallEntry[] }
140
+ | { ok: false, error: RunError, stdout: string[], stderr: string[], durationMs: number, cpuTimeMs: number, bridgeCalls: BridgeCallEntry[] }
141
+
142
+ // durationMs — wall-clock time of the run; cpuTimeMs — active V8 execution
143
+ // time (bridge waits excluded). Both measured in the runtime, µs resolution.
144
+
145
+ interface BridgeCallEntry { // recorded in the Rust runtime; one per attempt, in order
146
+ name: string // 'fetch', 'myTool', or '<specifier>.<path>' for host-module imports
147
+ startMs: number // offset from run start (same clock as durationMs)
148
+ durationMs: number // round-trip the sandbox waited (handler + IPC)
149
+ argBytes: number // serialized call payload size
150
+ responseBytes: number // serialized response value size (0 on handler error)
151
+ ok: boolean
152
+ blocked: boolean // blocked by a limit runtime-side; never reached the host
153
+ }
137
154
 
138
155
  interface RunError {
139
156
  code: RunErrorCode
@@ -166,7 +183,7 @@ Thrown errors keep their identity across the bridge, in both directions:
166
183
 
167
184
  V8 runs in a separate Rust subprocess communicating over a Unix domain socket.
168
185
  A pool of connections (one per `maxIsolates` slot) provides concurrency —
169
- five concurrent `prefix.run()` calls each get their own slot and execute in
186
+ five concurrent `prefix.execute()` calls each get their own slot and execute in
170
187
  parallel.
171
188
 
172
189
  ## License
package/dist/index.d.mts CHANGED
@@ -8,6 +8,18 @@
8
8
  * Multiple concurrent callers each get their own pool slot and run in
9
9
  * parallel. See DESIGN.md §1 and §13.
10
10
  */
11
+ /**
12
+ * Per-run resource caps. Every field is optional at the call site
13
+ * (`limits?: ResourceLimits`): pass only the limits you want to
14
+ * override. The client sends just those over the wire and the **runtime owns
15
+ * the defaults** — it fills in any field you leave unset. The `@default` values
16
+ * documented below mirror the runtime's defaults (defined in
17
+ * `native/v8-runtime/src/ipc.rs`, the source of truth); if they ever drift, the
18
+ * runtime wins.
19
+ *
20
+ * A field set to `0` is not the same as leaving it unset: `0` explicitly
21
+ * disables that limit, whereas unset yields the runtime default.
22
+ */
11
23
  interface ResourceLimits {
12
24
  /**
13
25
  * Hard cap on memory the isolate can use, in megabytes.
@@ -19,23 +31,26 @@ interface ResourceLimits {
19
31
  * Zero means no cap.
20
32
  * @default 64
21
33
  */
22
- memoryMb: number;
34
+ memoryMb?: number;
23
35
  /**
24
36
  * Maximum *active* execution time in milliseconds. Time spent waiting on
25
37
  * host bridge calls (globals, host imports) is excluded.
26
38
  * @default 5_000
27
39
  */
28
- cpuTimeMs: number;
40
+ cpuTimeMs?: number;
29
41
  /**
30
42
  * Hard wall-clock cap including async waits.
31
43
  * @default 30_000
32
44
  */
33
- wallTimeMs: number;
45
+ wallTimeMs?: number;
34
46
  /**
35
47
  * Maximum bytes the sandbox may send as arguments in a single bridge call
36
48
  * (sandbox → host direction). Protects the host from receiving unexpectedly
37
49
  * large payloads generated by untrusted sandbox code.
38
50
  *
51
+ * A violation terminates the run immediately with
52
+ * `ERR_BRIDGE_PAYLOAD_TOO_LARGE`; sandbox code cannot catch it.
53
+ *
39
54
  * Bridge responses (host → sandbox) are not separately capped here — the
40
55
  * natural limit is `memoryMb`: the sandbox cannot hold a response larger than
41
56
  * its own memory budget, and the framing layer enforces this automatically.
@@ -43,28 +58,28 @@ interface ResourceLimits {
43
58
  * Zero disables the per-call cap.
44
59
  * @default 16 * 1024 * 1024
45
60
  */
46
- maxBridgeCallBytes: number;
61
+ maxBridgeCallBytes?: number;
47
62
  /**
48
63
  * Maximum bytes allowed for the serialised export payload (all named exports
49
64
  * combined). Exceeding this limit terminates the run with `ERR_EXPORT_TOO_LARGE`.
50
65
  * Zero disables the cap.
51
66
  * @default 16 * 1024 * 1024
52
67
  */
53
- maxExportBytes: number;
68
+ maxExportBytes?: number;
54
69
  /**
55
70
  * Maximum bytes captured from `console.log` / `console.debug` / `console.info`
56
71
  * combined. Lines that would push the total over the limit are silently dropped.
57
72
  * Zero disables the cap.
58
73
  * @default 1 * 1024 * 1024
59
74
  */
60
- maxStdoutBytes: number;
75
+ maxStdoutBytes?: number;
61
76
  /**
62
77
  * Maximum bytes captured from `console.warn` / `console.error` combined.
63
78
  * Lines that would push the total over the limit are silently dropped.
64
79
  * Zero disables the cap.
65
80
  * @default 1 * 1024 * 1024
66
81
  */
67
- maxStderrBytes: number;
82
+ maxStderrBytes?: number;
68
83
  /**
69
84
  * Maximum number of bridge calls (globals + host imports combined) a
70
85
  * single run may make. Zero disables the per-run limit entirely.
@@ -73,9 +88,13 @@ interface ResourceLimits {
73
88
  * handlers (e.g. `while(true) { await myTool() }`) which consumes near-zero
74
89
  * CPU budget but can exhaust host resources (network, DB, LLM quota).
75
90
  *
91
+ * A violation terminates the run immediately with
92
+ * `ERR_BRIDGE_CALL_LIMIT_EXCEEDED`; sandbox code cannot catch it (unlike
93
+ * host handler errors, which reject the call's promise and are catchable).
94
+ *
76
95
  * @default 10
77
96
  */
78
- maxBridgeCalls: number;
97
+ maxBridgeCalls?: number;
79
98
  }
80
99
  /**
81
100
  * Host-provided globals. Any name not reserved by V8 or the runtime is
@@ -104,25 +123,48 @@ type HostGlobals = Record<string, HostGlobalValue>;
104
123
  *
105
124
  * - `HostExportFunction` — bridge call: every sandbox invocation dispatches
106
125
  * 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.
126
+ * - `string` — a JS expression the runtime evaluates once and installs as
127
+ * `globalThis.<name>`. Use for pure sandbox utilities that need no host
128
+ * involvement. The expression is evaluated by Rust as its own script, so it
129
+ * never shifts the line numbers of user code.
130
+ * - `DataGlobal` — a plain constant carried as data and installed natively;
131
+ * no code text, no host involvement.
110
132
  * - `BridgeWithShim` — bridge call + in-sandbox result wrapper. The handler
111
133
  * can be rebound per `prefix.run()`; the shim is compiled into the snapshot.
112
134
  */
113
- type HostGlobalValue = HostExportFunction | string | BridgeWithShim<any>;
135
+ type HostGlobalValue = HostExportFunction | string | BridgeWithShim<any> | DataGlobal;
136
+ /**
137
+ * A plain **constant** global — a data value installed directly on the sandbox
138
+ * global object, with no host involvement and no code text anywhere.
139
+ *
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):
142
+ *
143
+ * ```ts
144
+ * globals: { config: { kind: 'data', value: userConfig } }
145
+ * ```
146
+ *
147
+ * `value` accepts the same set as host-module data leaves (`HostExportData`):
148
+ * primitives, `bigint`, `string`, `Uint8Array`, and plain objects/arrays.
149
+ * Like string globals, a data global is a constant — it cannot be rebound per
150
+ * `prefix.run()`.
151
+ */
152
+ interface DataGlobal {
153
+ kind: "data";
154
+ value: HostExportData;
155
+ }
114
156
  /**
115
157
  * A global that pairs a bridge handler with an in-sandbox shim that wraps
116
158
  * its return value. Typical use: adding `.json()` / `.text()` convenience
117
159
  * methods to a fetch response without extra bridge round-trips.
118
160
  *
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
- * ```
161
+ * The runtime installs this natively:
162
+ * 1. `handler` is registered as a bridge stub under the private dispatch
163
+ * name `__iso4_<name>_h`.
164
+ * 2. Rust evaluates the shim expression and builds the wrapper
165
+ * `async (...args) => await shim(await globalThis["__iso4_<name>_h"](...args))`,
166
+ * then sets it on the global object under `<name>` via the V8 API — the
167
+ * public name is a plain string passed to `object.set`, never code.
126
168
  *
127
169
  * The shim is a JS function expression `(result) => transformedResult` (sync
128
170
  * or async). Sandbox built-ins (TextDecoder, JSON, …) are available in scope.
@@ -171,15 +213,15 @@ type RebindValue<V extends HostGlobalValue> = V extends BridgeWithShim<infer H>
171
213
  /**
172
214
  * The per-run globals override map for a `Prefix<G>`.
173
215
  *
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.
216
+ * String-valued and `DataGlobal` (constant) globals are filtered out entirely
217
+ * (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
219
+ * not appear as valid keys at all.
178
220
  *
179
221
  * Each remaining key is optional and typed as `RebindValue<G[K]>`, which
180
222
  * enforces the correct constraint per global kind.
181
223
  */
182
- type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string ? never : K]?: RebindValue<G[K]> };
224
+ type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string | DataGlobal ? never : K]?: RebindValue<G[K]> };
183
225
  /**
184
226
  * Top-level `imports` shape. Keys are import specifiers; values are either
185
227
  * a source string or a host-module description object.
@@ -309,6 +351,11 @@ interface Sandbox {
309
351
  /**
310
352
  * eslint-disable \@typescript-eslint/no-empty-object-type
311
353
  */
354
+ prepare: <G extends HostGlobals = {}, M extends Imports = {}>(options: PrecompileOptions<G, M>) => Promise<Prefix<G, M>>;
355
+ /**
356
+ * @deprecated Renamed to {@link Sandbox.prepare}. `precompile` stays as an
357
+ * alias (identical behavior) and is slated for removal in a future major.
358
+ */
312
359
  precompile: <G extends HostGlobals = {}, M extends Imports = {}>(options: PrecompileOptions<G, M>) => Promise<Prefix<G, M>>;
313
360
  /**
314
361
  * Tear down the Rust process. Outstanding prefixes are invalidated.
@@ -368,7 +415,7 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
368
415
  * **Currently a no-op placeholder.** Pass limits directly to each
369
416
  * `prefix.run()` call.
370
417
  */
371
- limits?: Partial<ResourceLimits>;
418
+ limits?: ResourceLimits;
372
419
  /**
373
420
  * Optional filename for stack traces. Default: "<prefix>".
374
421
  */
@@ -382,7 +429,7 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
382
429
  * declared global's implementation per run, but you cannot add names that
383
430
  * were not declared at precompile time.
384
431
  */
385
- interface Prefix<G extends HostGlobals, M extends Imports> {
432
+ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
386
433
  readonly id: string;
387
434
  /**
388
435
  * Execute dynamic code against this prefix's snapshot state.
@@ -393,10 +440,15 @@ interface Prefix<G extends HostGlobals, M extends Imports> {
393
440
  * host-import function exports declared in `I`.
394
441
  *
395
442
  * @example
396
- * const result = await prefix.run({
443
+ * const result = await prefix.execute({
397
444
  * code: `export default await (${agentFn})()`,
398
445
  * })
399
446
  */
447
+ execute: (options: PrefixRunOptions<G, M>) => Promise<RunResult>;
448
+ /**
449
+ * @deprecated Renamed to {@link Prefix.execute}. `run` stays as an alias
450
+ * (identical behavior) and is slated for removal in a future major.
451
+ */
400
452
  run: (options: PrefixRunOptions<G, M>) => Promise<RunResult>;
401
453
  /**
402
454
  * Release the snapshot. Subsequent run() calls reject. Idempotent.
@@ -437,13 +489,13 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
437
489
  * anything that slips through with `ERR_UNDECLARED_BINDING`.
438
490
  */
439
491
  imports?: RebindImports<M>;
440
- limits?: Partial<ResourceLimits>;
492
+ limits?: ResourceLimits;
441
493
  signal?: AbortSignal;
442
494
  filename?: string;
443
495
  }
444
496
  interface RunOptions {
445
497
  code: string;
446
- limits?: Partial<ResourceLimits>;
498
+ limits?: ResourceLimits;
447
499
  globals?: HostGlobals;
448
500
  imports?: Imports;
449
501
  signal?: AbortSignal;
@@ -458,6 +510,56 @@ interface RunOptions {
458
510
  type AbortReason = unknown;
459
511
  type RunResult = RunSuccess | RunFailure | RunAborted;
460
512
  /**
513
+ * Metadata for a single bridge call attempt, recorded by the Rust runtime on
514
+ * the run's own clock. No payloads — names, timing, and sizes only — so
515
+ * recording is cheap enough to stay always-on. Unbounded: every attempt gets
516
+ * an entry (~100 bytes); consumers that only care about a subset filter the
517
+ * list themselves.
518
+ */
519
+ interface BridgeCallEntry {
520
+ /**
521
+ * The name sandbox code called. Plain globals appear as-is (`fetch`),
522
+ * shimmed globals under their public name (not the private stub), and
523
+ * host-module import leaves as `<specifier>.<path>` (e.g.
524
+ * `tools:search.query`).
525
+ */
526
+ name: string;
527
+ /**
528
+ * Offset from run start to the attempt, in milliseconds — same clock as
529
+ * the result's `durationMs`, so entries line up on a run timeline.
530
+ */
531
+ startMs: number;
532
+ /**
533
+ * Round-trip time the sandbox waited for the response (host handler + IPC),
534
+ * in milliseconds. For calls still unanswered when the run ended
535
+ * (timeout/abort): the time until the run ended. `0` for blocked attempts.
536
+ */
537
+ durationMs: number;
538
+ /**
539
+ * Serialized size of the call payload (callId + target + arguments) in
540
+ * bytes — the same size `maxBridgeCallBytes` is enforced against. `0` for
541
+ * attempts blocked before argument serialization.
542
+ */
543
+ argBytes: number;
544
+ /**
545
+ * Serialized size of the successful response value in bytes. `0` when the
546
+ * handler failed or the call never settled.
547
+ */
548
+ responseBytes: number;
549
+ /**
550
+ * `true` when the host handler resolved and its response reached the
551
+ * sandbox. `false` for handler errors, blocked attempts, and calls still
552
+ * in flight when the run ended.
553
+ */
554
+ ok: boolean;
555
+ /**
556
+ * `true` when the attempt was blocked inside the runtime (`maxBridgeCalls`
557
+ * exceeded, payload over `maxBridgeCallBytes`, function argument) and never
558
+ * reached the host.
559
+ */
560
+ blocked: boolean;
561
+ }
562
+ /**
461
563
  * `status` is the primary discriminant across all three outcomes; `ok` is kept
462
564
  * as a convenience alias for `status === 'completed'`, so the common guard
463
565
  * stays `if (result.ok)`. Reach for `switch (result.status)` when a deliberate
@@ -469,7 +571,23 @@ interface RunSuccess {
469
571
  exports: SandboxExports;
470
572
  stdout: string[];
471
573
  stderr: string[];
574
+ /**
575
+ * Wall-clock time of the run (start of execution to result), measured in
576
+ * the runtime. Milliseconds with microsecond resolution.
577
+ */
472
578
  durationMs: number;
579
+ /**
580
+ * 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.
583
+ */
584
+ cpuTimeMs: number;
585
+ /**
586
+ * One entry per bridge call the sandbox attempted, in attempt order —
587
+ * including attempts blocked by limits ({@link BridgeCallEntry.blocked}).
588
+ * Recorded by the Rust runtime.
589
+ */
590
+ bridgeCalls: BridgeCallEntry[];
473
591
  }
474
592
  interface RunFailure {
475
593
  status: "failed";
@@ -478,6 +596,8 @@ interface RunFailure {
478
596
  stdout: string[];
479
597
  stderr: string[];
480
598
  durationMs: number;
599
+ cpuTimeMs: number;
600
+ bridgeCalls: BridgeCallEntry[];
481
601
  }
482
602
  /**
483
603
  * The run was stopped by an abort — a pre-aborted or mid-run `signal` passed to
@@ -494,6 +614,16 @@ interface RunAborted {
494
614
  stdout: string[];
495
615
  stderr: string[];
496
616
  durationMs: number;
617
+ cpuTimeMs: number;
618
+ /**
619
+ * Bridge calls recorded before the abort landed. Populated when the runtime
620
+ * terminates gracefully (#36) — the common case, where the run was suspended
621
+ * awaiting a bridge response. Empty (and `durationMs`/`cpuTimeMs` zero) only
622
+ * when graceful termination falls back to socket teardown — e.g. a run
623
+ * aborted while stuck in a tight synchronous loop, or a signal already
624
+ * aborted at run entry.
625
+ */
626
+ bridgeCalls: BridgeCallEntry[];
497
627
  }
498
628
  type SandboxExports = {
499
629
  /**
@@ -530,4 +660,4 @@ type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "
530
660
  //#region src/index.d.ts
531
661
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
532
662
  //#endregion
533
- export { type BridgeWithShim, type CreateSandbox, 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 };
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 };