@iso4/sandbox 0.0.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -448,8 +448,22 @@ interface RunOptions {
448
448
  signal?: AbortSignal;
449
449
  filename?: string;
450
450
  }
451
- type RunResult = RunSuccess | RunFailure;
451
+ /**
452
+ * Why a run was aborted — whatever value was passed to the aborting
453
+ * `AbortController.abort(reason)` (or left `undefined`). Opaque to iso4 and
454
+ * surfaced verbatim on {@link RunAborted.reason}; a consumer built on top
455
+ * (e.g. a durable-workflow kernel expressing "suspend") gives it meaning.
456
+ */
457
+ type AbortReason = unknown;
458
+ type RunResult = RunSuccess | RunFailure | RunAborted;
459
+ /**
460
+ * `status` is the primary discriminant across all three outcomes; `ok` is kept
461
+ * as a convenience alias for `status === 'completed'`, so the common guard
462
+ * stays `if (result.ok)`. Reach for `switch (result.status)` when a deliberate
463
+ * abort must be told apart from a genuine failure.
464
+ */
452
465
  interface RunSuccess {
466
+ status: "completed";
453
467
  ok: true;
454
468
  exports: SandboxExports;
455
469
  stdout: string[];
@@ -457,8 +471,25 @@ interface RunSuccess {
457
471
  durationMs: number;
458
472
  }
459
473
  interface RunFailure {
474
+ status: "failed";
475
+ ok: false;
476
+ error: RunError;
477
+ stdout: string[];
478
+ stderr: string[];
479
+ durationMs: number;
480
+ }
481
+ /**
482
+ * The run was stopped by an abort — a pre-aborted or mid-run `signal` passed to
483
+ * `run()`, or a host handler that aborted the run. A deliberate outcome, not a
484
+ * crash: `error` is retained (its `code` is always `ERR_ABORTED`) so existing
485
+ * `!result.ok` / `error.code` checks keep working, and `reason` carries the
486
+ * value handed to `abort(reason)`.
487
+ */
488
+ interface RunAborted {
489
+ status: "aborted";
460
490
  ok: false;
461
491
  error: RunError;
492
+ reason?: AbortReason;
462
493
  stdout: string[];
463
494
  stderr: string[];
464
495
  durationMs: number;
@@ -479,6 +510,10 @@ interface RunError {
479
510
  name: string;
480
511
  message: string;
481
512
  stack?: string;
513
+ /**
514
+ * Own enumerable properties of the thrown error, excluding name/message/stack. Present only for ERR_USER_CODE when the thrown value is an object with serializable own properties.
515
+ */
516
+ data?: unknown;
482
517
  }
483
518
  type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_EXPORT_UNRESOLVED_PROMISE" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_UNDECLARED_BINDING" | "ERR_PREFIX_DISPOSED" | "ERR_INTERNAL";
484
519
  //#endregion
package/dist/index.mjs CHANGED
@@ -225,6 +225,7 @@ function decodeRunCompletionPayload(buf) {
225
225
  return {
226
226
  runId,
227
227
  result: {
228
+ status: "completed",
228
229
  ok: true,
229
230
  exports: wireObjectToExports(exportsRaw),
230
231
  stdout,
@@ -239,6 +240,7 @@ function decodeRunCompletionPayload(buf) {
239
240
  const name = reader.readString();
240
241
  const message = reader.readString();
241
242
  const stack = reader.readU8() === 1 ? reader.readString() : void 0;
243
+ const data = reader.readU8() === 1 ? decodeWireValueFromReader(reader) : void 0;
242
244
  const stdout = reader.readStringList();
243
245
  const stderr = reader.readStringList();
244
246
  const durationMs = reader.readF64();
@@ -246,12 +248,14 @@ function decodeRunCompletionPayload(buf) {
246
248
  return {
247
249
  runId,
248
250
  result: {
251
+ status: "failed",
249
252
  ok: false,
250
253
  error: {
251
254
  code,
252
255
  name,
253
256
  message,
254
- stack
257
+ stack,
258
+ data
255
259
  },
256
260
  stdout,
257
261
  stderr,
@@ -290,6 +294,7 @@ function decodePrecompileResultPayload(buf) {
290
294
  const name = reader.readString();
291
295
  const message = reader.readString();
292
296
  const stack = reader.readU8() === 1 ? reader.readString() : void 0;
297
+ if (reader.readU8() === 1) decodeWireValueFromReader(reader);
293
298
  reader.assertDone();
294
299
  return {
295
300
  ok: false,
@@ -732,10 +737,32 @@ function formatByte(byte) {
732
737
  }
733
738
  //#endregion
734
739
  //#region src/client.ts
740
+ /**
741
+ * Thrown out of a run when its `AbortSignal` fires mid-flight. The connection
742
+ * is torn down (so the Rust isolate is reclaimed) before this propagates, and
743
+ * the client is marked unusable so the pool replaces it rather than reusing a
744
+ * half-dead slot. `index.ts` catches this and synthesizes the `ERR_ABORTED`
745
+ * `RunResult`.
746
+ */
747
+ var RunAbortedError = class extends Error {
748
+ /** The value passed to `AbortController.abort(reason)`, if any. */
749
+ reason;
750
+ constructor(reason, message = "run was aborted") {
751
+ super(message);
752
+ this.name = "RunAbortedError";
753
+ this.reason = reason;
754
+ }
755
+ };
735
756
  var RuntimeIpcClient = class RuntimeIpcClient {
736
757
  socket;
737
758
  reader;
738
759
  disposed = false;
760
+ /**
761
+ * Set when an in-flight abort tore this connection down. A broken client
762
+ * must not be returned to the pool's free list — `ConnectionPool.release`
763
+ * checks `usable` and replaces it with a fresh connection instead.
764
+ */
765
+ broken = false;
739
766
  constructor(socket) {
740
767
  this.socket = socket;
741
768
  this.reader = new FrameReader();
@@ -752,6 +779,14 @@ var RuntimeIpcClient = class RuntimeIpcClient {
752
779
  this.reader.close(/* @__PURE__ */ new Error("socket closed"));
753
780
  });
754
781
  }
782
+ /**
783
+ * A client is usable while its connection is intact. Once an in-flight abort
784
+ * (or a dispose) tears the socket down it becomes unusable and the pool must
785
+ * replace it.
786
+ */
787
+ get usable() {
788
+ return !this.disposed && !this.broken;
789
+ }
755
790
  static async connect(options) {
756
791
  const client = new RuntimeIpcClient(await connectSocket(options.socketPath));
757
792
  await client.write(encodeTsToRustFrame(TsToRustMessageTypes.Authenticate, encodeAuthenticatePayload({
@@ -777,7 +812,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
777
812
  globals: globalNames,
778
813
  imports: options?.imports
779
814
  })));
780
- return this.drainUntilResult(makeDispatcher(globals));
815
+ return this.drainUntilResult(makeDispatcher(globals), options?.signal);
781
816
  }
782
817
  async precompile(options) {
783
818
  if (this.disposed) throw new Error("runtime IPC client is disposed");
@@ -807,7 +842,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
807
842
  imports: options.imports,
808
843
  runId: this.nextRunIdValue()
809
844
  })));
810
- return this.drainUntilResult(makeDispatcher(globals));
845
+ return this.drainUntilResult(makeDispatcher(globals), options.signal);
811
846
  }
812
847
  async disposePrefix(prefixId) {
813
848
  if (this.disposed) return;
@@ -839,9 +874,50 @@ var RuntimeIpcClient = class RuntimeIpcClient {
839
874
  * garbage-collected when it eventually settles. Any in-flight I/O or timers
840
875
  * continue to completion. Rust silently ignores any late `BridgeResponse`
841
876
  * that arrives after the run has completed (see session.rs).
877
+ *
878
+ * ── In-flight abort ──────────────────────────────────────────────────────
879
+ * When `signal` fires mid-run — including while a bridge call is in flight —
880
+ * we tear the connection down immediately (`abortConnection`): the reader is
881
+ * closed so this loop throws, and the socket is destroyed so the Rust side
882
+ * observes EOF and reclaims the isolate promptly (rather than waiting for
883
+ * `wallTimeMs`). The loop then throws `RunAbortedError`, which `index.ts`
884
+ * maps to an `ERR_ABORTED` `RunResult`. Any late `BridgeResponse` written by
885
+ * an orphaned handler after this point fails silently (the socket is gone),
886
+ * so the sandbox never observes a return value for the in-flight call.
842
887
  * @param dispatcher
888
+ * @param signal
889
+ */
890
+ async drainUntilResult(dispatcher, signal) {
891
+ if (signal?.aborted) {
892
+ this.abortConnection();
893
+ throw new RunAbortedError(signal.reason);
894
+ }
895
+ const onAbort = () => {
896
+ this.abortConnection();
897
+ };
898
+ signal?.addEventListener("abort", onAbort, { once: true });
899
+ try {
900
+ return await this.drainFrames(dispatcher);
901
+ } catch (error) {
902
+ if (signal?.aborted) throw new RunAbortedError(signal.reason);
903
+ throw error;
904
+ } finally {
905
+ signal?.removeEventListener("abort", onAbort);
906
+ }
907
+ }
908
+ /**
909
+ * Tear down the connection in response to an in-flight abort. Idempotent.
910
+ * Marks the client `broken` (so the pool replaces it), closes the frame
911
+ * reader (so `drainFrames` stops awaiting), and destroys the socket (so the
912
+ * Rust session sees EOF and drops the isolate).
843
913
  */
844
- async drainUntilResult(dispatcher) {
914
+ abortConnection() {
915
+ if (this.broken) return;
916
+ this.broken = true;
917
+ this.reader.close(new RunAbortedError());
918
+ this.socket.destroy();
919
+ }
920
+ async drainFrames(dispatcher) {
845
921
  for await (const frame of this.reader) switch (frame.messageType) {
846
922
  case RustToTsMessageTypes.Result: return { result: frame.payload };
847
923
  case RustToTsMessageTypes.Log: break;
@@ -913,9 +989,11 @@ function connectSocket(socketPath) {
913
989
  var ConnectionPool = class {
914
990
  free;
915
991
  waiters = [];
992
+ connect;
916
993
  disposed = false;
917
- constructor(clients) {
994
+ constructor(clients, connect) {
918
995
  this.free = [...clients];
996
+ this.connect = connect;
919
997
  }
920
998
  /**
921
999
  * Borrow a client, run `fn`, then unconditionally return the client.
@@ -953,10 +1031,36 @@ var ConnectionPool = class {
953
1031
  client.dispose();
954
1032
  return;
955
1033
  }
1034
+ if (!client.usable) {
1035
+ this.replace(client).catch(() => {});
1036
+ return;
1037
+ }
956
1038
  const next = this.waiters.shift();
957
1039
  if (next !== void 0) next.resolve(client);
958
1040
  else this.free.push(client);
959
1041
  }
1042
+ /**
1043
+ * Dispose a dead slot and connect a fresh one in its place. If reconnection
1044
+ * fails (or no factory was supplied) the pool simply runs with one fewer
1045
+ * slot rather than handing back a broken connection; any waiter still gets
1046
+ * served by other slots as they free up.
1047
+ * @param dead
1048
+ */
1049
+ async replace(dead) {
1050
+ await dead.dispose().catch(() => {});
1051
+ if (this.connect === void 0) return;
1052
+ let fresh;
1053
+ try {
1054
+ fresh = await this.connect();
1055
+ } catch {
1056
+ return;
1057
+ }
1058
+ if (this.disposed) {
1059
+ await fresh.dispose().catch(() => {});
1060
+ return;
1061
+ }
1062
+ this.release(fresh);
1063
+ }
960
1064
  };
961
1065
  //#endregion
962
1066
  //#region src/globals.ts
@@ -1337,10 +1441,11 @@ async function createSandbox(options) {
1337
1441
  process.stderr.write(`[@iso4/sandbox] failed to start V8 process: ${err.message}\n`);
1338
1442
  });
1339
1443
  await waitForSocket(socketPath);
1340
- return new SandboxImpl(proc, new ConnectionPool(await Promise.all(Array.from({ length: maxIsolates }, () => RuntimeIpcClient.connect({
1444
+ const connect = () => RuntimeIpcClient.connect({
1341
1445
  socketPath,
1342
1446
  token
1343
- })))), socketPath);
1447
+ });
1448
+ return new SandboxImpl(proc, new ConnectionPool(await Promise.all(Array.from({ length: maxIsolates }, () => connect())), connect), socketPath);
1344
1449
  }
1345
1450
  async function waitForSocket(socketPath, timeoutMs = 5e3) {
1346
1451
  const deadline = Date.now() + timeoutMs;
@@ -1370,6 +1475,29 @@ function toWireLimits(limits) {
1370
1475
  maxBridgeCalls: limits?.maxBridgeCalls ?? 10
1371
1476
  };
1372
1477
  }
1478
+ /**
1479
+ * The `RunResult` returned when a run is aborted — whether the signal was
1480
+ * already aborted at run entry or fired mid-flight (surfaced as a
1481
+ * `RunAbortedError` from the client). Shared so both paths produce an
1482
+ * identical shape. `error` (code `ERR_ABORTED`) is retained for backward
1483
+ * compatibility; `reason` carries whatever was passed to `abort(reason)`.
1484
+ * @param reason
1485
+ */
1486
+ function abortedResult(reason) {
1487
+ return {
1488
+ status: "aborted",
1489
+ ok: false,
1490
+ error: {
1491
+ code: "ERR_ABORTED",
1492
+ name: "AbortError",
1493
+ message: "run was aborted"
1494
+ },
1495
+ reason,
1496
+ stdout: [],
1497
+ stderr: [],
1498
+ durationMs: 0
1499
+ };
1500
+ }
1373
1501
  var SandboxImpl = class {
1374
1502
  proc;
1375
1503
  pool;
@@ -1387,17 +1515,7 @@ var SandboxImpl = class {
1387
1515
  return this._alive;
1388
1516
  }
1389
1517
  async run(options) {
1390
- if (options.signal?.aborted) return {
1391
- ok: false,
1392
- error: {
1393
- code: "ERR_ABORTED",
1394
- name: "AbortError",
1395
- message: "run was aborted"
1396
- },
1397
- stdout: [],
1398
- stderr: [],
1399
- durationMs: 0
1400
- };
1518
+ if (options.signal?.aborted) return abortedResult(options.signal.reason);
1401
1519
  const { bridgeGlobals, preamble } = processGlobals(options.globals ?? {});
1402
1520
  const { bindings, registry, shape: _shape } = processImports(options.imports);
1403
1521
  const allGlobals = registry.size > 0 ? {
@@ -1405,14 +1523,20 @@ var SandboxImpl = class {
1405
1523
  [BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
1406
1524
  } : bridgeGlobals;
1407
1525
  const code = preamble ? `${preamble}\n${options.code}` : options.code;
1408
- return this.pool.withClient(async (client) => {
1409
- return decodeRunCompletionPayload((await client.runRawCode(code, {
1410
- filename: options.filename,
1411
- limits: toWireLimits(options.limits),
1412
- globals: allGlobals,
1413
- imports: bindings
1414
- })).result).result;
1415
- });
1526
+ try {
1527
+ return await this.pool.withClient(async (client) => {
1528
+ return decodeRunCompletionPayload((await client.runRawCode(code, {
1529
+ filename: options.filename,
1530
+ limits: toWireLimits(options.limits),
1531
+ globals: allGlobals,
1532
+ imports: bindings,
1533
+ signal: options.signal
1534
+ })).result).result;
1535
+ });
1536
+ } catch (error) {
1537
+ if (error instanceof RunAbortedError) return abortedResult(error.reason);
1538
+ throw error;
1539
+ }
1416
1540
  }
1417
1541
  /**
1418
1542
  * @param options
@@ -1494,6 +1618,7 @@ var PrefixImpl = class {
1494
1618
  }
1495
1619
  async run(options) {
1496
1620
  if (!this._alive) return {
1621
+ status: "failed",
1497
1622
  ok: false,
1498
1623
  error: {
1499
1624
  code: "ERR_PREFIX_DISPOSED",
@@ -1504,23 +1629,14 @@ var PrefixImpl = class {
1504
1629
  stderr: [],
1505
1630
  durationMs: 0
1506
1631
  };
1507
- if (options.signal?.aborted) return {
1508
- ok: false,
1509
- error: {
1510
- code: "ERR_ABORTED",
1511
- name: "AbortError",
1512
- message: "run was aborted"
1513
- },
1514
- stdout: [],
1515
- stderr: [],
1516
- durationMs: 0
1517
- };
1632
+ if (options.signal?.aborted) return abortedResult(options.signal.reason);
1518
1633
  const bridgeGlobals = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
1519
1634
  let registry;
1520
1635
  try {
1521
1636
  registry = extractRebindImports(options.imports, this.defaultRegistry, this.declaredImportShape);
1522
1637
  } catch (e) {
1523
1638
  if (e instanceof UndeclaredImportBindingError) return {
1639
+ status: "failed",
1524
1640
  ok: false,
1525
1641
  error: {
1526
1642
  code: "ERR_UNDECLARED_BINDING",
@@ -1537,15 +1653,21 @@ var PrefixImpl = class {
1537
1653
  ...bridgeGlobals,
1538
1654
  [BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
1539
1655
  } : bridgeGlobals;
1540
- return this.pool.withClient(async (client) => {
1541
- return decodeRunCompletionPayload((await client.prefixRun({
1542
- prefixId: this.id,
1543
- code: options.code,
1544
- filename: options.filename,
1545
- limits: toWireLimits(options.limits),
1546
- globals: allGlobals
1547
- })).result).result;
1548
- });
1656
+ try {
1657
+ return await this.pool.withClient(async (client) => {
1658
+ return decodeRunCompletionPayload((await client.prefixRun({
1659
+ prefixId: this.id,
1660
+ code: options.code,
1661
+ filename: options.filename,
1662
+ limits: toWireLimits(options.limits),
1663
+ globals: allGlobals,
1664
+ signal: options.signal
1665
+ })).result).result;
1666
+ });
1667
+ } catch (error) {
1668
+ if (error instanceof RunAbortedError) return abortedResult(error.reason);
1669
+ throw error;
1670
+ }
1549
1671
  }
1550
1672
  async dispose() {
1551
1673
  if (!this._alive) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iso4/sandbox",
3
- "version": "0.0.4",
3
+ "version": "0.2.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": [
@@ -47,10 +47,10 @@
47
47
  "vitest": "^4.1.5"
48
48
  },
49
49
  "optionalDependencies": {
50
- "@iso4/v8-darwin-arm64": "^0.0.4",
51
- "@iso4/v8-darwin-x64": "^0.0.4",
52
- "@iso4/v8-linux-arm64-gnu": "^0.0.4",
53
- "@iso4/v8-linux-x64-gnu": "^0.0.4"
50
+ "@iso4/v8-darwin-arm64": "^0.2.0",
51
+ "@iso4/v8-darwin-x64": "^0.2.0",
52
+ "@iso4/v8-linux-arm64-gnu": "^0.2.0",
53
+ "@iso4/v8-linux-x64-gnu": "^0.2.0"
54
54
  },
55
55
  "engines": {
56
56
  "node": ">=24.0.0"