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
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a Claude Code session is working on, for `sprag bar --json --detail`: the
|
|
3
|
+
* request the user typed, the last text the agent wrote back and its recent tool
|
|
4
|
+
* calls, read from the end of the session transcript.
|
|
5
|
+
*
|
|
6
|
+
* Nothing parses a whole transcript: the tail is read, and a request that is not
|
|
7
|
+
* in the tail is looked for further back in 4 MiB chunks, newest first, parsing
|
|
8
|
+
* only the lines that can hold one. The transcript is an internal Claude Code
|
|
9
|
+
* file, so every read is defensive and none throws. The user's own prompts pass
|
|
10
|
+
* through here, so nothing is logged; the caller decides what it keeps.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { basename } from 'node:path';
|
|
14
|
+
import { openSync, readSync, closeSync, fstatSync } from 'node:fs';
|
|
15
|
+
|
|
16
|
+
const TRANSCRIPT_TAIL = 256 * 1024;
|
|
17
|
+
/** Bytes scanned backwards for a request the tail does not hold, when no earlier snapshot says where to stop. */
|
|
18
|
+
export const DEEP_LIMIT = 64 * 1024 * 1024;
|
|
19
|
+
const DEEP_CHUNK = 4 * 1024 * 1024;
|
|
20
|
+
/** A scan that resumes from an earlier snapshot starts this far before the size it saw: that snapshot may have caught a line half written. */
|
|
21
|
+
const RESUME_OVERLAP = 64 * 1024;
|
|
22
|
+
const TEXT_MAX = 400;
|
|
23
|
+
const TARGET_MAX = 80;
|
|
24
|
+
const RECENT_MAX = 12;
|
|
25
|
+
|
|
26
|
+
/** Blocks the harness injects into a user message; they are not what the user typed. */
|
|
27
|
+
const WRAPPER_TAGS = [
|
|
28
|
+
'system-reminder', 'command-name', 'command-message', 'command-args',
|
|
29
|
+
'local-command-stdout', 'local-command-stderr', 'local-command-caveat',
|
|
30
|
+
'task-notification', 'user-prompt-submit-hook', 'pasted_content', 'agent-message', 'teammate-message',
|
|
31
|
+
];
|
|
32
|
+
const WRAPPER_RE = new RegExp(`<(${WRAPPER_TAGS.join('|')})(?:\\s[^>]*)?>[\\s\\S]*?</\\1>`, 'g');
|
|
33
|
+
|
|
34
|
+
/** Collapse whitespace runs and cut to `max` code points, ending a cut text with `…`. */
|
|
35
|
+
function tidy(text, max) {
|
|
36
|
+
const flat = String(text).replace(/\s+/g, ' ').trim();
|
|
37
|
+
const chars = Array.from(flat);
|
|
38
|
+
return chars.length > max ? `${chars.slice(0, max).join('')}…` : flat;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
42
|
+
const hostOf = (url) => {
|
|
43
|
+
try { return new URL(url).host || url; } catch { return url; }
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A short label for what a tool call is acting on. '' when there is nothing
|
|
48
|
+
* useful to show, for an unknown tool or an input of an unexpected shape.
|
|
49
|
+
*/
|
|
50
|
+
export function toolTarget(name, input) {
|
|
51
|
+
if (!input || typeof input !== 'object') return '';
|
|
52
|
+
let target = '';
|
|
53
|
+
switch (name) {
|
|
54
|
+
case 'Bash':
|
|
55
|
+
target = str(input.description) || str(input.command);
|
|
56
|
+
break;
|
|
57
|
+
case 'Read':
|
|
58
|
+
case 'Edit':
|
|
59
|
+
case 'Write':
|
|
60
|
+
case 'NotebookEdit': {
|
|
61
|
+
const path = str(input.file_path) || str(input.notebook_path);
|
|
62
|
+
target = path ? basename(path) : '';
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
case 'Grep':
|
|
66
|
+
case 'Glob':
|
|
67
|
+
target = str(input.pattern);
|
|
68
|
+
break;
|
|
69
|
+
case 'Agent':
|
|
70
|
+
case 'Task': {
|
|
71
|
+
const description = str(input.description);
|
|
72
|
+
const type = str(input.subagent_type);
|
|
73
|
+
target = type ? `${description} (${type})` : description;
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
case 'WebSearch':
|
|
77
|
+
target = str(input.query);
|
|
78
|
+
break;
|
|
79
|
+
case 'WebFetch':
|
|
80
|
+
target = hostOf(str(input.url));
|
|
81
|
+
break;
|
|
82
|
+
case 'Skill':
|
|
83
|
+
target = str(input.skill);
|
|
84
|
+
break;
|
|
85
|
+
default:
|
|
86
|
+
return '';
|
|
87
|
+
}
|
|
88
|
+
return tidy(target, TARGET_MAX);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const atOf = (entry) => {
|
|
92
|
+
const ms = typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : NaN;
|
|
93
|
+
return Number.isFinite(ms) ? ms : null;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const contentOf = (entry) => entry?.message?.content;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* What the user typed, from a line that can carry it: a `user` line, or the
|
|
100
|
+
* `queue-operation` line Claude Code writes for a message sent while the agent
|
|
101
|
+
* was working (the matching `remove` line repeats it and does not count).
|
|
102
|
+
* null for tool results, meta lines, context-compaction summaries and messages
|
|
103
|
+
* that hold nothing but harness wrappers.
|
|
104
|
+
*/
|
|
105
|
+
function promptOf(entry) {
|
|
106
|
+
let text;
|
|
107
|
+
if (entry.type === 'queue-operation') {
|
|
108
|
+
if (entry.operation !== 'enqueue' || typeof entry.content !== 'string') return null;
|
|
109
|
+
text = entry.content;
|
|
110
|
+
} else if (entry.type === 'user') {
|
|
111
|
+
if (entry.isMeta === true || entry.isCompactSummary === true || entry.isVisibleInTranscriptOnly === true) return null;
|
|
112
|
+
const content = contentOf(entry);
|
|
113
|
+
if (typeof content === 'string') {
|
|
114
|
+
text = content;
|
|
115
|
+
} else if (Array.isArray(content)) {
|
|
116
|
+
if (content.some((item) => item?.type === 'tool_result')) return null;
|
|
117
|
+
text = content.filter((item) => item?.type === 'text' && typeof item.text === 'string').map((item) => item.text).join('\n');
|
|
118
|
+
} else {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
} else {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
const clean = tidy(text.replace(WRAPPER_RE, ' '), TEXT_MAX);
|
|
125
|
+
return clean === '' ? null : clean;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function newestPrompt(entries) {
|
|
129
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
130
|
+
const text = promptOf(entries[i]);
|
|
131
|
+
if (text !== null) return { text, at: atOf(entries[i]) };
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function newestReply(entries) {
|
|
137
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
138
|
+
const e = entries[i];
|
|
139
|
+
if (e.type !== 'assistant' || !Array.isArray(contentOf(e))) continue;
|
|
140
|
+
const texts = contentOf(e).filter((item) => item?.type === 'text' && typeof item.text === 'string' && item.text.trim() !== '').map((item) => item.text);
|
|
141
|
+
if (texts.length) return { text: tidy(texts.join('\n'), TEXT_MAX), at: atOf(e) };
|
|
142
|
+
}
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function recentCalls(entries) {
|
|
147
|
+
const done = new Set();
|
|
148
|
+
const calls = [];
|
|
149
|
+
for (const e of entries) {
|
|
150
|
+
const content = contentOf(e);
|
|
151
|
+
if (!Array.isArray(content)) continue;
|
|
152
|
+
for (const item of content) {
|
|
153
|
+
if (e.type === 'user' && item?.type === 'tool_result' && typeof item.tool_use_id === 'string') done.add(item.tool_use_id);
|
|
154
|
+
if (e.type === 'assistant' && item?.type === 'tool_use' && typeof item.name === 'string') {
|
|
155
|
+
calls.push({ id: item.id, at: atOf(e), tool: item.name, target: toolTarget(item.name, item.input) });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return calls.slice(-RECENT_MAX).map(({ id, ...call }) => ({ ...call, pending: !done.has(id) }));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function readRange(fd, start, length) {
|
|
163
|
+
const buf = Buffer.alloc(length);
|
|
164
|
+
let got = 0;
|
|
165
|
+
while (got < length) {
|
|
166
|
+
const n = readSync(fd, buf, got, length - got, start + got);
|
|
167
|
+
if (n <= 0) break;
|
|
168
|
+
got += n;
|
|
169
|
+
}
|
|
170
|
+
return got === length ? buf : buf.subarray(0, got);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The newest prompt in bytes [lo, hi) of the file, looking at the newest 4 MiB
|
|
175
|
+
* first. Only lines that can hold a prompt are parsed. A line split by a chunk
|
|
176
|
+
* edge is completed by carrying its start over to the older chunk. `hi` must be
|
|
177
|
+
* the end of a line; `lo` may fall inside one, and that cut line is skipped.
|
|
178
|
+
*/
|
|
179
|
+
function scanBack(fd, lo, hi, chunkBytes) {
|
|
180
|
+
let end = hi;
|
|
181
|
+
let carry = Buffer.alloc(0);
|
|
182
|
+
while (end > lo) {
|
|
183
|
+
const start = Math.max(lo, end - chunkBytes);
|
|
184
|
+
let buf = Buffer.concat([readRange(fd, start, end - start), carry]);
|
|
185
|
+
carry = Buffer.alloc(0);
|
|
186
|
+
if (start > lo) {
|
|
187
|
+
// The first line of this chunk began in an older one: hold it back.
|
|
188
|
+
const nl = buf.indexOf(0x0a);
|
|
189
|
+
if (nl === -1) { carry = buf; end = start; continue; }
|
|
190
|
+
carry = buf.subarray(0, nl);
|
|
191
|
+
buf = buf.subarray(nl + 1);
|
|
192
|
+
}
|
|
193
|
+
const lines = buf.toString('utf8').split('\n');
|
|
194
|
+
// At `lo` the first line is whole only when lo is the start of the file.
|
|
195
|
+
if (start === lo && lo > 0) lines.shift();
|
|
196
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
197
|
+
const line = lines[i];
|
|
198
|
+
if (!line || !(line.includes('"type":"user"') || line.includes('"type":"queue-operation"'))) continue;
|
|
199
|
+
try {
|
|
200
|
+
const entry = JSON.parse(line);
|
|
201
|
+
if (!entry || typeof entry !== 'object' || entry.isSidechain === true) continue;
|
|
202
|
+
const text = promptOf(entry);
|
|
203
|
+
if (text !== null) return { text, at: atOf(entry) };
|
|
204
|
+
} catch { /* partial or foreign line */ }
|
|
205
|
+
}
|
|
206
|
+
end = start;
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The newest typed request, the newest text reply and the last 12 tool calls of
|
|
213
|
+
* a transcript. Never throws.
|
|
214
|
+
*
|
|
215
|
+
* Reply and tool calls come from the last `tailBytes`. A request can be older
|
|
216
|
+
* than that (a long run of tool results follows it), so it is looked for further
|
|
217
|
+
* back. `known` is what an earlier snapshot of the same file found, as
|
|
218
|
+
* `{ size, prompt }`: only the bytes written since then are scanned, and the
|
|
219
|
+
* earlier prompt stands when they hold none. Without it the scan goes back up
|
|
220
|
+
* to 64 MiB. `size` in the result is the file size this call saw, for the
|
|
221
|
+
* caller to keep as the next `known`.
|
|
222
|
+
*
|
|
223
|
+
* @returns {{ prompt: { text: string, at: number|null }|null, reply: { text: string, at: number|null }|null,
|
|
224
|
+
* recent: Array<{ at: number|null, tool: string, target: string, pending: boolean }>, size: number|null }}
|
|
225
|
+
*/
|
|
226
|
+
export function sessionDetail({
|
|
227
|
+
transcript, tailBytes = TRANSCRIPT_TAIL, known = null, chunkBytes = DEEP_CHUNK, deepLimit = DEEP_LIMIT,
|
|
228
|
+
}) {
|
|
229
|
+
const empty = { prompt: null, reply: null, recent: [], size: null };
|
|
230
|
+
if (typeof transcript !== 'string' || transcript === '') return empty;
|
|
231
|
+
let fd;
|
|
232
|
+
try {
|
|
233
|
+
fd = openSync(transcript, 'r');
|
|
234
|
+
const size = fstatSync(fd).size;
|
|
235
|
+
if (size <= 0) return empty;
|
|
236
|
+
const tailStart = Math.max(0, size - tailBytes);
|
|
237
|
+
const tail = readRange(fd, tailStart, size - tailStart);
|
|
238
|
+
const entries = [];
|
|
239
|
+
let lines = tail.toString('utf8').split('\n');
|
|
240
|
+
if (tailStart > 0) lines.shift();
|
|
241
|
+
for (const line of lines) {
|
|
242
|
+
if (!line) continue;
|
|
243
|
+
try {
|
|
244
|
+
const entry = JSON.parse(line);
|
|
245
|
+
if (entry && typeof entry === 'object' && entry.isSidechain !== true) entries.push(entry);
|
|
246
|
+
} catch { /* partial or foreign line */ }
|
|
247
|
+
}
|
|
248
|
+
let prompt = newestPrompt(entries);
|
|
249
|
+
if (!prompt && tailStart > 0) {
|
|
250
|
+
// The tail starts inside a line; that line's head is part of the older region.
|
|
251
|
+
const firstNl = tail.indexOf(0x0a);
|
|
252
|
+
const hi = firstNl === -1 ? size : tailStart + firstNl + 1;
|
|
253
|
+
const resumable = known && Number.isFinite(known.size) && known.size <= size;
|
|
254
|
+
const lo = resumable ? Math.max(0, known.size - RESUME_OVERLAP) : Math.max(0, tailStart - deepLimit);
|
|
255
|
+
if (lo < hi) prompt = scanBack(fd, lo, hi, chunkBytes);
|
|
256
|
+
if (!prompt && resumable) prompt = known.prompt ?? null;
|
|
257
|
+
}
|
|
258
|
+
return { prompt, reply: newestReply(entries), recent: recentCalls(entries), size };
|
|
259
|
+
} catch {
|
|
260
|
+
return empty;
|
|
261
|
+
} finally {
|
|
262
|
+
if (fd !== undefined) {
|
|
263
|
+
try { closeSync(fd); } catch { /* nothing to release */ }
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an agent session has used, for `sprag bar`: model, context, tokens, cost
|
|
3
|
+
* and the account limits Claude and Codex report.
|
|
4
|
+
*
|
|
5
|
+
* Every read is defensive and none throws: the files are internal to Claude Code
|
|
6
|
+
* and Codex, change shape without notice, and may be half-written. A missing or
|
|
7
|
+
* odd file gives null for that field and nothing else.
|
|
8
|
+
*
|
|
9
|
+
* - Claude limits come from the statusline's last-caps.json snapshot, which is
|
|
10
|
+
* only fresh while a statusline is rendering. Claude Code exposes no other
|
|
11
|
+
* way to read them.
|
|
12
|
+
* - Claude model and context come from the tail of the session transcript.
|
|
13
|
+
* The window size and a statusline-reported model come from ctx-window.json.
|
|
14
|
+
* - Claude tokens and cost come from session-cache.json, the parse cache the
|
|
15
|
+
* statusline keeps current. This module never parses a whole transcript.
|
|
16
|
+
* - Codex writes one rollout file per session under
|
|
17
|
+
* <codexHome>/sessions/YYYY/MM/DD/. A running `codex` process is tied to its
|
|
18
|
+
* rollout through the files it holds open (`lsof`), because a rollout does
|
|
19
|
+
* not record its process.
|
|
20
|
+
*
|
|
21
|
+
* The only child process started here is `lsof`, and only while a Codex process
|
|
22
|
+
* is running. It never re-runs the sprag CLI and never spawns a detached child.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { readdirSync, statSync, openSync, readSync, closeSync } from 'node:fs';
|
|
26
|
+
import { execFileSync } from 'node:child_process';
|
|
27
|
+
import { dirname, join, sep } from 'node:path';
|
|
28
|
+
import { loadRecentSnapshot } from './caps-cache.js';
|
|
29
|
+
import { liveModelFor, liveWindowFor } from './ctx-window-cache.js';
|
|
30
|
+
import { peekCached } from './session-cache.js';
|
|
31
|
+
import { sessionCostAcross } from './claude-price.js';
|
|
32
|
+
import { labelForKey, windowLabel } from './window-labels.js';
|
|
33
|
+
import { shortModelName } from './formatters/statusline.js';
|
|
34
|
+
import { readCodexSnapshot, readCodexTailLines } from './codex/parser.js';
|
|
35
|
+
|
|
36
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
37
|
+
/** The statusline writes last-caps.json every few seconds, so half an hour old means no statusline is running. */
|
|
38
|
+
const CAPS_MAX_AGE_MS = 30 * 60 * 1000;
|
|
39
|
+
const TRANSCRIPT_TAIL = 256 * 1024;
|
|
40
|
+
// One large tool result can fill the whole tail and push the last request out of it.
|
|
41
|
+
const TRANSCRIPT_WIDE_TAIL = 4 * 1024 * 1024;
|
|
42
|
+
const ROLLOUT_TAIL = 1024 * 1024;
|
|
43
|
+
const ROLLOUT_HEAD = 64 * 1024;
|
|
44
|
+
/** A lone Codex process with no open rollout is matched to a rollout written this recently. */
|
|
45
|
+
const SINGLE_ROW_FRESH_MS = 15 * 60 * 1000;
|
|
46
|
+
const ROLLOUT_NAME = /^rollout-.*\.jsonl$/;
|
|
47
|
+
const ROLLOUT_OPEN = /[\\/]rollout-[^\\/]*\.jsonl$/;
|
|
48
|
+
|
|
49
|
+
const finite = (n) => typeof n === 'number' && Number.isFinite(n);
|
|
50
|
+
const cents = (usd) => Math.round(usd * 100) / 100;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The last `tailBytes` of a file as text. `cut` is true when the file is longer,
|
|
54
|
+
* so the first line of `text` may be a fragment.
|
|
55
|
+
*
|
|
56
|
+
* @returns {{ text: string, cut: boolean }|null} null when the file cannot be read or is empty
|
|
57
|
+
*/
|
|
58
|
+
export function readTail(path, tailBytes = TRANSCRIPT_TAIL) {
|
|
59
|
+
if (typeof path !== 'string' || path === '') return null;
|
|
60
|
+
let fd;
|
|
61
|
+
try {
|
|
62
|
+
fd = openSync(path, 'r');
|
|
63
|
+
const size = statSync(path).size;
|
|
64
|
+
const len = Math.min(size, tailBytes);
|
|
65
|
+
if (len <= 0) return null;
|
|
66
|
+
const buf = Buffer.alloc(len);
|
|
67
|
+
const got = readSync(fd, buf, 0, len, size - len);
|
|
68
|
+
return { text: buf.toString('utf8', 0, got), cut: size > len };
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
} finally {
|
|
72
|
+
if (fd !== undefined) {
|
|
73
|
+
try { closeSync(fd); } catch { /* nothing to release */ }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ---------------------------------------------------------------- Claude
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The account windows from the statusline snapshot, or null when there is no
|
|
82
|
+
* snapshot younger than half an hour. A window with no usable percentage, or
|
|
83
|
+
* one that already reset, would show a number that is no longer true, so it is
|
|
84
|
+
* left out. `resetsAt` is stored in seconds and returned in milliseconds.
|
|
85
|
+
*
|
|
86
|
+
* @returns {{ windows: Array<{ key: string, label: string, usedPct: number, resetsAt: number|null, spend?: number, maxBudget?: number }> }|null}
|
|
87
|
+
*/
|
|
88
|
+
export function claudeLimits({ dataDir, now = Date.now() }) {
|
|
89
|
+
try {
|
|
90
|
+
const snap = loadRecentSnapshot({ maxAgeMs: CAPS_MAX_AGE_MS, path: join(dataDir, 'last-caps.json') });
|
|
91
|
+
const windows = snap?.caps?.windows;
|
|
92
|
+
if (!Array.isArray(windows)) return null;
|
|
93
|
+
const out = [];
|
|
94
|
+
for (const w of windows) {
|
|
95
|
+
if (!w || typeof w.key !== 'string' || !finite(w.usedPct)) continue;
|
|
96
|
+
const resetsAt = finite(w.resetsAt) && w.resetsAt > 0 ? w.resetsAt * 1000 : null;
|
|
97
|
+
if (resetsAt !== null && resetsAt <= now) continue;
|
|
98
|
+
const entry = { key: w.key, label: labelForKey(w.key).short, usedPct: w.usedPct, resetsAt };
|
|
99
|
+
// The spend limit window carries the money behind its percentage.
|
|
100
|
+
if (finite(w.spend)) entry.spend = w.spend;
|
|
101
|
+
if (finite(w.maxBudget)) entry.maxBudget = w.maxBudget;
|
|
102
|
+
out.push(entry);
|
|
103
|
+
}
|
|
104
|
+
return out.length ? { windows: out } : null;
|
|
105
|
+
} catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The last model id in a transcript tail; `<synthetic>` marks a stub Claude Code wrote itself. */
|
|
111
|
+
function lastModel(text) {
|
|
112
|
+
let model = null;
|
|
113
|
+
for (const m of text.matchAll(/"model":"([^"]+)"/g)) {
|
|
114
|
+
if (m[1] !== '<synthetic>') model = m[1];
|
|
115
|
+
}
|
|
116
|
+
return model;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const USAGE_RE = /"usage":\{"input_tokens":(\d+),"cache_creation_input_tokens":(\d+),"cache_read_input_tokens":(\d+)/;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Prompt size of the newest main-thread request in a transcript tail. A
|
|
123
|
+
* sidechain line belongs to a subagent, whose prompt is not this session's
|
|
124
|
+
* context. Counts input, cache writes and cache reads, as the statusline does.
|
|
125
|
+
*/
|
|
126
|
+
function lastContextTokens({ text, cut }) {
|
|
127
|
+
const lines = text.split('\n');
|
|
128
|
+
if (cut) lines.shift();
|
|
129
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
130
|
+
const line = lines[i];
|
|
131
|
+
if (!line.includes('"usage":{"input_tokens"') || line.includes('"isSidechain":true')) continue;
|
|
132
|
+
const m = USAGE_RE.exec(line);
|
|
133
|
+
if (m) return Number(m[1]) + Number(m[2]) + Number(m[3]);
|
|
134
|
+
}
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Tokens, requests and cost of a Claude session and its subagents, from the
|
|
140
|
+
* parse cache the statusline keeps. Subagent transcripts are cached under
|
|
141
|
+
* `<transcript minus .jsonl>/...`, so they are found by key prefix. The cache
|
|
142
|
+
* may lag the transcript by a few seconds, which is fine for a display.
|
|
143
|
+
*
|
|
144
|
+
* @returns {{ tokens: { input: number, cacheRead: number, cacheWrite: number, output: number }, requests: number, costUsd: number|null }|null}
|
|
145
|
+
*/
|
|
146
|
+
export function claudeUsage({ cache, transcript, sessionId, env, now }) {
|
|
147
|
+
if (!cache?.entries || typeof transcript !== 'string' || typeof sessionId !== 'string') return null;
|
|
148
|
+
const subPrefix = join(dirname(transcript), sessionId) + sep;
|
|
149
|
+
const summaries = [];
|
|
150
|
+
const own = peekCached(cache, transcript);
|
|
151
|
+
if (own) summaries.push(own);
|
|
152
|
+
for (const key of Object.keys(cache.entries)) {
|
|
153
|
+
if (!key.startsWith(subPrefix)) continue;
|
|
154
|
+
const s = peekCached(cache, key);
|
|
155
|
+
if (s) summaries.push(s);
|
|
156
|
+
}
|
|
157
|
+
const counted = summaries.filter((s) => s.totals && typeof s.totals === 'object');
|
|
158
|
+
if (!counted.length) return null;
|
|
159
|
+
const tokens = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
|
|
160
|
+
let requests = 0;
|
|
161
|
+
for (const s of counted) {
|
|
162
|
+
tokens.input += s.totals.input || 0;
|
|
163
|
+
tokens.cacheRead += s.totals.cacheRead || 0;
|
|
164
|
+
tokens.cacheWrite += s.totals.cacheCreation || 0;
|
|
165
|
+
tokens.output += s.totals.output || 0;
|
|
166
|
+
requests += s.requestCount || 0;
|
|
167
|
+
}
|
|
168
|
+
let costUsd = null;
|
|
169
|
+
try {
|
|
170
|
+
const cost = sessionCostAcross(counted, { env, now });
|
|
171
|
+
// Nothing priced means "unknown", not zero dollars.
|
|
172
|
+
if (!(cost.unpriced > 0 && !(cost.actual > 0)) && finite(cost.actual)) costUsd = cents(cost.actual);
|
|
173
|
+
} catch { costUsd = null; }
|
|
174
|
+
return { tokens, requests, costUsd };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Model, context and usage of one Claude session. `cache` is the loaded
|
|
179
|
+
* session-cache.json, shared by every row of one snapshot.
|
|
180
|
+
*
|
|
181
|
+
* @returns {{ model: string|null, modelName: string|null,
|
|
182
|
+
* context: { tokens: number, window: number|null, pct: number|null }|null,
|
|
183
|
+
* usage: object|null }}
|
|
184
|
+
*/
|
|
185
|
+
export function claudeSessionDetail({ sessionId, transcript, dataDir, cache, env, now }) {
|
|
186
|
+
const detail = { model: null, modelName: null, context: null, usage: null };
|
|
187
|
+
try {
|
|
188
|
+
const ctxPath = join(dataDir, 'ctx-window.json');
|
|
189
|
+
const tail = readTail(transcript);
|
|
190
|
+
detail.model = liveModelFor(sessionId, ctxPath) ?? (tail ? lastModel(tail.text) : null);
|
|
191
|
+
detail.modelName = detail.model ? shortModelName(detail.model) : null;
|
|
192
|
+
let tokens = tail ? lastContextTokens(tail) : null;
|
|
193
|
+
if (tokens === null && tail?.cut) {
|
|
194
|
+
const wide = readTail(transcript, TRANSCRIPT_WIDE_TAIL);
|
|
195
|
+
if (wide) tokens = lastContextTokens(wide);
|
|
196
|
+
}
|
|
197
|
+
if (tokens !== null) {
|
|
198
|
+
const window = liveWindowFor(sessionId, ctxPath);
|
|
199
|
+
detail.context = { tokens, window, pct: window ? Math.round(tokens / window * 100) : null };
|
|
200
|
+
}
|
|
201
|
+
detail.usage = claudeUsage({ cache, transcript, sessionId, env, now });
|
|
202
|
+
} catch { /* keep whatever was read */ }
|
|
203
|
+
return detail;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ----------------------------------------------------------------- Codex
|
|
207
|
+
|
|
208
|
+
const pad2 = (n) => String(n).padStart(2, '0');
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Rollout files written in the last `withinMs`, newest first. Codex files them
|
|
212
|
+
* by local date, so only today's and yesterday's folders are read.
|
|
213
|
+
*
|
|
214
|
+
* @returns {Array<{ file: string, mtimeMs: number }>}
|
|
215
|
+
*/
|
|
216
|
+
export function recentRollouts({ codexHome, now = Date.now(), withinMs = DAY_MS }) {
|
|
217
|
+
const out = [];
|
|
218
|
+
try {
|
|
219
|
+
const days = new Set();
|
|
220
|
+
for (const t of [now, now - DAY_MS]) {
|
|
221
|
+
const d = new Date(t);
|
|
222
|
+
days.add(join(codexHome, 'sessions', String(d.getFullYear()), pad2(d.getMonth() + 1), pad2(d.getDate())));
|
|
223
|
+
}
|
|
224
|
+
for (const dir of days) {
|
|
225
|
+
let names;
|
|
226
|
+
try { names = readdirSync(dir); } catch { continue; }
|
|
227
|
+
for (const name of names) {
|
|
228
|
+
if (!ROLLOUT_NAME.test(name)) continue;
|
|
229
|
+
const file = join(dir, name);
|
|
230
|
+
try {
|
|
231
|
+
const mtimeMs = statSync(file).mtimeMs;
|
|
232
|
+
if (now - mtimeMs <= withinMs) out.push({ file, mtimeMs });
|
|
233
|
+
} catch { /* removed since the listing */ }
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
} catch { /* no codex home */ }
|
|
237
|
+
return out.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.file < b.file ? 1 : -1));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The files each pid holds open, from one `lsof` call. A pid that exited
|
|
242
|
+
* between `ps` and `lsof` makes lsof exit 1 while it still prints the others,
|
|
243
|
+
* so output on a failed run is used too.
|
|
244
|
+
*
|
|
245
|
+
* @returns {Map<number, string[]>|null} null on Windows, when lsof is missing or prints nothing
|
|
246
|
+
*/
|
|
247
|
+
export function defaultOpenFiles(pids) {
|
|
248
|
+
if (process.platform === 'win32' || !Array.isArray(pids) || !pids.length) return null;
|
|
249
|
+
let out;
|
|
250
|
+
try {
|
|
251
|
+
out = execFileSync('lsof', ['-a', '-p', pids.join(','), '-Fpn'], {
|
|
252
|
+
encoding: 'utf8', timeout: 1500, maxBuffer: 8 * 1024 * 1024, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'],
|
|
253
|
+
});
|
|
254
|
+
} catch (e) {
|
|
255
|
+
out = typeof e?.stdout === 'string' ? e.stdout : null;
|
|
256
|
+
}
|
|
257
|
+
if (!out) return null;
|
|
258
|
+
const map = new Map();
|
|
259
|
+
let files = null;
|
|
260
|
+
for (const line of out.split('\n')) {
|
|
261
|
+
if (line.startsWith('p')) {
|
|
262
|
+
const pid = Number(line.slice(1));
|
|
263
|
+
files = Number.isFinite(pid) ? [] : null;
|
|
264
|
+
if (files) map.set(pid, files);
|
|
265
|
+
} else if (line.startsWith('n') && files) {
|
|
266
|
+
files.push(line.slice(1));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return map;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The rollout a Codex process is writing: the first rollout among the files its
|
|
274
|
+
* pids hold open. Without one, a lone Codex process falls back to the newest
|
|
275
|
+
* rollout written in the last 15 minutes. With several processes nothing says
|
|
276
|
+
* which rollout is whose, so none is guessed.
|
|
277
|
+
*
|
|
278
|
+
* @param {number[]} pids the process and its Codex children (the native binary may hold the file)
|
|
279
|
+
* @returns {string|null}
|
|
280
|
+
*/
|
|
281
|
+
export function pickRollout({ pids, open, rollouts, onlyRow, now = Date.now() }) {
|
|
282
|
+
if (open instanceof Map) {
|
|
283
|
+
for (const pid of pids) {
|
|
284
|
+
const hit = (open.get(pid) ?? []).find((f) => ROLLOUT_OPEN.test(f));
|
|
285
|
+
if (hit) return hit;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (!onlyRow) return null;
|
|
289
|
+
const fresh = rollouts.find((r) => now - r.mtimeMs <= SINGLE_ROW_FRESH_MS);
|
|
290
|
+
return fresh ? fresh.file : null;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** `cwd` from the session_meta line at the head of a rollout. That line can be longer than the head read, so a cut line is searched by pattern. */
|
|
294
|
+
function readSessionCwd(file) {
|
|
295
|
+
let fd;
|
|
296
|
+
try {
|
|
297
|
+
fd = openSync(file, 'r');
|
|
298
|
+
const buf = Buffer.alloc(ROLLOUT_HEAD);
|
|
299
|
+
const got = readSync(fd, buf, 0, ROLLOUT_HEAD, 0);
|
|
300
|
+
const first = buf.toString('utf8', 0, got).split('\n')[0];
|
|
301
|
+
try {
|
|
302
|
+
const cwd = JSON.parse(first)?.payload?.cwd;
|
|
303
|
+
if (typeof cwd === 'string' && cwd) return cwd;
|
|
304
|
+
} catch { /* cut or malformed: search the text */ }
|
|
305
|
+
const m = /"cwd":("(?:[^"\\]|\\.)*")/.exec(first);
|
|
306
|
+
if (m) {
|
|
307
|
+
const cwd = JSON.parse(m[1]);
|
|
308
|
+
if (typeof cwd === 'string' && cwd) return cwd;
|
|
309
|
+
}
|
|
310
|
+
return null;
|
|
311
|
+
} catch {
|
|
312
|
+
return null;
|
|
313
|
+
} finally {
|
|
314
|
+
if (fd !== undefined) {
|
|
315
|
+
try { closeSync(fd); } catch { /* nothing to release */ }
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Running totals of the newest `token_count` record in the tail lines. */
|
|
321
|
+
function lastTotalUsage(lines) {
|
|
322
|
+
if (!lines) return null;
|
|
323
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
324
|
+
const line = lines[i];
|
|
325
|
+
if (!line.includes('"token_count"')) continue;
|
|
326
|
+
try {
|
|
327
|
+
const e = JSON.parse(line);
|
|
328
|
+
const u = e?.payload?.type === 'token_count' ? e.payload.info?.total_token_usage : null;
|
|
329
|
+
if (u && typeof u === 'object') return u;
|
|
330
|
+
} catch { /* partial record */ }
|
|
331
|
+
}
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* What one rollout says: the parser's snapshot (model, effort, status, context,
|
|
337
|
+
* rate limits), the running token totals and the working folder. null when the
|
|
338
|
+
* file cannot be read.
|
|
339
|
+
*/
|
|
340
|
+
export function readRollout(file) {
|
|
341
|
+
try {
|
|
342
|
+
const snapshot = readCodexSnapshot(file, { tailBytes: ROLLOUT_TAIL });
|
|
343
|
+
if (!snapshot) return null;
|
|
344
|
+
return {
|
|
345
|
+
snapshot,
|
|
346
|
+
total: lastTotalUsage(readCodexTailLines(file, ROLLOUT_TAIL)),
|
|
347
|
+
cwd: readSessionCwd(file),
|
|
348
|
+
};
|
|
349
|
+
} catch {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const CODEX_STATE = { working: 'busy', idle: 'idle', interrupted: 'idle' };
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* The row fields a rollout fills in. Codex cost is not priced here: the
|
|
358
|
+
* rollout carries token counts only, and a number that disagrees with the
|
|
359
|
+
* Codex panel would be worse than none, so `requests` and `costUsd` stay null.
|
|
360
|
+
*/
|
|
361
|
+
export function codexRowFields(rollout) {
|
|
362
|
+
const s = rollout.snapshot;
|
|
363
|
+
const model = typeof s.model === 'string' && s.model ? s.model : null;
|
|
364
|
+
const tokens = finite(s.lastContextTokens) ? s.lastContextTokens : null;
|
|
365
|
+
const window = finite(s.contextWindow) ? s.contextWindow : null;
|
|
366
|
+
const u = rollout.total;
|
|
367
|
+
const count = (n) => (finite(n) && n >= 0 ? n : 0);
|
|
368
|
+
return {
|
|
369
|
+
model,
|
|
370
|
+
modelName: model,
|
|
371
|
+
effort: typeof s.effort === 'string' && s.effort ? s.effort : null,
|
|
372
|
+
state: CODEX_STATE[s.status] ?? null,
|
|
373
|
+
context: tokens === null ? null : { tokens, window, pct: window ? Math.round(tokens / window * 100) : null },
|
|
374
|
+
usage: u ? {
|
|
375
|
+
tokens: {
|
|
376
|
+
input: Math.max(0, count(u.input_tokens) - count(u.cached_input_tokens)),
|
|
377
|
+
cacheRead: count(u.cached_input_tokens),
|
|
378
|
+
cacheWrite: count(u.cache_write_input_tokens),
|
|
379
|
+
output: count(u.output_tokens),
|
|
380
|
+
},
|
|
381
|
+
requests: null,
|
|
382
|
+
costUsd: null,
|
|
383
|
+
} : null,
|
|
384
|
+
cwd: rollout.cwd,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* The Codex account windows from a rollout's `rate_limits`. A window with no
|
|
390
|
+
* percentage or one that already reset is left out, as for Claude.
|
|
391
|
+
*
|
|
392
|
+
* @returns {{ plan: string|null, windows: Array<{ key: string, label: string, usedPct: number, resetsAt: number|null }> }|null}
|
|
393
|
+
*/
|
|
394
|
+
export function codexLimits(rateLimits, now = Date.now()) {
|
|
395
|
+
try {
|
|
396
|
+
if (!rateLimits || typeof rateLimits !== 'object') return null;
|
|
397
|
+
const windows = [];
|
|
398
|
+
for (const key of ['primary', 'secondary']) {
|
|
399
|
+
const w = rateLimits[key];
|
|
400
|
+
if (!finite(w?.used_percent)) continue;
|
|
401
|
+
const resetsAt = finite(w.resets_at) ? w.resets_at * 1000 : null;
|
|
402
|
+
if (resetsAt !== null && resetsAt <= now) continue;
|
|
403
|
+
windows.push({ key, label: windowLabel(w.window_minutes, key), usedPct: w.used_percent, resetsAt });
|
|
404
|
+
}
|
|
405
|
+
if (!windows.length) return null;
|
|
406
|
+
return { plan: typeof rateLimits.plan_type === 'string' ? rateLimits.plan_type : null, windows };
|
|
407
|
+
} catch {
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
}
|