@iso4/sandbox 0.8.0 → 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' }
@@ -70,7 +70,7 @@ await sandbox.dispose()
70
70
 
71
71
  ## How globals work
72
72
 
73
- `globals` wires any non-reserved identifier directly into the sandbox's global
73
+ `globals` wires any non-reserved name directly into the sandbox's global
74
74
  object as a bridge stub. The bridge is fully generic — `fetch` is not
75
75
  special-cased:
76
76
 
@@ -88,16 +88,67 @@ const options = {
88
88
  Functions in bridge return values are currently dropped — return plain data,
89
89
  not class instances with methods.
90
90
 
91
- Global names must be usable by bare name: iso4 refuses one that is not a
92
- JavaScript identifier (`my-tool`) or is a reserved word (`class`, `true`)
93
- with `ERR_INVALID_GLOBAL_NAME`. Unicode identifiers (`café`) and `eval` and
94
- `arguments` are allowed.
91
+ A global name can be any well-formed string the runtime does not reserve.
92
+ One that is not a JavaScript identifier
93
+ (`my-tool`, `user.lookup`) or is a reserved word (`class`) is reachable only
94
+ as `globalThis['my-tool']`, not by bare name.
95
+
96
+ `@iso4/sandbox/utils` exports the name rules. `SANDBOX_GLOBALS` is a `Set`
97
+ of every name a fresh sandbox already defines. Check generated names against
98
+ it before installing them. `RESERVED_WORDS` is a `Set` of names that cannot be
99
+ a binding in module source, such as `class` or `eval`; iso4 refuses
100
+ host-module export names in it, except `default`.
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):
95
110
 
96
- `SANDBOX_GLOBALS` is a `Set` of every name a fresh sandbox already defines.
97
- Check generated names against it before installing them. `RESERVED_WORDS`
98
- is a `Set` of names that cannot be a binding in module source, such as
99
- `class` or `eval`; iso4 refuses host-module export names in it, and global
100
- names in it other than `eval` and `arguments`.
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
+
126
+ To check generated names before `prepare()` instead of getting a failed
127
+ setup back, import the predicates from `@iso4/sandbox/utils`. That entry
128
+ never loads the client or the native binary:
129
+
130
+ ```ts
131
+ import { isValidExportName, isValidGlobalName } from '@iso4/sandbox/utils'
132
+
133
+ for (const name of Object.keys(tools)) {
134
+ if (!isValidExportName(name))
135
+ throw new Error(`'${name}' cannot be a host-module export`)
136
+ }
137
+ if (!isValidGlobalName(globalName))
138
+ throw new Error(`'${globalName}' cannot be a host global`)
139
+ ```
140
+
141
+ `isValidExportName` answers whether a string can be a key of a host-module
142
+ object in `imports`: an identifier per `IDENTIFIER_NAME` (Unicode included,
143
+ so `café` is fine) that is not in `RESERVED_WORDS`, or `default`, which maps
144
+ to the module's default export. `default` cannot be written as
145
+ `export const default` in generated source. `isValidGlobalName` is the check `prepare()` and
146
+ `run()` apply to host global names: any well-formed string except the
147
+ runtime-owned names (`console`, `Response`, `NaN`, …), a copy of the
148
+ runtime's list that a test checks against the runtime. Names starting with
149
+ `__iso4_` are iso4's internal namespace (the dispatcher, shim handlers): a
150
+ host global there may be silently overwritten or dropped, and
151
+ `isValidGlobalName` does not flag it.
101
152
 
102
153
  ## TypeScript-checked rebinding
103
154
 
@@ -115,7 +166,16 @@ prefix.execute({ globals: { unknown: handler } }) // ❌ TS error
115
166
 
116
167
  ## Resource limits
