sprag-cli 3.107.0 → 3.107.1

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/bin/cli.js CHANGED
@@ -118,7 +118,8 @@ function segmentsFromArgs() {
118
118
 
119
119
  /**
120
120
  * Terminal width for the statusline wrap: `--columns N`, else the COLUMNS that
121
- * Claude Code exports to the statusline process, else 0 (no wrapping). The demo
121
+ * Claude Code exports to the statusline process, else 0 (the caller decides; the
122
+ * live statusline then assumes 120). The demo
122
123
  * passes `useEnv: false` so recordings do not change with the shell they run in.
123
124
  */
124
125
  function columnsFromArgs({ useEnv = true } = {}) {
@@ -249,7 +250,7 @@ Usage:
249
250
  sprag --uninstall-hook remove that hook
250
251
  sprag --statusline one-line output for Claude Code statusline
251
252
  --verbose / --no-color / --icon / --no-timer / --single-line
252
- --columns N wrap chips to N cells (default: $COLUMNS, which Claude Code sets)
253
+ --columns N fit lines to N cells (default: $COLUMNS, which Claude Code sets, else 120)
253
254
 
254
255
  Run any subcommand with --help for its own options where available.
255
256
  Bug reports & feature requests: https://github.com/rootstudioyaml/sprag/issues
@@ -1081,6 +1082,7 @@ async function main() {
1081
1082
  // This session's subagent runs, matched to the session Claude Code is
1082
1083
  // drawing for by the transcript path / session id in its payload.
1083
1084
  let sessionDelegation;
1085
+ let runningNow = null;
1084
1086
  // Delegation-rule counts, read only when `--segments` names `rules`: the
1085
1087
  // chip is opt-in, so nothing else would look at them.
1086
1088
  let ruleStats;
@@ -1095,6 +1097,18 @@ async function main() {
1095
1097
  } catch (e) {
1096
1098
  debug('statusline-data:session-delegation', e);
1097
1099
  }
1100
+ // Subagents working right now, from the session's subagent transcripts: one
1101
+ // readdir and a stat per file, never a parse of a whole transcript.
1102
+ try {
1103
+ const { runningSubagents } = await import('../src/statusline-running.js');
1104
+ const running = runningSubagents(extractTranscriptPath(stdinJson));
1105
+ if (running) {
1106
+ const { userLanguage } = await import('../src/config.js');
1107
+ runningNow = { ...running, lang: userLanguage() };
1108
+ }
1109
+ } catch (e) {
1110
+ debug('statusline-running', e);
1111
+ }
1098
1112
  if (rulesRequested) {
1099
1113
  try {
1100
1114
  const { delegationRuleStats } = await import('../src/statusline-data.js');
@@ -1145,6 +1159,7 @@ async function main() {
1145
1159
  gradeActions: isStatusline ? gradeActions : undefined,
1146
1160
  relaxUntil: isStatusline ? relaxUntilNow : undefined,
1147
1161
  sessionDelegation,
1162
+ runningSubagents: runningNow,
1148
1163
  ruleStats,
1149
1164
  ttlBucket,
1150
1165
  };
@@ -1157,7 +1172,7 @@ async function main() {
1157
1172
  const { formatReport } = await import('../src/formatters/csv.js');
1158
1173
  output = formatReport(data);
1159
1174
  } else if (format === 'statusline') {
1160
- const { formatReport } = await import('../src/formatters/statusline.js');
1175
+ const { formatReport, DEFAULT_COLUMNS } = await import('../src/formatters/statusline.js');
1161
1176
  const { statuslineDefaults } = await import('../src/config.js');
1162
1177
  const cfg = statuslineDefaults();
1163
1178
 
@@ -1184,7 +1199,10 @@ async function main() {
1184
1199
  // multi-line statusline in some versions (anthropics/claude-code#35176)
1185
1200
  // — --single-line restores the legacy one-line layout in that case.
1186
1201
  singleLine: hasFlag('--single-line'),
1187
- columns: columnsFromArgs(),
1202
+ // `--columns`, else the COLUMNS Claude Code exports, else a 120 cell
1203
+ // terminal: an unknown width must not mean "no limit", since the lines
1204
+ // are then cut or folded by the terminal in the middle of a chip.
1205
+ columns: columnsFromArgs() || DEFAULT_COLUMNS,
1188
1206
  });
1189
1207
  } else {
1190
1208
  // The first screen is the pitch: what share of recent work a cheaper model
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.107.0",
3
+ "version": "3.107.1",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  # Delegation bounds
2
2
 
3
- You were spawned by a delegation call from another session. These four rules
3
+ You were spawned by a delegation call from another session. These five rules
4
4
  keep your exploration finite and your output usable by the caller that spawned
5
5
  you.
6
6
 
@@ -28,3 +28,9 @@ you.
28
28
  from memory. A citation lets the caller check your claim in one step; an
29
29
  unattributed claim forces the caller to redo the very search you were
30
30
  delegated to save it from doing.
31
+
32
+ 5. **Write shell commands that survive zsh.** Print separators with
33
+ `printf '%s\n' '----'`, not `echo ====` (zsh reads a leading `=` as a
34
+ command lookup and fails). Quote any argument with `?`, `*` or `[`, URLs
35
+ above all. The shell tool is `Bash`, with a capital B. A refused command
36
+ line wastes a call and reads as a failure in the caller's records.
@@ -607,6 +607,28 @@ function buildSessionDelegationSeg(sd, c, isIcon, verbose, g) {
607
607
  return `${c(CYAN)}${label} ${total}${c(RESET)}${split}${spent}`;
608
608
  }
609
609
 
610
+ /**
611
+ * Subagents running right now: `⏳ 서브에이전트 2개 실행 중 (sonnet 1, opus 1)`
612
+ * (English: `⏳ 2 subagents running (sonnet 1, opus 1)`). It leads the first
613
+ * line and exists only while something is running, so its appearance is the
614
+ * signal. The session chip further down counts every run the session started;
615
+ * this one answers "is anything working for me at this moment". The model split
616
+ * covers the runs whose model could be read, and is left off when none could.
617
+ * Icon modes draw the hourglass; text mode and the narrow set use words alone.
618
+ */
619
+ function buildRunningSeg(rs, c, isIcon, g) {
620
+ const n = Number(rs && rs.count);
621
+ if (!Number.isFinite(n) || n <= 0) return null;
622
+ const ko = rs.lang === 'ko';
623
+ const words = ko ? `서브에이전트 ${n}개 실행 중` : `${n} ${n === 1 ? 'subagent' : 'subagents'} running`;
624
+ const glyph = isIcon && g.running ? `${g.running} ` : '';
625
+ const families = Array.isArray(rs.families)
626
+ ? rs.families.filter((f) => f && Number(f.runs) > 0).map((f) => `${f.family} ${f.runs}`)
627
+ : [];
628
+ const split = families.length ? ` ${c(GRAY)}(${families.join(', ')})${c(RESET)}` : '';
629
+ return `${c(BOLD)}${c(CYAN)}${glyph}${words}${c(RESET)}${split}`;
630
+ }
631
+
610
632
  /**
611
633
  * Cap-warn chip builder — shared by the full report and the no-session
612
634
  * fallback line. At 90%+ the user wants to know "when can I send again", so
@@ -643,6 +665,54 @@ const HEADLINE_INDENT = ' ';
643
665
 
644
666
  const availWidth = (columns) => Math.max(20, columns - STATUSLINE_MARGIN);
645
667
 
668
+ /** Width assumed for the statusline when neither `--columns` nor COLUMNS says. */
669
+ export const DEFAULT_COLUMNS = 120;
670
+ /** Model pairs the routing headline keeps when it has to shorten itself. */
671
+ const HEADLINE_PAIRS_SHORT = 2;
672
+
673
+ /**
674
+ * A headline split at its joints: sections joined by a gray `|`, items by a
675
+ * gray `·`. Each piece carries the separator that precedes it.
676
+ */
677
+ function splitHeadline(line, c) {
678
+ const bar = ` ${c(GRAY)}|${c(RESET)} `;
679
+ const dot = ` ${c(GRAY)}·${c(RESET)} `;
680
+ const pieces = [];
681
+ line.split(bar).forEach((section, i) => {
682
+ section.split(dot).forEach((text, j) => pieces.push({ text, sep: j ? dot : i ? bar : '' }));
683
+ });
684
+ return pieces;
685
+ }
686
+
687
+ /**
688
+ * One headline on one row. A headline that is too wide gives up its tail items,
689
+ * lowest priority first (they are listed biggest first), and ends in `…`; it is
690
+ * not wrapped onto more rows. The routing headline tries its short form (top
691
+ * pairs plus `+N`) before anything is cut. The first piece always stays.
692
+ *
693
+ * @param {{ line: string, short?: string|null }} h
694
+ * @param {number} avail cells available for the row
695
+ * @param {(v: string) => string} c
696
+ * @param {string} [lead] text that will sit in front of the row (width only)
697
+ */
698
+ function fitHeadline(h, avail, c, lead = '') {
699
+ const room = avail - cellWidth(lead);
700
+ if (cellWidth(h.line) <= room) return h.line;
701
+ const body = h.short && cellWidth(h.short) <= room ? h.short : (h.short || h.line);
702
+ if (cellWidth(body) <= room) return body;
703
+ const marker = ` ${c(GRAY)}…${c(RESET)}`;
704
+ const markerW = 2;
705
+ const kept = [];
706
+ let used = 0;
707
+ for (const { text, sep } of splitHeadline(body, c)) {
708
+ const w = cellWidth(text) + (kept.length ? cellWidth(sep) : 0);
709
+ if (kept.length && used + w + markerW > room) break;
710
+ used += w;
711
+ kept.push(kept.length ? sep + text : text);
712
+ }
713
+ return kept.join('') + marker;
714
+ }
715
+
646
716
  /**
647
717
  * Wrap one headline line to `avail` cells. A headline is sections joined by a
648
718
  * gray `|`, and a section is items joined by a gray `·` (see buildDelegatedSeg
@@ -653,12 +723,7 @@ const availWidth = (columns) => Math.max(20, columns - STATUSLINE_MARGIN);
653
723
  */
654
724
  function wrapHeadline(line, avail, c) {
655
725
  if (cellWidth(line) <= avail) return [line];
656
- const bar = ` ${c(GRAY)}|${c(RESET)} `;
657
- const dot = ` ${c(GRAY)}·${c(RESET)} `;
658
- const pieces = [];
659
- line.split(bar).forEach((section, i) => {
660
- section.split(dot).forEach((text, j) => pieces.push({ text, sep: j ? dot : i ? bar : '' }));
661
- });
726
+ const pieces = splitHeadline(line, c);
662
727
  const rows = [];
663
728
  let row = '';
664
729
  let used = 0;
@@ -1248,6 +1313,7 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1248
1313
  // icon: "🔀 Routing saved $9.8 | opus→haiku ×2 $6.4 · fable→sonnet ×1 $3.4"
1249
1314
  // text: "Routing saved $9.8 | opus→haiku ×2 $6.4 · fable→sonnet ×1 $3.4"
1250
1315
  let totalsLine = null;
1316
+ let totalsShort = null;
1251
1317
  const totalsNum = Number(totals && totals.total);
1252
1318
  // A zero total gets its line only when a reset mark explains it; see the
1253
1319
  // note above `routingSince`.
@@ -1272,11 +1338,22 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1272
1338
  .join(` ${c(GRAY)}·${c(RESET)} `);
1273
1339
  // A net loss must not read as a win, and a zero is neither.
1274
1340
  const tone = totalsNum < 0 ? RED : totalsNum > 0 ? GREEN : GRAY;
1275
- totalsLine =
1341
+ const compose = (text) =>
1276
1342
  `${c(tone)}${c(BOLD)}${head}${c(RESET)} ` +
1277
1343
  `${c(tone)}${formatMoney(totalsNum)}${c(RESET)}` +
1278
1344
  sinceWord(routingSince) + scanTag +
1279
- (pairText ? ` ${c(GRAY)}|${c(RESET)} ${pairText}` : '');
1345
+ (text ? ` ${c(GRAY)}|${c(RESET)} ${text}` : '');
1346
+ totalsLine = compose(pairText);
1347
+ // The short form for a line that is too wide: the two biggest moves (the
1348
+ // ledger lists them biggest first) and the count of the rest. The full list
1349
+ // stays the default whenever it fits, and a user who named `delegated` in
1350
+ // `--segments` always gets it (see buildHeadlines).
1351
+ if (pairs.length > HEADLINE_PAIRS_SHORT) {
1352
+ const top = pairs.slice(0, HEADLINE_PAIRS_SHORT)
1353
+ .map((p) => `${c(GRAY)}${p.from}→${p.to} ×${p.runs} ${formatMoney(p.usd)}${c(RESET)}`)
1354
+ .join(` ${c(GRAY)}·${c(RESET)} `);
1355
+ totalsShort = compose(`${top} ${c(GRAY)}·${c(RESET)} ${c(GRAY)}+${pairs.length - HEADLINE_PAIRS_SHORT}${c(RESET)}`);
1356
+ }
1280
1357
  }
1281
1358
 
1282
1359
  // The effort guard line (multi-line layout): the top line of the statusline,
@@ -1310,7 +1387,7 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1310
1387
  ? [unresolvedSeg, guardLine ? null : raisedSeg, modelUpSeg, gradeSeg]
1311
1388
  : [guardLine ? null : raisedSeg, modelUpSeg, gradeSeg])
1312
1389
  : [delegateSeg, guardLine ? null : raisedSeg, modelUpSeg, gradeSeg, delegateExtra],
1313
- headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine } : null,
1390
+ headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine, short: totalsShort } : null,
1314
1391
  guardLine,
1315
1392
  };
1316
1393
  }
