agent-run-inspector 0.0.0-stage → 0.8.2
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/LICENSE +21 -0
- package/README.ko.md +158 -0
- package/README.md +157 -2
- package/THIRD_PARTY_NOTICES.md +49 -0
- package/bin/cli.js +245 -0
- package/brand-map.json +51 -0
- package/package.json +44 -4
- package/prices.json +405 -0
- package/src/adapters/claude-code/agents.js +272 -0
- package/src/adapters/claude-code/index.js +246 -0
- package/src/adapters/claude-code/llm.js +160 -0
- package/src/adapters/claude-code/tools.js +116 -0
- package/src/adapters/codex/agents.js +91 -0
- package/src/adapters/codex/index.js +217 -0
- package/src/adapters/codex/llm.js +91 -0
- package/src/adapters/codex/tools.js +132 -0
- package/src/app.js +59 -0
- package/src/config.js +43 -0
- package/src/cost.js +104 -0
- package/src/dock.js +62 -0
- package/src/files.js +143 -0
- package/src/groups.js +53 -0
- package/src/index/index.js +73 -0
- package/src/index/scan.js +339 -0
- package/src/index/summary.js +265 -0
- package/src/live/sse.js +202 -0
- package/src/live/tail.js +98 -0
- package/src/live/watch.js +216 -0
- package/src/macos/AppIcon.icns +0 -0
- package/src/macos/app.js +324 -0
- package/src/model/detail.js +142 -0
- package/src/model/provider.js +30 -0
- package/src/model/redact.js +94 -0
- package/src/model/roles.js +23 -0
- package/src/model/tool-brand.js +52 -0
- package/src/model/tool-category.js +28 -0
- package/src/model/totals.js +87 -0
- package/src/model/types.js +72 -0
- package/src/open.js +74 -0
- package/src/roots.js +47 -0
- package/src/server/api-detail.js +40 -0
- package/src/server/api.js +125 -0
- package/src/server/auth.js +46 -0
- package/src/server/http.js +86 -0
- package/src/server/static.js +68 -0
- package/src/service.js +178 -0
- package/src/strings.js +76 -0
- package/src/update-check.js +44 -0
- package/web/agent-panel.js +125 -0
- package/web/api.js +116 -0
- package/web/app.css +453 -0
- package/web/app.js +302 -0
- package/web/call-detail.js +181 -0
- package/web/card.js +286 -0
- package/web/format.js +34 -0
- package/web/graph-layout.js +343 -0
- package/web/graph.js +295 -0
- package/web/groups.js +171 -0
- package/web/icon-192.png +0 -0
- package/web/icon-32.png +0 -0
- package/web/icon-512.png +0 -0
- package/web/icons.js +30 -0
- package/web/index.html +28 -0
- package/web/list-resize.js +43 -0
- package/web/live-follow.js +32 -0
- package/web/manifest.webmanifest +15 -0
- package/web/mini.js +167 -0
- package/web/run-header.js +230 -0
- package/web/session-list.js +378 -0
- package/web/state.js +26 -0
- package/web/strings.js +190 -0
- package/web/timeline-group.js +44 -0
- package/web/timeline-scale.js +146 -0
- package/web/timeline.js +499 -0
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { providerOf } from '../../model/provider.js';
|
|
2
|
+
import { ClaudeCodeSession } from './index.js';
|
|
3
|
+
import { AGENT_TOOLS } from './tools.js';
|
|
4
|
+
import { MSG } from '../../strings.js';
|
|
5
|
+
|
|
6
|
+
const RECENT_MS = 10 * 60 * 1000;
|
|
7
|
+
|
|
8
|
+
const str = (v) => (typeof v === 'string' && v ? v : undefined);
|
|
9
|
+
const isLive = (last, now) => last !== null && last !== undefined && now >= last && now - last < RECENT_MS;
|
|
10
|
+
|
|
11
|
+
export const agentSpanId = (toolUseId) => `ag:${toolUseId}`;
|
|
12
|
+
export const externalSpanId = (key) => `ext:${key}`;
|
|
13
|
+
export const orphanSpanId = (agentId) => `ag:file:${agentId}`;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Turns Agent/Task tool_use blocks (and their results) into agent spans.
|
|
17
|
+
* One collector per file; it only ever reads ids, flags, short names and timestamps,
|
|
18
|
+
* never prompts or result bodies. Sub-agent files get linked through `lookup`.
|
|
19
|
+
*/
|
|
20
|
+
export class AgentCollector {
|
|
21
|
+
/** @param {{ sessionId: string, fileId: string, parentId: string, depth: number, nextSeq: () => number }} ctx */
|
|
22
|
+
constructor(ctx) {
|
|
23
|
+
this.ctx = ctx;
|
|
24
|
+
this.calls = new Map(); // tool_use id -> call
|
|
25
|
+
this.orphans = new Map(); // result seen before its call
|
|
26
|
+
this.notes = []; // task-notification lines: { ts, text } (matched against ids only)
|
|
27
|
+
this.stopCalls = new Map(); // TaskStop tool_use id -> task_id
|
|
28
|
+
this.stopped = new Map(); // teammate name -> when the lead stopped it or learned it shut down
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
#stop(name, ts) {
|
|
32
|
+
if (name && ts !== null) this.stopped.set(name, Math.max(ts, this.stopped.get(name) ?? ts));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
onAssistant(rec, ts, line) {
|
|
36
|
+
const content = rec.message?.content;
|
|
37
|
+
if (!Array.isArray(content)) return;
|
|
38
|
+
for (const b of content) {
|
|
39
|
+
if (!b || b.type !== 'tool_use' || typeof b.id !== 'string' || typeof b.name !== 'string') continue;
|
|
40
|
+
if (b.name === 'TaskStop') { const t = str(b.input?.task_id); if (t) this.stopCalls.set(b.id, t); continue; }
|
|
41
|
+
if (!AGENT_TOOLS.has(b.name.toLowerCase()) || this.calls.has(b.id)) continue;
|
|
42
|
+
const i = b.input && typeof b.input === 'object' ? b.input : {};
|
|
43
|
+
const c = {
|
|
44
|
+
id: b.id,
|
|
45
|
+
start: ts ?? 0,
|
|
46
|
+
line,
|
|
47
|
+
name: str(i.name),
|
|
48
|
+
agentType: str(i.subagent_type),
|
|
49
|
+
task: str(i.description),
|
|
50
|
+
model: str(i.model),
|
|
51
|
+
team: str(i.team_name),
|
|
52
|
+
closed: false,
|
|
53
|
+
seq: this.ctx.nextSeq(),
|
|
54
|
+
};
|
|
55
|
+
this.calls.set(b.id, c);
|
|
56
|
+
const early = this.orphans.get(b.id);
|
|
57
|
+
if (early) {
|
|
58
|
+
this.orphans.delete(b.id);
|
|
59
|
+
this.#apply(c, early);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
onUser(rec, ts) {
|
|
65
|
+
if (rec.origin?.kind === 'task-notification' && ts !== null) {
|
|
66
|
+
const m = rec.message?.content;
|
|
67
|
+
const text = typeof m === 'string' ? m : Array.isArray(m) ? m.map((x) => (typeof x?.text === 'string' ? x.text : '')).join('\n') : '';
|
|
68
|
+
this.notes.push({ ts, text });
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const content = rec.message?.content;
|
|
72
|
+
// teammate messages relayed to the lead: "<name> has shut down." / the teammate approving its shutdown
|
|
73
|
+
if (typeof content === 'string' && content.includes('teammate-message')) {
|
|
74
|
+
for (const m of content.matchAll(/"type":"teammate_terminated","message":"([^"]+?) has shut down\./g)) this.#stop(m[1], ts);
|
|
75
|
+
for (const m of content.matchAll(/"type":"shutdown_approved"[^}]*?"from":"([^"]+)"/g)) this.#stop(m[1], ts);
|
|
76
|
+
}
|
|
77
|
+
if (!Array.isArray(content)) return;
|
|
78
|
+
for (const b of content) {
|
|
79
|
+
const task = b?.type === 'tool_result' ? this.stopCalls.get(b.tool_use_id) : undefined;
|
|
80
|
+
if (!task) continue;
|
|
81
|
+
// stopped now, or already not running ("not running (status: completed)", "No task found")
|
|
82
|
+
const text = typeof b.content === 'string' ? b.content : JSON.stringify(b.content ?? '');
|
|
83
|
+
if (!b.is_error || /not running|No task found/.test(text)) this.#stop(task, ts);
|
|
84
|
+
}
|
|
85
|
+
const blocks = content.filter((b) => b && b.type === 'tool_result' && typeof b.tool_use_id === 'string');
|
|
86
|
+
const tur = rec.toolUseResult && typeof rec.toolUseResult === 'object' && blocks.length === 1 ? rec.toolUseResult : {};
|
|
87
|
+
for (const b of blocks) {
|
|
88
|
+
const res = {
|
|
89
|
+
ts,
|
|
90
|
+
isError: b.is_error === true,
|
|
91
|
+
interrupted: rec.toolUseResult?.interrupted === true,
|
|
92
|
+
status: str(tur.status),
|
|
93
|
+
agentId: str(tur.agentId),
|
|
94
|
+
teammateId: str(tur.teammate_id),
|
|
95
|
+
teamName: str(tur.team_name),
|
|
96
|
+
};
|
|
97
|
+
const c = this.calls.get(b.tool_use_id);
|
|
98
|
+
if (c) this.#apply(c, res);
|
|
99
|
+
else this.orphans.set(b.tool_use_id, res);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
#apply(c, res) {
|
|
104
|
+
if (c.closed) return;
|
|
105
|
+
c.closed = true;
|
|
106
|
+
Object.assign(c, { resultTs: res.ts, isError: res.isError, interrupted: res.interrupted, status: res.status, agentId: res.agentId, teammateId: res.teammateId, teamName: res.teamName });
|
|
107
|
+
c.seq = this.ctx.nextSeq();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Agent ids and tool_use ids this file launched (for linking sub-agent files). */
|
|
111
|
+
agentIds() {
|
|
112
|
+
return [...this.calls.values()].map((c) => ({ toolUseId: c.id, agentId: c.agentId }));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* @param {{ lastTs: number | null, now: number, lookup?: AgentLookup }} clock
|
|
117
|
+
* @returns {import('../../model/types.js').RunSpan[]}
|
|
118
|
+
*/
|
|
119
|
+
spans({ lastTs, now, lookup }) {
|
|
120
|
+
const out = [];
|
|
121
|
+
const base = { parentId: this.ctx.parentId, sessionId: this.ctx.sessionId, source: 'claude-code', kind: 'agent' };
|
|
122
|
+
// the same teammate spawned again: only the latest call keeps the ext:<key> node
|
|
123
|
+
const lastSpawn = new Map();
|
|
124
|
+
for (const c of this.calls.values()) if (c.status === 'teammate_spawned') lastSpawn.set(c.teammateId ?? c.id, c);
|
|
125
|
+
for (const c of this.calls.values()) {
|
|
126
|
+
if (c.status === 'teammate_spawned' && lastSpawn.get(c.teammateId ?? c.id) !== c) continue;
|
|
127
|
+
const ref = { fileId: this.ctx.fileId, line: c.line };
|
|
128
|
+
if (c.status === 'teammate_spawned') {
|
|
129
|
+
const key = c.teammateId ?? c.id;
|
|
130
|
+
const mate = lookup?.find(undefined, key);
|
|
131
|
+
if (mate?.mate) {
|
|
132
|
+
mate.claimed = true;
|
|
133
|
+
const last = mate.mtime ?? mate.lastTs;
|
|
134
|
+
// a teammate is done once its turn ended, it shut down, or the lead stopped it after this spawn
|
|
135
|
+
const stoppedAt = this.stopped.get(key.split('@')[0]);
|
|
136
|
+
const live = isLive(last, now) && !mate.turnEnded && !mate.shutDown && !(stoppedAt >= c.start);
|
|
137
|
+
const end = live ? null : (mate.lastTs ?? c.start);
|
|
138
|
+
const model = c.model ?? mate.model;
|
|
139
|
+
out.push({
|
|
140
|
+
...base, id: externalSpanId(key), name: c.name ?? key.split('@')[0], status: live ? 'running' : 'ok',
|
|
141
|
+
start: c.start, end, ref: { fileId: mate.fileId, line: 1 }, depth: this.ctx.depth + 1, role: 'worker',
|
|
142
|
+
...(c.agentType ? { agentType: c.agentType } : {}), ...(c.task ? { task: c.task } : {}),
|
|
143
|
+
...(model ? { model, provider: providerOf(model) } : {}),
|
|
144
|
+
lastActivity: end ?? last ?? c.start, seq: c.seq,
|
|
145
|
+
});
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const name = c.name ?? c.teammateId?.split('@')[0] ?? c.agentType ?? 'teammate';
|
|
149
|
+
out.push({
|
|
150
|
+
...base, id: externalSpanId(key), name, status: 'unknown', start: c.start, end: null, ref,
|
|
151
|
+
depth: this.ctx.depth + 1, role: 'worker', external: true,
|
|
152
|
+
...(c.agentType ? { agentType: c.agentType } : {}), lastActivity: c.start, seq: c.seq,
|
|
153
|
+
});
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
const entry = lookup?.find(c.id, c.agentId);
|
|
157
|
+
if (entry) entry.claimed = true;
|
|
158
|
+
const meta = entry?.meta ?? {};
|
|
159
|
+
const note = this.notes.find((n) => n.ts >= c.start && (n.text.includes(c.id) || (entry && n.text.includes(entry.agentId))));
|
|
160
|
+
const fileLast = entry ? (entry.mtime ?? entry.lastTs ?? null) : null;
|
|
161
|
+
let status;
|
|
162
|
+
let end = null;
|
|
163
|
+
if (meta.stoppedByUser === true) { status = 'cancelled'; end = entry.lastTs ?? c.resultTs ?? c.start; }
|
|
164
|
+
else if (meta.finished === true) { status = 'ok'; end = entry.lastTs ?? c.resultTs ?? c.start; }
|
|
165
|
+
else if (note) { status = 'ok'; end = note.ts; }
|
|
166
|
+
else if (entry) { status = isLive(fileLast, now) ? 'running' : 'unknown'; }
|
|
167
|
+
else if (c.closed && c.status !== 'async_launched' && c.status !== 'teammate_spawned') {
|
|
168
|
+
if (c.interrupted) status = 'cancelled';
|
|
169
|
+
else if (c.isError) status = 'error';
|
|
170
|
+
else status = 'ok';
|
|
171
|
+
end = c.resultTs ?? c.start;
|
|
172
|
+
} else status = isLive(lastTs, now) ? 'running' : 'unknown';
|
|
173
|
+
const model = meta.model ?? c.model ?? entry?.model;
|
|
174
|
+
const lastActivity = end ?? fileLast ?? c.resultTs ?? c.start;
|
|
175
|
+
out.push({
|
|
176
|
+
...base,
|
|
177
|
+
id: agentSpanId(c.id),
|
|
178
|
+
name: c.name ?? str(meta.name) ?? c.agentType ?? 'Agent',
|
|
179
|
+
status, start: c.start, end, ref,
|
|
180
|
+
depth: Number.isFinite(meta.spawnDepth) ? meta.spawnDepth : this.ctx.depth + 1,
|
|
181
|
+
role: 'worker',
|
|
182
|
+
...(status === 'error' ? { error: { message: MSG.agentFailed } } : {}),
|
|
183
|
+
...((c.agentType ?? str(meta.agentType)) ? { agentType: c.agentType ?? str(meta.agentType) } : {}),
|
|
184
|
+
...((c.task ?? str(meta.description)) ? { task: c.task ?? str(meta.description) } : {}),
|
|
185
|
+
...(model ? { model, provider: providerOf(model) } : {}),
|
|
186
|
+
lastActivity, seq: c.seq,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* @typedef {object} AgentEntry
|
|
195
|
+
* @property {string} agentId @property {object} meta @property {number|null} lastTs
|
|
196
|
+
* @property {number} [mtime] @property {string} [model] @property {boolean} [claimed]
|
|
197
|
+
*/
|
|
198
|
+
export class AgentLookup {
|
|
199
|
+
constructor() {
|
|
200
|
+
this.byToolUse = new Map();
|
|
201
|
+
this.byAgent = new Map();
|
|
202
|
+
this.entries = [];
|
|
203
|
+
}
|
|
204
|
+
add(entry) {
|
|
205
|
+
this.entries.push(entry);
|
|
206
|
+
if (str(entry.meta?.toolUseId)) this.byToolUse.set(entry.meta.toolUseId, entry);
|
|
207
|
+
this.byAgent.set(entry.agentId, entry);
|
|
208
|
+
}
|
|
209
|
+
find(toolUseId, agentId) {
|
|
210
|
+
return this.byToolUse.get(toolUseId) ?? (agentId ? this.byAgent.get(agentId) : undefined);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Parse a main file plus its `subagents/` files into one span tree.
|
|
216
|
+
* @param {{ main: { fileId: string, text: string },
|
|
217
|
+
* subagents?: { fileId: string, agentId: string, text: string, meta?: object, mtime?: number, mate?: boolean }[],
|
|
218
|
+
* (mate: an agent-team teammate's own session file, agentId = its `name@team`)
|
|
219
|
+
* now?: number }} input
|
|
220
|
+
*/
|
|
221
|
+
export function buildSessionTree({ main, subagents = [], now }) {
|
|
222
|
+
const clock = now ?? Date.now();
|
|
223
|
+
const mainSession = new ClaudeCodeSession({ fileId: main.fileId, now: clock });
|
|
224
|
+
mainSession.push(main.text);
|
|
225
|
+
const sid = mainSession.sessionId ?? '';
|
|
226
|
+
const rootId = `${sid}:main`;
|
|
227
|
+
|
|
228
|
+
const lookup = new AgentLookup();
|
|
229
|
+
const parsed = [];
|
|
230
|
+
const lastMate = new Map(subagents.filter((f) => f.mate).map((f) => [f.agentId, f]));
|
|
231
|
+
for (const f of subagents) {
|
|
232
|
+
const meta = f.meta && typeof f.meta === 'object' ? f.meta : {};
|
|
233
|
+
// a teammate file hangs under the lead's teammate_spawned span (ext:<name@team>); an older file of a
|
|
234
|
+
// respawned teammate gets its own node under the root instead
|
|
235
|
+
const spanId = f.mate ? (lastMate.get(f.agentId) === f ? externalSpanId(f.agentId) : orphanSpanId(`${f.agentId}~${f.fileId}`))
|
|
236
|
+
: str(meta.toolUseId) ? agentSpanId(meta.toolUseId) : orphanSpanId(f.agentId);
|
|
237
|
+
const depth = Number.isFinite(meta.spawnDepth) ? meta.spawnDepth : 1;
|
|
238
|
+
const s = new ClaudeCodeSession({ fileId: f.fileId, sessionId: sid, parentId: spanId, depth, now: clock });
|
|
239
|
+
s.push(f.text);
|
|
240
|
+
const lastLlm = s.llm.lastModel();
|
|
241
|
+
const entry = { agentId: f.agentId, meta, lastTs: s.lastTs, firstTs: s.firstTs, mtime: f.mtime, model: lastLlm, fileId: f.fileId, ...(f.mate ? { mate: true, turnEnded: s.turnEnded, shutDown: s.shutDown } : {}) };
|
|
242
|
+
lookup.add(entry);
|
|
243
|
+
parsed.push({ f, s, entry, spanId, depth });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// children first, so the root's status can account for running agents
|
|
247
|
+
const sessions = [mainSession, ...parsed.map((p) => p.s)];
|
|
248
|
+
const children = sessions.flatMap((s) => s.childSpans(lookup));
|
|
249
|
+
// a stopped teammate's file is still fresh, but a call it left open will never finish
|
|
250
|
+
const doneMates = new Set(children.filter((c) => c.id.startsWith('ext:') && c.status !== 'running').map((c) => c.id));
|
|
251
|
+
for (const c of children) if (c.status === 'running' && doneMates.has(c.parentId)) c.status = 'unknown';
|
|
252
|
+
for (const p of parsed) {
|
|
253
|
+
if (p.entry.claimed) continue;
|
|
254
|
+
const m = p.entry.meta;
|
|
255
|
+
const last = p.entry.mtime ?? p.entry.lastTs;
|
|
256
|
+
let status; let end = null;
|
|
257
|
+
if (m.stoppedByUser === true) { status = 'cancelled'; end = p.entry.lastTs; }
|
|
258
|
+
else if (m.finished === true) { status = 'ok'; end = p.entry.lastTs; }
|
|
259
|
+
else status = isLive(last, clock) ? 'running' : 'unknown';
|
|
260
|
+
const model = m.model ?? p.entry.model;
|
|
261
|
+
children.push({
|
|
262
|
+
id: p.spanId, parentId: rootId, sessionId: sid, source: 'claude-code', kind: 'agent',
|
|
263
|
+
name: str(m.name) ?? str(m.agentType) ?? (p.f.mate ? p.f.agentId.split('@')[0] : 'Agent'), status,
|
|
264
|
+
start: p.entry.firstTs ?? 0, end, ref: { fileId: p.f.fileId, line: 1 }, depth: p.depth, role: 'worker',
|
|
265
|
+
...(str(m.agentType) ? { agentType: m.agentType } : {}),
|
|
266
|
+
...(str(m.description) ? { task: m.description } : {}),
|
|
267
|
+
...(model ? { model, provider: providerOf(model) } : {}),
|
|
268
|
+
lastActivity: end ?? last ?? p.entry.firstTs ?? 0, seq: 0,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
return mainSession.snapshot({ children });
|
|
272
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { LlmCollector } from './llm.js';
|
|
2
|
+
import { ToolCollector } from './tools.js';
|
|
3
|
+
import { AgentCollector } from './agents.js';
|
|
4
|
+
import { providerOf } from '../../model/provider.js';
|
|
5
|
+
import { MSG } from '../../strings.js';
|
|
6
|
+
|
|
7
|
+
const DEFAULT_RUNNING_MS = 10 * 60 * 1000;
|
|
8
|
+
/** stop_reason values of an answer that hands the turn back to the user. */
|
|
9
|
+
export const ENDS_TURN = new Set(['end_turn', 'stop_sequence']);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Agent-team shutdown seen from the teammate's own log: true when this record approves a shutdown
|
|
13
|
+
* (the teammate exits right after, so the call never gets a result) or is the lead's shutdown request
|
|
14
|
+
* left unanswered; false for any other user or assistant record; undefined (no change) for tool results.
|
|
15
|
+
*/
|
|
16
|
+
export function shutdownSignal(rec) {
|
|
17
|
+
const c = rec?.message?.content;
|
|
18
|
+
if (rec?.type === 'assistant') {
|
|
19
|
+
return Array.isArray(c) && c.some((b) => b?.type === 'tool_use' && b.name === 'SendMessage' && b.input?.approve === true
|
|
20
|
+
&& (b.input.type === 'shutdown_response' || b.input.message?.type === 'shutdown_response'));
|
|
21
|
+
}
|
|
22
|
+
if (rec?.type !== 'user') return undefined;
|
|
23
|
+
if (typeof c === 'string') return c.includes('"type":"shutdown_request"');
|
|
24
|
+
return Array.isArray(c) && c.every((b) => b?.type === 'tool_result') ? undefined : false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Id of the root agent span under the session span (Codex: `cx:<sid>:main`). */
|
|
28
|
+
export const rootAgentId = (sessionId) => `${sessionId}:main`;
|
|
29
|
+
|
|
30
|
+
function lastSegment(path) {
|
|
31
|
+
const parts = String(path).split(/[\\/]+/).filter(Boolean);
|
|
32
|
+
return parts.at(-1) ?? '';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Incremental parser for one Claude Code main session file.
|
|
37
|
+
* `push(text)` accepts any chunking; only newline-terminated lines are consumed,
|
|
38
|
+
* a trailing fragment waits for the next chunk. Feeding a file whole or in pieces
|
|
39
|
+
* gives the same `snapshot()`.
|
|
40
|
+
*/
|
|
41
|
+
export class ClaudeCodeSession {
|
|
42
|
+
/**
|
|
43
|
+
* @param {{ fileId: string, sessionId?: string, parentId?: string, depth?: number, now?: number }} opts
|
|
44
|
+
*/
|
|
45
|
+
constructor({ fileId, sessionId, parentId, depth, now } = {}) {
|
|
46
|
+
this.fileId = fileId ?? '0';
|
|
47
|
+
this.sessionId = sessionId ?? null;
|
|
48
|
+
this.now = now;
|
|
49
|
+
this.pending = '';
|
|
50
|
+
this.lineNo = 0;
|
|
51
|
+
this.seq = 0;
|
|
52
|
+
this.prevTs = null;
|
|
53
|
+
this.firstTs = null;
|
|
54
|
+
this.lastTs = null;
|
|
55
|
+
this.title = undefined;
|
|
56
|
+
// The last turn closed and nothing came after it: the model's final answer (stop_reason end_turn)
|
|
57
|
+
// or system/turn_duration (not written for every turn).
|
|
58
|
+
this.turnEnded = false;
|
|
59
|
+
this.shutDown = false; // see shutdownSignal
|
|
60
|
+
this.cwd = undefined;
|
|
61
|
+
this.branch = undefined;
|
|
62
|
+
this.sessionSeq = 0;
|
|
63
|
+
this.llm = new LlmCollector({
|
|
64
|
+
sessionId: this.sessionId,
|
|
65
|
+
fileId: this.fileId,
|
|
66
|
+
parentId: parentId ?? (this.sessionId ? rootAgentId(this.sessionId) : undefined),
|
|
67
|
+
depth: depth ?? 0,
|
|
68
|
+
nextSeq: () => ++this.seq,
|
|
69
|
+
});
|
|
70
|
+
this.tools = new ToolCollector(this.llm.ctx);
|
|
71
|
+
this.agents = new AgentCollector(this.llm.ctx);
|
|
72
|
+
this.markers = [];
|
|
73
|
+
this.turns = [];
|
|
74
|
+
this.parentIdOverride = parentId;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
push(chunk) {
|
|
78
|
+
this.pending += chunk;
|
|
79
|
+
let nl;
|
|
80
|
+
while ((nl = this.pending.indexOf('\n')) !== -1) {
|
|
81
|
+
const text = this.pending.slice(0, nl);
|
|
82
|
+
this.pending = this.pending.slice(nl + 1);
|
|
83
|
+
this.lineNo++;
|
|
84
|
+
this.#line(text, this.lineNo);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
#line(text, line) {
|
|
89
|
+
if (!text.trim()) return;
|
|
90
|
+
let rec;
|
|
91
|
+
try {
|
|
92
|
+
rec = JSON.parse(text);
|
|
93
|
+
} catch {
|
|
94
|
+
return; // cut or damaged line
|
|
95
|
+
}
|
|
96
|
+
if (!rec || typeof rec !== 'object') return;
|
|
97
|
+
const t = typeof rec.timestamp === 'string' ? Date.parse(rec.timestamp) : NaN;
|
|
98
|
+
const ts = Number.isFinite(t) ? t : null;
|
|
99
|
+
|
|
100
|
+
if (this.sessionId === null && typeof rec.sessionId === 'string') {
|
|
101
|
+
this.sessionId = rec.sessionId;
|
|
102
|
+
this.llm.ctx.sessionId = rec.sessionId;
|
|
103
|
+
if (this.parentIdOverride === undefined) this.llm.ctx.parentId = rootAgentId(rec.sessionId);
|
|
104
|
+
}
|
|
105
|
+
if (typeof rec.cwd === 'string' && rec.cwd) this.cwd = rec.cwd;
|
|
106
|
+
if (typeof rec.gitBranch === 'string' && rec.gitBranch) this.branch = rec.gitBranch;
|
|
107
|
+
|
|
108
|
+
this.shutDown = shutdownSignal(rec) ?? this.shutDown;
|
|
109
|
+
switch (rec.type) {
|
|
110
|
+
case 'ai-title':
|
|
111
|
+
if (typeof rec.aiTitle === 'string' && rec.aiTitle) {
|
|
112
|
+
this.title = rec.aiTitle;
|
|
113
|
+
this.sessionSeq = ++this.seq;
|
|
114
|
+
}
|
|
115
|
+
break;
|
|
116
|
+
case 'api-request':
|
|
117
|
+
this.llm.onApiRequest(rec, ts);
|
|
118
|
+
break;
|
|
119
|
+
case 'assistant':
|
|
120
|
+
this.turnEnded = ENDS_TURN.has(rec.message?.stop_reason);
|
|
121
|
+
this.llm.onAssistant(rec, ts, line, this.prevTs);
|
|
122
|
+
this.tools.onAssistant(rec, ts, line);
|
|
123
|
+
this.agents.onAssistant(rec, ts, line);
|
|
124
|
+
break;
|
|
125
|
+
case 'user':
|
|
126
|
+
this.turnEnded = false;
|
|
127
|
+
this.tools.onUser(rec, ts);
|
|
128
|
+
this.agents.onUser(rec, ts);
|
|
129
|
+
break;
|
|
130
|
+
case 'system':
|
|
131
|
+
this.#system(rec, ts, line);
|
|
132
|
+
break;
|
|
133
|
+
default:
|
|
134
|
+
break; // other kinds are handled by later tasks or skipped
|
|
135
|
+
}
|
|
136
|
+
if (ts !== null) {
|
|
137
|
+
this.prevTs = ts;
|
|
138
|
+
this.firstTs ??= ts;
|
|
139
|
+
this.lastTs = this.lastTs === null ? ts : Math.max(this.lastTs, ts);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
#system(rec, ts, line) {
|
|
144
|
+
if (ts === null) return;
|
|
145
|
+
if (rec.subtype === 'compact_boundary') {
|
|
146
|
+
const m = rec.compactMetadata ?? {};
|
|
147
|
+
this.markers.push({
|
|
148
|
+
kind: 'compact',
|
|
149
|
+
ts,
|
|
150
|
+
...(Number.isFinite(m.preTokens) ? { preTokens: m.preTokens } : {}),
|
|
151
|
+
...(Number.isFinite(m.postTokens) ? { postTokens: m.postTokens } : {}),
|
|
152
|
+
ref: { fileId: this.fileId, line },
|
|
153
|
+
});
|
|
154
|
+
} else if (rec.subtype === 'turn_duration' && Number.isFinite(rec.durationMs)) {
|
|
155
|
+
this.turns.push({ ts, durationMs: rec.durationMs }); // reference value only
|
|
156
|
+
}
|
|
157
|
+
if (rec.subtype === 'turn_duration') this.turnEnded = true; // the agent waits for the user now
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** @returns {import('../../model/types.js').RunSpan[]} */
|
|
161
|
+
#sessionSpan(children) {
|
|
162
|
+
const project = this.cwd ? lastSegment(this.cwd) : '';
|
|
163
|
+
const start = this.firstTs ?? 0;
|
|
164
|
+
const end = this.lastTs ?? start;
|
|
165
|
+
const now = this.now ?? Date.now();
|
|
166
|
+
// Recent writes mean running, unless the last turn has ended (waiting for the user).
|
|
167
|
+
const running = !this.turnEnded && now - end < DEFAULT_RUNNING_MS && now >= end;
|
|
168
|
+
const status = children.some((s) => s.status === 'running') || running ? 'running' : 'ok';
|
|
169
|
+
return {
|
|
170
|
+
id: this.sessionId ?? '',
|
|
171
|
+
parentId: null,
|
|
172
|
+
sessionId: this.sessionId ?? '',
|
|
173
|
+
source: 'claude-code',
|
|
174
|
+
kind: 'session',
|
|
175
|
+
name: this.title ?? (project || MSG.untitledSession),
|
|
176
|
+
status,
|
|
177
|
+
start,
|
|
178
|
+
end: status === 'running' ? null : end,
|
|
179
|
+
ref: { fileId: this.fileId, line: 1 },
|
|
180
|
+
lastActivity: end,
|
|
181
|
+
seq: Math.max(this.sessionSeq, ...children.map((s) => s.seq), 0),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The main thread's own agent span: depth 0, parent of everything the main file does. */
|
|
186
|
+
#rootAgent(session) {
|
|
187
|
+
const model = this.llm.lastModel();
|
|
188
|
+
return {
|
|
189
|
+
id: rootAgentId(this.sessionId ?? ''),
|
|
190
|
+
parentId: session.id,
|
|
191
|
+
sessionId: session.sessionId,
|
|
192
|
+
source: 'claude-code',
|
|
193
|
+
kind: 'agent',
|
|
194
|
+
name: model ?? MSG.mainAgent,
|
|
195
|
+
status: session.status,
|
|
196
|
+
start: session.start,
|
|
197
|
+
end: session.end,
|
|
198
|
+
ref: session.ref,
|
|
199
|
+
depth: 0,
|
|
200
|
+
role: 'orchestrator',
|
|
201
|
+
...(model ? { model, provider: providerOf(model) } : {}),
|
|
202
|
+
lastActivity: session.lastActivity,
|
|
203
|
+
seq: session.seq,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* llm, tool and agent spans of this file (no session / root agent).
|
|
209
|
+
* @param {import('./agents.js').AgentLookup} [lookup] sub-agent files, to link and to time agent spans
|
|
210
|
+
*/
|
|
211
|
+
childSpans(lookup) {
|
|
212
|
+
const now = this.now ?? Date.now();
|
|
213
|
+
const clock = { lastTs: this.lastTs, now };
|
|
214
|
+
return [...this.llm.spans(), ...this.tools.spans(clock), ...this.agents.spans({ ...clock, lookup })];
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* @param {{ children?: import('../../model/types.js').RunSpan[] }} [opts]
|
|
219
|
+
* children: precomputed spans for the whole tree (see buildSessionTree); default = this file only
|
|
220
|
+
* @returns {{ session: { id: string|null, title?: string, project: string, cwd?: string, branch?: string },
|
|
221
|
+
* spans: import('../../model/types.js').RunSpan[] }}
|
|
222
|
+
*/
|
|
223
|
+
snapshot({ children } = {}) {
|
|
224
|
+
const kids = children ?? this.childSpans();
|
|
225
|
+
const session = this.#sessionSpan(kids);
|
|
226
|
+
return {
|
|
227
|
+
session: {
|
|
228
|
+
id: this.sessionId,
|
|
229
|
+
...(this.title !== undefined ? { title: this.title } : {}),
|
|
230
|
+
project: this.cwd ? lastSegment(this.cwd) : '',
|
|
231
|
+
...(this.cwd !== undefined ? { cwd: this.cwd } : {}),
|
|
232
|
+
...(this.branch !== undefined ? { branch: this.branch } : {}),
|
|
233
|
+
},
|
|
234
|
+
markers: this.markers.slice(),
|
|
235
|
+
turns: this.turns.slice(),
|
|
236
|
+
spans: [session, this.#rootAgent(session), ...kids],
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Parse a whole file's text in one go. */
|
|
242
|
+
export function parseSessionText(text, opts) {
|
|
243
|
+
const s = new ClaudeCodeSession(opts);
|
|
244
|
+
s.push(text);
|
|
245
|
+
return s.snapshot();
|
|
246
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { providerOf } from '../../model/provider.js';
|
|
2
|
+
|
|
3
|
+
const SYNTHETIC_MODEL = '<synthetic>';
|
|
4
|
+
|
|
5
|
+
const num = (v) => (Number.isFinite(v) ? v : 0);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Claude Code `usage` (or one `usage.iterations[]` entry) -> Tokens.
|
|
9
|
+
* Cache writes are the 5m + 1h split when present, else the flat total.
|
|
10
|
+
* Thinking tokens are already part of `output_tokens`, hence includedInOutput.
|
|
11
|
+
* @returns {import('../../model/types.js').Tokens}
|
|
12
|
+
*/
|
|
13
|
+
export function mapUsage(usage) {
|
|
14
|
+
const u = usage && typeof usage === 'object' ? usage : {};
|
|
15
|
+
const split = u.cache_creation;
|
|
16
|
+
const cacheWrite =
|
|
17
|
+
split && typeof split === 'object'
|
|
18
|
+
? num(split.ephemeral_5m_input_tokens) + num(split.ephemeral_1h_input_tokens)
|
|
19
|
+
: num(u.cache_creation_input_tokens);
|
|
20
|
+
const tokens = {
|
|
21
|
+
input: num(u.input_tokens),
|
|
22
|
+
output: num(u.output_tokens),
|
|
23
|
+
cacheRead: num(u.cache_read_input_tokens),
|
|
24
|
+
cacheWrite,
|
|
25
|
+
};
|
|
26
|
+
const thinking = u.output_tokens_details?.thinking_tokens;
|
|
27
|
+
if (Number.isFinite(thinking) && thinking > 0) {
|
|
28
|
+
tokens.reasoning = thinking;
|
|
29
|
+
tokens.includedInOutput = true;
|
|
30
|
+
}
|
|
31
|
+
return tokens;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const ZERO_TOKENS = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Groups assistant lines by `message.id` into one llm span each (usage counted once)
|
|
38
|
+
* and splits advisor iterations into child llm spans.
|
|
39
|
+
*/
|
|
40
|
+
export class LlmCollector {
|
|
41
|
+
/**
|
|
42
|
+
* @param {{ sessionId: string, fileId: string, parentId: string, nextSeq: () => number }} ctx
|
|
43
|
+
*/
|
|
44
|
+
constructor(ctx) {
|
|
45
|
+
this.ctx = ctx;
|
|
46
|
+
this.requests = new Map(); // api-request id -> epoch ms
|
|
47
|
+
this.groups = new Map(); // message.id -> group
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
onApiRequest(rec, ts) {
|
|
51
|
+
if (typeof rec.id === 'string' && ts !== null) this.requests.set(rec.id, ts);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param {object} rec parsed assistant line
|
|
56
|
+
* @param {number | null} ts epoch ms of this line
|
|
57
|
+
* @param {number} line 1-based line number
|
|
58
|
+
* @param {number | null} prevTs timestamp of the nearest earlier line that had one
|
|
59
|
+
*/
|
|
60
|
+
onAssistant(rec, ts, line, prevTs) {
|
|
61
|
+
const msg = rec.message;
|
|
62
|
+
if (!msg || typeof msg.id !== 'string') return;
|
|
63
|
+
let g = this.groups.get(msg.id);
|
|
64
|
+
if (!g) {
|
|
65
|
+
g = { id: msg.id, line, start: null, startApprox: false, end: null };
|
|
66
|
+
this.groups.set(msg.id, g);
|
|
67
|
+
}
|
|
68
|
+
if (!g.exact) {
|
|
69
|
+
const reqTs = typeof rec.requestRef === 'string' ? this.requests.get(rec.requestRef) : undefined;
|
|
70
|
+
if (reqTs !== undefined) {
|
|
71
|
+
g.start = reqTs;
|
|
72
|
+
g.startApprox = false;
|
|
73
|
+
g.exact = true;
|
|
74
|
+
} else if (g.start === null) {
|
|
75
|
+
g.start = prevTs ?? ts;
|
|
76
|
+
g.startApprox = true;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (ts !== null) g.end = ts;
|
|
80
|
+
// The last line wins; spec says repeated lines carry identical usage.
|
|
81
|
+
g.msg = msg;
|
|
82
|
+
g.error = rec.isApiErrorMessage === true || msg.model === SYNTHETIC_MODEL ? rec : null;
|
|
83
|
+
g.seq = this.ctx.nextSeq();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Model of the newest real (non-synthetic) response, if any. */
|
|
87
|
+
lastModel() {
|
|
88
|
+
let model;
|
|
89
|
+
for (const g of this.groups.values()) {
|
|
90
|
+
const m = g.msg?.model;
|
|
91
|
+
if (typeof m === 'string' && m !== SYNTHETIC_MODEL) model = m;
|
|
92
|
+
}
|
|
93
|
+
return model;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** @returns {import('../../model/types.js').RunSpan[]} */
|
|
97
|
+
spans() {
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const g of this.groups.values()) {
|
|
100
|
+
const msg = g.msg;
|
|
101
|
+
const start = g.start ?? g.end ?? 0;
|
|
102
|
+
const end = g.end ?? start;
|
|
103
|
+
const base = {
|
|
104
|
+
parentId: this.ctx.parentId,
|
|
105
|
+
sessionId: this.ctx.sessionId,
|
|
106
|
+
source: 'claude-code',
|
|
107
|
+
kind: 'llm',
|
|
108
|
+
start,
|
|
109
|
+
end,
|
|
110
|
+
...(g.startApprox ? { startApprox: true } : {}),
|
|
111
|
+
ref: { fileId: this.ctx.fileId, line: g.line },
|
|
112
|
+
lastActivity: end,
|
|
113
|
+
seq: g.seq,
|
|
114
|
+
};
|
|
115
|
+
const id = `llm:${g.id}`;
|
|
116
|
+
if (g.error) {
|
|
117
|
+
const code = g.error.apiErrorStatus;
|
|
118
|
+
out.push({
|
|
119
|
+
...base,
|
|
120
|
+
id,
|
|
121
|
+
name: SYNTHETIC_MODEL,
|
|
122
|
+
status: 'error',
|
|
123
|
+
model: SYNTHETIC_MODEL,
|
|
124
|
+
provider: providerOf(SYNTHETIC_MODEL),
|
|
125
|
+
tokens: ZERO_TOKENS(),
|
|
126
|
+
error: {
|
|
127
|
+
message: typeof g.error.error === 'string' && g.error.error ? g.error.error : 'API error',
|
|
128
|
+
...(code !== undefined && code !== null ? { code } : {}),
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const model = typeof msg.model === 'string' ? msg.model : undefined;
|
|
134
|
+
out.push({
|
|
135
|
+
...base,
|
|
136
|
+
id,
|
|
137
|
+
name: model ?? 'unknown model',
|
|
138
|
+
status: msg.stop_reason ? 'ok' : 'unknown',
|
|
139
|
+
...(model ? { model, provider: providerOf(model) } : {}),
|
|
140
|
+
tokens: mapUsage(msg.usage),
|
|
141
|
+
});
|
|
142
|
+
const iterations = Array.isArray(msg.usage?.iterations) ? msg.usage.iterations : [];
|
|
143
|
+
let n = 0;
|
|
144
|
+
for (const it of iterations) {
|
|
145
|
+
if (!it || it.type !== 'advisor_message') continue;
|
|
146
|
+
const m = typeof it.model === 'string' ? it.model : undefined;
|
|
147
|
+
out.push({
|
|
148
|
+
...base,
|
|
149
|
+
id: `${id}:advisor:${n++}`,
|
|
150
|
+
parentId: id,
|
|
151
|
+
name: m ?? 'advisor',
|
|
152
|
+
status: 'ok',
|
|
153
|
+
...(m ? { model: m, provider: providerOf(m) } : {}),
|
|
154
|
+
tokens: mapUsage(it),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
}
|