sprag-cli 3.130.0 → 3.132.0

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.
Files changed (42) hide show
  1. package/bin/cli.js +11 -1
  2. package/mac/SpragBar.swift +3141 -0
  3. package/mod/sprag-statusline/hooks/register.tsx +58 -3
  4. package/package.json +2 -1
  5. package/src/agent-activity.js +485 -0
  6. package/src/agent-detail.js +266 -0
  7. package/src/agent-usage.js +410 -0
  8. package/src/agent-warnings.js +128 -0
  9. package/src/bar-app.js +330 -0
  10. package/src/bar-rules.js +133 -0
  11. package/src/bar-settings.js +78 -0
  12. package/src/brief.js +40 -13
  13. package/src/caps-cache.js +4 -3
  14. package/src/claude-version.js +38 -0
  15. package/src/codex/budget.js +1 -1
  16. package/src/codex/delegation-diagnostics.js +1 -1
  17. package/src/codex/panel.js +1 -7
  18. package/src/commands/bar.js +370 -0
  19. package/src/commands/delegate.js +1 -0
  20. package/src/commands/feedback.js +2 -2
  21. package/src/commands/install.js +4 -1
  22. package/src/commands/last.js +1 -1
  23. package/src/commands/route-scan.js +39 -1
  24. package/src/commands/team.js +1 -1
  25. package/src/commands/uninstall.js +2 -0
  26. package/src/commands/upgrade.js +1 -1
  27. package/src/compact-window.js +1 -1
  28. package/src/cowork-sync.js +1 -1
  29. package/src/ctx-window-cache.js +11 -8
  30. package/src/delegation-agents.js +41 -2
  31. package/src/doc2md.cjs +1 -0
  32. package/src/gateway-auth.js +1 -0
  33. package/src/handoff.js +1 -0
  34. package/src/history.js +18 -1
  35. package/src/installer.js +43 -0
  36. package/src/korean-style.js +1 -1
  37. package/src/permission-secrets.js +1 -1
  38. package/src/session-cache.js +19 -0
  39. package/src/statusline-guard.js +17 -0
  40. package/src/team-sync.js +1 -1
  41. package/src/transcript-lines.js +1 -1
  42. package/src/window-labels.js +11 -0
