@tangle-network/sdk-cli-runner 0.3.14 → 0.3.16

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
@@ -163,13 +163,15 @@ interface CliProcess {
163
163
  /**
164
164
  * Configuration for stream parsing.
165
165
  *
166
- * Three modes cover every CLI output shape we've encountered:
166
+ * Choose the unit the native CLI emits:
167
167
  *
168
168
  * - **"json"** (default): newline-delimited JSON. Each line is parsed via
169
169
  * `JSON.parse`, then passed to `transform`. Used by claude-code, codex.
170
170
  * - **"lines"**: plaintext with one logical event per line. Each line is
171
171
  * passed to `transform` as a raw trimmed string with no JSON parsing.
172
172
  * Used by hermes quiet mode plaintext response lines.
173
+ * - **"chunks"**: each decoded UTF-8 stdout chunk reaches the consumer as it
174
+ * arrives, including incomplete lines and whitespace.
173
175
  * - **"raw"**: stdout chunks delivered verbatim with no per-line splitting.
174
176
  * `transform` is NOT called; instead the parser maintains a single
175
177
  * accumulating buffer that the consumer reads in `onComplete`. Used by
@@ -187,15 +189,16 @@ interface StreamParserConfig<T> {
187
189
  * Parse mode. See the interface docstring for the contract per mode.
188
190
  * Defaults to "json".
189
191
  */
190
- parseAs?: "json" | "lines" | "raw";
192
+ parseAs?: "json" | "lines" | "chunks" | "raw";
191
193
  /**
192
194
  * Transform a parsed event to the desired type (return null to skip).
193
195
  * In "json" mode the input is the JSON.parse result; in "lines" mode it
194
196
  * is the raw trimmed line string. **Ignored in "raw" mode** — the
195
- * consumer reads the full buffer via `onRawComplete`.
197
+ * consumer reads the full buffer via `onComplete`. In "chunks" mode
198
+ * the input is the decoded stdout chunk.
196
199
  */
197
200
  transform?: (raw: unknown) => T | null;
198
- /** Called for each parsed event ("json" and "lines" modes only). */
201
+ /** Called for each transformed event, except in "raw" mode. */
199
202
  onEvent: (event: T) => void;
200
203
  /** Called on parse errors (only fires in "json" mode) */
201
204
  onError?: (error: Error, rawLine: string) => void;
@@ -204,7 +207,7 @@ interface StreamParserConfig<T> {
204
207
  *
205
208
  * In "raw" mode, the full untouched stdout buffer is passed as the
206
209
  * argument so consumers can parse it however they want (single
207
- * `JSON.parse`, regex extraction, etc). In "json" and "lines" modes the
210
+ * `JSON.parse`, regex extraction, etc). In all other modes the
208
211
  * argument is undefined — events were already delivered via `onEvent`.
209
212
  */
210
213
  onComplete?: (rawBuffer?: string) => void;
@@ -326,10 +329,34 @@ interface HeldSpareRegistry<TEvent, TExtra extends object = object> {
326
329
  parser: StreamParserConfig<TEvent>;
327
330
  signal: AbortSignal;
328
331
  }): HeldSpareProcess;
329
- /** Stop every spare no turn claimed, and wait for the processes to exit. */
330
- 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.
347
+ */
348
+ readonly lockAgeMs: number | undefined;
349
+ readonly spareAgeMs: number;
350
+ }
351
+ interface HeldSpareRegistryOptions<TEvent, TExtra extends object = object> {
352
+ /**
353
+ * The lock files this harness's CLI takes while it writes in its HOME. A
354
+ * CLI killed while it holds one leaves it, and the next process there waits
355
+ * on a lock nobody will release; a discard lets such a spare finish.
356
+ */
357
+ locks?(spare: HeldSpare<TEvent, TExtra>): readonly string[];
331
358
  }
332
- declare function createHeldSpareRegistry<TEvent, TExtra extends object = object>(): HeldSpareRegistry<TEvent, TExtra>;
359
+ declare function createHeldSpareRegistry<TEvent, TExtra extends object = object>(options?: HeldSpareRegistryOptions<TEvent, TExtra>): HeldSpareRegistry<TEvent, TExtra>;
333
360
  /** The argument after `flag`, if any. */
334
361
  declare function argAfter(args: readonly string[], flag: string): string | undefined;
335
362
  /**
@@ -608,10 +635,11 @@ declare function mergeSpawnEnv(base: NodeJS.ProcessEnv, overrides: Record<string
608
635
  //#endregion
609
636
  //#region src/stream-parser.d.ts
610
637
  /**
611
- * Creates a stdout stream parser. Three modes:
638
+ * Creates a stdout stream parser.
612
639
  *
613
640
  * - "json" (default): newline-delimited JSON, JSON.parse per line.
614
641
  * - "lines": plaintext, raw trimmed line per `transform` call.
642
+ * - "chunks": each decoded stdout chunk goes straight to the consumer.
615
643
  * - "raw": no per-line splitting — accumulate the entire stream into a
616
644
  * single buffer and deliver it via `onComplete(buffer)`.
617
645
  *
@@ -619,5 +647,5 @@ declare function mergeSpawnEnv(base: NodeJS.ProcessEnv, overrides: Record<string
619
647
  */
