@tangle-network/sdk-cli-runner 0.3.9 → 0.3.10

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
@@ -344,6 +344,16 @@ declare function launchDifferences(spare: Pick<HeldSpareFields<unknown>, "args"
344
344
  }, comparable?: (key: string, value: string | undefined) => string | undefined): string[];
345
345
  //#endregion
346
346
  //#region src/owned-process-tree.d.ts
347
+ /**
348
+ * A harness process started before its turn runs at the lowest CPU priority
349
+ * until a turn adopts it, so its boot does not slow the box's first command
350
+ * (run 12, eu1: a claimed box's first `node -v` took 5106 ms p50 with 25
351
+ * claims at once against 1677 ms alone, while each claim booted OpenCode on
352
+ * the guest's 2 vCPUs). Only where the adopting turn can raise it back.
353
+ */
354
+ declare function yieldUntilAdopted(pid: number | undefined): void;
355
+ /** The adopting turn runs the process at the sidecar's own priority. */
356
+ declare function restoreTurnPriority(pid: number | undefined): void;
347
357
  type ProcessIdentity = {
348
358
  pid: number;
349
359
  parent: number;
@@ -583,5 +593,5 @@ declare function mergeSpawnEnv(base: NodeJS.ProcessEnv, overrides: Record<string
583
593
  */
584
594
  declare function createStreamParser<T>(config: StreamParserConfig<T>): StreamParser<T>;
585
595
  //#endregion
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 };
596
+ 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, restoreTurnPriority, shellQuote, spawnCliProcess, spawnRpcBridge, summarizeRawCapture, trimRawCapture, withRawCaptureAttempt, yieldUntilAdopted };
587
597
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -6,8 +6,8 @@ import { AsyncLocalStorage } from "node:async_hooks";
6
6
  import { createHash, randomUUID } from "node:crypto";
7
7
  import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeSync } from "node:fs";
8
8
  import { open } from "node:fs/promises";
9
+ import { getPriority, setPriority, tmpdir } from "node:os";
9
10
  import { once } from "node:events";
10
- import { tmpdir } from "node:os";
11
11
  import { PassThrough } from "node:stream";
12
12
  //#region src/attachment-error.ts
13
13
  /** An attachment cannot be delivered to a native CLI. */
@@ -773,6 +773,80 @@ var ProcessCapture = class {
773
773
  };
774
774
  //#endregion
775
775
  //#region src/owned-process-tree.ts
