@iso4/sandbox 0.8.1 → 0.9.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
@@ -35,7 +35,7 @@ import { createSafeFetch } from '@iso4/fetch'
35
35
 
36
36
  const sandbox = await createSandbox({ memoryMb: 128 }) // per-isolate heap cap
37
37
 
38
- // Validate and prepare host setup once
38
+ // Store host setup once; it is evaluated on each cold start
39
39
  const prefix = await sandbox.prepare({
40
40
  code: `
41
41
  const config = { apiBase: 'https://api.example.com' }
@@ -99,6 +99,30 @@ it before installing them. `RESERVED_WORDS` is a `Set` of names that cannot be
99
99
  a binding in module source, such as `class` or `eval`; iso4 refuses
100
100
  host-module export names in it, except `default`.
101
101
 
102
+ `prepare()` stores the prefix without running it, and checks only what needs
103
+ no isolate: global names, the import shape, and option ranges. A prefix that
104
+ does not compile, throws, or imports something unknown fails its first run
105
+ with the prefix's own code (`ERR_USER_CODE`, `ERR_MODULE_NOT_FOUND`,
106
+ `ERR_IMPORT`, `ERR_PREFIX_BRIDGE_CALL`, `ERR_PREFIX_DID_NOT_SETTLE`,
107
+ `ERR_WARMUP_LIMIT`). Validate it yourself where it matters — parse the
108
+ source with a tool such as `oxc`, or do one trial run (its instance stays
109
+ warm, so nothing is wasted):
110
+
111
+ ```ts
112
+ const prefix = await sandbox.prepare({ code })
113
+ const check = await prefix.execute({ code: 'export default 0' })
114
+ if (!check.ok)
115
+ throw new Error(`broken prefix: ${check.error.message}`)
116
+ ```
117
+
118
+ A failure of the prefix itself carries `error.stage === 'prefix'`, so a
119
+ host can tell it from a failure of the run code. The runtime remembers it:
120
+ `prefix.status` becomes `'broken'`, `prefix.error` holds the failure, and
121
+ every later `execute()`/`call()` rejects with `ERR_PREFIX_BROKEN` (its
122
+ `cause` is that failure) without booting an isolate. `dispose()` still
123
+ works; the only retry is a new `prepare()`. Failures that depend on load
124
+ (`ERR_WARMUP_LIMIT`, `ERR_MEMORY_LIMIT`) never break a prefix.
125
+
102
126
  To check generated names before `prepare()` instead of getting a failed
103
127
  setup back, import the predicates from `@iso4/sandbox/utils`. That entry
104
128
  never loads the client or the native binary:
@@ -142,7 +166,16 @@ prefix.execute({ globals: { unknown: handler } }) // ❌ TS error
142
166
 
143
167
  ## Resource limits
144
168
 
169
+ `prepare({ limits })` sets the defaults for every run on that prefix. A run's
170
+ own `limits` overrides them field by field; anything set in neither place
171
+ takes the runtime default.
172
+
145
173
  ```ts
174
+ const prefix = await sandbox.prepare({ code: prefixCode, limits: { cpuTimeMs: 200, maxBridgeCalls: 10 } })
175
+
176
+ prefix.execute({ code: agentCode }) // cpuTimeMs 200, maxBridgeCalls 10
177
+ prefix.execute({ code: agentCode, limits: { cpuTimeMs: 50 } }) // cpuTimeMs 50, maxBridgeCalls 10
178
+
146
179
  prefix.execute({
147
180
  code: agentCode,
148
181
  limits: {
@@ -190,7 +223,7 @@ one call at a time, so concurrency means more instances (the engine can
190
223
  already interleave several runs on one instance — that switches on with
191
224
  wire multiplexing). Top-level names never collide across runs
192
225
  (each run is its own module). A prefix that can't finish evaluating under
193
- the fixed warm-up budget is rejected by `prepare()` with
226
+ the fixed warm-up budget fails the cold-starting call with
194
227
  `ERR_WARMUP_LIMIT`. `console.*` from prefix evaluation arrives on the
195
228
  cold-starting call's result.
196
229
 
@@ -413,8 +446,9 @@ interface RunError {
413
446
  message: string
414
447
  stack?: string
415
448
  fields?: Record<string, unknown> // all other own-enumerable props of the thrown error
416
- resetCause?: 'cpu' | 'memory' | 'wall' | 'abort' | 'internal' // ERR_INSTANCE_RESET only
449
+ resetCause?: 'cpu' | 'memory' | 'wall' | 'abort' | 'internal' | 'unsupported' // ERR_INSTANCE_RESET only
417
450
  culpritRunId?: number // ERR_INSTANCE_RESET only: the run whose interruption reset the instance
451
+ stage?: 'prefix' // the prefix itself failed to evaluate on this run's cold start
418
452
  }
419
453
  ```
420
454
 
@@ -424,13 +458,15 @@ crashed, binary not found) and for invalid options, the same way `prepare()`
424
458
  does. `sandbox.run()`, `prefix.run()` and `prefix.call()` reject with an
425
459
  `Error` whose `code` is a `SetupErrorCode`: `ERR_RESERVED_NAME` (a global
426
460
  name the runtime owns), `ERR_UNDECLARED_BINDING`, `ERR_FROZEN_BINDING` or
427
- `ERR_INVALID_REBIND` (a rebind the prefix does not allow), or
428
- `ERR_PREFIX_DISPOSED`. The client checks these before anything is sent, and
461
+ `ERR_INVALID_REBIND` (a rebind the prefix does not allow),
462
+ `ERR_PREFIX_DISPOSED`, or `ERR_PREFIX_BROKEN` (the prefix failed to
463
+ evaluate on an earlier run; `cause` is that failure). The client checks
464
+ these before anything is sent, and
429
465
  the runtime repeats the checks. A malformed option, such as a limit out of range or a
430
466
  global name that is not a well-formed string, rejects with a plain
431
467
  `TypeError`. Nothing ran, so retrying with the same options can never
432
- succeed. Every other code, including `ERR_COMPILE`, is a
433
- result.
468
+ succeed. Every other code, including a syntax error (`ERR_USER_CODE`
469
+ named `SyntaxError`), is a result.
434
470
 
435
471
  ```ts
436
472
  import type { SetupErrorCode } from '@iso4/sandbox'
@@ -441,6 +477,7 @@ const setupCodes: readonly string[] = [
441
477
  'ERR_FROZEN_BINDING',
442
478
  'ERR_INVALID_REBIND',
443
479
  'ERR_PREFIX_DISPOSED',
480
+ 'ERR_PREFIX_BROKEN',
444
481
  ] satisfies SetupErrorCode[]
445
482
 
446
483
  try {
package/dist/index.d.mts CHANGED
@@ -437,7 +437,9 @@ type HostExportData = null | undefined | boolean | number | bigint | string | Da
437
437
  * Args and return are `unknown` — the bridge serialises/deserialises values
438
438
  * with V8 ValueSerializer; we don't try to model that at the type level.
439
439
  * The one invariant that matters (functions cannot cross the boundary as
440
- * argument values) is enforced at runtime by the V8 layer, not here.
440
+ * argument values) is enforced at runtime by the V8 layer, not here. Arrays
441
+ * with holes are refused as arguments too, host-side, and the sandbox call
442
+ * rejects with a catchable `TypeError` before the handler runs.
441
443
  *
442
444
  * Use specific function types for your handlers and let TypeScript infer
443
445
  * them through `HostGlobals`, `RebindGlobals<G>`, and `RebindImports<M>`.
@@ -732,12 +734,32 @@ interface Sandbox {
732
734
  * deploy/registration path (IaC-style declaration exports read when a
733
735
  * function is created, never per request). Builds no prefix and retains
734
736
  * nothing. Function exports are skipped and reported, so a module that
735
- * also exports handlers reads cleanly. Rejects on compile/runtime errors,
736
- * like `prepare()`.
737
+ * also exports handlers reads cleanly. Rejects on a syntax or runtime
738
+ * error (`ERR_USER_CODE`), a missing import, or any other run failure.
737
739
  */
738
740
  readExports: (options: ReadExportsOptions) => Promise<ReadExportsResult>;
739
741
  /**
740
- * Validate and prepare a prefix of code for repeated runs.
742
+ * Prepare a prefix of code for repeated runs.
743
+ *
744
+ * `prepare()` stores the source and declared shape; it does not evaluate
745
+ * the prefix. It rejects only for options it can check without running
746
+ * anything: a reserved or malformed global name, an invalid import shape,
747
+ * a bad limit or `memoryMb`. A prefix that does not compile, throws at top
748
+ * level, imports something unknown, calls the bridge, never settles, or
749
+ * exceeds the warm-up budget fails on its first `execute()`/`call()` as an
750
+ * `{ ok: false }` result with the matching {@link RunErrorCode}
751
+ * (`ERR_USER_CODE`, `ERR_MODULE_NOT_FOUND`, `ERR_IMPORT`,
752
+ * `ERR_PREFIX_BRIDGE_CALL`, `ERR_PREFIX_DID_NOT_SETTLE`,
753
+ * `ERR_WARMUP_LIMIT`). Validating a prefix is the caller's job: parse the
754
+ * source yourself (an `oxc`/`acorn` pass catches syntax errors), or do one
755
+ * trial run after `prepare()` — its instance stays warm, so nothing is
756
+ * wasted:
757
+ *
758
+ * ```ts
759
+ * const prefix = await sandbox.prepare({ code })
760
+ * const check = await prefix.execute({ code: 'export default 0' })
761
+ * if (!check.ok) throw new Error(`broken prefix: ${check.error.message}`)
762
+ * ```
741
763
  *
742
764
  * The type parameter `G` is inferred from the `globals` you pass and flows
743
765
  * into the returned `Prefix<G>`. This lets TypeScript enforce at the call
@@ -838,14 +860,14 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
838
860
  */
839
861
  imports?: M;
840
862
  /**
841
- * Resource limits applied to prefix code evaluation.
863
+ * Default limits for every `execute()`/`call()` on this prefix. A run's
864
+ * own `limits` overrides them field by field, so a run can change one
865
+ * knob without restating the rest; a field set in neither place takes the
866
+ * runtime default. Checked here like per-run limits (a `TypeError` for a
867
+ * bad value). The heap cap is not part of this: set it with `memoryMb`.
842
868
  *
843
- * **Currently a no-op placeholder.** Pass limits directly to each
844
- * `prefix.run()` call. The one budget that DOES apply here is not
845
- * configurable: prefix evaluation runs under the fixed warm-up budget
846
- * (1 s wall / 1 s CPU) — a prefix that cannot evaluate inside it is
847
- * rejected with `ERR_WARMUP_LIMIT` at `prepare()` time, because it could
848
- * never cold-start a warm instance either.
869
+ * Prefix evaluation itself runs under the fixed warm-up budget
870
+ * (1 s wall / 1 s CPU), not these limits.
849
871
  */
850
872
  limits?: ResourceLimits;
851
873
  /**
@@ -912,16 +934,45 @@ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
912
934
  */
913
935
  call: (options: PrefixCallOptions<G, M>) => Promise<CallResult>;
914
936
  /**
915
- * Release the prepared prefix. Subsequent run() calls reject. Idempotent.
937
+ * Release the prepared prefix. Subsequent run() calls reject with
938
+ * `ERR_PREFIX_DISPOSED`. Idempotent, and works on a broken prefix too.
916
939
  */
917
940
  dispose: () => Promise<void>;
918
941
  /**
919
942
  * Enables `await using prefix = await sandbox.precompile(...)` syntax.
920
943
  */
921
944
  [Symbol.asyncDispose]: () => Promise<void>;
945
+ /**
946
+ * `true` until `dispose()`. A broken prefix is still alive: it is held
947
+ * by the runtime and the host still owns its disposal.
948
+ */
922
949
  readonly alive: boolean;
950
+ /**
951
+ * `'ready'` until the runtime reports a prefix-stage failure, `'broken'`
952
+ * from then on (see {@link PrefixStatus}), `'disposed'` after
953
+ * `dispose()`. The client learns `'broken'` from the first run's
954
+ * `{ ok: false, error: { stage: 'prefix' } }` result, or from an
955
+ * `ERR_PREFIX_BROKEN` refusal if that result went to another client.
956
+ */
957
+ readonly status: PrefixStatus;
958
+ /**
959
+ * The stored cold-start failure once the prefix is broken, `undefined`
960
+ * before. Kept through `dispose()`. Always has `code`, `name`, `message`
961
+ * and `stack`; `stage` and `fields` are present only when this client saw
962
+ * the failing run's own result rather than a later `ERR_PREFIX_BROKEN`
963
+ * refusal.
964
+ */
965
+ readonly error: RunError | undefined;
923
966
  }
924
967
  /**
968
+ * Lifecycle of a {@link Prefix}. `'broken'` means the prefix failed to
969
+ * evaluate with one of its own, repeatable errors; every later run is
970
+ * refused with `ERR_PREFIX_BROKEN` and the only retry is a new `prepare()`.
971
+ * Load-dependent cold-start failures (`ERR_WARMUP_LIMIT`,
972
+ * `ERR_MEMORY_LIMIT`) never break a prefix — the next run cold-starts again.
973
+ */
974
+ type PrefixStatus = "ready" | "broken" | "disposed";
975
+ /**
925
976
  * Options for `prefix.run()`.
926
977
  *
927
978
  * `G` is the declared-globals shape from the matching `precompile()` call.
@@ -954,6 +1005,10 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
954
1005
  * `ERR_INVALID_REBIND` for a non-function override value.
955
1006
  */
956
1007
  imports?: RebindImports<M>;
1008
+ /**
1009
+ * Limits for this run, applied field by field on top of the prefix's
1010
+ * `prepare({ limits })` defaults. `memoryMb` is not a per-run option here.
1011
+ */
957
1012
  limits?: ResourceLimits;
958
1013
  /**
959
1014
  * Abort the run. Firing this is always SOFT: while queued the caller is
@@ -995,6 +1050,10 @@ interface PrefixCallOptions<G extends HostGlobals, M extends Imports> extends Ca
995
1050
  * rules as {@link PrefixRunOptions.imports}.
996
1051
  */
997
1052
  imports?: RebindImports<M>;
1053
+ /**
1054
+ * Limits for this call, applied field by field on top of the prefix's
1055
+ * `prepare({ limits })` defaults. `memoryMb` is not a per-run option here.
1056
+ */
998
1057
  limits?: ResourceLimits;
999
1058
  /**
1000
1059
  * Abort the run. Firing this is always SOFT: while queued the caller is
@@ -1097,8 +1156,8 @@ interface ReadExportsOptions {
1097
1156
  }
1098
1157
  /**
1099
1158
  * What `sandbox.readExports()` resolves to. Unlike `run()`, failures reject
1100
- * the returned promise (like `prepare()`), since the deploy path treats a
1101
- * broken module as exceptional rather than as a result variant.
1159
+ * the returned promise, since the deploy path treats a broken module as
1160
+ * exceptional rather than as a result variant.
1102
1161
  */
1103
1162
  interface ReadExportsResult {
1104
1163
  exports: SandboxExports;
@@ -1486,12 +1545,26 @@ interface RunError {
1486
1545
  * the victims of one reset, so they can be correlated.
1487
1546
  */
1488
1547
  culpritRunId?: number;
1548
+ /**
1549
+ * `'prefix'` when the cold start this run paid for failed with one of the
1550
+ * prefix's own, repeatable errors (`ERR_USER_CODE`, `ERR_MODULE_NOT_FOUND`,
1551
+ * `ERR_IMPORT`, `ERR_PREFIX_BRIDGE_CALL`, `ERR_PREFIX_DID_NOT_SETTLE`), so
1552
+ * the failure is the prefix's, not the run code's. Absent for run-code
1553
+ * failures and for load-dependent cold-start failures (`ERR_WARMUP_LIMIT`,
1554
+ * `ERR_MEMORY_LIMIT`), which do not break the prefix. The same run moves
1555
+ * {@link Prefix.status} to `'broken'` (DESIGN.md §16.4).
1556
+ */
1557
+ stage?: "prefix";
1489
1558
  }
1490
1559
  /**
1491
1560
  * Why a shared instance was reset under an innocent victim — see
1492
- * `RunError.resetCause`.
1561
+ * `RunError.resetCause`. Every cause describes what the culprit run
1562
+ * (`culpritRunId`) did, never this run.
1563
+ *
1564
+ * `'unsupported'`: the culprit used something the runtime does not support
1565
+ * (today: dynamic `import()`), so the runtime ended it.
1493
1566
  */
1494
- type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
1567
+ type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal" | "unsupported";
1495
1568
  /**
1496
1569
  * Why a run's options were refused before anything ran. `sandbox.run()`,
1497
1570
  * `prefix.run()`, `prefix.call()` and `prepare()` reject with an `Error`
@@ -1501,15 +1574,16 @@ type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
1501
1574
  * answer the same way. `ERR_PREFIX_DISPOSED`: the prefix was disposed, or the
1502
1575
  * runtime no longer holds it.
1503
1576
  */
1504
- type SetupErrorCode = "ERR_PREFIX_DISPOSED" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND";
1577
+ type SetupErrorCode = "ERR_PREFIX_DISPOSED" | "ERR_PREFIX_BROKEN" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND";
1505
1578
  /**
1506
1579
  * Why a run failed, in a `{ ok: false }` result. Setup refusals are thrown
1507
- * instead and carry a {@link SetupErrorCode}. `prepare()` and
1508
- * `readExports()` reject on any failure.
1580
+ * instead and carry a {@link SetupErrorCode}. `readExports()` rejects on
1581
+ * any failure; `prepare()` never runs anything, so a broken prefix reports
1582
+ * these on its first run.
1509
1583
  */
1510
- 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_MEMORY" | "ERR_QUEUE_FULL" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1584
+ type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_IMPORT" | "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_MEMORY" | "ERR_QUEUE_FULL" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1511
1585
  //#endregion
1512
1586
  //#region src/index.d.ts
1513
1587
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
1514
1588
  //#endregion
1515
- export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, 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 SetupErrorCode, type StringGlobal, type WaitUntilResult, createSandbox };
1589
+ export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, 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 PrefixStatus, 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 SetupErrorCode, type StringGlobal, type WaitUntilResult, createSandbox };
package/dist/index.mjs CHANGED
@@ -1093,6 +1093,10 @@ var PayloadDecodeError = class extends Error {
1093
1093
  var PayloadReader = class {
1094
1094
  view;
1095
1095
  offset = 0;
1096
+ /**
1097
+ * Byte length of the blob the last `readValueBlob()` consumed.
1098
+ */
1099
+ lastValueBlobBytes = 0;
1096
1100
  constructor(buf) {
1097
1101
  this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1098
1102
  }
@@ -1181,7 +1185,8 @@ var PayloadReader = class {
1181
1185
  * Read a value slot: `u32 byteLength` + V8 serialization blob.
1182
1186
  */
1183
1187
  readValueBlob() {
1184
- return deserializeValue(this.readRawBytes(this.readU32()));
1188
+ this.lastValueBlobBytes = this.readU32();
1189
+ return deserializeValue(this.readRawBytes(this.lastValueBlobBytes));
1185
1190
  }
1186
1191
  /**
1187
1192
  * Read an `Optional<value slot>`: a presence byte, then the slot when set.
@@ -1310,6 +1315,7 @@ function decodeBridgeCallPayload(buf) {
1310
1315
  };
1311
1316
  const decoded = reader.readValueBlob();
1312
1317
  if (!Array.isArray(decoded)) throw new PayloadDecodeError(`BridgeCall args must decode to an array, got ${decoded === null ? "null" : typeof decoded}`);
1318
+ assertNoArrayHoles(decoded, reader.lastValueBlobBytes);
1313
1319
  return {
1314
1320
  runId,
1315
1321
  callId,
@@ -1318,6 +1324,50 @@ function decodeBridgeCallPayload(buf) {
1318
1324
  };
1319
1325
  }
1320
1326
  /**
1327
+ * Refuse bridge arguments holding an array with holes, at any depth
1328
+ * (DESIGN.md §12.1). A dense slot costs at least one wire byte, so array
1329
+ * lengths summing past the blob size prove a hole before any index is read.
1330
+ * @param args the decoded argument list
1331
+ * @param blobBytes byte length of the value blob the arguments arrived in
1332
+ */
1333
+ function assertNoArrayHoles(args, blobBytes) {
1334
+ const seen = /* @__PURE__ */ new Set();
1335
+ const stack = [args];
1336
+ let slots = 0;
1337
+ for (let v = stack.pop(); v !== void 0; v = stack.pop()) {
1338
+ if (seen.has(v)) continue;
1339
+ seen.add(v);
1340
+ if (Array.isArray(v)) {
1341
+ slots += v.length;
1342
+ if (slots > blobBytes) throw new PayloadDecodeError("bridge call argument contains an array with holes");
1343
+ for (let i = 0; i < v.length; i++) {
1344
+ if (!(i in v)) throw new PayloadDecodeError("bridge call argument contains an array with holes");
1345
+ const item = v[i];
1346
+ if (item !== null && typeof item === "object") stack.push(item);
1347
+ }
1348
+ const keys = Object.keys(v);
1349
+ for (let j = v.length; j < keys.length; j++) {
1350
+ const item = v[keys[j]];
1351
+ if (item !== null && typeof item === "object") stack.push(item);
1352
+ }
1353
+ continue;
1354
+ }
1355
+ const proto = Object.getPrototypeOf(v);
1356
+ if (proto === Object.prototype || proto === null) for (const key in v) {
1357
+ const item = v[key];
1358
+ if (item !== null && typeof item === "object") stack.push(item);
1359
+ }
1360
+ else if (v instanceof Map) {
1361
+ for (const k of v.keys()) if (k !== null && typeof k === "object") stack.push(k);
1362
+ for (const item of v.values()) if (item !== null && typeof item === "object") stack.push(item);
1363
+ } else if (v instanceof Set) {
1364
+ for (const item of v) if (item !== null && typeof item === "object") stack.push(item);
1365
+ } else if (v instanceof Error) {
1366
+ if (v.cause !== null && typeof v.cause === "object") stack.push(v.cause);
1367
+ }
1368
+ }
1369
+ }
1370
+ /**
1321
1371
  * Build a `BridgeErrorPayload` from whatever a host handler threw.
1322
1372
  *
1323
1373
  * Own-enumerable properties beyond `name`/`message`/`stack` travel as
@@ -1680,6 +1730,8 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
1680
1730
  const stack = reader.readU8() === 1 ? reader.readString() : void 0;
1681
1731
  const fields = reader.readOptionalValueBlob();
1682
1732
  const reset = readResetInfo(reader);
1733
+ const stage = readPrefixStage(reader);
1734
+ const prefixCause = readErrorCause(reader);
1683
1735
  const stdout = reader.readStringList();
1684
1736
  const stderr = reader.readStringList();
1685
1737
  const durationMs = reader.readF64();
@@ -1701,7 +1753,8 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
1701
1753
  message,
1702
1754
  stack,
1703
1755
  fields,
1704
- ...reset
1756
+ ...reset,
1757
+ ...stage
1705
1758
  },
1706
1759
  stdout,
1707
1760
  stderr,
@@ -1710,7 +1763,45 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
1710
1763
  cpuTimeMs,
1711
1764
  bridgeCalls,
1712
1765
  heapUsedBytes
1713
- }
1766
+ },
1767
+ ...prefixCause === void 0 ? {} : { prefixCause }
1768
+ };
1769
+ }
1770
+ /**
1771
+ * The stage byte trailing every `RunErrorPayload`: `1` when the prefix failed
1772
+ * to evaluate on this run's cold start. A spreadable fragment, so run-stage
1773
+ * errors add nothing.
1774
+ * @param reader
1775
+ */
1776
+ function readPrefixStage(reader) {
1777
+ const byte = reader.readU8();
1778
+ if (byte === 0) return {};
1779
+ if (byte !== 1) throw new PayloadDecodeError(`invalid prefix-stage byte: ${byte}`);
1780
+ return { stage: "prefix" };
1781
+ }
1782
+ /**
1783
+ * The optional cause trailing every `RunErrorPayload`, present only on an
1784
+ * `ERR_PREFIX_BROKEN` refusal: the stored cold-start failure's code, name,
1785
+ * message and stack.
1786
+ * @param reader
1787
+ */
1788
+ function readErrorCause(reader) {
1789
+ const present = reader.readU8();
1790
+ if (present === 0) return void 0;
1791
+ if (present !== 1) throw new PayloadDecodeError(`invalid error-cause presence byte: ${present}`);
1792
+ const code = reader.readString();
1793
+ const name = reader.readString();
1794
+ const message = reader.readString();
1795
+ const stack = reader.readU8() === 1 ? reader.readString() : void 0;
1796
+ return stack === void 0 ? {
1797
+ code,
1798
+ name,
1799
+ message
1800
+ } : {
1801
+ code,
1802
+ name,
1803
+ message,
1804
+ stack
1714
1805
  };
1715
1806
  }
1716
1807
  /**
@@ -1729,7 +1820,8 @@ function readResetInfo(reader) {
1729
1820
  "memory",
1730
1821
  "abort",
1731
1822
  "internal",
1732
- "wall"
1823
+ "wall",
1824
+ "unsupported"
1733
1825
  ][causeByte];
1734
1826
  if (resetCause === void 0) throw new PayloadDecodeError(`invalid instance-reset cause byte: ${causeByte}`);
1735
1827
  return {
@@ -1840,6 +1932,8 @@ function decodePrecompileResultPayload(buf) {
1840
1932
  const stack = reader.readU8() === 1 ? reader.readString() : void 0;
1841
1933
  reader.readOptionalValueBlob();
1842
1934
  readResetInfo(reader);
1935
+ readPrefixStage(reader);
1936
+ readErrorCause(reader);
1843
1937
  reader.assertDone();
1844
1938
  return {
1845
1939
  ok: false,
@@ -2058,10 +2152,8 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2058
2152
  */
2059
2153
  controlWaiters = [];
2060
2154
  /**
2061
- * Pending `precompile()` requests keyed by their wire `requestId`.
2062
- * Precompiles are answered on runtime worker threads, so with several in
2063
- * flight on one connection the replies can return out of request order —
2064
- * FIFO matching would cross-assign prefix ids between callers.
2155
+ * Pending `precompile()` requests keyed by their wire `requestId`, so a
2156
+ * reply is matched by id and never by arrival order.
2065
2157
  */
2066
2158
  precompileWaiters = /* @__PURE__ */ new Map();
2067
2159
  /**
@@ -3862,7 +3954,8 @@ const SETUP_ERROR_CODES = new Set([
3862
3954
  "ERR_UNDECLARED_BINDING",
3863
3955
  "ERR_FROZEN_BINDING",
3864
3956
  "ERR_INVALID_REBIND",
3865
- "ERR_PREFIX_DISPOSED"
3957
+ "ERR_PREFIX_DISPOSED",
3958
+ "ERR_PREFIX_BROKEN"
3866
3959
  ]);
3867
3960
  /**
3868
3961
  * The error `prepare()`, `readExports()` and `run()` throw for a failure the
@@ -4026,8 +4119,8 @@ var SandboxImpl = class {
4026
4119
  }
4027
4120
  /**
4028
4121
  * Load a module once and read its serializable exports — the deploy path.
4029
- * Function exports are skipped and reported; failures reject, like
4030
- * `prepare()`. See {@link Sandbox.readExports}.
4122
+ * Function exports are skipped and reported; failures reject. See
4123
+ * {@link Sandbox.readExports}.
4031
4124
  * @param options
4032
4125
  */
4033
4126
  async readExports(options) {
@@ -4050,11 +4143,12 @@ var SandboxImpl = class {
4050
4143
  return this.prepare(options);
4051
4144
  }
4052
4145
  /**
4053
- * Validate and prepare a prefix for repeated runs. See
4146
+ * Store a prefix for repeated runs; nothing is evaluated. See
4054
4147
  * {@link Sandbox.prepare}.
4055
4148
  * @param options
4056
4149
  */
4057
4150
  async prepare(options) {
4151
+ if (typeof options.code !== "string") throw new TypeError(`prepare({ code }) must be a string, got ${options.code === null ? "null" : typeof options.code}`);
4058
4152
  validateMemoryMb(options.memoryMb, "memoryMb");
4059
4153
  validateLimits(options.limits);
4060
4154
  const prefixMemoryMb = options.memoryMb ?? this.memoryMb;
@@ -4075,7 +4169,7 @@ var SandboxImpl = class {
4075
4169
  imports: bindings
4076
4170
  }));
4077
4171
  if (!result.ok) throw thrownRunError(result.error);
4078
- return new PrefixImpl(result.prefixId, this.pool, declaredGlobals, handlers, declaredImportShape(bindings), this.brandKey, prefixMemoryMb);
4172
+ return new PrefixImpl(result.prefixId, this.pool, declaredGlobals, handlers, declaredImportShape(bindings), this.brandKey, prefixMemoryMb, wireLimits(options.limits));
4079
4173
  });
4080
4174
  }
4081
4175
  async dispose() {
@@ -4121,11 +4215,20 @@ var PrefixImpl = class {
4121
4215
  */
4122
4216
  memoryMb;
4123
4217
  /**
4218
+ * `prepare({ limits })` snapshot: the per-run defaults, overridden field by field.
4219
+ */
4220
+ defaultLimits;
4221
+ /**
4124
4222
  * Session brand key for host-type descriptors — see `SandboxImpl`.
4125
4223
  */
4126
4224
  brandKey;
4127
- _alive = true;
4128
- constructor(id, pool, declaredGlobals, defaultImportHandlers, declaredImports, brandKey, memoryMb) {
4225
+ _status = "ready";
4226
+ /**
4227
+ * The cold-start failure that broke this prefix, cached from the first
4228
+ * result or refusal that reported it; later runs throw it without a round trip.
4229
+ */
4230
+ _error;
4231
+ constructor(id, pool, declaredGlobals, defaultImportHandlers, declaredImports, brandKey, memoryMb, defaultLimits = {}) {
4129
4232
  this.id = id;
4130
4233
  this.pool = pool;
4131
4234
  this.declaredGlobals = declaredGlobals;
@@ -4133,9 +4236,34 @@ var PrefixImpl = class {
4133
4236
  this.declaredImports = declaredImports;
4134
4237
  this.brandKey = brandKey;
4135
4238
  this.memoryMb = memoryMb;
4239
+ this.defaultLimits = defaultLimits;
4136
4240
  }
4137
4241
  get alive() {
4138
- return this._alive;
4242
+ return this._status !== "disposed";
4243
+ }
4244
+ get status() {
4245
+ return this._status;
4246
+ }
4247
+ get error() {
4248
+ return this._error;
4249
+ }
4250
+ /**
4251
+ * Remember the prefix-stage failure that broke this prefix. Disposal wins.
4252
+ * @param error the stored cold-start failure
4253
+ */
4254
+ markBroken(error) {
4255
+ if (this._status !== "ready") return;
4256
+ this._status = "broken";
4257
+ this._error = error;
4258
+ }
4259
+ /**
4260
+ * The `ERR_PREFIX_BROKEN` refusal, with the cold-start failure as `cause`.
4261
+ * @param cause the stored failure, or the one a runtime refusal carried
4262
+ */
4263
+ brokenError(cause = this._error) {
4264
+ const err = setupError("ERR_PREFIX_BROKEN", `prefix '${this.id}' is broken: its cold start failed with ${cause?.code}: ${cause?.message}`);
4265
+ err.cause = cause;
4266
+ return err;
4139
4267
  }
4140
4268
  /**
4141
4269
  * Execute dynamic code against this prefix. See
@@ -4179,7 +4307,8 @@ var PrefixImpl = class {
4179
4307
  * @param buildPayload
4180
4308
  */
4181
4309
  async dispatch(options, buildPayload) {
4182
- if (!this._alive) throw setupError("ERR_PREFIX_DISPOSED", `prefix '${this.id}' has been disposed or never existed`);
4310
+ if (this._status === "disposed") throw setupError("ERR_PREFIX_DISPOSED", `prefix '${this.id}' has been disposed or never existed`);
4311
+ if (this._status === "broken") throw this.brokenError();
4183
4312
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
4184
4313
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
4185
4314
  validateLimits(options.limits);
@@ -4201,6 +4330,7 @@ var PrefixImpl = class {
4201
4330
  code: payload.code,
4202
4331
  filename: options.filename,
4203
4332
  limits: {
4333
+ ...this.defaultLimits,
4204
4334
  ...wireLimits(options.limits),
4205
4335
  ...heapCapsForWire(this.memoryMb)
4206
4336
  },
@@ -4213,7 +4343,13 @@ var PrefixImpl = class {
4213
4343
  call: payload.call,
4214
4344
  streams
4215
4345
  });
4216
- const decoded = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => payload.call === void 0 ? decodeRunCompletionPayload(raw.result, void 0, raw.droppedCallIds).result : decodeRunCompletionPayload(raw.result, "call", raw.droppedCallIds).result);
4346
+ const completion = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => payload.call === void 0 ? decodeRunCompletionPayload(raw.result, void 0, raw.droppedCallIds) : decodeRunCompletionPayload(raw.result, "call", raw.droppedCallIds));
4347
+ const decoded = completion.result;
4348
+ if (decoded.status === "failed" && decoded.error.code === "ERR_PREFIX_BROKEN") {
4349
+ if (completion.prefixCause !== void 0) this.markBroken(completion.prefixCause);
4350
+ throw this.brokenError(completion.prefixCause ?? this._error);
4351
+ }
4352
+ if (decoded.status === "failed" && decoded.error.stage === "prefix") this.markBroken(decoded.error);
4217
4353
  if (decoded.status === "failed" && SETUP_ERROR_CODES.has(decoded.error.code)) throw thrownRunError({
4218
4354
  ...decoded.error,
4219
4355
  code: decoded.error.code
@@ -4234,8 +4370,8 @@ var PrefixImpl = class {
4234
4370
  }
4235
4371
  }
4236
4372
  async dispose() {
4237
- if (!this._alive) return;
4238
- this._alive = false;
4373
+ if (this._status === "disposed") return;
4374
+ this._status = "disposed";
4239
4375
  this.declaredGlobals = /* @__PURE__ */ new Map();
4240
4376
  this.defaultImportHandlers = /* @__PURE__ */ new Map();
4241
4377
  this.declaredImports = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iso4/sandbox",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Two-process architecture for crash isolation.",
6
6
  "keywords": [
@@ -53,10 +53,10 @@
53
53
  "vitest": "^4.1.5"
54
54
  },
55
55
  "optionalDependencies": {
56
- "@iso4/v8-darwin-arm64": "^0.8.1",
57
- "@iso4/v8-darwin-x64": "^0.8.1",
58
- "@iso4/v8-linux-arm64-gnu": "^0.8.1",
59
- "@iso4/v8-linux-x64-gnu": "^0.8.1"
56
+ "@iso4/v8-darwin-arm64": "^0.9.0",
57
+ "@iso4/v8-darwin-x64": "^0.9.0",
58
+ "@iso4/v8-linux-arm64-gnu": "^0.9.0",
59
+ "@iso4/v8-linux-x64-gnu": "^0.9.0"
60
60
  },
61
61
  "engines": {
62
62
  "node": ">=24.0.0"