@@ -99,6 +99,36 @@ export function statuslinePayload(input: {
99
99
  return payload
100
100
  }
101
101
 
102
+ /**
103
+ * The argv with `--columns <n>` added, so sprag fits its chips to the band and
104
+ * wraps them at chip boundaries instead of the band wrapping them mid-chip. A
105
+ * command that already names its width, or an unknown width, is left as it is.
106
+ */
107
+ export function withColumns(argv: string[], columns: number | undefined): string[] {
108
+ if (!columns || !Number.isFinite(columns) || columns < 20) return argv
109
+ if (argv.includes('--columns')) return argv
110
+ return [...argv, '--columns', String(Math.floor(columns))]
111
+ }
112
+
113
+ // First engine whose Box takes overflowX="scroll" and whose Text takes
114
+ // wrap="clip". Older engines check a tree's props by name and value and skip a
115
+ // hook whose tree has one they do not know, so the band would vanish there.
116
+ export const CLIP_MIN_VERSION = '2.1.326'
117
+
118
+ /** Whether a release version (`2.1.326`, `2.1.330-dev`) is at least `min`. */
119
+ export function atLeast(version: string | undefined, min: string): boolean {
120
+ const parse = (v: string) => /^(\d+)\.(\d+)\.(\d+)/.exec(v)?.slice(1).map(Number)
121
+ const a = version ? parse(version) : undefined
122
+ const b = parse(min)
123
+ if (!a || !b) return false
124
+ for (let i = 0; i < 3; i++) {
125
+ const x = a[i] ?? 0
126
+ const y = b[i] ?? 0
127
+ if (x !== y) return x > y
128
+ }
129
+ return true
130
+ }
131
+
102
132
  /** Output with stray ANSI escapes removed and blank lines dropped. */
103
133
  export function cleanOutput(text: string): string[] {
104
134
  return text
@@ -111,6 +141,19 @@ export function cleanOutput(text: string): string[] {
111
141
 
112
142
  let isRunning = false
113
143
  let timer: { cancel: () => void } | undefined
144
+ // The band's width as the last draw saw it; the next run fits the text to it
145
+ let bandColumns: number | undefined
146
+ // Whether this engine takes the clip props; read once, after a reload again
147
+ let canClip: Promise<boolean> | undefined
148
+
149
+ /** Whether the engine is CLIP_MIN_VERSION or later. An engine that cannot say counts as older. */
150
+ function engineCanClip($: EngineInterface): Promise<boolean> {
151
+ canClip ??= $.session
152
+ .version()
153
+ .then(v => atLeast(v.base ?? v.version, CLIP_MIN_VERSION))
154
+ .catch(() => false)
155
+ return canClip
156
+ }
114
157
 
115
158
  /** Runs the statusline once and stores its text; any failure leaves the last text as it was. */
116
159
  async function refresh($: EngineInterface): Promise<void> {
@@ -125,7 +168,7 @@ async function refresh($: EngineInterface): Promise<void> {
125
168
  $.session.usage(),
126
169
  $.settings.read(),
127
170
  ])
128
- const run = await $.process.run(statuslineArgv(settings), {
171
+ const run = await $.process.run(withColumns(statuslineArgv(settings), bandColumns), {
129
172
  stdin: JSON.stringify(statuslinePayload({ sessionId, cwd, model, usage })),
130
173
  timeoutMs: RUN_TIMEOUT_MS,
131
174
  })
@@ -158,15 +201,27 @@ export const register: Register = on => {
158
201
 
159
202
  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
160
203
  if (e.surface !== 'desktop' || e.props.hasSurvey) return next(e)
204
+ // A new width refits the text now rather than at the next tick
205
+ const columns = e.props.bodyColumns
206
+ if (typeof columns === 'number' && columns !== bandColumns) {
207
+ bandColumns = columns
208
+ void refresh($)
209
+ }
161
210
  const shown = (await read($, lines)).slice(0, Math.max(0, e.props.maxRows))
162
211
  if (!shown.length) return next(e)
163
212
 
164
213
  const { Box, Text } = $.ui.resolve(e)
214
+ // On an engine that has them, a line wider than the band stays on its row
215
+ // and scrolls sideways instead of wrapping in the middle of a chip. They go
216
+ // in as spreads so the module still type-checks against older engine types.
217
+ const clip = await engineCanClip($)
218
+ const boxProps = clip ? { overflowX: 'scroll' as const } : {}
219
+ const textProps = clip ? { wrap: 'clip' as const } : {}
165
220
  // One statusline line per row; a Box lays its children out in a row unless told otherwise
166
221
  return (
167
- <Box flexDirection="column">
222
+ <Box flexDirection="column" {...boxProps}>
168
223
  {shown.map((line, i) => (
169
- <Text key={`line-${i}`} dimColor>
224
+ <Text key={`line-${i}`} dimColor {...textProps}>
170
225
  {line}
171
226
  </Text>
172
227
  ))}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.130.0",
3
+ "version": "3.132.0",
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": {
@@ -36,6 +36,7 @@
36
36
  "mod/*/hooks/**",
37
37
  "mod/*/types/**",
38
38
  "presets/",
39
+ "mac/SpragBar.swift",
39
40
  "examples/",
40
41
  "README.md",
41
42
  "README.ko.md",
@@ -0,0 +1,485 @@
1
+ /**
2
+ * What each running agent session is doing right now, and what it costs the
3
+ * machine, for `sprag bar` (terminal table, JSON, SwiftBar/xbar menu bar text).
4
+ *
5
+ * Where the data comes from:
6
+ * - Claude Code writes <claudeDir>/sessions/<pid>.json for every running
7
+ * process: pid, sessionId, cwd, name, status ('busy' or 'idle'),
8
+ * statusUpdatedAt, updatedAt, kind, entrypoint. This is an undocumented
9
+ * internal file; the fields were checked against Claude Code 2.1.319 on
10
+ * 2026-11-21. It may be missing or change shape, so every read here is
11
+ * defensive and a surprise never fails the command. The `.key` files in the
12
+ * same folder are never read.
13
+ * - The tool a busy session is running is the last `tool_use` in its
14
+ * transcript that has no `tool_result` yet, found by regex over the final
15
+ * bytes of the file. Nothing parses a whole transcript.
16
+ * - Subagents come from runningSubagents() (statusline-running.js).
17
+ * - CPU and memory come from one `ps` call. Every process is charged to the
18
+ * nearest session root above it, so a session's row includes its tool
19
+ * processes and an inner session started from a tool counts only for itself.
20
+ * The process taking the snapshot and its children are charged to no one.
21
+ * The figures are one instant: a helper that lives a fraction of a second,
22
+ * such as a statusline refresh, shows in one snapshot and not the next, so
23
+ * a caller that redraws should smooth over several snapshots.
24
+ * - Codex has no session file; a `codex` process with no codex or Claude
25
+ * session above it is a row of its own. Its rollout file is found through
26
+ * the files the process holds open (agent-usage.js).
27
+ * - Warnings (the statusline's `⚠` issue chip and `🚨` rate-limit chips, with
28
+ * their advice) come from agent-warnings.js: the limits above, the chip
29
+ * state and the history files in the user data folder.
30
+ * - Model, context window use, tokens, cost and the account limits come from
31
+ * agent-usage.js: the transcript tail, the statusline's caches in the user
32
+ * data folder, and the Codex rollout files.
33
+ * - A Claude row's effort level is the one the statusline recorded in the user
34
+ * data folder (session-effort.js); Codex rows read theirs from the rollout.
35
+ * - With `detail`, each row also carries the session's latest typed request, its
36
+ * last reply, its recent tool calls (agent-detail.js, from the transcript tail)
37
+ * and its heaviest child processes. Without it none of that is read.
38
+ *
39
+ * The child processes this module starts are `ps`, and `lsof` while a Codex
40
+ * process is running. It never re-runs the sprag CLI and never spawns a
41
+ * detached child. The one file it writes is <dataDir>/bar-prompts.json, and only
42
+ * with `detail`: per transcript, the size seen and the request found, so the
43
+ * next snapshot scans just the bytes added since. It holds the user's own text,
44
+ * so it is mode 0600, and entries unseen for 24 hours are dropped.
45
+ */
46
+
47
+ import { readdirSync, readFileSync, chmodSync } from 'node:fs';
48
+ import { execFileSync } from 'node:child_process';
49
+ import os from 'node:os';
50
+ import { basename, join } from 'node:path';
51
+ import { claudeConfigDir, projectTranscriptDir } from './commands/panel.js';
52
+ import { runningSubagents } from './statusline-running.js';
53
+ import { userDataDir } from './paths.js';
54
+ import { readTeamChip } from './team-sync.js';
55
+ import { SPECIES, GRADES } from './office-species.js';
56
+ import { scorePctOf, nextOf, floorPct } from './team-standing.js';
57
+ import { loadCache } from './session-cache.js';
58
+ import { codexUserDir } from './agent.js';
59
+ import { userLanguage } from './config.js';
60
+ import { readSessionEffort } from './session-effort.js';
61
+ import { sessionDetail } from './agent-detail.js';
62
+ import { writeStateFile } from './state-file.js';
63
+ import { currentWarnings } from './agent-warnings.js';
64
+ import {
65
+ readTail, claudeLimits, claudeSessionDetail, recentRollouts, defaultOpenFiles, pickRollout,
66
+ readRollout, codexRowFields, codexLimits,
67
+ } from './agent-usage.js';
68
+
69
+ export const PS_ARGS = ['-A', '-o', 'pid=,ppid=,pcpu=,rss=,comm='];
70
+ /** Program names (lowercase, no .exe) a live Claude Code process can show in `ps`. */
71
+ const CLAUDE_COMMS = new Set(['claude', 'node', 'bun']);
72
+ /** Most parent hops followed when charging a process to a session. */
73
+ const MAX_HOPS = 64;
74
+ /** Child processes listed per row with `detail`. */
75
+ const DETAIL_PROCS = 5;
76
+ const PROMPT_CACHE_FILE = 'bar-prompts.json';
77
+ const PROMPT_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
78
+ /** An unchanged entry is rewritten for its `seenAt` only this often, so a poll every few seconds does not write every time. */
79
+ const PROMPT_SEEN_REFRESH_MS = 60 * 60 * 1000;
80
+
81
+ /**
82
+ * Parse `ps -o pid=,ppid=,pcpu=,rss=,comm=` output. The first four columns are
83
+ * numbers and the rest of the line is the command, which on macOS is a full
84
+ * path that may hold spaces. Lines of any other shape are skipped.
85
+ *
86
+ * @returns {Map<number, { pid: number, ppid: number, cpu: number, rssKb: number, comm: string }>}
87
+ */
88
+ export function parsePs(text) {
89
+ const table = new Map();
90
+ for (const line of String(text ?? '').split('\n')) {
91
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+(?:\.\d+)?)\s+(\d+)\s+(\S.*?)\s*$/.exec(line);
92
+ if (!m) continue;
93
+ const pid = Number(m[1]);
94
+ table.set(pid, { pid, ppid: Number(m[2]), cpu: Number(m[3]), rssKb: Number(m[4]), comm: m[5] });
95
+ }
96
+ return table;
97
+ }
98
+
99
+ const samePrompt = (a, b) => (a === null || b === null ? a === b : a.text === b.text && a.at === b.at);
100
+
101
+ function validEntry(e) {
102
+ if (!e || typeof e !== 'object' || !Number.isFinite(e.size) || !Number.isFinite(e.seenAt)) return false;
103
+ const p = e.prompt;
104
+ return p === null || (p && typeof p === 'object' && typeof p.text === 'string' && (p.at === null || Number.isFinite(p.at)));
105
+ }
106
+
107
+ /**
108
+ * The request each transcript showed the last time `--detail` ran, with the file
109
+ * size it was seen at. Any failure to read or write it means no cache: the
110
+ * snapshot is still produced, only a slower first look at a long transcript.
111
+ */
112
+ function openPromptCache(dataDir, now) {
113
+ const file = join(dataDir, PROMPT_CACHE_FILE);
114
+ let entries = {};
115
+ try {
116
+ const data = JSON.parse(readFileSync(file, 'utf8'));
117
+ if (data?.version === 1 && data.entries && typeof data.entries === 'object') {
118
+ for (const [key, e] of Object.entries(data.entries)) if (validEntry(e)) entries[key] = e;
119
+ }
120
+ } catch { entries = {}; }
121
+ let dirty = false;
122
+ return {
123
+ known(transcript) {
124
+ const e = entries[transcript];
125
+ return e ? { size: e.size, prompt: e.prompt } : null;
126
+ },
127
+ remember(transcript, size, prompt) {
128
+ const old = entries[transcript];
129
+ if (old && old.size === size && samePrompt(old.prompt, prompt) && now - old.seenAt < PROMPT_SEEN_REFRESH_MS) return;
130
+ entries[transcript] = { size, prompt, seenAt: now };
131
+ dirty = true;
132
+ },
133
+ save() {
134
+ try {
135
+ for (const [key, e] of Object.entries(entries)) {
136
+ if (now - e.seenAt > PROMPT_CACHE_TTL_MS) { delete entries[key]; dirty = true; }
137
+ }
138
+ if (!dirty) return;
139
+ writeStateFile(file, JSON.stringify({ version: 1, entries }));
140
+ if (process.platform !== 'win32') {
141
+ try { chmodSync(file, 0o600); } catch { /* the file is written; the mode is best effort */ }
142
+ }
143
+ } catch { /* no cache this time */ }
144
+ },
145
+ };
146
+ }
147
+
148
+ /** The process table from one `ps` call, or null when there is no ps (Windows) or it fails. */
149
+ export function defaultPs() {
150
+ if (process.platform === 'win32') return null;
151
+ try {
152
+ const out = execFileSync('ps', PS_ARGS, { encoding: 'utf8', timeout: 1500, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
153
+ return parsePs(out);
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ /** The session files of running Claude Code processes. Unreadable or malformed ones are skipped. */
160
+ export function readClaudeSessions(claudeDir) {
161
+ const dir = join(claudeDir, 'sessions');
162
+ let names;
163
+ try {
164
+ names = readdirSync(dir);
165
+ } catch {
166
+ return [];
167
+ }
168
+ const out = [];
169
+ for (const name of names) {
170
+ if (!name.endsWith('.json')) continue;
171
+ try {
172
+ const data = JSON.parse(readFileSync(join(dir, name), 'utf8'));
173
+ if (!data || typeof data !== 'object') continue;
174
+ if (!Number.isFinite(data.pid) || typeof data.sessionId !== 'string') continue;
175
+ out.push(data);
176
+ } catch { /* partial write or foreign file */ }
177
+ }
178
+ return out;
179
+ }
180
+
181
+ /**
182
+ * Names of the tool calls near the end of a transcript that have no result yet,
183
+ * in the order they were called. Calls whose result is older than the tail
184
+ * window cannot be seen, which only ever hides a finished call.
185
+ *
186
+ * @returns {string[]} [] when the file cannot be read
187
+ */
188
+ export function pendingTools(transcriptPath, { tailBytes = 256 * 1024 } = {}) {
189
+ const tail = readTail(transcriptPath, tailBytes);
190
+ if (!tail) return [];
191
+ const calls = new Map();
192
+ for (const m of tail.text.matchAll(/"type":"tool_use","id":"([^"]+)","name":"([^"]+)"/g)) {
193
+ if (!calls.has(m[1])) calls.set(m[1], m[2]);
194
+ }
195
+ for (const m of tail.text.matchAll(/"tool_use_id":"([^"]+)"/g)) calls.delete(m[1]);
196
+ return [...calls.values()];
197
+ }
198
+
199
+ function defaultIsAlive(pid) {
200
+ try {
201
+ process.kill(pid, 0);
202
+ return true;
203
+ } catch (e) {
204
+ return e?.code === 'EPERM';
205
+ }
206
+ }
207
+
208
+ /** Lowercase program name of a `ps` comm, without directories or a trailing .exe. */
209
+ function commName(comm) {
210
+ return basename(String(comm ?? '')).toLowerCase().replace(/\.exe$/, '');
211
+ }
212
+
213
+ const round1 = (n) => Math.round(n * 10) / 10;
214
+ const finiteOr = (v, fallback = null) => (Number.isFinite(v) ? v : fallback);
215
+
216
+ /**
217
+ * The ranking behind the animal, for a menu bar: an animal alone reads as
218
+ * decoration, so the rank, the score percentile and the next species go with it.
219
+ * `st` is the standing readTeamChip() returns; the species is known to exist.
220
+ */
221
+ function standingFor(st, { lang, org }) {
222
+ const name = (key) => (lang === 'ko' ? SPECIES[key].ko : SPECIES[key].en);
223
+ const sr = scorePctOf(st);
224
+ const up = nextOf(st, sr);
225
+ const upRow = up && SPECIES[up.grade] ? GRADES.find((g) => g.key === up.grade) : null;
226
+ return {
227
+ grade: st.grade,
228
+ emoji: SPECIES[st.grade].emoji,
229
+ name: name(st.grade),
230
+ org: typeof org === 'string' && org ? org : null,
231
+ rank: finiteOr(st.rank),
232
+ ranked: finiteOr(st.ranked),
233
+ crown: !!st.crown,
234
+ idle: st.idle === true,
235
+ // 0..100, the share of ranked people this score is ahead of.
236
+ scorePct: Number.isFinite(sr) ? Math.round(sr * 100) : null,
237
+ spendRank: finiteOr(st.spendRank),
238
+ dlgRank: finiteOr(st.dlgRank),
239
+ next: upRow ? {
240
+ grade: up.grade, emoji: SPECIES[up.grade].emoji, name: name(up.grade),
241
+ floorPct: floorPct(upRow), pass: finiteOr(up.pass), needDlg: !!up.needDlg,
242
+ } : null,
243
+ };
244
+ }
245
+ /** Logical cores: `ps` reports CPU per core, so 100% is one core and a busy machine adds up past 100. */
246
+ const defaultCores = () => os.availableParallelism?.() ?? os.cpus().length;
247
+ const dirName = (cwd) => (typeof cwd === 'string' && cwd ? basename(cwd) || null : null);
248
+
249
+ function claudeRow(file, { claudeDir, dataDir, now, table, env, getCache, detail, promptCache }) {
250
+ const cwd = typeof file.cwd === 'string' && file.cwd ? file.cwd : null;
251
+ const project = dirName(cwd);
252
+ const name = typeof file.name === 'string' && file.name.trim() ? file.name : (project || `claude ${file.pid}`);
253
+ const state = typeof file.status === 'string' ? file.status : null;
254
+ let transcript = null;
255
+ if (cwd) {
256
+ try { transcript = join(projectTranscriptDir(cwd, { claudeDir }), `${file.sessionId}.jsonl`); } catch { transcript = null; }
257
+ }
258
+ let subagents = 0;
259
+ try { subagents = runningSubagents(transcript, { now })?.count ?? 0; } catch { subagents = 0; }
260
+ // A call the user interrupted never gets a result, so only a busy session shows tools.
261
+ const tools = state === 'busy' ? pendingTools(transcript) : [];
262
+ const usage = claudeSessionDetail({ sessionId: file.sessionId, transcript, dataDir, cache: getCache(), env, now });
263
+ let effort = null;
264
+ try { effort = readSessionEffort(file.sessionId, { dir: dataDir }); } catch { effort = null; }
265
+ const row = {
266
+ agent: 'claude',
267
+ pid: file.pid,
268
+ sessionId: file.sessionId,
269
+ name,
270
+ project,
271
+ cwd,
272
+ kind: typeof file.kind === 'string' ? file.kind : null,
273
+ state,
274
+ stateSince: Number.isFinite(file.statusUpdatedAt) ? file.statusUpdatedAt : null,
275
+ tools,
276
+ subagents,
277
+ model: usage.model,
278
+ modelName: usage.modelName,
279
+ effort,
280
+ context: usage.context,
281
+ usage: usage.usage,
282
+ cpu: table ? 0 : null,
283
+ cpuPct: null,
284
+ rssMb: table ? 0 : null,
285
+ procs: table ? 0 : null,
286
+ };
287
+ if (detail) {
288
+ const known = transcript && promptCache ? promptCache.known(transcript) : null;
289
+ const { size, ...seen } = sessionDetail({ transcript, known });
290
+ if (transcript && promptCache && Number.isFinite(size)) promptCache.remember(transcript, size, seen.prompt);
291
+ row.detail = { ...seen, procs: [] };
292
+ }
293
+ return row;
294
+ }
295
+
296
+ // The order never depends on a live reading. A menu bar panel redraws every few
297
+ // seconds, and rows sorted by CPU traded places while no session had changed.
298
+ function compareRows(a, b) {
299
+ const busy = (r) => (r.state === 'busy' ? 0 : 1);
300
+ return busy(a) - busy(b) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0) || a.pid - b.pid;
301
+ }
302
+
303
+ /**
304
+ * One snapshot of every running agent session. Never throws: a missing sessions
305
+ * folder gives zero rows and a failed `ps` gives rows with null resources.
306
+ */
307
+ export function collectActivity({
308
+ claudeDir = claudeConfigDir(),
309
+ dataDir = userDataDir(),
310
+ ps = defaultPs,
311
+ now = Date.now(),
312
+ isAlive = defaultIsAlive,
313
+ readChip = () => readTeamChip({ dir: dataDir }),
314
+ codexHome = codexUserDir(),
315
+ openFiles = defaultOpenFiles,
316
+ cores = defaultCores(),
317
+ env = process.env,
318
+ selfPid = process.pid,
319
+ lang = userLanguage(),
320
+ warningsOf = currentWarnings,
321
+ detail = false,
322
+ } = {}) {
323
+ let codexPidsOf = null;
324
+ let table = null;
325
+ try { table = ps(); } catch { table = null; }
326
+ if (!(table instanceof Map)) table = null;
327
+
328
+ // One read of the parse cache serves every row of the snapshot.
329
+ let cache;
330
+ const getCache = () => (cache ??= loadCache(join(dataDir, 'session-cache.json')));
331
+
332
+ const promptCache = detail ? openPromptCache(dataDir, now) : null;
333
+ const rows = [];
334
+ try {
335
+ for (const file of readClaudeSessions(claudeDir)) {
336
+ // A pid that `ps` shows as some other program is a stale file whose pid was reused.
337
+ const alive = table
338
+ ? (table.has(file.pid) && CLAUDE_COMMS.has(commName(table.get(file.pid).comm)))
339
+ : isAlive(file.pid);
340
+ if (!alive) continue;
341
+ rows.push(claudeRow(file, { claudeDir, dataDir, now, table, env, getCache, detail, promptCache }));
342
+ }
343
+ } catch { /* keep whatever was read */ }
344
+ promptCache?.save();
345
+
346
+ const rootOf = new Map(rows.map((r) => [r.pid, r]));
347
+ const claudePids = new Set(rootOf.keys());
348
+
349
+ if (table) {
350
+ for (const p of table.values()) {
351
+ if (commName(p.comm) !== 'codex' || claudePids.has(p.pid)) continue;
352
+ let nested = false;
353
+ let cur = table.get(p.ppid);
354
+ for (let hop = 0; cur && hop < MAX_HOPS; hop++) {
355
+ if (claudePids.has(cur.pid) || commName(cur.comm) === 'codex') { nested = true; break; }
356
+ cur = table.get(cur.ppid);
357
+ }
358
+ if (nested) continue;
359
+ const row = {
360
+ agent: 'codex', pid: p.pid, sessionId: null, name: 'codex', project: null, cwd: null, kind: null,
361
+ state: null, stateSince: null, tools: [], subagents: 0,
362
+ model: null, modelName: null, effort: null, context: null, usage: null,
363
+ cpu: 0, cpuPct: null, rssMb: 0, procs: 0,
364
+ };
365
+ if (detail) row.detail = { prompt: null, reply: null, recent: [], procs: [] };
366
+ rows.push(row);
367
+ rootOf.set(p.pid, row);
368
+ }
369
+
370
+ const kb = new Map(rows.map((r) => [r, { cpu: 0, kb: 0 }]));
371
+ const charged = detail ? new Map(rows.map((r) => [r, []])) : null;
372
+ // A Codex row's own process and the codex processes under it: the native
373
+ // binary behind a wrapper may be the one holding the rollout file open.
374
+ const codexPids = new Map(rows.filter((r) => r.agent === 'codex').map((r) => [r, []]));
375
+ for (const p of table.values()) {
376
+ let cur = p;
377
+ let root = null;
378
+ const seen = new Set();
379
+ for (let hop = 0; cur && hop <= MAX_HOPS && !seen.has(cur.pid); hop++) {
380
+ seen.add(cur.pid);
381
+ // This process and the `ps` it started are the measurement, not the session's work.
382
+ if (cur.pid === selfPid) break;
383
+ if (rootOf.has(cur.pid)) { root = rootOf.get(cur.pid); break; }
384
+ cur = table.get(cur.ppid);
385
+ }
386
+ if (!root) continue;
387
+ const acc = kb.get(root);
388
+ acc.cpu += p.cpu;
389
+ acc.kb += p.rssKb;
390
+ root.procs += 1;
391
+ if (charged && p.pid !== root.pid) charged.get(root).push(p);
392
+ if (codexPids.has(root) && commName(p.comm) === 'codex') codexPids.get(root).push(p.pid);
393
+ }
394
+ for (const [row, acc] of kb) {
395
+ row.cpu = round1(acc.cpu);
396
+ row.rssMb = Math.round(acc.kb / 1024);
397
+ }
398
+ codexPidsOf = codexPids;
399
+ if (charged) {
400
+ for (const [row, list] of charged) {
401
+ list.sort((a, b) => b.cpu - a.cpu || b.rssKb - a.rssKb || a.pid - b.pid);
402
+ row.detail.procs = list.slice(0, DETAIL_PROCS).map((p) => ({
403
+ pid: p.pid,
404
+ name: basename(String(p.comm ?? '')).replace(/\.exe$/i, ''),
405
+ cpuPct: cores > 0 ? round1(p.cpu / cores) : null,
406
+ rssMb: Math.round(p.rssKb / 1024),
407
+ }));
408
+ }
409
+ }
410
+ }
411
+
412
+ const rollouts = recentRollouts({ codexHome, now });
413
+ const rolloutAt = new Map();
414
+ const rolloutOf = (file) => {
415
+ if (!rolloutAt.has(file)) rolloutAt.set(file, readRollout(file));
416
+ return rolloutAt.get(file);
417
+ };
418
+ const codexRows = rows.filter((r) => r.agent === 'codex');
419
+ if (codexRows.length) {
420
+ let open = null;
421
+ try { open = openFiles([...new Set(codexRows.flatMap((r) => codexPidsOf?.get(r) ?? [r.pid]))]); } catch { open = null; }
422
+ for (const row of codexRows) {
423
+ const file = pickRollout({ pids: codexPidsOf?.get(row) ?? [row.pid], open, rollouts, onlyRow: codexRows.length === 1, now });
424
+ const rollout = file ? rolloutOf(file) : null;
425
+ if (!rollout) continue;
426
+ const { cwd, ...fields } = codexRowFields(rollout);
427
+ Object.assign(row, fields, { cwd, project: dirName(cwd), name: dirName(cwd) || 'codex' });
428
+ }
429
+ }
430
+
431
+ const resources = table !== null;
432
+ for (const r of rows) r.cpuPct = resources && cores > 0 ? round1(r.cpu / cores) : null;
433
+
434
+ rows.sort(compareRows);
435
+
436
+ let animal = null;
437
+ let standing = null;
438
+ try {
439
+ const chip = readChip();
440
+ const grade = chip?.standing?.grade;
441
+ if (typeof grade === 'string' && SPECIES[grade]) {
442
+ animal = { grade, emoji: SPECIES[grade].emoji };
443
+ try { standing = standingFor(chip.standing, { lang, org: chip.org }); } catch { standing = null; }
444
+ }
445
+ } catch { animal = null; standing = null; }
446
+
447
+ const sum = (key) => rows.reduce((n, r) => n + r[key], 0);
448
+ const costs = rows.map((r) => r.usage?.costUsd).filter((c) => typeof c === 'number' && Number.isFinite(c));
449
+ const totalCpu = resources ? round1(sum('cpu')) : null;
450
+ let codexUsage = null;
451
+ try {
452
+ const newest = rollouts[0] ? rolloutOf(rollouts[0].file) : null;
453
+ const limits = codexLimits(newest?.snapshot?.rateLimits, now);
454
+ // `at` is when that rollout was last written. With no Codex running the
455
+ // figure can be most of a day old, and a reader should be able to say so.
456
+ codexUsage = limits ? { ...limits, at: Math.round(rollouts[0].mtimeMs) } : null;
457
+ } catch { codexUsage = null; }
458
+ const claude = claudeLimits({ dataDir, now });
459
+ let warnings = [];
460
+ try {
461
+ const found = warningsOf({ dataDir, now, lang, limits: claude });
462
+ warnings = Array.isArray(found) ? found : [];
463
+ } catch { warnings = []; }
464
+ return {
465
+ at: now,
466
+ resources,
467
+ cores,
468
+ animal,
469
+ standing,
470
+ usage: { claude, codex: codexUsage },
471
+ warnings,
472
+ totals: {
473
+ sessions: rows.length,
474
+ warnings: warnings.length,
475
+ busy: rows.filter((r) => r.state === 'busy').length,
476
+ subagents: sum('subagents'),
477
+ cpu: totalCpu,
478
+ cpuPct: resources && cores > 0 ? round1(totalCpu / cores) : null,
479
+ costUsd: costs.length ? Math.round(costs.reduce((n, c) => n + c, 0) * 100) / 100 : null,
480
+ rssMb: resources ? sum('rssMb') : null,
481
+ procs: resources ? sum('procs') : null,
482
+ },
483
+ sessions: rows,
484
+ };
485
+ }