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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.ko.md +158 -0
  3. package/README.md +157 -2
  4. package/THIRD_PARTY_NOTICES.md +49 -0
  5. package/bin/cli.js +245 -0
  6. package/brand-map.json +51 -0
  7. package/package.json +44 -4
  8. package/prices.json +405 -0
  9. package/src/adapters/claude-code/agents.js +272 -0
  10. package/src/adapters/claude-code/index.js +246 -0
  11. package/src/adapters/claude-code/llm.js +160 -0
  12. package/src/adapters/claude-code/tools.js +116 -0
  13. package/src/adapters/codex/agents.js +91 -0
  14. package/src/adapters/codex/index.js +217 -0
  15. package/src/adapters/codex/llm.js +91 -0
  16. package/src/adapters/codex/tools.js +132 -0
  17. package/src/app.js +59 -0
  18. package/src/config.js +43 -0
  19. package/src/cost.js +104 -0
  20. package/src/dock.js +62 -0
  21. package/src/files.js +143 -0
  22. package/src/groups.js +53 -0
  23. package/src/index/index.js +73 -0
  24. package/src/index/scan.js +339 -0
  25. package/src/index/summary.js +265 -0
  26. package/src/live/sse.js +202 -0
  27. package/src/live/tail.js +98 -0
  28. package/src/live/watch.js +216 -0
  29. package/src/macos/AppIcon.icns +0 -0
  30. package/src/macos/app.js +324 -0
  31. package/src/model/detail.js +142 -0
  32. package/src/model/provider.js +30 -0
  33. package/src/model/redact.js +94 -0
  34. package/src/model/roles.js +23 -0
  35. package/src/model/tool-brand.js +52 -0
  36. package/src/model/tool-category.js +28 -0
  37. package/src/model/totals.js +87 -0
  38. package/src/model/types.js +72 -0
  39. package/src/open.js +74 -0
  40. package/src/roots.js +47 -0
  41. package/src/server/api-detail.js +40 -0
  42. package/src/server/api.js +125 -0
  43. package/src/server/auth.js +46 -0
  44. package/src/server/http.js +86 -0
  45. package/src/server/static.js +68 -0
  46. package/src/service.js +178 -0
  47. package/src/strings.js +76 -0
  48. package/src/update-check.js +44 -0
  49. package/web/agent-panel.js +125 -0
  50. package/web/api.js +116 -0
  51. package/web/app.css +453 -0
  52. package/web/app.js +302 -0
  53. package/web/call-detail.js +181 -0
  54. package/web/card.js +286 -0
  55. package/web/format.js +34 -0
  56. package/web/graph-layout.js +343 -0
  57. package/web/graph.js +295 -0
  58. package/web/groups.js +171 -0
  59. package/web/icon-192.png +0 -0
  60. package/web/icon-32.png +0 -0
  61. package/web/icon-512.png +0 -0
  62. package/web/icons.js +30 -0
  63. package/web/index.html +28 -0
  64. package/web/list-resize.js +43 -0
  65. package/web/live-follow.js +32 -0
  66. package/web/manifest.webmanifest +15 -0
  67. package/web/mini.js +167 -0
  68. package/web/run-header.js +230 -0
  69. package/web/session-list.js +378 -0
  70. package/web/state.js +26 -0
  71. package/web/strings.js +190 -0
  72. package/web/timeline-group.js +44 -0
  73. package/web/timeline-scale.js +146 -0
  74. package/web/timeline.js +499 -0
