@tangle-network/sdk-cli-runner 0.3.15 → 0.3.17

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
@@ -329,10 +329,35 @@ interface HeldSpareRegistry<TEvent, TExtra extends object = object> {
329
329
  parser: StreamParserConfig<TEvent>;
330
330
  signal: AbortSignal;
331
331
  }): HeldSpareProcess;
332
- /** Stop every spare no turn claimed, and wait for the processes to exit. */
333
- discard(): Promise<void>;
332
+ /**
333
+ * End every spare no turn claimed, and wait for the processes to exit.
334
+ * Answers the spares it let finish where it kills (see `locks`).
335
+ */
336
+ discard(): Promise<HeldSpareLetFinish[]>;
337
+ }
338
+ /** A spare a discard stopped with a grace where it kills, and why. */
339
+ interface HeldSpareLetFinish {
340
+ readonly home: string;
341
+ /** False when /proc never showed the spare's whole group stopped. */
342
+ readonly frozen: boolean;
343
+ /**
344
+ * How long before the discard the lock it found was last written. One
345
+ * written before the spare started is not the spare's: it was cloned into
346
+ * this HOME with a snapshot, or an earlier process left it. Undefined for
347
+ * a spare not shown frozen, and for a lock that could not be read.
348
+ */
349
+ readonly lockAgeMs: number | undefined;
350
+ readonly spareAgeMs: number;
351
+ }
352
+ interface HeldSpareRegistryOptions<TEvent, TExtra extends object = object> {
353
+ /**
354
+ * The lock files this harness's CLI takes while it writes in its HOME. A
355
+ * CLI killed while it holds one leaves it, and the next process there waits
356
+ * on a lock nobody will release; a discard lets such a spare finish.
357
+ */
358
+ locks?(spare: HeldSpare<TEvent, TExtra>): readonly string[];
334
359
  }
335
- declare function createHeldSpareRegistry<TEvent, TExtra extends object = object>(): HeldSpareRegistry<TEvent, TExtra>;
360
+ declare function createHeldSpareRegistry<TEvent, TExtra extends object = object>(options?: HeldSpareRegistryOptions<TEvent, TExtra>): HeldSpareRegistry<TEvent, TExtra>;
336
361
  /** The argument after `flag`, if any. */
337
362
  declare function argAfter(args: readonly string[], flag: string): string | undefined;
338
363
  /**
@@ -623,5 +648,5 @@ declare function mergeSpawnEnv(base: NodeJS.ProcessEnv, overrides: Record<string
623
648
  */
624
649
  declare function createStreamParser<T>(config: StreamParserConfig<T>): StreamParser<T>;
625
650
  //#endregion
