@tangle-network/sdk-cli-runner 0.3.0 → 0.3.2

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
@@ -61,6 +61,13 @@ interface CliSpawnConfig {
61
61
  * may start a process meant to outlive it (a dev server a preview serves).
62
62
  */
63
63
  ownProcessGroup?: boolean;
64
+ /**
65
+ * What a child that rejects its stdin (closes the pipe early) gets. "stop"
66
+ * (default) stops it, because an adapter's turn cannot continue without its
67
+ * input. "report" lets it exit on its own and reports `stdinError`, for a
68
+ * caller that judges the exit itself.
69
+ */
70
+ stdinFailure?: "stop" | "report";
64
71
  }
65
72
  /** What a consumer-owned launch is asked to start, after env assembly. */
66
73
  interface CliLaunchSpec {
@@ -119,6 +126,8 @@ interface CliExitResult {
119
126
  spawnError?: string;
120
127
  /** The native child closed or rejected stdin before its input was delivered. */
121
128
  stdinError?: string;
129
+ /** The errno code of `stdinError` (EPIPE for a pipe the child closed). */
130
+ stdinErrorCode?: string;
122
131
  /** Raw evidence could not be written or flushed; the process is not a complete trace. */
123
132
  captureError?: string;
124
133
  /** The caller's abort signal fired before the process exited. */
@@ -176,8 +185,7 @@ interface CliProcess {
176
185
  interface StreamParserConfig<T> {
177
186
  /**
178
187
  * Parse mode. See the interface docstring for the contract per mode.
179
- * Defaults to "json" for backwards compatibility with the original
180
- * JSONL-only API.
188
+ * Defaults to "json".
181
189
  */
182
190
  parseAs?: "json" | "lines" | "raw";
183
191
  /**
@@ -229,6 +237,8 @@ interface CliExecResult<T> {
229
237
  interface CliExecOptions {
230
238
  /** Newest stdout and stderr bytes retained per stream. Default 64 MiB. */
231
239
  maxOutputBytes?: number;
240
+ /** Written to the child's stdin, which then closes. Omitted: stdin stays as the config leaves it. */
241
+ stdin?: string;
232
242
  }
233
243
  /**
234
244
  * One value the runner writes to a child process's standard input. A string
@@ -333,6 +343,16 @@ declare function launchDifferences(spare: Pick<HeldSpareFields<unknown>, "args"
333
343
  env: Readonly<Record<string, string | undefined>>;
334
344
  }, comparable?: (key: string, value: string | undefined) => string | undefined): string[];
335
345
  //#endregion
346
+ //#region src/owned-process-tree.d.ts
347
+ type ProcessIdentity = {
348
+ pid: number;
349
+ parent: number;
350
+ group: number;
351
+ start: string;
352
+ state: string;
353
+ };
354
+ declare function readProcessIdentity(pid: number): ProcessIdentity | undefined;
355
+ //#endregion
336
356
  //#region src/raw-capture.d.ts
337
357
  /** Hard encoded-byte bound across canonical JSON spool files, including live writers.
338
358
  * Temporary trim copies and filesystem allocation are separate from this budget.
@@ -436,7 +456,7 @@ interface RpcBridgeLogger {
436
456
  warn: (msg: string, meta?: Record<string, unknown>) => void;
437
457
  error: (msg: string, meta?: Record<string, unknown>) => void;
438
458
  }
439
- interface RpcBridgeConfig {
459
+ interface RpcBridgeConfig extends Pick<CliSpawnConfig, "inheritEnv"> {
440
460
  command: string;
441
461
  args: string[];
442
462
  cwd: string;
@@ -532,13 +552,7 @@ declare class RpcRequestTimeoutError extends Error {
532
552
  }
533
553
  //#endregion
534
554
  //#region src/rpc-stdio-process.d.ts
535
- /**
536
- * Spawn an RpcBridge over a long-running stdio child process.
537
- *
538
- * The bridge is usable immediately after this call — outbound writes
539
- * before the child has booted are buffered by Node's stdin pipe. Inbound
540
- * dispatch starts as soon as the child writes its first line.
541
- */
555
+ /** Spawn one stdio RPC child; early writes buffer until it boots. */
542
556
  declare function spawnRpcBridge(config: RpcBridgeConfig): RpcBridge;
543
557
  //#endregion
544
558
  //#region src/shell-quote.d.ts
@@ -569,5 +583,5 @@ declare function mergeSpawnEnv(base: NodeJS.ProcessEnv, overrides: Record<string
569
583
  */
570
584
  declare function createStreamParser<T>(config: StreamParserConfig<T>): StreamParser<T>;
571
585
  //#endregion
572
- 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, createDeferredParser, createHeldSpareRegistry, createStreamParser, execCli, launchCliProcess, launchDifferences, mergeSpawnEnv, openRawCapture, removeRawCapture, resolveRawCapturePath, shellQuote, spawnCliProcess, spawnRpcBridge, summarizeRawCapture, trimRawCapture, withRawCaptureAttempt };
586
+ 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, createDeferredParser, createHeldSpareRegistry, createStreamParser, execCli, launchCliProcess, launchDifferences, mergeSpawnEnv, openRawCapture, readProcessIdentity, removeRawCapture, resolveRawCapturePath, shellQuote, spawnCliProcess, spawnRpcBridge, summarizeRawCapture, trimRawCapture, withRawCaptureAttempt };
573
587
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -770,7 +770,7 @@ var ProcessCapture = class {
770
770
  };
771
771
  //#endregion
772
772
  //#region src/owned-process-tree.ts
773
- function identity(pid) {
773
+ function readProcessIdentity(pid) {
774
774
  try {
775
775
  const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
776
776
  const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(/\s+/);
@@ -794,7 +794,7 @@ var OwnedProcessTree = class {
794
794
  groups = /* @__PURE__ */ new Map();
795
795
  root;
796
796
  constructor(rootPid) {
797
- const root = identity(rootPid);
797
+ const root = readProcessIdentity(rootPid);
798
798
  this.root = root;
799
799
  if (root) {
800
800
  this.processes.set(rootPid, root);
@@ -809,7 +809,7 @@ var OwnedProcessTree = class {
809
809
  const key = `${expected.pid}:${expected.start}`;
810
810
  if (seen.has(key)) continue;
811
811
  seen.add(key);
812
- const current = identity(expected.pid);
812
+ const current = readProcessIdentity(expected.pid);
813
813
  if (!current || current.start !== expected.start || current.state === "Z" || current.state === "X") {
814
814
  if (this.processes.get(expected.pid)?.start === expected.start) this.processes.delete(expected.pid);
815
815
  continue;
@@ -826,7 +826,7 @@ var OwnedProcessTree = class {
826
826
  for (const value of children.trim().split(/\s+/).filter(Boolean)) {
827
827
  const pid = Number(value);
828
828
  if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("Invalid child process identity");
829
- const child = identity(pid);
829
+ const child = readProcessIdentity(pid);
830
830
  if (!child || child.parent !== current.pid) continue;
831
831
  this.processes.set(pid, child);
832
832
  queue.push(child);
@@ -837,7 +837,7 @@ var OwnedProcessTree = class {
837
837
  }
838
838
  live() {
839
839
  return [...this.processes.values()].flatMap((expected) => {
840
- const current = identity(expected.pid);
840
+ const current = readProcessIdentity(expected.pid);
841
841
  return current && current.start === expected.start && current.state !== "Z" && current.state !== "X" ? [current] : [];
842
842
  });
843
843
  }
@@ -854,14 +854,14 @@ var OwnedProcessTree = class {
854
854
  }
855
855
  for (const entry of readdirSync("/proc")) {
856
856
  if (!/^[1-9][0-9]*$/.test(entry)) continue;
857
- const member = identity(Number(entry));
857
+ const member = readProcessIdentity(Number(entry));
858
858
  if (member && member.group === root.group && member.state !== "Z" && member.state !== "X") this.processes.set(member.pid, member);
859
859
  }
860
860
  return this.live().length > 0;
861
861
  }
862
862
  ownsRootGroup() {
863
863
  if (!this.root || this.root.group !== this.root.pid) return false;
864
- const current = identity(this.root.pid);
864
+ const current = readProcessIdentity(this.root.pid);
865
865
  return !current || current.start === this.root.start;
866
866
  }
867
867
  signal(signal) {
@@ -875,7 +875,7 @@ var OwnedProcessTree = class {
875
875
  }
876
876
  for (const member of this.live()) {
877
877
  const groupStart = this.groups.get(member.group);
878
- const leader = groupStart === void 0 ? void 0 : identity(member.group);
878
+ const leader = groupStart === void 0 ? void 0 : readProcessIdentity(member.group);
879
879
  const target = groupStart !== void 0 && (!leader || leader.start === groupStart) ? -member.group : member.pid;
880
880
  if (target < 0 && signaledGroups.has(target)) continue;
881
881
  try {
@@ -1118,7 +1118,7 @@ function attachCliProcess(config, parserConfig, run) {
1118
1118
  const { launch, killer, capture, detached } = run;
1119
1119
  const child = launch.child;
1120
1120
  const spawnedAt = Date.now();
1121
- const stdin = watchStdinFailure(child, killer);
1121
+ const stdin = watchStdinFailure(child, killer, config.stdinFailure);
1122
1122
  const group = config.ownProcessGroup && detached && process.platform !== "win32" && child.pid ? new CliProcessGroup(child.pid) : void 0;
1123
1123
  child.stdout?.on("data", (chunk) => capture.frame("stdout", chunk));
1124
1124
  child.stderr?.on("data", (chunk) => capture.frame("stderr", chunk));
@@ -1201,11 +1201,16 @@ function spawnChild(config, processEnv, detached) {
1201
1201
  ...isolated ? safeSpawnOptions : spawnOptions
1202
1202
  });
1203
1203
  }
1204
- function watchStdinFailure(child, killer) {
1205
- const failure = { error: void 0 };
1204
+ function watchStdinFailure(child, killer, mode = "stop") {
1205
+ const failure = {
1206
+ error: void 0,
1207
+ code: void 0
1208
+ };
1206
1209
  child.stdin?.on("error", (error) => {
1207
1210
  if (failure.error !== void 0) return;
1208
1211
  failure.error = error.message;
1212
+ failure.code = error.code;
1213
+ if (mode === "report") return;
1209
1214
  killer.kill("SIGTERM");
1210
1215
  if (!killer.escalating) killer.escalate(() => child.exitCode === null && child.signalCode === null);
1211
1216
  });
@@ -1280,6 +1285,7 @@ function createExitPromise(child, run) {
1280
1285
  timeoutReason: deadlines.timeoutReason,
1281
1286
  timeoutDiagnostic: deadlines.timeoutDiagnostic,
1282
1287
  stdinError: stdin.error,
1288
+ ...stdin.code === void 0 ? {} : { stdinErrorCode: stdin.code },
1283
1289
  captureError: capture.error,
1284
1290
  ...abort.aborted ? { aborted: true } : {},
1285
1291
  ...processGroupError === void 0 ? {} : { processGroupError },
@@ -1325,6 +1331,10 @@ async function execCli(config, parserConfig, options = {}) {
1325
1331
  } : void 0);
1326
1332
  cliProcess.process.stderr?.on("data", (chunk) => stderr.append(chunk));
1327
1333
  if (!parserConfig) cliProcess.process.stdout?.on("data", (chunk) => stdout.append(chunk));
1334
+ if (options.stdin !== void 0) {
1335
+ if (options.stdin) cliProcess.write(options.stdin);
1336
+ cliProcess.closeInput();
1337
+ }
1328
1338
  return {
1329
1339
  exit: await cliProcess.exitPromise,
1330
1340
  stderr: stderr.text(),
@@ -2123,17 +2133,10 @@ const noopLogger = {
2123
2133
  warn: () => {},
2124
2134
  error: () => {}
2125
2135
  };
2126
- /**
2127
- * Spawn an RpcBridge over a long-running stdio child process.
2128
- *
2129
- * The bridge is usable immediately after this call — outbound writes
2130
- * before the child has booted are buffered by Node's stdin pipe. Inbound
2131
- * dispatch starts as soon as the child writes its first line.
2132
- */
2136
+ /** Spawn one stdio RPC child; early writes buffer until it boots. */
2133
2137
  function spawnRpcBridge(config) {
2134
2138
  const { maxPendingRequests = DEFAULT_MAX_PENDING, maxStderrBytes = DEFAULT_MAX_STDERR_BYTES, defaultRequestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, defaultCloseGraceMs = DEFAULT_CLOSE_GRACE_MS, hardCloseDeadlineMs = DEFAULT_HARD_CLOSE_DEADLINE_MS, logger = noopLogger, rawCapturePath, rawCapturePerTurn = false, detached = false, stdinCloseGraceMs = 0 } = config;
2135
- const processEnv = mergeSpawnEnv(process.env, config.env);
2136
- applyChildToolPath(processEnv);
2139
+ const processEnv = buildChildEnv(config);
2137
2140
  const capture = new RpcByteCapture(rawCapturePath, rawCapturePerTurn, (killSignal) => owner.kill(killSignal), () => owner.captureTree(), () => lifecycle.childError?.message ?? null);
2138
2141
  let child;
2139
2142
  let isolatedLaunch;
@@ -2200,13 +2203,14 @@ function spawnRpcBridge(config) {
2200
2203
  }
2201
2204
  /** Start the bridge's child: through the runner for an isolated identity. */
2202
2205
  function spawnBridgeChild(config, processEnv) {
2203
- const { command, args, cwd, env, uid, gid, isolatedIdentity } = config;
2206
+ const { command, args, cwd, uid, gid, isolatedIdentity } = config;
2204
2207
  if (isolatedIdentity) {
2205
2208
  const isolatedLaunch = spawnCliProcess({
2206
2209
  command,
2207
2210
  args,
2208
2211
  cwd,
2209
- env,
2212
+ env: processEnv,
2213
+ inheritEnv: false,
2210
2214
  isolatedIdentity,
2211
2215
  spawnOptions: {
2212
2216
  uid: uid ?? isolatedIdentity.uid,
@@ -2270,6 +2274,6 @@ function shellQuote(value) {
2270
2274
  return `'${value.replace(/'/g, `'"'"'`)}'`;
2271
2275
  }
2272
2276
  //#endregion
2273
- export { BridgeClosedError, HELD_SPARE_IDLE_MS, InvalidAttachmentError, JsonRpcError, RAW_CAPTURE_ROOT, RAW_CAPTURE_TOTAL_CAP_BYTES, RpcRequestTimeoutError, allowRetainedRawCapture, argAfter, createDeferredParser, createHeldSpareRegistry, createStreamParser, execCli, launchCliProcess, launchDifferences, mergeSpawnEnv, openRawCapture, removeRawCapture, resolveRawCapturePath, shellQuote, spawnCliProcess, spawnRpcBridge, summarizeRawCapture, trimRawCapture, withRawCaptureAttempt };
2277
+ export { BridgeClosedError, HELD_SPARE_IDLE_MS, InvalidAttachmentError, JsonRpcError, RAW_CAPTURE_ROOT, RAW_CAPTURE_TOTAL_CAP_BYTES, RpcRequestTimeoutError, allowRetainedRawCapture, argAfter, createDeferredParser, createHeldSpareRegistry, createStreamParser, execCli, launchCliProcess, launchDifferences, mergeSpawnEnv, openRawCapture, readProcessIdentity, removeRawCapture, resolveRawCapturePath, shellQuote, spawnCliProcess, spawnRpcBridge, summarizeRawCapture, trimRawCapture, withRawCaptureAttempt };
2274
2278
 
2275
2279
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-cli-runner",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
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": "e962211a1ce5f2e11a99b60421e45fca5547ca2d",
30
- "mergedAt": "2026-10-27T03:53:58-06:00"
29
+ "sourceSha": "bc9b917e225d6978056079834c77d338dabb5ded",
30
+ "mergedAt": "2026-11-01T17:57:50-08:00"
31
31
  },
32
32
  "scripts": {
33
33
  "build": "tsdown",