@@ -0,0 +1,116 @@
1
+ import { toolBrandOf, isShellTool } from '../../model/tool-brand.js';
2
+ import { toolCategoryOf } from '../../model/tool-category.js';
3
+ import { MSG } from '../../strings.js';
4
+
5
+ // Sub-agent launches become agent spans (T11), not tool spans.
6
+ export const AGENT_TOOLS = new Set(['agent', 'task']);
7
+
8
+ /**
9
+ * Pairs tool_use / server_tool_use blocks with their results (tool_use_id) into tool spans.
10
+ * Result bodies are never read: only the ids, flags and timestamps.
11
+ */
12
+ export class ToolCollector {
13
+ /**
14
+ * @param {{ sessionId: string, fileId: string, parentId: string, nextSeq: () => number }} ctx
15
+ */
16
+ constructor(ctx) {
17
+ this.ctx = ctx;
18
+ this.tools = new Map(); // tool_use id -> record
19
+ this.orphans = new Map(); // result seen before its call
20
+ }
21
+
22
+ /** Called for assistant lines: opens tools and picks up server tool results. */
23
+ onAssistant(rec, ts, line) {
24
+ const content = rec.message?.content;
25
+ if (!Array.isArray(content)) return;
26
+ for (const b of content) {
27
+ if (!b || typeof b !== 'object' || typeof b.id !== 'string' && typeof b.tool_use_id !== 'string') continue;
28
+ if (b.type === 'tool_use' || b.type === 'server_tool_use') {
29
+ this.#open(b, ts, line);
30
+ } else if (typeof b.type === 'string' && b.type.endsWith('_tool_result')) {
31
+ this.#close(b.tool_use_id, ts, { isError: false, interrupted: false });
32
+ }
33
+ }
34
+ }
35
+
36
+ /** Called for user lines: tool_result blocks close their tools. */
37
+ onUser(rec, ts) {
38
+ const content = rec.message?.content;
39
+ if (!Array.isArray(content)) return;
40
+ const interrupted = rec.toolUseResult?.interrupted === true;
41
+ for (const b of content) {
42
+ if (!b || b.type !== 'tool_result') continue;
43
+ this.#close(b.tool_use_id, ts, { isError: b.is_error === true, interrupted });
44
+ }
45
+ }
46
+
47
+ #open(b, ts, line) {
48
+ if (typeof b.id !== 'string' || typeof b.name !== 'string') return;
49
+ if (AGENT_TOOLS.has(b.name.toLowerCase())) return;
50
+ if (this.tools.has(b.id)) return; // repeated lines of one message.id
51
+ const command = isShellTool(b.name) && typeof b.input?.command === 'string' ? b.input.command : undefined;
52
+ const t = { id: b.id, name: b.name, command, start: ts, line, closed: false, seq: this.ctx.nextSeq() };
53
+ this.tools.set(b.id, t);
54
+ const early = this.orphans.get(b.id);
55
+ if (early) {
56
+ this.orphans.delete(b.id);
57
+ this.#apply(t, early.ts, early.res);
58
+ }
59
+ }
60
+
61
+ #close(id, ts, res) {
62
+ if (typeof id !== 'string') return;
63
+ const t = this.tools.get(id);
64
+ if (t) this.#apply(t, ts, res);
65
+ else this.orphans.set(id, { ts, res });
66
+ }
67
+
68
+ #apply(t, ts, res) {
69
+ if (t.closed) return;
70
+ t.closed = true;
71
+ t.end = ts;
72
+ t.isError = res.isError;
73
+ t.interrupted = res.interrupted;
74
+ t.seq = this.ctx.nextSeq();
75
+ }
76
+
77
+ /**
78
+ * @param {{ lastTs: number | null, now: number }} clock lastTs = newest line time of the file
79
+ * @returns {import('../../model/types.js').RunSpan[]}
80
+ */
81
+ spans({ lastTs, now }) {
82
+ const live = lastTs !== null && now >= lastTs && now - lastTs < 10 * 60 * 1000;
83
+ const out = [];
84
+ for (const t of this.tools.values()) {
85
+ const start = t.start ?? t.end ?? 0;
86
+ const open = !t.closed;
87
+ let status;
88
+ if (open) status = live ? 'running' : 'unknown';
89
+ else if (t.interrupted) status = 'cancelled';
90
+ else if (t.isError) status = 'error';
91
+ else status = 'ok';
92
+ const end = open ? null : (t.end ?? start);
93
+ const isError = status === 'error';
94
+ const brand = toolBrandOf({ name: t.name, command: t.command, isError });
95
+ out.push({
96
+ id: `tool:${t.id}`,
97
+ parentId: this.ctx.parentId,
98
+ sessionId: this.ctx.sessionId,
99
+ source: 'claude-code',
100
+ kind: 'tool',
101
+ name: t.name,
102
+ status,
103
+ start,
104
+ end,
105
+ ...(isError ? { error: { message: MSG.toolFailed } } : {}),
106
+ ref: { fileId: this.ctx.fileId, line: t.line },
107
+ toolCategory: toolCategoryOf({ name: t.name, command: t.command }),
108
+ ...(brand ? { toolBrand: brand } : {}),
109
+ ...(t.command !== undefined ? { command: t.command } : {}),
110
+ lastActivity: end ?? start,
111
+ seq: t.seq,
112
+ });
113
+ }
114
+ return out;
115
+ }
116
+ }
@@ -0,0 +1,91 @@
1
+ // Codex sub-agents: each child thread is its own rollout file. This module joins
2
+ // child parsers onto a parent parser and returns one flat span list.
3
+ //
4
+ // Link rule (spec 5.3 / 11-5):
5
+ // - exact: the parent has a SubAgentActivity naming the child's thread id (0.166+).
6
+ // - inferred (linkApprox + startApprox): no such item, so the child hangs off the
7
+ // spawn_agent call that started last at or before the child's session_meta
8
+ // timestamp. Calls are consumed one child at a time (calls at the same instant
9
+ // go in file order). No earlier call left -> the parent's root agent.
10
+ // The spawn call is always picked by time; only the parent link can be exact.
11
+ // Hangul-free: UI text lives in strings.js.
12
+
13
+ const byStart = (a, b) => a.start - b.start || (a.id < b.id ? -1 : 1);
14
+
15
+ function pickSpawn(spawns, claimed, childStart) {
16
+ let best = null;
17
+ for (const s of spawns) {
18
+ if (claimed.has(s.callId) || s.start > childStart) continue;
19
+ if (!best || s.start > best.start) best = s; // strict >: first of a tie wins
20
+ }
21
+ return best;
22
+ }
23
+
24
+ /**
25
+ * @param {ReturnType<import('./index.js').createCodexParser>} root
26
+ * @param {Array<ReturnType<import('./index.js').createCodexParser>>} pool any rollouts; unrelated ones are ignored
27
+ * @returns {{ spans: object[] }}
28
+ */
29
+ export function linkCodexAgents(root, pool = []) {
30
+ const rootMeta = root.meta();
31
+ if (!rootMeta) return { spans: root.spans() };
32
+ const rootSession = rootMeta.id;
33
+
34
+ const kids = new Map(); // parent thread id -> [{ p, meta, start }]
35
+ for (const p of pool) {
36
+ const m = p.meta();
37
+ if (!m?.parentThreadId || p === root) continue;
38
+ const start = p.spans().find((s) => s.kind === 'session')?.start ?? 0;
39
+ if (!kids.has(m.parentThreadId)) kids.set(m.parentThreadId, []);
40
+ kids.get(m.parentThreadId).push({ p, m, start, id: m.id });
41
+ }
42
+
43
+ const out = [...root.spans()];
44
+ const seen = new Set([rootMeta.id]);
45
+
46
+ function attach(parent, parentMeta, parentAgentId, parentDepth) {
47
+ const list = (kids.get(parentMeta.id) ?? []).filter((k) => !seen.has(k.id)).sort(byStart);
48
+ if (!list.length) return;
49
+ const spawns = parent.spawns();
50
+ const exactIds = new Set(parent.activities().map((a) => a.agentThreadId));
51
+ const claimed = new Set();
52
+ const link = new Map(); // child id -> spawn record | null
53
+ // exact links claim first so inferred ones cannot take their call
54
+ for (const pass of [true, false]) {
55
+ for (const k of list) {
56
+ if (exactIds.has(k.id) !== pass) continue;
57
+ const s = pickSpawn(spawns, claimed, k.start);
58
+ if (s) claimed.add(s.callId);
59
+ link.set(k.id, s);
60
+ }
61
+ }
62
+ for (const k of list) {
63
+ if (seen.has(k.id)) continue;
64
+ seen.add(k.id);
65
+ const spawn = link.get(k.id);
66
+ const exact = exactIds.has(k.id);
67
+ const spawnSpan = spawn ? out.find((s) => s.id === `cx:${parentMeta.id}:${spawn.callId}`) : null;
68
+ const agentId = `cx:${k.id}:main`;
69
+ if (spawnSpan) spawnSpan.spawnsAgentId = agentId;
70
+ const sess = k.p.spans().find((s) => s.kind === 'session');
71
+ for (const s of k.p.spans()) {
72
+ if (s.kind === 'session') continue;
73
+ const c = { ...s, sessionId: rootSession };
74
+ if (s.id === agentId) {
75
+ c.parentId = spawnSpan ? spawnSpan.id : parentAgentId;
76
+ c.depth = parentDepth + 1;
77
+ c.name = k.m.nickname ?? s.name;
78
+ if (k.m.role) c.task = k.m.role;
79
+ c.status = sess.status;
80
+ c.end = sess.end;
81
+ if (!exact) { c.linkApprox = true; c.startApprox = true; }
82
+ }
83
+ out.push(c);
84
+ }
85
+ attach(k.p, k.m, agentId, parentDepth + 1);
86
+ }
87
+ }
88
+
89
+ attach(root, rootMeta, `cx:${rootSession}:main`, 0);
90
+ return { spans: out };
91
+ }
@@ -0,0 +1,217 @@
1
+ // Codex rollout adapter: incremental, line-at-a-time parser (T21 tail reuses it).
2
+ // Input: (lineNo, parsed line). Output: the RunSpans added or changed by that line.
3
+ // Unknown line types are skipped silently. Hangul-free: UI text lives in strings.js.
4
+ import { basename } from 'node:path';
5
+ import { MSG } from '../../strings.js';
6
+ import { createToolTracker } from './tools.js';
7
+ import { createLlmTracker } from './llm.js';
8
+
9
+ export const RECENT_MS = 10 * 60 * 1000;
10
+
11
+ const ts = (o, fallback) => {
12
+ const t = typeof o?.timestamp === 'string' ? Date.parse(o.timestamp) : NaN;
13
+ return Number.isNaN(t) ? fallback : t;
14
+ };
15
+
16
+ /**
17
+ * @param {{ fileId: string, now?: () => number }} opts
18
+ */
19
+ export function createCodexParser({ fileId, now = Date.now }) {
20
+ let sessionId = null;
21
+ let unknownFormat = false;
22
+ let meta = null; // session_meta payload
23
+ let startTs = null;
24
+ let lastTs = 0;
25
+ let currentModel = null;
26
+ let currentTurn = null; // open turn id
27
+ const turns = new Map(); // turnId -> band
28
+ const models = [];
29
+ let tracker = null;
30
+ let llm = null;
31
+ const emitted = new Map(); // span id -> JSON of last emitted
32
+ let first = true;
33
+ const activities = []; // SubAgentActivity items: { kind, agentThreadId, ts }
34
+
35
+ const sessionSpanId = () => `cx:${sessionId}`;
36
+ const agentSpanId = () => `cx:${sessionId}:main`;
37
+ const live = () => now() - lastTs <= RECENT_MS;
38
+ // The last turn closed (task_complete / turn_aborted): waiting for the user, not running.
39
+ const turnEnded = () => [...turns.values()].at(-1)?.status != null;
40
+
41
+ function turnList() {
42
+ const isLive = live();
43
+ return [...turns.values()].map((t) => ({
44
+ ...t,
45
+ status: t.status ?? (isLive ? 'running' : 'unknown'),
46
+ }));
47
+ }
48
+
49
+ // A file with no parsable line never reaches push(), so it looks like an unknown format too.
50
+ const unknown = () => unknownFormat || !meta;
51
+
52
+ function sessionSpan() {
53
+ if (unknown()) {
54
+ const id = `cx:unknown:${fileId}`;
55
+ return {
56
+ id, parentId: null, sessionId: id, source: 'codex', kind: 'session', name: MSG.unknownFormat,
57
+ status: 'unknown', start: startTs ?? 0, end: null, ref: { fileId, line: 1 }, lastActivity: startTs ?? 0,
58
+ };
59
+ }
60
+ const list = turnList();
61
+ const lastTurn = list.at(-1);
62
+ let status;
63
+ if (live() && !turnEnded()) status = 'running';
64
+ else if (lastTurn?.status === 'cancelled') status = 'cancelled';
65
+ else if (lastTurn?.status === 'ok') status = 'ok';
66
+ else status = 'unknown';
67
+ const s = {
68
+ id: sessionSpanId(), parentId: null, sessionId, source: 'codex', kind: 'session',
69
+ name: meta?.cwd ? basename(meta.cwd) : MSG.codexSession,
70
+ status, start: startTs, end: status === 'running' ? null : lastTs,
71
+ ref: { fileId, line: 1 }, lastActivity: lastTs,
72
+ };
73
+ if (currentModel) s.model = currentModel;
74
+ return s;
75
+ }
76
+
77
+ function agentSpan() {
78
+ return {
79
+ id: agentSpanId(), parentId: sessionSpanId(), sessionId, source: 'codex', kind: 'agent',
80
+ name: currentModel ?? MSG.codexSession,
81
+ status: live() && !turnEnded() ? 'running' : ([...turns.values()].at(-1)?.status ?? 'unknown'),
82
+ start: startTs, end: null, ref: { fileId, line: 1 }, depth: 0, lastActivity: lastTs,
83
+ ...(currentModel ? { model: currentModel } : {}),
84
+ };
85
+ }
86
+
87
+ function allSpans() {
88
+ if (unknown()) return [sessionSpan()];
89
+ const isLive = live();
90
+ const out = [sessionSpan(), agentSpan()];
91
+ out.push(...llm.spans());
92
+ for (const rec of tracker.records()) out.push(tracker.render(rec, isLive && !rec.closed));
93
+ return out;
94
+ }
95
+
96
+ function diff(candidates) {
97
+ const out = [];
98
+ for (const s of candidates) {
99
+ const j = JSON.stringify(s);
100
+ if (emitted.get(s.id) !== j) { emitted.set(s.id, j); out.push(JSON.parse(j)); }
101
+ }
102
+ return out;
103
+ }
104
+
105
+ /** Spans added or changed by this line. */
106
+ function push(lineNo, obj) {
107
+ if (first) {
108
+ first = false;
109
+ if (obj?.type !== 'session_meta' || typeof obj.payload?.id !== 'string') {
110
+ unknownFormat = true;
111
+ startTs = ts(obj, 0);
112
+ lastTs = startTs;
113
+ return diff([sessionSpan()]);
114
+ }
115
+ meta = obj.payload;
116
+ sessionId = meta.id;
117
+ startTs = Date.parse(meta.timestamp);
118
+ if (Number.isNaN(startTs)) startTs = ts(obj, 0);
119
+ lastTs = startTs;
120
+ tracker = createToolTracker({ sessionId, fileId, parentId: agentSpanId() });
121
+ llm = createLlmTracker({ sessionId, fileId, parentId: agentSpanId(), startTs });
122
+ return diff(allSpans());
123
+ }
124
+ if (unknownFormat || !obj || typeof obj !== 'object') return [];
125
+ const t = ts(obj, lastTs);
126
+ lastTs = Math.max(lastTs, t);
127
+ const p = obj.payload;
128
+ if (!p || typeof p !== 'object') return diff(allSpans());
129
+
130
+ if (obj.type === 'turn_context') {
131
+ if (typeof p.model === 'string') {
132
+ currentModel = p.model;
133
+ if (!models.includes(p.model)) models.push(p.model);
134
+ const band = turns.get(p.turn_id);
135
+ if (band) band.model = p.model;
136
+ }
137
+ } else if (obj.type === 'event_msg') {
138
+ switch (p.type) {
139
+ case 'task_started':
140
+ currentTurn = p.turn_id;
141
+ turns.set(p.turn_id, { turnId: p.turn_id, start: t, end: null, status: null });
142
+ break;
143
+ case 'task_complete':
144
+ case 'turn_aborted': {
145
+ const aborted = p.type === 'turn_aborted';
146
+ const band = turns.get(p.turn_id);
147
+ if (band) {
148
+ band.end = t;
149
+ band.status = aborted ? 'cancelled' : 'ok';
150
+ if (aborted && typeof p.reason === 'string') band.reason = p.reason;
151
+ }
152
+ tracker.onTurnEnd(p.turn_id, t, aborted);
153
+ if (currentTurn === p.turn_id) currentTurn = null;
154
+ break;
155
+ }
156
+ case 'user_message':
157
+ llm.onInput(t);
158
+ break;
159
+ case 'token_count':
160
+ llm.onTokenCount(lineNo, t, p, currentModel);
161
+ break;
162
+ case 'item_completed':
163
+ tracker.onItem(t, p);
164
+ if (/^subagentactivity$/i.test(p.item?.type) && typeof p.item.agent_thread_id === 'string') {
165
+ activities.push({ kind: p.item.kind, agentThreadId: p.item.agent_thread_id, ts: t });
166
+ }
167
+ break;
168
+ default:
169
+ }
170
+ } else if (obj.type === 'response_item') {
171
+ if (p.type === 'message' && p.role === 'user') llm.onInput(t);
172
+ else if (p.type === 'function_call' || p.type === 'custom_tool_call') tracker.onCall(lineNo, t, p, currentTurn);
173
+ else if (p.type === 'function_call_output' || p.type === 'custom_tool_call_output') {
174
+ llm.onInput(t);
175
+ tracker.onOutput(t, p);
176
+ }
177
+ } else if (obj.type === 'token_usage_record') {
178
+ llm.onRecord(lineNo, t, p, currentModel);
179
+ }
180
+ return diff(allSpans());
181
+ }
182
+
183
+ const spawnInfo = () => meta?.source?.subagent?.thread_spawn;
184
+
185
+ return {
186
+ push,
187
+ /** Current full state, in stable order. */
188
+ spans: () => allSpans(),
189
+ /** Turn bands for the time axis (not spans). */
190
+ turns: turnList,
191
+ /** spawn_agent calls of this session (agents.js pairs them with child rollouts). */
192
+ spawns: () => (tracker ? tracker.records().filter((r) => r.name === 'spawn_agent') : []),
193
+ activities: () => activities,
194
+ meta: () => (unknown() ? null : {
195
+ id: sessionId, cwd: meta.cwd, cliVersion: meta.cli_version, provider: meta.model_provider,
196
+ branch: meta.git?.branch, models: [...models],
197
+ parentThreadId: meta.parent_thread_id ?? spawnInfo()?.parent_thread_id,
198
+ nickname: meta.agent_nickname ?? spawnInfo()?.agent_nickname,
199
+ role: meta.agent_role ?? spawnInfo()?.agent_role,
200
+ }),
201
+ };
202
+ }
203
+
204
+ /** Feed already-parsed lines (null for an unparsable line) in order; returns the final spans. */
205
+ export function parseLines(fileId, lines, opts = {}) {
206
+ const p = createCodexParser({ fileId, ...opts });
207
+ lines.forEach((o, i) => p.push(i + 1, o));
208
+ return p;
209
+ }
210
+
211
+ /** Parse rollout text; lines that are not valid JSON become null and are skipped. */
212
+ export function parseRolloutText(fileId, text, opts = {}) {
213
+ const lines = text.split('\n').filter((l) => l.length > 0).map((l) => {
214
+ try { return JSON.parse(l); } catch { return null; }
215
+ });
216
+ return parseLines(fileId, lines, opts);
217
+ }
@@ -0,0 +1,91 @@
1
+ // Codex LLM calls from token accounting lines (spec 5.3, 11-3, 11-6).
2
+ //
3
+ // Decisions:
4
+ // - One `event_msg/token_count` = one response (llm span). end = that line's time.
5
+ // - `info.total_token_usage` is cumulative, so it is never summed. We read
6
+ // `info.last_token_usage`. A line whose cumulative total equals the previous
7
+ // one is a repeat and is dropped.
8
+ // - `info: null` (old versions) carries no usage and is skipped.
9
+ // - `cached_input_tokens` is part of `input_tokens` (input >= cached held in
10
+ // the real-record scan), so Tokens.input = input - cached (clamped at 0) and
11
+ // cacheRead = cached.
12
+ // - 0.166 writes a `token_usage_record` per response next to the token_count.
13
+ // Once one is seen, the record is the only source: later token_count lines
14
+ // are ignored, otherwise every response would count twice. Records are
15
+ // deduplicated by response_id.
16
+ // - start = time of the nearest preceding user input / tool output line. If no
17
+ // such line came since the last response, the last response's end, else the
18
+ // session start. It is always an approximation (startApprox).
19
+ // - Codex gives no stop reason, so a counted response is status 'ok'.
20
+ // - reasoning_output_tokens are part of output_tokens (includedInOutput).
21
+ import { providerOf } from '../../model/provider.js';
22
+
23
+ const num = (v) => (Number.isFinite(v) ? v : 0);
24
+
25
+ /** Codex usage object -> Tokens. */
26
+ export function mapUsage(u) {
27
+ const input = num(u.input_tokens);
28
+ const cached = num(u.cached_input_tokens);
29
+ const tokens = {
30
+ input: Math.max(0, input - cached),
31
+ output: num(u.output_tokens),
32
+ cacheRead: cached,
33
+ cacheWrite: num(u.cache_write_input_tokens),
34
+ };
35
+ if (Number.isFinite(u.reasoning_output_tokens) && u.reasoning_output_tokens > 0) {
36
+ tokens.reasoning = u.reasoning_output_tokens;
37
+ tokens.includedInOutput = true;
38
+ }
39
+ return tokens;
40
+ }
41
+
42
+ const isUsage = (u) => u && typeof u === 'object' && !Array.isArray(u);
43
+
44
+ export function createLlmTracker({ sessionId, fileId, parentId, startTs }) {
45
+ const calls = [];
46
+ const seenResponses = new Set();
47
+ let recordMode = false;
48
+ let lastInput = null; // ts of latest input/tool-output line not yet used as a start
49
+ let lastEnd = null;
50
+ let lastTotal = null; // JSON of the previous cumulative total
51
+
52
+ function add({ id, line, ts, usage, model }) {
53
+ const start = Math.min(lastInput ?? lastEnd ?? startTs, ts);
54
+ lastInput = null;
55
+ lastEnd = ts;
56
+ const span = {
57
+ id, parentId, sessionId, source: 'codex', kind: 'llm',
58
+ name: model ?? 'unknown model', status: 'ok', start, end: ts, startApprox: true,
59
+ ref: { fileId, line }, tokens: mapUsage(usage), lastActivity: ts,
60
+ };
61
+ if (model) { span.model = model; span.provider = providerOf(model); }
62
+ calls.push(span);
63
+ return span;
64
+ }
65
+
66
+ /** A user message or tool output: the next response starts here. */
67
+ function onInput(ts) { lastInput = ts; }
68
+
69
+ /** @returns {object|null} the new span, or null if the line is not a response. */
70
+ function onTokenCount(line, ts, payload, model) {
71
+ if (recordMode) return null;
72
+ const info = payload.info;
73
+ if (!info || typeof info !== 'object') return null;
74
+ const total = JSON.stringify(info.total_token_usage ?? null);
75
+ if (info.total_token_usage != null && total === lastTotal) return null;
76
+ if (info.total_token_usage != null) lastTotal = total;
77
+ if (!isUsage(info.last_token_usage)) return null;
78
+ return add({ id: `cx:${sessionId}:llm:L${line}`, line, ts, usage: info.last_token_usage, model });
79
+ }
80
+
81
+ function onRecord(line, ts, payload, model) {
82
+ recordMode = true;
83
+ if (!isUsage(payload?.usage)) return null;
84
+ const rid = typeof payload.response_id === 'string' ? payload.response_id : `L${line}`;
85
+ if (seenResponses.has(rid)) return null;
86
+ seenResponses.add(rid);
87
+ return add({ id: `cx:${sessionId}:llm:${rid}`, line, ts, usage: payload.usage, model });
88
+ }
89
+
90
+ return { onInput, onTokenCount, onRecord, spans: () => calls };
91
+ }
@@ -0,0 +1,132 @@
1
+ // Codex tool calls: function_call / custom_tool_call <-> *_output (call_id),
2
+ // plus the 0.166 item_completed overlay for time and status.
3
+ //
4
+ // Decisions (spec 5.3, 11-4):
5
+ // - Older versions carry no structural success signal, so a paired call is
6
+ // status 'unknown'. Output bodies are never parsed for exit codes.
7
+ // - item_completed.item.id does not match call_id in real records (4 of 542),
8
+ // so items are linked by time: the unclaimed call whose start is closest to
9
+ // item.started_at_ms, within ITEM_MATCH_MS.
10
+ // - A call with no output is 'running' while the session is live and its turn
11
+ // is still open, 'cancelled' if its turn was aborted, otherwise 'unknown'.
12
+ import { toolBrandOf } from '../../model/tool-brand.js';
13
+ import { toolCategoryOf } from '../../model/tool-category.js';
14
+
15
+ const ITEM_MATCH_MS = 2000;
16
+ // Item types that are not tool executions; they never claim a call.
17
+ const NON_TOOL_ITEMS = /^(subagentactivity|agentmessage|usermessage|reasoning|plan|contextcompaction)$/i;
18
+ const SHELL_FLAGS = new Set(['-c', '-lc', '-ic', '-ilc', '-cl']);
19
+
20
+ /** Pull a printable command out of function_call.arguments (JSON string). Output bodies are never read. */
21
+ export function commandOf(args) {
22
+ let a = args;
23
+ if (typeof a === 'string') {
24
+ try { a = JSON.parse(a); } catch { return undefined; }
25
+ }
26
+ if (!a || typeof a !== 'object') return undefined;
27
+ const c = a.command ?? a.cmd;
28
+ if (typeof c === 'string') return c;
29
+ if (Array.isArray(c) && c.every((x) => typeof x === 'string') && c.length) {
30
+ if (c.length >= 3 && SHELL_FLAGS.has(c[1])) return c[2];
31
+ return c.join(' ');
32
+ }
33
+ return undefined;
34
+ }
35
+
36
+ export function createToolTracker({ sessionId, fileId, parentId }) {
37
+ const calls = new Map(); // callId -> record
38
+ const order = [];
39
+
40
+ function onCall(lineNo, ts, payload, turnId) {
41
+ const callId = payload.call_id;
42
+ if (typeof callId !== 'string' || calls.has(callId)) return [];
43
+ const name = typeof payload.name === 'string' ? payload.name : 'unknown';
44
+ const rec = {
45
+ callId, name, start: ts, line: lineNo, turnId: turnId ?? null,
46
+ command: commandOf(payload.arguments),
47
+ outputTs: null, closed: null, item: null, last: ts,
48
+ };
49
+ calls.set(callId, rec);
50
+ order.push(rec);
51
+ return [rec];
52
+ }
53
+
54
+ function onOutput(ts, payload) {
55
+ const rec = calls.get(payload.call_id);
56
+ if (!rec || rec.outputTs !== null) return [];
57
+ rec.outputTs = ts;
58
+ rec.last = Math.max(rec.last, ts);
59
+ return [rec];
60
+ }
61
+
62
+ function onItem(ts, payload) {
63
+ const item = payload.item;
64
+ if (!item || typeof item !== 'object' || typeof item.type !== 'string' || NON_TOOL_ITEMS.test(item.type)) return [];
65
+ const sMs = payload.started_at_ms;
66
+ if (typeof sMs !== 'number') return [];
67
+ let best = null;
68
+ let bestD = Infinity;
69
+ for (const rec of order) {
70
+ if (rec.item) continue;
71
+ const d = Math.abs(rec.start - sMs);
72
+ if (d <= ITEM_MATCH_MS && d < bestD) { best = rec; bestD = d; }
73
+ }
74
+ if (!best) return [];
75
+ const failed = item.status === 'failed' || (typeof item.exit_code === 'number' && item.exit_code !== 0);
76
+ const done = item.status === 'completed' && !failed;
77
+ best.item = {
78
+ start: sMs,
79
+ end: typeof payload.completed_at_ms === 'number' ? payload.completed_at_ms : null,
80
+ status: failed ? 'error' : done ? 'ok' : null,
81
+ error: typeof item.error?.message === 'string' ? item.error.message : null,
82
+ };
83
+ best.last = Math.max(best.last, best.item.end ?? ts, ts);
84
+ return [best];
85
+ }
86
+
87
+ /** A turn ended: pending calls of that turn stop being live. */
88
+ function onTurnEnd(turnId, ts, aborted) {
89
+ const changed = [];
90
+ for (const rec of order) {
91
+ if (rec.turnId !== turnId || rec.outputTs !== null || rec.closed) continue;
92
+ rec.closed = { ts, aborted };
93
+ changed.push(rec);
94
+ }
95
+ return changed;
96
+ }
97
+
98
+ function render(rec, live) {
99
+ const start = rec.item?.start ?? rec.start;
100
+ let end = rec.item?.end ?? rec.outputTs;
101
+ let status = rec.item?.status;
102
+ if (!status) {
103
+ if (rec.outputTs !== null) status = 'unknown';
104
+ else if (rec.closed?.aborted) status = 'cancelled';
105
+ else if (rec.closed) status = 'unknown';
106
+ else status = live ? 'running' : 'unknown';
107
+ }
108
+ if (end == null && status === 'cancelled') end = rec.closed.ts;
109
+ const isError = status === 'error';
110
+ const span = {
111
+ id: `cx:${sessionId}:${rec.callId}`,
112
+ parentId,
113
+ sessionId,
114
+ source: 'codex',
115
+ kind: 'tool',
116
+ name: rec.name,
117
+ status,
118
+ start,
119
+ end: end ?? null,
120
+ ref: { fileId, line: rec.line },
121
+ toolCategory: toolCategoryOf({ name: rec.name, command: rec.command }),
122
+ lastActivity: Math.max(rec.last, end ?? 0, start),
123
+ };
124
+ const brand = toolBrandOf({ name: rec.name, command: rec.command, isError });
125
+ if (brand) span.toolBrand = brand;
126
+ if (rec.command !== undefined) span.command = rec.command;
127
+ if (rec.item?.error) span.error = { message: rec.item.error };
128
+ return span;
129
+ }
130
+
131
+ return { onCall, onOutput, onItem, onTurnEnd, render, records: () => order };
132
+ }