626
- export { BridgeClosedError, type CliExecOptions, type CliExecResult, type CliExitResult, type CliLaunch, type CliLaunchSpec, type CliLauncher, type CliProcess, type CliSpawnConfig, type CliStdinValue, HELD_SPARE_IDLE_MS, type HeldSpare, type HeldSpareRegistry, InvalidAttachmentError, JsonRpcError, RAW_CAPTURE_ROOT, RAW_CAPTURE_TOTAL_CAP_BYTES, type RawCaptureProcess, type RpcBridge, type RpcBridgeConfig, type RpcCloseReason, type RpcNotificationHandler, type RpcRequestHandler, type RpcRequestOptions, RpcRequestTimeoutError, type StreamParserConfig, allowRetainedRawCapture, argAfter, configurePrivilegeDrop, createDeferredParser, createHeldSpareRegistry, createStreamParser, execCli, launchCliProcess, launchDifferences, mergeSpawnEnv, openRawCapture, privilegeDropCommand, privilegeDropIdentity, readProcessIdentity, removeRawCapture, resolveRawCapturePath, restoreTurnPriority, shellQuote, spawnCliProcess, spawnRpcBridge, summarizeRawCapture, trimRawCapture, trustedToolPath, withRawCaptureAttempt, yieldUntilAdopted };
651
+ export { BridgeClosedError, type CliExecOptions, type CliExecResult, type CliExitResult, type CliLaunch, type CliLaunchSpec, type CliLauncher, type CliProcess, type CliSpawnConfig, type CliStdinValue, HELD_SPARE_IDLE_MS, type HeldSpare, type HeldSpareLetFinish, type HeldSpareRegistry, InvalidAttachmentError, JsonRpcError, RAW_CAPTURE_ROOT, RAW_CAPTURE_TOTAL_CAP_BYTES, type RawCaptureProcess, type RpcBridge, type RpcBridgeConfig, type RpcCloseReason, type RpcNotificationHandler, type RpcRequestHandler, type RpcRequestOptions, RpcRequestTimeoutError, type StreamParserConfig, allowRetainedRawCapture, argAfter, configurePrivilegeDrop, createDeferredParser, createHeldSpareRegistry, createStreamParser, execCli, launchCliProcess, launchDifferences, mergeSpawnEnv, openRawCapture, privilegeDropCommand, privilegeDropIdentity, readProcessIdentity, removeRawCapture, resolveRawCapturePath, restoreTurnPriority, shellQuote, spawnCliProcess, spawnRpcBridge, summarizeRawCapture, trimRawCapture, trustedToolPath, withRawCaptureAttempt, yieldUntilAdopted };
627
652
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -9,6 +9,7 @@ import { open } from "node:fs/promises";
9
9
  import { getPriority, setPriority, tmpdir } from "node:os";
10
10
  import { once } from "node:events";
11
11
  import { PassThrough } from "node:stream";
12
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
12
13
  //#region src/attachment-error.ts
13
14
  /** An attachment cannot be delivered to a native CLI. */
14
15
  var InvalidAttachmentError = class extends Error {
@@ -872,6 +873,26 @@ function reniceTree(root, priority) {
872
873
  }
873
874
  } catch {}
874
875
  }