@@ -1587,7 +1664,7 @@ function arrangeSegments(order, s) {
1587
1664
  /**
1588
1665
  * The headline lines that sit above the chips, as one string of `line\n` pairs.
1589
1666
  */
1590
- function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v, teamLine = null) {
1667
+ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v, teamLine = null, { trim = false, lead = null } = {}) {
1591
1668
  // Each savings source that earned real money gets a headline line, ordered
1592
1669
  // biggest saver first — the top line is the one the eye lands on, so it
1593
1670
  // goes to whichever habit is actually paying for the tool. The diagnostics
@@ -1601,9 +1678,18 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
1601
1678
  if (delegated.guardLine && want('delegated')) headlines.unshift({ usd: 0, line: delegated.guardLine });
1602
1679
  // The team line comes last: identity and standing, after the money.
1603
1680
  if (teamLine && want('team')) headlines.push(teamLine);
1681
+ // The running-subagents chip leads the first row. It is joined before the
1682
+ // row is fitted so its width counts, and it is never the part that is cut.
1683
+ const join = lead && headlines.length ? `${lead}${CHIP_SEP}` : '';
1604
1684
  const rows = columns
1605
- ? headlines.flatMap((h) => wrapHeadline(h.line, availWidth(columns), c))
1606
- : headlines.map((h) => h.line);
1685
+ ? headlines.flatMap((h, i) => {
1686
+ const prefix = i === 0 ? join : '';
1687
+ // `trim` is the default layout: one row per headline, tail given up with
1688
+ // `…`. A user who picked the segments gets every item, wrapped instead.
1689
+ if (trim) return [prefix + fitHeadline(h, availWidth(columns), c, prefix)];
1690
+ return wrapHeadline(prefix + h.line, availWidth(columns), c);
1691
+ })
1692
+ : headlines.map((h, i) => (i === 0 ? join : '') + h.line);
1607
1693
  return rows.map((row) => row + eol + '\n').join('');
1608
1694
  }
