@iso4/sandbox 0.3.0 → 0.4.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/README.md CHANGED
@@ -132,8 +132,21 @@ postfix. See DESIGN.md §16.
132
132
 
133
133
  ```ts
134
134
  type RunResult
135
- = | { ok: true, exports: SandboxExports, stdout: string[], stderr: string[], durationMs: number }
136
- | { ok: false, error: RunError, stdout: string[], stderr: string[], durationMs: number }
135
+ = | { ok: true, exports: SandboxExports, stdout: string[], stderr: string[], durationMs: number, cpuTimeMs: number, bridgeCalls: BridgeCallEntry[] }
136
+ | { ok: false, error: RunError, stdout: string[], stderr: string[], durationMs: number, cpuTimeMs: number, bridgeCalls: BridgeCallEntry[] }
137
+
138
+ // durationMs — wall-clock time of the run; cpuTimeMs — active V8 execution
139
+ // time (bridge waits excluded). Both measured in the runtime, µs resolution.
140
+
141
+ interface BridgeCallEntry { // recorded in the Rust runtime; one per attempt, in order
142
+ name: string // 'fetch', 'myTool', or '<specifier>.<path>' for host-module imports
143
+ startMs: number // offset from run start (same clock as durationMs)
144
+ durationMs: number // round-trip the sandbox waited (handler + IPC)
145
+ argBytes: number // serialized call payload size
146
+ responseBytes: number // serialized response value size (0 on handler error)
147
+ ok: boolean
148
+ blocked: boolean // blocked by a limit runtime-side; never reached the host
149
+ }
137
150
 
138
151
  interface RunError {
139
152
  code: RunErrorCode
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.
@@ -198,14 +240,15 @@ type ImportValue = string | HostModuleObject;
198
240
  * A host-module description object. Each property is either:
199
241
  *
200
242
  * - A function — becomes an async bridge stub in the generated module.
201
- * - A plain data value (primitive, plain object/array, `Date`, `BigInt`,
243
+ * - A plain data value (primitive, plain object/array, `BigInt`,
202
244
  * `Uint8Array`) — becomes a JS literal in the generated module.
203
245
  * - A nested object that itself contains a mix of functions and data —
204
246
  * walked recursively.
205
247
  *
206
- * `Map`, `Set`, circular references, class instances with prototype
207
- * methods, and stateful handles (streams, sockets) are rejected at
208
- * registration with a clear error.
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.
209
252
  */
210
253
  interface HostModuleObject {
211
254
  [name: string]: HostModuleValue;
@@ -218,7 +261,7 @@ type HostModuleValue = HostExportFunction | HostExportData | HostModuleObject;
218
261
  * The set of plain-data values supported as data leaves in the host-module
219
262
  * shape. The JS-literal emitter knows how to emit each of these.
220
263
  */
221
- type HostExportData = null | undefined | boolean | number | bigint | string | Uint8Array | Date | HostExportData[] | {
264
+ type HostExportData = null | undefined | boolean | number | bigint | string | Uint8Array | HostExportData[] | {
222
265
  [key: string]: HostExportData;
223
266
  };
224
267
  /**
@@ -367,7 +410,7 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
367
410
  * **Currently a no-op placeholder.** Pass limits directly to each
368
411
  * `prefix.run()` call.
369
412
  */
370
- limits?: Partial<ResourceLimits>;
413
+ limits?: ResourceLimits;
371
414
  /**
372
415
  * Optional filename for stack traces. Default: "<prefix>".
373
416
  */
@@ -381,7 +424,7 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
381
424
  * declared global's implementation per run, but you cannot add names that
382
425
  * were not declared at precompile time.
383
426
  */
384
- interface Prefix<G extends HostGlobals, M extends Imports> {
427
+ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
385
428
  readonly id: string;
386
429
  /**
387
430
  * Execute dynamic code against this prefix's snapshot state.
@@ -436,13 +479,13 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
436
479
  * anything that slips through with `ERR_UNDECLARED_BINDING`.
437
480
  */
438
481
  imports?: RebindImports<M>;
439
- limits?: Partial<ResourceLimits>;
482
+ limits?: ResourceLimits;
440
483
  signal?: AbortSignal;
441
484
  filename?: string;
442
485
  }
443
486
  interface RunOptions {
444
487
  code: string;
445
- limits?: Partial<ResourceLimits>;
488
+ limits?: ResourceLimits;
446
489
  globals?: HostGlobals;
447
490
  imports?: Imports;
448
491
  signal?: AbortSignal;
@@ -457,6 +500,56 @@ interface RunOptions {
457
500
  type AbortReason = unknown;
458
501
  type RunResult = RunSuccess | RunFailure | RunAborted;
459
502
  /**
503
+ * Metadata for a single bridge call attempt, recorded by the Rust runtime on
504
+ * the run's own clock. No payloads — names, timing, and sizes only — so
505
+ * recording is cheap enough to stay always-on. Unbounded: every attempt gets
506
+ * an entry (~100 bytes); consumers that only care about a subset filter the
507
+ * list themselves.
508
+ */
509
+ interface BridgeCallEntry {
510
+ /**
511
+ * The name sandbox code called. Plain globals appear as-is (`fetch`),
512
+ * shimmed globals under their public name (not the private stub), and
513
+ * host-module import leaves as `<specifier>.<path>` (e.g.
514
+ * `tools:search.query`).
515
+ */
516
+ name: string;
517
+ /**
518
+ * Offset from run start to the attempt, in milliseconds — same clock as
519
+ * the result's `durationMs`, so entries line up on a run timeline.
520
+ */
521
+ startMs: number;
522
+ /**
523
+ * Round-trip time the sandbox waited for the response (host handler + IPC),
524
+ * in milliseconds. For calls still unanswered when the run ended
525
+ * (timeout/abort): the time until the run ended. `0` for blocked attempts.
526
+ */
527
+ durationMs: number;
528
+ /**
529
+ * Serialized size of the call payload (callId + target + arguments) in
530
+ * bytes — the same size `maxBridgeCallBytes` is enforced against. `0` for
531
+ * attempts blocked before argument serialization.
532
+ */
533
+ argBytes: number;
534
+ /**
535
+ * Serialized size of the successful response value in bytes. `0` when the
536
+ * handler failed or the call never settled.
537
+ */
538
+ responseBytes: number;
539
+ /**
540
+ * `true` when the host handler resolved and its response reached the
541
+ * sandbox. `false` for handler errors, blocked attempts, and calls still
542
+ * in flight when the run ended.
543
+ */
544
+ ok: boolean;
545
+ /**
546
+ * `true` when the attempt was blocked inside the runtime (`maxBridgeCalls`
547
+ * exceeded, payload over `maxBridgeCallBytes`, function argument) and never
548
+ * reached the host.
549
+ */
550
+ blocked: boolean;
551
+ }
552
+ /**
460
553
  * `status` is the primary discriminant across all three outcomes; `ok` is kept
461
554
  * as a convenience alias for `status === 'completed'`, so the common guard
462
555
  * stays `if (result.ok)`. Reach for `switch (result.status)` when a deliberate
@@ -468,7 +561,23 @@ interface RunSuccess {
468
561
  exports: SandboxExports;
469
562
  stdout: string[];
470
563
  stderr: string[];
564
+ /**
565
+ * Wall-clock time of the run (start of execution to result), measured in
566
+ * the runtime. Milliseconds with microsecond resolution.
567
+ */
471
568
  durationMs: number;
569
+ /**
570
+ * Active V8 execution time — time spent waiting on host bridge calls is
571
+ * excluded. Milliseconds with microsecond resolution. The remainder
572
+ * (`durationMs - cpuTimeMs`) is bridge waits plus scheduling.
573
+ */
574
+ cpuTimeMs: number;
575
+ /**
576
+ * One entry per bridge call the sandbox attempted, in attempt order —
577
+ * including attempts blocked by limits ({@link BridgeCallEntry.blocked}).
578
+ * Recorded by the Rust runtime.
579
+ */
580
+ bridgeCalls: BridgeCallEntry[];
472
581
  }
473
582
  interface RunFailure {
474
583
  status: "failed";
@@ -477,6 +586,8 @@ interface RunFailure {
477
586
  stdout: string[];
478
587
  stderr: string[];
479
588
  durationMs: number;
589
+ cpuTimeMs: number;
590
+ bridgeCalls: BridgeCallEntry[];
480
591
  }
481
592
  /**
482
593
  * The run was stopped by an abort — a pre-aborted or mid-run `signal` passed to
@@ -493,6 +604,16 @@ interface RunAborted {
493
604
  stdout: string[];
494
605
  stderr: string[];
495
606
  durationMs: number;
607
+ cpuTimeMs: number;
608
+ /**
609
+ * Bridge calls recorded before the abort landed. Populated when the runtime
610
+ * terminates gracefully (#36) — the common case, where the run was suspended
611
+ * awaiting a bridge response. Empty (and `durationMs`/`cpuTimeMs` zero) only
612
+ * when graceful termination falls back to socket teardown — e.g. a run
613
+ * aborted while stuck in a tight synchronous loop, or a signal already
614
+ * aborted at run entry.
615
+ */
616
+ bridgeCalls: BridgeCallEntry[];
496
617
  }
497
618
  type SandboxExports = {
498
619
  /**
@@ -529,4 +650,4 @@ type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "
529
650
  //#region src/index.d.ts
530
651
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
531
652
  //#endregion
532
- 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 };
653
+ 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 };