776
+ /** Every process /proc lists that is neither a zombie nor dead. */
777
+ function liveProcesses() {
778
+ return readdirSync("/proc").flatMap((entry) => {
779
+ let member;
780
+ try {
781
+ if (/^[1-9][0-9]*$/.test(entry)) member = readProcessIdentity(+entry);
782
+ } catch {}
783
+ return member && member.state !== "Z" && member.state !== "X" ? [member] : [];
784
+ });
785
+ }
786
+ /**
787
+ * The sidecar may set a niceness back to its own: CAP_SYS_NICE, or an
788
+ * RLIMIT_NICE its harness inherits that allows it.
789
+ */
790
+ function canRaisePriority() {
791
+ if (process.platform !== "linux") return false;
792
+ const status = readFileSync("/proc/self/status", "utf8");
793
+ const caps = /^CapEff:\s+([0-9a-f]+)$/m.exec(status)?.[1];
794
+ if (caps && BigInt(`0x${caps}`) >> 23n & 1n) return true;
795
+ const limits = readFileSync("/proc/self/limits", "utf8");
796
+ const limit = /^Max nice priority\s+(\S+)/m.exec(limits)?.[1];
797
+ return limit === "unlimited" || 20 - Number(limit) <= getPriority();
798
+ }
799
+ /**
800
+ * Set the niceness of every thread of `root`, of its process group, and of
801
+ * every descendant that left that group. Linux niceness is per thread, and a
802
+ * thread or child started later inherits its creator's, so a pass repeats
803
+ * (up to three) while it still finds one to change. Best effort: a member
804
+ * that exits meanwhile is skipped, and the process runs on either way.
805
+ */
806
+ function reniceTree(root, priority) {
807
+ try {
808
+ if (!root || !canRaisePriority()) return;
809
+ for (let pass = 0, changed = true; changed && pass < 3; pass += 1) {
810
+ changed = false;
811
+ const live = liveProcesses();
812
+ const members = new Set([root]);
813
+ for (let grew = true; grew;) {
814
+ grew = false;
815
+ for (const { pid, group, parent } of live) {
816
+ if (members.has(pid) || group !== root && !members.has(parent)) continue;
817
+ members.add(pid);
818
+ grew = true;
819
+ }
820
+ }
821
+ for (const pid of members) for (const thread of threadsOf(pid)) try {
822
+ if (getPriority(+thread) === priority) continue;
823
+ setPriority(+thread, priority);
824
+ changed = true;
825
+ } catch {}
826
+ }
827
+ } catch {}
828
+ }
829
+ function threadsOf(pid) {
830
+ try {
831
+ return readdirSync(`/proc/${pid}/task`);
832
+ } catch {
833
+ return [];
834
+ }
835
+ }
836
+ /**
837
+ * A harness process started before its turn runs at the lowest CPU priority
838
+ * until a turn adopts it, so its boot does not slow the box's first command
839
+ * (run 12, eu1: a claimed box's first `node -v` took 5106 ms p50 with 25
840
+ * claims at once against 1677 ms alone, while each claim booted OpenCode on
841
+ * the guest's 2 vCPUs). Only where the adopting turn can raise it back.
842
+ */
843
+ function yieldUntilAdopted(pid) {
844
+ reniceTree(pid, 19);
845
+ }
846
+ /** The adopting turn runs the process at the sidecar's own priority. */
847
+ function restoreTurnPriority(pid) {
848
+ reniceTree(pid, getPriority());
849
+ }
776
850
  function readProcessIdentity(pid) {
777
851
  try {
778
852
  const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
@@ -856,11 +930,7 @@ var OwnedProcessTree = class {
856
930
  if (error.code === "ESRCH") return false;
857
931
  throw error;
858
932
  }
859
- for (const entry of readdirSync("/proc")) {
860
- if (!/^[1-9][0-9]*$/.test(entry)) continue;
861
- const member = readProcessIdentity(Number(entry));
862
- if (member && member.group === root.group && member.state !== "Z" && member.state !== "X") this.processes.set(member.pid, member);
863
- }
933
+ for (const member of liveProcesses()) if (member.group === root.group) this.processes.set(member.pid, member);
864
934
  return this.live().length > 0;
865
935
  }
866
936
  ownsRootGroup() {
@@ -1431,6 +1501,23 @@ async function execCli(config, parserConfig, options = {}) {
1431
1501
  //#endregion
1432
1502
  //#region src/held-spare.ts
1433
1503
  /**
1504
+ * A CLI process started before the turn that uses it.
1505
+ *
1506
+ * A one-shot CLI spends 150-400 ms starting (config, auth, settings, MCP)
1507
+ * before it reads its prompt. A process started with its stdin held open does
1508
+ * that work ahead of the turn; the turn then writes its prompt and the first
1509
+ * model request leaves in tens of milliseconds (tests/harness/spikes/
1510
+ * held-stdin.mjs measured claude 2.1.296 and codex 0.162.1 doing exactly
1511
+ * this).
1512
+ *
1513
+ * A spare belongs to one runtime HOME. A turn adopts it only when the turn
1514
+ * would have launched an identical process: same argv, same environment, bar
1515
+ * what the caller names as free to differ. Anything else stops the spare and
1516
+ * the turn starts its own process, as it does without a spare.
1517
+ *
1518
+ * One registry per harness: `createHeldSpareRegistry()`.
1519
+ */
1520
+ /**
1434
1521
  * A parser that holds the spare's output until a turn adopts the process, then
1435
1522
  * hands the turn's own parser everything the CLI printed so far, in order.
1436
1523
  */
@@ -1502,6 +1589,7 @@ function createHeldSpareRegistry() {
1502
1589
  };
1503
1590
  const claim = (spare) => {
1504
1591
  spare.state = "claimed";
1592
+ restoreTurnPriority(spare.process.pid);
1505
1593
  if (spare.idleTimer) clearTimeout(spare.idleTimer);
1506
1594
  if (spares.get(spare.home) === spare) spares.delete(spare.home);
1507
1595
  };
@@ -1509,6 +1597,7 @@ function createHeldSpareRegistry() {
1509
1597
  spareFor: (home) => home ? spares.get(home) : void 0,
1510
1598
  register: (spare) => {
1511
1599
  spares.set(spare.home, spare);
1600
+ yieldUntilAdopted(spare.process.pid);
1512
1601
  },
1513
1602
  has: (home) => spares.has(home),
1514
1603
  stop,
@@ -2360,6 +2449,6 @@ function shellQuote(value) {
2360
2449
  return `'${value.replace(/'/g, `'"'"'`)}'`;
2361
2450
  }
2362
2451
  //#endregion
2363
- 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 };
2452
+ 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, restoreTurnPriority, shellQuote, spawnCliProcess, spawnRpcBridge, summarizeRawCapture, trimRawCapture, withRawCaptureAttempt, yieldUntilAdopted };
2364
2453
 
2365
2454
  //# 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.9",
3
+ "version": "0.3.10",
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": "72e7f17f94d9512ecaca0d9b938c582954362a4a",
30
- "mergedAt": "2026-11-05T14:42:53-08:00"
29
+ "sourceSha": "9b98f0b7cbbe555b62b5937c822e9a353aa4f7aa",
30
+ "mergedAt": "2026-11-07T13:30:34-08:00"
31
31
  },
32
32
  "scripts": {
33
33
  "build": "tsdown",