1609
1695
 
@@ -1708,17 +1794,36 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1708
1794
  const order = resolveSegmentOrder(segments, caps, updateAvailable);
1709
1795
  const segs = arrangeSegments(order, built);
1710
1796
 
1797
+ // Leads the first line, ahead of every segment. A caller's `--segments` list
1798
+ // is a filter, so the chip needs a name in it too: `running`, or the
1799
+ // subagent names it belongs with.
1800
+ const runningSeg = !allow || ['running', 'subagents', 'delegated'].some((n) => allow.has(n))
1801
+ ? buildRunningSeg(data.runningSubagents, c, isIcon, g)
1802
+ : null;
1803
+ // Items the user picked are never given up for width: only the default layout
1804
+ // trims a headline to one row with `…`; an explicit list wraps instead.
1805
+ const trim = !allow;
1806
+
1711
1807
  // Trailing erase-to-end-of-line so any leftover characters from a previous
1712
1808
  // (longer) statusline render don't bleed into ours. \x1b[K is the standard
1713
1809
  // "erase from cursor to EOL" CSI. Only emitted when color (i.e. ANSI) is
1714
1810
  // allowed — --no-color/NO_COLOR consumers expect escape-free output.
1715
1811
  const eol = color ? '\x1b[K' : '';
1716
- if (singleLine || !columns) return buildHeadlines(delegated, doc2md, want, eol, 0, c, teamLine) + segs.join(' · ') + eol;
1717
- const headlines = buildHeadlines(delegated, doc2md, want, eol, columns, c, teamLine);
1812
+ // With a headline row the chip joins that row; without one it is the first chip.
1813
+ const hasHeadline = !!((delegated.headline && want('delegated')) || (delegated.guardLine && want('delegated'))
1814
+ || (doc2md.headline && want('doc2md')) || (teamLine && want('team')));
1815
+ const lead = runningSeg && hasHeadline ? runningSeg : null;
1816
+ if (runningSeg && !lead) segs.unshift(runningSeg);
1817
+ if (singleLine || !columns) return buildHeadlines(delegated, doc2md, want, eol, 0, c, teamLine, { lead }) + segs.join(' · ') + eol;
1818
+ const headlines = buildHeadlines(delegated, doc2md, want, eol, columns, c, teamLine, { trim, lead });
1718
1819
 