876
+ /**
877
+ * Whether process `leader` and its process group are stopped: every thread of
878
+ * every live member reads stopped in /proc. A stop signal is delivered to each
879
+ * thread on its own, so a group just sent one may still have a thread inside
880
+ * a system call. False where /proc cannot say (not Linux).
881
+ */
882
+ function groupStopped(leader) {
883
+ try {
884
+ return liveProcesses().filter(({ pid, group }) => pid === leader || group === leader).every(({ pid }) => threadsOf(pid).every((thread) => {
885
+ try {
886
+ const stat = readFileSync(`/proc/${pid}/task/${thread}/stat`, "utf8");
887
+ return /^[TtZX]/.test(stat.slice(stat.lastIndexOf(")") + 2));
888
+ } catch {
889
+ return true;
890
+ }
891
+ }));
892
+ } catch {
893
+ return false;
894
+ }
895
+ }
875
896
  function threadsOf(pid) {
876
897
  try {
877
898
  return readdirSync(`/proc/${pid}/task`);
@@ -1607,14 +1628,28 @@ function createDeferredParser() {
1607
1628
  /** How long a spare no turn adopted keeps its process. */
1608
1629
  const HELD_SPARE_IDLE_MS = 12e4;
1609
1630
  /**
1610
- * How long a stopped spare has to exit after SIGTERM before it is killed.
1611
- * Its HOME stays taken, and a turn that waits for it waits, until it exits.
1631
+ * How long a stopped spare has to exit after SIGTERM before the registry
1632
+ * kills it. Its HOME stays taken, and a turn that waits for it waits, until
1633
+ * it exits. A spare launched with its controller's signal is killed sooner:
1634
+ * aborting the controller starts the runner's own escalation, 1 s
1635
+ * (child-killer.ts), and this timer is the backstop for one that was not.
1612
1636
  */
1613
1637
  const HELD_SPARE_STOP_GRACE_MS = 2e3;
1614
- function createHeldSpareRegistry() {
1638
+ /** How long a discard waits to see a killed spare exit before it fails. */
1639
+ const HELD_SPARE_EXIT_BOUND_MS = 2e3;
1640
+ /** How long a discard waits for a spare it froze to read stopped in /proc. */
1641
+ const HELD_SPARE_FREEZE_BOUND_MS = 30;
1642
+ /**
1643
+ * How long a lock may stay, with the spare frozen, before it is the spare's.
1644
+ * Another process in that HOME holds one for a single write and lets go.
1645
+ */
1646
+ const HELD_SPARE_LOCK_SETTLE_MS = 50;
1647
+ const HELD_SPARE_LOCK_POLL_MS = 5;
1648
+ function createHeldSpareRegistry(options = {}) {
1615
1649
  const spares = /* @__PURE__ */ new Map();
1616
- const stop = (spare) => {
1617
- if (spare.state === "claimed" || spare.state === "stopped") return;
1650
+ /** Takes a spare out of service; false when a turn has it or it is going. */
1651
+ const retire = (spare) => {
1652
+ if (spare.state === "claimed" || spare.state === "stopped") return false;
1618
1653
  spare.state = "stopped";
1619
1654
  if (spare.idleTimer) clearTimeout(spare.idleTimer);
1620
1655
  const forget = () => {
@@ -1627,9 +1662,77 @@ function createHeldSpareRegistry() {
1627
1662
  forget();
1628
1663
  };
1629
1664
  spare.process.exitPromise.then(exited, exited);
1665
+ return true;
1666
+ };
1667
+ const stop = (spare) => {
1668
+ if (!retire(spare)) return;
1630
1669
  spare.controller.abort();
1631
1670
  spare.process.kill();
1632
1671
  };
1672
+ /** Freezes a spare; true once /proc shows its whole group stopped. */
1673
+ const freeze = async (spare) => {
1674
+ spare.process.kill("SIGSTOP");
1675
+ const until = performance.now() + HELD_SPARE_FREEZE_BOUND_MS;
1676
+ while (!(spare.process.pid && groupStopped(spare.process.pid))) {
1677
+ if (performance.now() >= until) return false;
1678
+ await setTimeout$1(1);
1679
+ }
1680
+ return true;
1681
+ };
1682
+ /**
1683
+ * The lock a frozen spare holds, if it holds one: its age, or "unreadable"
1684
+ * for one that cannot be read (taken to be held). A lock that goes while
1685
+ * the spare cannot run is another process's (a tenant's own turn in that
1686
+ * HOME, writing); one that stays is taken to be the spare's.
1687
+ */
1688
+ const heldLock = async (spare) => {
1689
+ const paths = options.locks?.(spare) ?? [];
1690
+ const look = () => {
1691
+ for (const path of paths) try {
1692
+ const lock = statSync(path, { throwIfNoEntry: false });
1693
+ if (lock) return Date.now() - lock.mtimeMs;
1694
+ } catch {
1695
+ return "unreadable";
1696
+ }
1697
+ };
1698
+ const until = performance.now() + HELD_SPARE_LOCK_SETTLE_MS;
1699
+ for (let lock = look(); lock !== void 0; lock = look()) {
1700
+ if (performance.now() >= until) return lock;
1701
+ await setTimeout$1(HELD_SPARE_LOCK_POLL_MS);
1702
+ }
1703
+ };
1704
+ /**
1705
+ * Ends a spare for a discard. The box is changing identity and waits on the
1706
+ * exit, and a spare no turn ran on has nothing worth a graceful stop: it is
1707
+ * killed at once, its whole process group with it. The one exception is a
1708
+ * spare inside a write its harness guards with a lock (`locks`): killed
1709
+ * there it would leave the lock, so it is stopped as a turn stops it and
1710
+ * releases it. The discard freezes the spare before it looks, so the spare
1711
+ * serves nothing and takes no lock in between; one it cannot show frozen is
1712
+ * taken to be writing. A spare a turn already stopped is still exiting, and
1713
+ * is ended the same way.
1714
+ */
1715
+ const discardOne = async (spare) => {
1716
+ const running = retire(spare);
1717
+ const frozen = options.locks === void 0 || await freeze(spare);
1718
+ const lock = frozen ? await heldLock(spare) : void 0;
1719
+ if (running) spare.controller.abort();
1720
+ if (frozen && lock === void 0) {
1721
+ spare.process.kill("SIGKILL");
1722
+ return { boundMs: HELD_SPARE_EXIT_BOUND_MS };
1723
+ }
1724
+ if (running) spare.process.kill();
1725
+ spare.process.kill("SIGCONT");
1726
+ return {
1727
+ boundMs: HELD_SPARE_STOP_GRACE_MS + HELD_SPARE_EXIT_BOUND_MS,
1728
+ letFinish: {
1729
+ home: spare.home,
1730
+ frozen,
1731
+ lockAgeMs: typeof lock === "number" ? lock : void 0,
1732
+ spareAgeMs: performance.now() - spare.startedAt
1733
+ }
1734
+ };
1735
+ };
1633
1736
  const claim = (spare) => {
1634
1737
  spare.state = "claimed";
1635
1738
  restoreTurnPriority(spare.process.pid);
@@ -1643,7 +1746,7 @@ function createHeldSpareRegistry() {
1643
1746
  yieldUntilAdopted(spare.process.pid);
1644
1747
  },
1645
1748
  has: (home) => spares.has(home),
1646
- stop,
1749
+ stop: (spare) => stop(spare),
1647
1750
  claim,
1648
1751
  adopt: (spare, turn) => {
1649
1752
  if (spare.state === "stopped" || spare.state === "claimed") throw new Error(`A ${spare.state} spare cannot be adopted`);
@@ -1664,12 +1767,14 @@ function createHeldSpareRegistry() {
1664
1767
  };
1665
1768
  },
1666
1769
  discard: async () => {
1667
- const stopping = [];
1668
- for (const spare of [...spares.values()]) {
1669
- stop(spare);
1670
- stopping.push(spare.process.exitPromise.catch(() => void 0));
1671
- }
1672
- await Promise.all(stopping);
1770
+ const discarded = [...spares.values()];
1771
+ const ended = await Promise.all(discarded.map(discardOne));
1772
+ const boundMs = Math.max(0, ...ended.map((end) => end.boundMs));
1773
+ let bound;
1774
+ if (!await Promise.race([Promise.all(discarded.map((spare) => spare.process.exitPromise.catch(() => void 0))).then(() => true), new Promise((resolve) => {
1775
+ bound = setTimeout(() => resolve(false), boundMs);
1776
+ })]).finally(() => clearTimeout(bound))) throw new Error(`A held spare did not exit within ${boundMs} ms of being stopped`);
1777
+ return ended.flatMap((end) => end.letFinish ? [end.letFinish] : []);
1673
1778
  }
1674
1779
  };
1675
1780
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-cli-runner",
3
- "version": "0.3.15",
3
+ "version": "0.3.17",
4
4
  "description": "Generic CLI process spawning with stdin/stdout streaming and JSONL parsing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -26,8 +26,8 @@
26
26
  "registry": "https://registry.npmjs.org"
27
27
  },
28
28
  "tangleRelease": {
29
- "sourceSha": "51b269bed8de37eb53a80b87424adfd869bb1de9",
30
- "mergedAt": "2026-11-19T20:08:54-08:00"
29
+ "sourceSha": "e71746bf3cf7d504d76e0e24659e55501b42a175",
30
+ "mergedAt": "2026-11-22T22:31:59-08:00"
31
31
  },
32
32
  "scripts": {
33
33
  "build": "tsdown",