620
648
  declare function createStreamParser<T>(config: StreamParserConfig<T>): StreamParser<T>;
621
649
  //#endregion
622
- 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 };
650
+ 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 };
623
651
  //# 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`);
@@ -1170,10 +1191,11 @@ function stdoutFileFor(stdio, parsed) {
1170
1191
  //#endregion
1171
1192
  //#region src/stream-parser.ts
1172
1193
  /**
1173
- * Creates a stdout stream parser. Three modes:
1194
+ * Creates a stdout stream parser.
1174
1195
  *
1175
1196
  * - "json" (default): newline-delimited JSON, JSON.parse per line.
1176
1197
  * - "lines": plaintext, raw trimmed line per `transform` call.
1198
+ * - "chunks": each decoded stdout chunk goes straight to the consumer.
1177
1199
  * - "raw": no per-line splitting — accumulate the entire stream into a
1178
1200
  * single buffer and deliver it via `onComplete(buffer)`.
1179
1201
  *
@@ -1182,6 +1204,14 @@ function stdoutFileFor(stdio, parsed) {
1182
1204
  function createStreamParser(config) {
1183
1205
  let buffer = "";
1184
1206
  const { parseAs = "json", transform, onEvent, onError, onComplete } = config;
1207
+ function emit(value) {
1208
+ const event = transform ? transform(value) : value;
1209
+ if (event !== null) onEvent(event);
1210
+ }
1211
+ if (parseAs === "chunks") return {
1212
+ push: emit,
1213
+ end: () => onComplete?.()
1214
+ };
1185
1215
  if (parseAs === "raw") return {
1186
1216
  push(chunk) {
1187
1217
  buffer += chunk;
@@ -1195,14 +1225,11 @@ function createStreamParser(config) {
1195
1225
  const trimmed = line.trim();
1196
1226
  if (!trimmed) return;
1197
1227
  if (parseAs === "lines") {
1198
- const event = transform ? transform(trimmed) : trimmed;
1199
- if (event !== null) onEvent(event);
1228
+ emit(trimmed);
1200
1229
  return;
1201
1230
  }
1202
1231
  try {
1203
- const parsed = JSON.parse(trimmed);
1204
- const event = transform ? transform(parsed) : parsed;
1205
- if (event !== null) onEvent(event);
1232
+ emit(JSON.parse(trimmed));
1206
1233
  } catch (error) {
1207
1234
  onError?.(error instanceof Error ? error : new Error(String(error)), trimmed);
1208
1235
  }
@@ -1605,10 +1632,21 @@ const HELD_SPARE_IDLE_MS = 12e4;
1605
1632
  * Its HOME stays taken, and a turn that waits for it waits, until it exits.
1606
1633
  */
1607
1634
  const HELD_SPARE_STOP_GRACE_MS = 2e3;
1608
- function createHeldSpareRegistry() {
1635
+ /** How long a discard waits to see a killed spare exit before it fails. */
1636
+ const HELD_SPARE_EXIT_BOUND_MS = 2e3;
1637
+ /** How long a discard waits for a spare it froze to read stopped in /proc. */
1638
+ const HELD_SPARE_FREEZE_BOUND_MS = 30;
1639
+ /**
1640
+ * How long a lock may stay, with the spare frozen, before it is the spare's.
1641
+ * Another process in that HOME holds one for a single write and lets go.
1642
+ */
1643
+ const HELD_SPARE_LOCK_SETTLE_MS = 50;
1644
+ const HELD_SPARE_LOCK_POLL_MS = 5;
1645
+ function createHeldSpareRegistry(options = {}) {
1609
1646
  const spares = /* @__PURE__ */ new Map();
1610
- const stop = (spare) => {
1611
- if (spare.state === "claimed" || spare.state === "stopped") return;
1647
+ /** Takes a spare out of service; false when a turn has it or it is going. */
1648
+ const retire = (spare) => {
1649
+ if (spare.state === "claimed" || spare.state === "stopped") return false;
1612
1650
  spare.state = "stopped";
1613
1651
  if (spare.idleTimer) clearTimeout(spare.idleTimer);
1614
1652
  const forget = () => {
@@ -1621,9 +1659,74 @@ function createHeldSpareRegistry() {
1621
1659
  forget();
1622
1660
  };
1623
1661
  spare.process.exitPromise.then(exited, exited);
1662
+ return true;
1663
+ };
1664
+ const stop = (spare) => {
1665
+ if (!retire(spare)) return;
1624
1666
  spare.controller.abort();
1625
1667
  spare.process.kill();
1626
1668
  };
1669
+ /** Freezes a spare; true once /proc shows its whole group stopped. */
1670
+ const freeze = async (spare) => {
1671
+ spare.process.kill("SIGSTOP");
1672
+ const until = performance.now() + HELD_SPARE_FREEZE_BOUND_MS;
1673
+ while (!(spare.process.pid && groupStopped(spare.process.pid))) {
1674
+ if (performance.now() >= until) return false;
1675
+ await setTimeout$1(1);
1676
+ }
1677
+ return true;
1678
+ };
1679
+ /**
1680
+ * The age of a lock a frozen spare holds, if it holds one. A lock that goes
1681
+ * while the spare cannot run is another process's (a tenant's own turn in
1682
+ * that HOME, writing); one that stays is taken to be the spare's.
1683
+ */
1684
+ const heldLockAgeMs = async (spare) => {
1685
+ const paths = options.locks?.(spare) ?? [];
1686
+ const ageMs = () => {
1687
+ for (const path of paths) {
1688
+ const lock = statSync(path, { throwIfNoEntry: false });
1689
+ if (lock) return Date.now() - lock.mtimeMs;
1690
+ }
1691
+ };
1692
+ const until = performance.now() + HELD_SPARE_LOCK_SETTLE_MS;
1693
+ for (let age = ageMs(); age !== void 0; age = ageMs()) {
1694
+ if (performance.now() >= until) return age;
1695
+ await setTimeout$1(HELD_SPARE_LOCK_POLL_MS);
1696
+ }
1697
+ };
1698
+ /**
1699
+ * Ends a spare for a discard. The box is changing identity and waits on the
1700
+ * exit, and a spare no turn ran on has nothing worth a graceful stop: it is
1701
+ * killed at once, its whole process group with it. The one exception is a
1702
+ * spare inside a write its harness guards with a lock (`locks`): killed
1703
+ * there it would leave the lock, so it is stopped as a turn stops it and
1704
+ * releases it. The discard freezes the spare before it looks, so the spare
1705
+ * serves nothing and takes no lock in between; one it cannot show frozen is
1706
+ * taken to be writing. A spare a turn already stopped is still exiting, and
1707
+ * is ended the same way.
1708
+ */
1709
+ const discardOne = async (spare) => {
1710
+ const running = retire(spare);
1711
+ const frozen = options.locks === void 0 || await freeze(spare);
1712
+ const lockAgeMs = frozen ? await heldLockAgeMs(spare) : void 0;
1713
+ if (running) spare.controller.abort();
1714
+ if (frozen && lockAgeMs === void 0) {
1715
+ spare.process.kill("SIGKILL");
1716
+ return { boundMs: HELD_SPARE_EXIT_BOUND_MS };
1717
+ }
1718
+ if (running) spare.process.kill();
1719
+ spare.process.kill("SIGCONT");
1720
+ return {
1721
+ boundMs: HELD_SPARE_STOP_GRACE_MS + HELD_SPARE_EXIT_BOUND_MS,
1722
+ letFinish: {
1723
+ home: spare.home,
1724
+ frozen,
1725
+ lockAgeMs,
1726
+ spareAgeMs: performance.now() - spare.startedAt
1727
+ }
1728
+ };
1729
+ };
1627
1730
  const claim = (spare) => {
1628
1731
  spare.state = "claimed";
1629
1732
  restoreTurnPriority(spare.process.pid);
@@ -1637,7 +1740,7 @@ function createHeldSpareRegistry() {
1637
1740
  yieldUntilAdopted(spare.process.pid);
1638
1741
  },
1639
1742
  has: (home) => spares.has(home),
1640
- stop,
1743
+ stop: (spare) => stop(spare),
1641
1744
  claim,
1642
1745
  adopt: (spare, turn) => {
1643
1746
  if (spare.state === "stopped" || spare.state === "claimed") throw new Error(`A ${spare.state} spare cannot be adopted`);
@@ -1658,12 +1761,14 @@ function createHeldSpareRegistry() {
1658
1761
  };
1659
1762
  },
1660
1763
  discard: async () => {
1661
- const stopping = [];
1662
- for (const spare of [...spares.values()]) {
1663
- stop(spare);
1664
- stopping.push(spare.process.exitPromise.catch(() => void 0));
1665
- }
1666
- await Promise.all(stopping);
1764
+ const discarded = [...spares.values()];
1765
+ const ended = await Promise.all(discarded.map(discardOne));
1766
+ const boundMs = Math.max(0, ...ended.map((end) => end.boundMs));
1767
+ let bound;
1768
+ if (!await Promise.race([Promise.all(discarded.map((spare) => spare.process.exitPromise.catch(() => void 0))).then(() => true), new Promise((resolve) => {
1769
+ bound = setTimeout(() => resolve(false), boundMs);
1770
+ })]).finally(() => clearTimeout(bound))) throw new Error(`A held spare did not exit within ${boundMs} ms of being stopped`);
1771
+ return ended.flatMap((end) => end.letFinish ? [end.letFinish] : []);
1667
1772
  }
1668
1773
  };
1669
1774
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-cli-runner",
3
- "version": "0.3.14",
3
+ "version": "0.3.16",
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": "ee12a88481d6685639672d562db9ad1b37a8ae0d",
30
- "mergedAt": "2026-11-19T16:48:01-08:00"
29
+ "sourceSha": "ab69b47e583110faa55b91d66c6ccc24c69cc105",
30
+ "mergedAt": "2026-11-22T22:13:55-08:00"
31
31
  },
32
32
  "scripts": {
33
33
  "build": "tsdown",