1719
1820
  // The chips that stop the work: layoutChips drops from the tail when the
1720
1821
  // terminal is narrow, and these must survive that.
1721
1822
  const protectedSegs = new Set([built.capWarn, built.spike, built.ctx, ...built.usage.map((u) => u.seg)].filter(Boolean));
1823
+ // The running chip, and everything the user named in `--segments`, is kept
1824
+ // whatever the width: the chip budget gives up the default tail instead.
1825
+ if (runningSeg && !lead) protectedSegs.add(runningSeg);
1826
+ if (allow) for (const seg of segs) protectedSegs.add(seg);
1722
1827
  const fitted = fitChips(segs, { columns, maxLines, eol, protectedSegs, color });
1723
1828
  // Verbose labels are the first thing to give up: if they only fit by dropping
1724
1829
  // chips, the compact layout (same chips, shorter text) may keep all of them.
package/src/glyphs.js CHANGED
@@ -58,6 +58,10 @@ const ICON = {
58
58
  doc: '📄',
59
59
  hit: '🧠',
60
60
  ttl: '⏳',
61
+ // Subagents running right now (the statusline's leading chip). The same hourglass
62
+ // as the cache timer: both say "time is passing", and the words beside it tell
63
+ // them apart.
64
+ running: '⏳',
61
65
  month: '💵',
62
66
  // Team: the people this machine is ranked among. U+1F465, East Asian Width W.
63
67
  team: '👥',
@@ -92,6 +96,7 @@ const NARROW = {
92
96
  doc: '≣', // stacked lines: a page of text
93
97
  hit: '◉', // bullseye: a cache hit
94
98
  ttl: '◔', // a partly elapsed dial
99
+ running: '', // no second font-verified dial; the chip's words lead it
95
100
  month: '∑', // a running total
96
101
  team: '', // no glyph verified in the font yet; the team line's own words lead it
97
102
  ctx: '◧', // a box filling up
@@ -74,6 +74,15 @@ const NO_SIGNAL_RE = /^\s*(Command failed with no output|Exit code \d+)\s*$/;
74
74
  // curl's transport-timeout exit, never a generic non-zero exit.
75
75
  const ENVIRONMENT_RE = /command not found|curl: \(28\)|Operation timed out after|ETIMEDOUT|ENOTFOUND|getaddrinfo/i;
76
76
 
77
+ // The shell refusing the command line before it runs, and a call to a tool the
78
+ // agent does not have, say nothing about the task either. On a zsh machine
79
+ // `echo ====` as a separator fails with "(eval):3: ==== not found" after the
80
+ // real output was already collected, and an unquoted URL with "?" fails with
81
+ // "no matches found". In 2026-11-09's review of the run rule's 34 "failed"
82
+ // delegations, these made 53 of 101 counted errors (sprag sessions, 14 days),
83
+ // and 32 of the 34 runs had finished with a full report anyway.
84
+ const SHELL_SYNTAX_RE = /\(eval\):\d+: (?:=\S* not found|no matches found:|parse error near)|No such tool available|is not among the tools available here/;
85
+
77
86
  function toolResultText(content) {
78
87
  if (typeof content === 'string') return content;
79
88
  if (!Array.isArray(content)) return '';
@@ -84,7 +93,7 @@ function isRealToolError(block) {
84
93
  if (!block || block.type !== 'tool_result' || !block.is_error) return false;
85
94
  const txt = toolResultText(block.content);
86
95
  return !REJECTION_RE.test(txt) && !SELF_CORRECTED_RE.test(txt)
87
- && !ENVIRONMENT_RE.test(txt) && !NO_SIGNAL_RE.test(txt);
96
+ && !ENVIRONMENT_RE.test(txt) && !NO_SIGNAL_RE.test(txt) && !SHELL_SYNTAX_RE.test(txt);
88
97
  }
89
98
 
90
99
  export async function collectSessionRecords(filePath, { includeContent = true } = {}) {
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Subagents that are running right now, for the statusline's leading chip.
3
+ *
4
+ * Claude Code keeps one transcript per subagent run beside the session's own:
5
+ * <projects>/<slug>/<sessionId>.jsonl the session
6
+ * <projects>/<slug>/<sessionId>/subagents/agent-<id>.jsonl one per run
7
+ * <projects>/<slug>/<sessionId>/subagents/agent-<id>.meta.json
8
+ *
9
+ * Which signal says "finished" was measured on 418 real subagent transcripts
10
+ * (2026-11-09), not guessed:
11
+ * - The last record of a finished run is usually NOT an assistant answer. Of
12
+ * the last 400 transcripts older than 10 minutes, 303 ended on a `user`
13
+ * tool_result (a SubagentHandback call returns one and the file stops
14
+ * there) and only 83 on an assistant `end_turn`. A "last record is the
15
+ * final answer" test would call most finished runs still running.
16
+ * - The sibling `agent-<id>.meta.json` carries `"finished": true` once the run
17
+ * ended. Of 418 transcripts, 391 had the key; the 2 being written at
18
+ * measurement time and 25 stale ones (24 older than 10 minutes, killed
19
+ * with their session) did not. The meta file is a few hundred bytes, so it
20
+ * is the cheapest and most reliable signal.
21
+ * - A run killed with its session never gets the key. The recent-modification
22
+ * window below is what keeps those from counting forever.
23
+ * So a run is "running" when its transcript was modified within the window and
24
+ * its meta file does not say `finished`.
25
+ *
26
+ * This is the statusline path, re-run every few seconds, so the cost is one
27
+ * readdir and one stat per transcript, a meta read for the few recent ones and a
28
+ * tail read (a few KB) for at most MAX_FILES of them. Nothing parses a whole file.
29
+ */
30
+
31
+ import { closeSync, openSync, readdirSync, readFileSync, readSync, statSync } from 'node:fs';
32
+ import { join } from 'node:path';
33
+ import { modelFamily } from './savings-ledger.js';
34
+
35
+ /**
36
+ * A run silent for longer than this is treated as gone. A live run writes a
37
+ * record per model turn and per tool result, but a long tool call (a test suite,
38
+ * a render) writes nothing until it returns, so the window is wider than a turn.
39
+ */
40
+ export const RUNNING_WINDOW_MS = 30_000;
41
+ /** Most transcripts whose model is read per render. */
42
+ export const MAX_FILES = 5;
43
+ const TAIL_BYTES = 16 * 1024;
44
+ /** Longest family name shown, as in the session chip. */
45
+ const FAMILY_MAX = 14;
46
+
47
+ /** The model id named last in the final bytes of a transcript, or null. */
48
+ function modelFromTail(file, size) {
49
+ let fd;
50
+ try {
51
+ fd = openSync(file, 'r');
52
+ const len = Math.min(size, TAIL_BYTES);
53
+ const buf = Buffer.alloc(len);
54
+ readSync(fd, buf, 0, len, size - len);
55
+ const hits = [...buf.toString('utf8').matchAll(/"model":"([^"]+)"/g)];
56
+ return hits.length ? hits[hits.length - 1][1] : null;
57
+ } catch {
58
+ return null;
59
+ } finally {
60
+ if (fd !== undefined) {
61
+ try { closeSync(fd); } catch { /* nothing to release */ }
62
+ }
63
+ }
64
+ }
65
+
66
+ /** True when the run's meta file says it ended. Unreadable or absent counts as running. */
67
+ function isFinished(metaFile) {
68
+ try {
69
+ return JSON.parse(readFileSync(metaFile, 'utf8')).finished === true;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * The subagents of the session behind `transcriptPath` that are still working.
77
+ *
78
+ * @param {string|null} transcriptPath the statusline payload's `transcript_path`
79
+ * @param {{ now?: number, windowMs?: number, maxFiles?: number }} [o]
80
+ * @returns {{ count: number, families: Array<{ family: string, runs: number }> }|null}
81
+ * null when nothing is running (the common case) or the directory is missing
82
+ */
83
+ export function runningSubagents(transcriptPath, { now = Date.now(), windowMs = RUNNING_WINDOW_MS, maxFiles = MAX_FILES } = {}) {
84
+ if (typeof transcriptPath !== 'string' || !transcriptPath.endsWith('.jsonl')) return null;
85
+ const dir = join(transcriptPath.slice(0, -'.jsonl'.length), 'subagents');
86
+ let names;
87
+ try {
88
+ names = readdirSync(dir);
89
+ } catch {
90
+ return null;
91
+ }
92
+ const live = [];
93
+ for (const name of names) {
94
+ if (!name.startsWith('agent-') || !name.endsWith('.jsonl')) continue;
95
+ const file = join(dir, name);
96
+ let st;
97
+ try { st = statSync(file); } catch { continue; }
98
+ if (now - st.mtimeMs > windowMs) continue;
99
+ if (isFinished(file.slice(0, -'.jsonl'.length) + '.meta.json')) continue;
100
+ live.push({ file, size: st.size, mtimeMs: st.mtimeMs });
101
+ }
102
+ if (live.length === 0) return null;
103
+ live.sort((a, b) => b.mtimeMs - a.mtimeMs);
104
+ const byFamily = new Map();
105
+ for (const run of live.slice(0, maxFiles)) {
106
+ const model = modelFromTail(run.file, run.size);
107
+ if (!model) continue;
108
+ const fam = modelFamily(model);
109
+ const name = fam.length > FAMILY_MAX ? `${fam.slice(0, FAMILY_MAX - 1)}…` : fam;
110
+ byFamily.set(name, (byFamily.get(name) || 0) + 1);
111
+ }
112
+ const families = [...byFamily.entries()]
113
+ .map(([family, runs]) => ({ family, runs }))
114
+ .sort((a, b) => b.runs - a.runs || a.family.localeCompare(b.family));
115
+ return { count: live.length, families };
116
+ }