117
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
+
118
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
+
119
179
  prefix.execute({
120
180
  code: agentCode,
121
181
  limits: {
@@ -163,7 +223,7 @@ one call at a time, so concurrency means more instances (the engine can
163
223
  already interleave several runs on one instance — that switches on with
164
224
  wire multiplexing). Top-level names never collide across runs
165
225
  (each run is its own module). A prefix that can't finish evaluating under
166
- the fixed warm-up budget is rejected by `prepare()` with
226
+ the fixed warm-up budget fails the cold-starting call with
167
227
  `ERR_WARMUP_LIMIT`. `console.*` from prefix evaluation arrives on the
168
228
  cold-starting call's result.
169
229
 
@@ -386,14 +446,50 @@ interface RunError {
386
446
  message: string
387
447
  stack?: string
388
448
  fields?: Record<string, unknown> // all other own-enumerable props of the thrown error
389
- resetCause?: 'cpu' | 'memory' | 'wall' | 'abort' | 'internal' // ERR_INSTANCE_RESET only
449
+ resetCause?: 'cpu' | 'memory' | 'wall' | 'abort' | 'internal' | 'unsupported' // ERR_INSTANCE_RESET only
390
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
391
452
  }
392
453
  ```
393
454
 
394
- `run()` never throws for sandboxed failures — only for infrastructure errors
395
- (subprocess crashed, binary not found). `ok: false` with an error code is the
396
- normal failure path.
455
+ `run()` never throws for sandboxed failures. `ok: false` with an error code is
456
+ the normal failure path. It throws only for infrastructure errors (subprocess
457
+ crashed, binary not found) and for invalid options, the same way `prepare()`
458
+ does. `sandbox.run()`, `prefix.run()` and `prefix.call()` reject with an
459
+ `Error` whose `code` is a `SetupErrorCode`: `ERR_RESERVED_NAME` (a global
460
+ name the runtime owns), `ERR_UNDECLARED_BINDING`, `ERR_FROZEN_BINDING` or
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
465
+ the runtime repeats the checks. A malformed option, such as a limit out of range or a
466
+ global name that is not a well-formed string, rejects with a plain
467
+ `TypeError`. Nothing ran, so retrying with the same options can never
468
+ succeed. Every other code, including a syntax error (`ERR_USER_CODE`
469
+ named `SyntaxError`), is a result.
470
+
471
+ ```ts
472
+ import type { SetupErrorCode } from '@iso4/sandbox'
473
+
474
+ const setupCodes: readonly string[] = [
475
+ 'ERR_RESERVED_NAME',
476
+ 'ERR_UNDECLARED_BINDING',
477
+ 'ERR_FROZEN_BINDING',
478
+ 'ERR_INVALID_REBIND',
479
+ 'ERR_PREFIX_DISPOSED',
480
+ 'ERR_PREFIX_BROKEN',
481
+ ] satisfies SetupErrorCode[]
482
+
483
+ try {
484
+ const result = await sandbox.run({ code, globals })
485
+ if (!result.ok)
486
+ console.log('the program failed:', result.error.code)
487
+ } catch (error) {
488
+ if (!(error instanceof Error && 'code' in error && setupCodes.includes(error.code as string)))
489
+ throw error
490
+ console.log('the options are wrong:', error.code as SetupErrorCode)
491
+ }
492
+ ```
397
493
 
398
494
  One code is about a _neighbor_, not your own run: `ERR_INSTANCE_RESET` means a
399
495
  run sharing the same warm instance had to be terminated mid-execution
package/dist/index.d.mts CHANGED
@@ -12,18 +12,6 @@
12
12
  * parallel. See DESIGN.md §1 and §13.
13
13
  */
14
14
  /**
15
- * Per-run resource caps. Every field is optional at the call site
16
- * (`limits?: ResourceLimits`): pass only the limits you want to
17
- * override. The client sends just those over the wire and the **runtime owns
18
- * the defaults** — it fills in any field you leave unset. The `@default` values
19
- * documented below mirror the runtime's defaults (defined in
20
- * `native/v8-runtime/src/ipc.rs`, the source of truth); if they ever drift, the
21
- * runtime wins.
22
- *
23
- * A field set to `0` is not the same as leaving it unset: `0` explicitly
24
- * disables that limit, whereas unset yields the runtime default.
25
- */
26
- /**
27
15
  * The two heap lines a REUSED isolate is held to, when the managed default
28
16
  * is not what you want. One-off `run()` isolates are never reused and take a
29
17
  * plain `memoryMb` number, enforced exactly.
@@ -78,6 +66,22 @@ interface OneOffResourceLimits extends ResourceLimits {
78
66
  */
79
67
  memoryMb?: number;
80
68
  }
69
+ /**
70
+ * Per-run resource caps. Every field is optional at the call site
71
+ * (`limits?: ResourceLimits`): pass only the limits you want to
72
+ * override. The client sends just those over the wire and the **runtime owns
73
+ * the defaults** — it fills in any field you leave unset. The `@default` values
74
+ * documented below mirror the runtime's defaults (defined in
75
+ * `native/v8-runtime/src/ipc.rs`, the source of truth); if they ever drift, the
76
+ * runtime wins.
77
+ *
78
+ * A field set to `0` is not the same as leaving it unset: `0` explicitly
79
+ * disables that limit, whereas unset yields the runtime default.
80
+ *
81
+ * Every field must be an integer from `0` to `2³² − 1`. Anything else
82
+ * (negative, fractional, `NaN`, `Infinity`, a non-number) rejects the call
83
+ * with a `TypeError` before anything runs.
84
+ */
81
85
  interface ResourceLimits {
82
86
  /**
83
87
  * Maximum CPU time in milliseconds — what the run's own thread actually
@@ -161,24 +165,29 @@ interface ResourceLimits {
161
165
  graceMs?: number;
162
166
  }
163
167
  /**
164
- * Host-provided globals. Any name not reserved by the runtime that sandbox
165
- * code can reference by bare name is permitted. Each value becomes a bridge
166
- * stub in the sandbox global object.
168
+ * Host-provided globals. Any string not reserved by the runtime is permitted
169
+ * as a name. Each value becomes a property of the sandbox's `globalThis`.
167
170
  *
168
171
  * Reserved names (rejected with `ERR_RESERVED_NAME`): `console`,
169
172
  * `waitUntil`, `setTimeout`, `clearTimeout`, `Headers`, `Request`,
170
- * `Response`, `TextEncoder`, `TextDecoder`, `URL`, `URLSearchParams`. These
171
- * are owned by the runtime; shadowing `Response` would silently break
172
- * serialization.
173
+ * `Response`, `TextEncoder`, `TextDecoder`, `URL`, `URLSearchParams`, plus
174
+ * `NaN`, `undefined`, `Infinity` and `__proto__`. The first are owned by the
175
+ * runtime; shadowing `Response` would silently break serialization. `NaN`,
176
+ * `undefined` and `Infinity` are non-writable on the global object, so a host
177
+ * global could never take effect; assigning `__proto__` replaces a prototype
178
+ * instead of creating a property.
173
179
  *
174
- * A name sandbox code cannot reference by bare name is rejected with
175
- * `ERR_INVALID_GLOBAL_NAME`: one that is not a JavaScript identifier
176
- * (`my-tool`, `1abc`; Unicode identifiers such as `café` are fine), or one in
177
- * {@link RESERVED_WORDS} other than `eval` and `arguments`. Keys nested inside
178
- * a global's value are unrestricted.
180
+ * A name that is not a JavaScript identifier (`my-tool`, `user.lookup`), or
181
+ * is in `RESERVED_WORDS` other than `eval` and `arguments`, is
182
+ * reachable only as `globalThis[name]`, not by bare name. A name that is
183
+ * not a well-formed string (`'y\uD800'`) throws a `TypeError` before
184
+ * anything is sent. Names starting with `__iso4_` are iso4's internal
185
+ * namespace (the dispatcher, shim handlers): a host global there may be
186
+ * silently overwritten or dropped, and `isValidGlobalName` does not flag it.
179
187
  *
180
- * {@link SANDBOX_GLOBALS} holds every name a fresh sandbox defines, V8
181
- * built-ins included.
188
+ * `SANDBOX_GLOBALS` holds every name a fresh sandbox defines, V8 built-ins
189
+ * included. Both sets and `isValidGlobalName`, which checks a name before
190
+ * `prepare()`, come from `@iso4/sandbox/utils`.
182
191
  *
183
192
  * Common usage:
184
193
  * ```ts
@@ -357,7 +366,9 @@ type RebindValue<V extends HostGlobalValue> = V extends BridgeWithShim<infer H>
357
366
  type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string | DataGlobal | StringGlobal ? never : K]?: RebindValue<G[K]> };
358
367
  /**
359
368
  * Top-level `imports` shape. Keys are import specifiers; values are either
360
- * a source string or a host-module description object.
369
+ * a source string or a host-module description object. A specifier that is
370
+ * not a well-formed string (`'x\uD800'`) throws a `TypeError` before
371
+ * anything is sent.
361
372
  *
362
373
  * `M` is the literal shape of the map. `precompile()` infers it from the
363
374
  * object literal so the declared specifiers and their value shapes flow
@@ -426,7 +437,9 @@ type HostExportData = null | undefined | boolean | number | bigint | string | Da
426
437
  * Args and return are `unknown` — the bridge serialises/deserialises values
427
438
  * with V8 ValueSerializer; we don't try to model that at the type level.
428
439
  * The one invariant that matters (functions cannot cross the boundary as
429
- * 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.
430
443
  *
431
444
  * Use specific function types for your handlers and let TypeScript infer
432
445
  * them through `HostGlobals`, `RebindGlobals<G>`, and `RebindImports<M>`.
@@ -703,6 +716,14 @@ interface Sandbox {
703
716
  * call: { export: 'default.fetch', args: [request] },
704
717
  * })
705
718
  * ```
719
+ *
720
+ * Invalid options reject, like `prepare()`: a global name the runtime owns
721
+ * rejects with an `Error` whose `code` is `ERR_RESERVED_NAME`; a malformed
722
+ * option (a bad limit or `memoryMb`, a global name that is not a
723
+ * well-formed string, an invalid host-module shape) rejects with a plain
724
+ * `Error`/`TypeError`.
725
+ * Nothing ran. Everything that happens once the run starts resolves as
726
+ * `{ ok: false, error }` — see {@link RunErrorCode}.
706
727
  */
707
728
  run: {
708
729
  (options: RunCallOptions): Promise<CallResult>;
@@ -713,12 +734,32 @@ interface Sandbox {
713
734
  * deploy/registration path (IaC-style declaration exports read when a
714
735
  * function is created, never per request). Builds no prefix and retains
715
736
  * nothing. Function exports are skipped and reported, so a module that
716
- * also exports handlers reads cleanly. Rejects on compile/runtime errors,
717
- * 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.
718
739
  */
719
740
  readExports: (options: ReadExportsOptions) => Promise<ReadExportsResult>;
720
741
  /**
721
- * 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
+ * ```
722
763
  *
723
764
  * The type parameter `G` is inferred from the `globals` you pass and flows
724
765
  * into the returned `Prefix<G>`. This lets TypeScript enforce at the call
@@ -819,14 +860,14 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
819
860
  */
820
861
  imports?: M;
821
862
  /**
822
- * 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`.
823
868
  *
824
- * **Currently a no-op placeholder.** Pass limits directly to each
825
- * `prefix.run()` call. The one budget that DOES apply here is not
826
- * configurable: prefix evaluation runs under the fixed warm-up budget
827
- * (1 s wall / 1 s CPU) — a prefix that cannot evaluate inside it is
828
- * rejected with `ERR_WARMUP_LIMIT` at `prepare()` time, because it could
829
- * 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.
830
871
  */
831
872
  limits?: ResourceLimits;
832
873
  /**
@@ -893,23 +934,52 @@ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
893
934
  */
894
935
  call: (options: PrefixCallOptions<G, M>) => Promise<CallResult>;
895
936
  /**
896
- * 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.
897
939
  */
898
940
  dispose: () => Promise<void>;
899
941
  /**
900
942
  * Enables `await using prefix = await sandbox.precompile(...)` syntax.
901
943
  */
902
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
+ */
903
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;
904
966
  }
905
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
+ /**
906
976
  * Options for `prefix.run()`.
907
977
  *
908
978
  * `G` is the declared-globals shape from the matching `precompile()` call.
909
979
  * The `globals` field is typed as `Partial<G>` — only names present in `G`
910
980
  * may be overridden. Passing any other name is a TypeScript error at compile
911
- * time and `ERR_UNDECLARED_BINDING` at runtime (`ERR_INVALID_GLOBAL_NAME`
912
- * first, for a name sandbox code cannot reference by bare name).
981
+ * time and rejects with `ERR_UNDECLARED_BINDING` at runtime. Every rebind
982
+ * refusal rejects; nothing runs.
913
983
  */
914
984
  interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
915
985
  /**
@@ -919,8 +989,8 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
919
989
  /**
920
990
  * Override implementations for a **subset** of globals declared at
921
991
  * precompile time. Only names present in `G` are accepted (TypeScript
922
- * error + runtime `ERR_UNDECLARED_BINDING` for anything else, or
923
- * `ERR_INVALID_GLOBAL_NAME` for a name unusable by bare name), but the
992
+ * error + a runtime rejection with `ERR_UNDECLARED_BINDING` for anything
993
+ * else), but the
924
994
  * function signature does not need to match the precompile-time handler
925
995
  * exactly — any `HostExportFunction`-compatible value is accepted.
926
996
  */
@@ -930,11 +1000,15 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
930
1000
  * Source module imports are frozen at prepare() time and cannot be rebound;
931
1001
  * data exports are baked into the synthetic module. TypeScript enforces
932
1002
  * this at the type level via `RebindImports<M>`; anything that slips
933
- * through is rejected at runtime — `ERR_UNDECLARED_BINDING` for locations
1003
+ * through rejects the run at runtime — `ERR_UNDECLARED_BINDING` for locations
934
1004
  * never declared, `ERR_FROZEN_BINDING` for source modules and data leaves,
935
1005
  * `ERR_INVALID_REBIND` for a non-function override value.
936
1006
  */
937
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
+ */
938
1012
  limits?: ResourceLimits;
939
1013
  /**
940
1014
  * Abort the run. Firing this is always SOFT: while queued the caller is
@@ -976,6 +1050,10 @@ interface PrefixCallOptions<G extends HostGlobals, M extends Imports> extends Ca
976
1050
  * rules as {@link PrefixRunOptions.imports}.
977
1051
  */
978
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
+ */
979
1057
  limits?: ResourceLimits;
980
1058
  /**
981
1059
  * Abort the run. Firing this is always SOFT: while queued the caller is
@@ -1078,8 +1156,8 @@ interface ReadExportsOptions {
1078
1156
  }
1079
1157
  /**
1080
1158
  * What `sandbox.readExports()` resolves to. Unlike `run()`, failures reject
1081
- * the returned promise (like `prepare()`), since the deploy path treats a
1082
- * 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.
1083
1161
  */
1084
1162
  interface ReadExportsResult {
1085
1163
  exports: SandboxExports;
@@ -1467,34 +1545,45 @@ interface RunError {
1467
1545
  * the victims of one reset, so they can be correlated.
1468
1546
  */
1469
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";
1470
1558
  }
1471
1559
  /**
1472
1560
  * Why a shared instance was reset under an innocent victim — see
1473
- * `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.
1474
1566
  */
1475
- type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
1476
- 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_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_INVALID_GLOBAL_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";
1477
- //#endregion
1478
- //#region src/globals.d.ts
1567
+ type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal" | "unsupported";
1479
1568
  /**
1480
- * Every global name a fresh sandbox defines: the JS built-ins of the bundled
1481
- * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
1482
- * A host global under one of these names replaces the built-in, or is
1483
- * silently ignored for `undefined`, `NaN` and `Infinity`. Names the grammar
1484
- * forbids outright are in {@link RESERVED_WORDS}.
1569
+ * Why a run's options were refused before anything ran. `sandbox.run()`,
1570
+ * `prefix.run()`, `prefix.call()` and `prepare()` reject with an `Error`
1571
+ * whose `code` is one of these; a run never returns them as a result. The
1572
+ * client checks first and throws without a runtime round trip; the runtime
1573
+ * repeats every check (except `ERR_INVALID_REBIND`) and the client throws its
1574
+ * answer the same way. `ERR_PREFIX_DISPOSED`: the prefix was disposed, or the
1575
+ * runtime no longer holds it.
1485
1576
  */
1486
- declare const SANDBOX_GLOBALS: ReadonlySet<string>;
1577
+ type SetupErrorCode = "ERR_PREFIX_DISPOSED" | "ERR_PREFIX_BROKEN" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND";
1487
1578
  /**
1488
- * Every name that cannot be a binding in module source, so it cannot be a
1489
- * host-module export name. As host global names, all but `eval` and
1490
- * `arguments` are refused with `ERR_INVALID_GLOBAL_NAME`. `default` is
1491
- * included, though iso4 itself accepts it as a host-module export (emitted as
1492
- * `export default`). Unlike {@link SANDBOX_GLOBALS}, which lists names that
1493
- * are taken, these are names the grammar forbids.
1579
+ * Why a run failed, in a `{ ok: false }` result. Setup refusals are thrown
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.
1494
1583
  */
1495
- declare const RESERVED_WORDS: ReadonlySet<string>;
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";
1496
1585
  //#endregion
1497
1586
  //#region src/index.d.ts
1498
1587
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
1499
1588
  //#endregion
1500
- 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, RESERVED_WORDS, 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, SANDBOX_GLOBALS, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, 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 };