sprag-cli 3.131.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.
- package/bin/cli.js +11 -1
- package/mac/SpragBar.swift +3141 -0
- package/package.json +2 -1
- package/src/agent-activity.js +485 -0
- package/src/agent-detail.js +266 -0
- package/src/agent-usage.js +410 -0
- package/src/agent-warnings.js +128 -0
- package/src/bar-app.js +330 -0
- package/src/bar-rules.js +133 -0
- package/src/bar-settings.js +78 -0
- package/src/brief.js +40 -13
- package/src/caps-cache.js +4 -3
- package/src/codex/panel.js +1 -7
- package/src/commands/bar.js +370 -0
- package/src/commands/install.js +1 -0
- package/src/commands/last.js +1 -1
- package/src/commands/route-scan.js +29 -0
- package/src/commands/uninstall.js +2 -0
- package/src/ctx-window-cache.js +11 -8
- package/src/history.js +18 -1
- package/src/installer.js +43 -0
- package/src/session-cache.js +19 -0
- package/src/statusline-guard.js +17 -0
- package/src/window-labels.js +11 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
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
|
+
}
|