@dorywoof/agentreplay 0.0.0-stage → 0.2.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.
@@ -0,0 +1,173 @@
1
+ import path from 'node:path';
2
+ import { readJsonl, toText, truncate, parsePatch } from '../util.js';
3
+
4
+ const MAX_OUTPUT = 4000;
5
+
6
+ /** Does this file look like a Codex rollout log? */
7
+ export function detect(records) {
8
+ return records.some((r) => r.type === 'session_meta' || (r.type === 'response_item' && r.payload));
9
+ }
10
+
11
+ /**
12
+ * Parse a Codex rollout (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl)
13
+ * into the normalized replay shape shared by every parser.
14
+ */
15
+ export function parse(file) {
16
+ const records = readJsonl(file);
17
+ const session = {
18
+ agent: 'Codex',
19
+ id: path.basename(file, '.jsonl').replace(/^rollout-/, ''),
20
+ title: null,
21
+ cwd: null,
22
+ branch: null,
23
+ models: new Set(),
24
+ events: [],
25
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 },
26
+ usageByModel: {},
27
+ };
28
+ const toolById = new Map();
29
+ let lastTotals = null;
30
+ let currentModel = null;
31
+
32
+ for (const r of records) {
33
+ const p = r.payload || {};
34
+ const ts = Date.parse(r.timestamp);
35
+
36
+ if (r.type === 'session_meta') {
37
+ session.cwd ||= p.cwd;
38
+ session.branch ||= p.git?.branch || null;
39
+ if (p.id) session.id = p.id;
40
+ }
41
+ if (r.type === 'turn_context') {
42
+ session.cwd ||= p.cwd;
43
+ if (p.model) currentModel = p.model;
44
+ }
45
+ if (r.type === 'event_msg' && p.type === 'thread_settings_applied' && p.thread_settings?.model) {
46
+ currentModel = p.thread_settings.model;
47
+ }
48
+ if (currentModel) session.models.add(currentModel);
49
+
50
+ if (r.type === 'event_msg' && p.type === 'token_count' && p.info?.total_token_usage) {
51
+ lastTotals = p.info.total_token_usage; // cumulative — keep the last one
52
+ continue;
53
+ }
54
+ if (r.type !== 'response_item') continue;
55
+
56
+ switch (p.type) {
57
+ case 'message': {
58
+ if (p.role === 'developer' || p.role === 'system') break;
59
+ const text = toText(p.content).trim();
60
+ if (!text) break;
61
+ if (p.role === 'user') {
62
+ // Codex injects environment / instruction blocks as user messages.
63
+ if (/^<(environment_context|user_instructions|permissions|INSTRUCTIONS)/.test(text)) break;
64
+ if (text.startsWith('# AGENTS.md instructions')) break;
65
+ session.events.push({ kind: 'user', t: ts, text });
66
+ session.title ||= text.split('\n')[0].slice(0, 80);
67
+ } else {
68
+ session.events.push({ kind: 'assistant', t: ts, text });
69
+ }
70
+ break;
71
+ }
72
+ case 'reasoning': {
73
+ const text = (p.summary || []).map(toText).join('\n').trim();
74
+ if (text) session.events.push({ kind: 'thinking', t: ts, text });
75
+ break;
76
+ }
77
+ case 'function_call':
78
+ case 'custom_tool_call':
79
+ case 'local_shell_call': {
80
+ const raw = p.type === 'function_call' ? p.arguments : p.type === 'custom_tool_call' ? p.input : JSON.stringify(p.action);
81
+ const ev = toolEvent(p.name || 'shell', raw, ts);
82
+ if (p.call_id) toolById.set(p.call_id, ev);
83
+ session.events.push(ev);
84
+ break;
85
+ }
86
+ case 'function_call_output':
87
+ case 'custom_tool_call_output':
88
+ case 'local_shell_call_output': {
89
+ const ev = toolById.get(p.call_id);
90
+ if (!ev) break;
91
+ const { text, exitCode } = parseOutput(p.output);
92
+ ev.output = truncate(text, MAX_OUTPUT);
93
+ ev.isError = exitCode != null && exitCode !== 0;
94
+ ev.endT = ts;
95
+ break;
96
+ }
97
+ }
98
+ }
99
+
100
+ if (lastTotals) {
101
+ const cached = lastTotals.cached_input_tokens || 0;
102
+ session.usage.input = (lastTotals.input_tokens || 0) - cached; // OpenAI counts cached inside input
103
+ session.usage.cacheRead = cached;
104
+ session.usage.cacheWrite = lastTotals.cache_write_input_tokens || 0;
105
+ session.usage.output = lastTotals.output_tokens || 0;
106
+ const model = [...session.models].pop() || 'unknown';
107
+ session.usageByModel[model] = { ...session.usage };
108
+ }
109
+ session.models = [...session.models];
110
+ return session;
111
+ }
112
+
113
+ function parseOutput(output) {
114
+ let text = typeof output === 'string' ? output : toText(output);
115
+ let exitCode = null;
116
+ // Outputs are often JSON envelopes like {"output": "...", "metadata": {"exit_code": 0}}
117
+ const pieces = [];
118
+ for (const chunk of text.split('\n')) {
119
+ const trimmed = chunk.trim();
120
+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
121
+ try {
122
+ const o = JSON.parse(trimmed);
123
+ if ('exit_code' in o) exitCode = o.exit_code;
124
+ if (o.metadata && 'exit_code' in o.metadata) exitCode = o.metadata.exit_code;
125
+ if (typeof o.output === 'string') {
126
+ pieces.push(o.output);
127
+ continue;
128
+ }
129
+ } catch {
130
+ /* not JSON */
131
+ }
132
+ }
133
+ pieces.push(chunk);
134
+ }
135
+ text = pieces.join('\n').trim();
136
+ return { text, exitCode };
137
+ }
138
+
139
+ function toolEvent(name, raw, ts) {
140
+ let args = raw;
141
+ if (typeof raw === 'string') {
142
+ try {
143
+ args = JSON.parse(raw);
144
+ } catch {
145
+ args = raw;
146
+ }
147
+ }
148
+ const ev = { kind: 'tool', t: ts, name, summary: '', input: null, output: '', isError: false };
149
+
150
+ const patch = typeof args === 'string' && args.includes('*** Begin Patch') ? args : args?.input?.includes?.('*** Begin Patch') ? args.input : null;
151
+ if (patch) {
152
+ Object.assign(ev, fromPatch(patch));
153
+ ev.name = 'apply_patch';
154
+ return ev;
155
+ }
156
+
157
+ if (args && typeof args === 'object') {
158
+ const cmd = Array.isArray(args.command) ? args.command.join(' ') : args.command || args.cmd;
159
+ ev.summary = cmd || Object.values(args).find((v) => typeof v === 'string') || '';
160
+ ev.input = truncate(JSON.stringify(args, null, 2), MAX_OUTPUT);
161
+ } else {
162
+ const s = String(args ?? '');
163
+ const cmd = s.match(/cmd:\s*"((?:[^"\\]|\\.)*)"/);
164
+ ev.summary = cmd ? cmd[1].replace(/\\"/g, '"') : s.split('\n')[0];
165
+ ev.input = truncate(s, MAX_OUTPUT);
166
+ }
167
+ ev.summary = ev.summary.slice(0, 200);
168
+ return ev;
169
+ }
170
+
171
+ function fromPatch(patch) {
172
+ return parsePatch(patch, MAX_OUTPUT);
173
+ }
@@ -0,0 +1,467 @@
1
+ /**
2
+ * The universal parser. Most coding agents store a conversation as a list of
3
+ * messages in one of a handful of dialects: Anthropic content blocks, OpenAI
4
+ * chat messages with tool_calls, Gemini parts, or something close to one of
5
+ * them. This module recognises all of those field by field, so new agents (and
6
+ * any exported chat log) replay without a dedicated parser.
7
+ */
8
+ import path from 'node:path';
9
+ import fs from 'node:fs';
10
+ import { readJsonAny, toText, stripHarnessTags, truncate, lineDelta, toMs, newSession, addUsage, parsePatch, parseSearchReplace } from '../util.js';
11
+
12
+ const MAX = 4000;
13
+ const LIST_KEYS = ['messages', 'history', 'conversation', 'chat_messages', 'chatMessages', 'turns', 'items', 'events', 'entries', 'log', 'data'];
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Finding the messages
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /** Pull a flat, ordered list of message-like objects out of any JSON shape. */
20
+ export function extractMessages(input) {
21
+ if (Array.isArray(input)) {
22
+ // JSONL lines, or a top-level array of messages
23
+ const out = [];
24
+ for (const item of input) {
25
+ if (looksLikeMessage(item)) out.push(item);
26
+ else if (item && typeof item === 'object') {
27
+ const inner = unwrap(item);
28
+ if (inner) out.push(inner);
29
+ else {
30
+ const nested = findList(item);
31
+ if (nested) out.push(...extractMessages(nested));
32
+ }
33
+ }
34
+ }
35
+ return out;
36
+ }
37
+ if (input && typeof input === 'object') {
38
+ const list = findList(input);
39
+ if (list) return extractMessages(list);
40
+ if (looksLikeMessage(input)) return [input];
41
+ }
42
+ return [];
43
+ }
44
+
45
+ function findList(obj) {
46
+ for (const k of LIST_KEYS) if (Array.isArray(obj[k]) && obj[k].length) return obj[k];
47
+ for (const k of LIST_KEYS) if (obj[k] && typeof obj[k] === 'object' && !Array.isArray(obj[k])) {
48
+ const l = findList(obj[k]);
49
+ if (l) return l;
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /** JSONL envelopes: {type, timestamp, message:{…}} / {payload:{…}} / {data:{…}} */
55
+ function unwrap(rec) {
56
+ for (const k of ['message', 'payload', 'data', 'msg', 'item']) {
57
+ const inner = rec[k];
58
+ if (inner && typeof inner === 'object' && !Array.isArray(inner) && looksLikeMessage({ ...inner, type: inner.type ?? rec.type })) {
59
+ return {
60
+ ...inner,
61
+ role: inner.role ?? roleFromType(rec.type),
62
+ type: inner.type ?? rec.type,
63
+ timestamp: inner.timestamp ?? rec.timestamp ?? rec.ts ?? rec.created_at ?? rec.createdAt,
64
+ model: inner.model ?? rec.model,
65
+ usage: inner.usage ?? rec.usage ?? rec.usageMetadata ?? rec.tokens,
66
+ id: inner.id ?? rec.uuid ?? rec.id,
67
+ };
68
+ }
69
+ }
70
+ return null;
71
+ }
72
+
73
+ function looksLikeMessage(o) {
74
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return false;
75
+ const hasRole = typeof o.role === 'string' || typeof o.type === 'string' || typeof o.author === 'string' || typeof o.sender === 'string' || typeof o.from === 'string';
76
+ const hasBody =
77
+ 'content' in o || 'parts' in o || 'text' in o || 'tool_calls' in o || 'toolCalls' in o || 'toolRequests' in o ||
78
+ 'functionCall' in o || 'function_call' in o || 'output' in o || 'result' in o || 'thoughts' in o;
79
+ return hasRole && hasBody;
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Roles
84
+ // ---------------------------------------------------------------------------
85
+
86
+ function roleFromType(t) {
87
+ if (typeof t !== 'string') return undefined;
88
+ const s = t.toLowerCase();
89
+ if (/^(user|human)\b|user[._-]?(message|prompt|input)/.test(s)) return 'user';
90
+ if (/^(assistant|ai|model|gemini|bot|agent)\b|assistant[._-]?message|agent[._-]?message/.test(s)) return 'assistant';
91
+ if (/tool[._-]?(result|output|response|execution[._-]?complete)|function[._-]?(result|response|call[._-]?output)/.test(s)) return 'tool';
92
+ if (/^(system|developer|info|meta|summary)/.test(s)) return 'system';
93
+ return undefined;
94
+ }
95
+
96
+ function roleOf(m) {
97
+ const raw = (m.role || m.author?.role || m.author || m.sender || m.from || '').toString().toLowerCase();
98
+ if (['user', 'human', 'you', 'me'].includes(raw)) return 'user';
99
+ if (['assistant', 'ai', 'model', 'gemini', 'bot', 'agent', 'claude', 'gpt', 'copilot'].includes(raw)) return 'assistant';
100
+ if (['tool', 'function', 'tool_result', 'ipython'].includes(raw)) return 'tool';
101
+ if (['system', 'developer'].includes(raw)) return 'system';
102
+ return roleFromType(m.type) || (raw ? 'assistant' : 'system');
103
+ }
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // Building the replay
107
+ // ---------------------------------------------------------------------------
108
+
109
+ /**
110
+ * @param {object[]} messages ordered message-like objects
111
+ * @param {object} opts { agent, id, title, cwd, model, baseTime, file }
112
+ */
113
+ export function buildSession(messages, opts = {}) {
114
+ const s = newSession(opts.agent || 'AI agent', opts.id);
115
+ s.title = opts.title || null;
116
+ s.cwd = opts.cwd || null;
117
+ const pending = new Map(); // tool call id → event
118
+ const order = []; // pending tool events without a result, oldest first
119
+
120
+ const attach = (id, name, output, isError, t) => {
121
+ let ev = id != null ? pending.get(String(id)) : null;
122
+ if (!ev && name) ev = [...order].reverse().find((e) => !e.done && e.rawName === name);
123
+ if (!ev) ev = order.find((e) => !e.done);
124
+ if (!ev) return false;
125
+ ev.output = truncate(stripHarnessTags(output || ''), MAX);
126
+ ev.isError = !!isError;
127
+ ev.done = true;
128
+ if (t) ev.endT = t;
129
+ return true;
130
+ };
131
+
132
+ const push = (ev) => s.events.push(ev);
133
+
134
+ for (const m of messages) {
135
+ const role = roleOf(m);
136
+ if (role === 'system') continue;
137
+ const t = toMs(m.timestamp ?? m.time?.created ?? m.created_at ?? m.createdAt ?? m.created ?? m.ts ?? m.date ?? m.meta?.sentAt ?? m.sentAt);
138
+ const model = modelOf(m) || opts.model;
139
+ if (model) s.models.add(model);
140
+ const u = readUsage(m.usage ?? m.tokens ?? m.usageMetadata ?? m.usage_metadata ?? m.metrics);
141
+ if (u) addUsage(s, model, u);
142
+ if (typeof m.cost === 'number' && m.cost > 0) s.reportedCost = (s.reportedCost || 0) + m.cost;
143
+
144
+ // Tool result messages (OpenAI role:"tool", Gemini functionResponse, Copilot tool.execution_complete …)
145
+ if (role === 'tool') {
146
+ const id = m.tool_call_id ?? m.toolCallId ?? m.call_id ?? m.tool_use_id ?? m.id;
147
+ const out = m.content ?? m.output ?? m.result ?? m.response ?? m.parts;
148
+ const parts = Array.isArray(m.parts) ? m.parts : Array.isArray(m.content) ? m.content : null;
149
+ if (parts && parts.some((p) => p && (p.functionResponse || p.type === 'tool_result'))) {
150
+ for (const p of parts) handleBlock(p, 'user', t);
151
+ } else {
152
+ attach(id, m.name ?? m.toolName, resultText(out), m.is_error || m.success === false || m.status === 'error', t);
153
+ }
154
+ continue;
155
+ }
156
+
157
+ // Reasoning first, then what the model said, then the tools it called
158
+ for (const th of m.thoughts || []) {
159
+ const text = typeof th === 'string' ? th : [th.subject, th.description].filter(Boolean).join(': ');
160
+ if (text) push({ kind: 'thinking', t, text });
161
+ }
162
+ if (typeof m.reasoning_content === 'string' && m.reasoning_content.trim()) push({ kind: 'thinking', t, text: m.reasoning_content.trim() });
163
+
164
+ // Plain text / content blocks / parts
165
+ const blocks = blocksOf(m);
166
+ for (const b of blocks) handleBlock(b, role, t);
167
+
168
+ // Side-channel tool calls
169
+ for (const tc of m.tool_calls || m.toolCalls || m.toolRequests || m.function_calls || []) toolCall(tc, t);
170
+ if (m.function_call) toolCall({ function: m.function_call }, t);
171
+ }
172
+
173
+ function handleBlock(b, role, t) {
174
+ if (b == null) return;
175
+ if (typeof b === 'string') return text(b, role, t);
176
+ const type = b.type;
177
+ if (b.thought === true && typeof b.text === 'string') return push({ kind: 'thinking', t, text: b.text.trim() });
178
+ if (type === 'thinking' || type === 'reasoning' || type === 'redacted_thinking') {
179
+ const tx = (b.thinking ?? b.text ?? toText(b.summary) ?? '').trim();
180
+ if (tx) push({ kind: 'thinking', t, text: tx });
181
+ return;
182
+ }
183
+ if (type === 'tool_use' || type === 'tool-call' || type === 'tool_call' || type === 'function_call' || b.functionCall) {
184
+ return toolCall(b.functionCall ? { ...b.functionCall, id: b.functionCall.id ?? b.id } : b, t);
185
+ }
186
+ if (type === 'tool' && (b.tool || b.state)) return opencodeTool(b, t);
187
+ if (type === 'tool_result' || type === 'tool-result' || type === 'function_call_output' || b.functionResponse) {
188
+ const fr = b.functionResponse;
189
+ const id = b.tool_use_id ?? b.toolUseID ?? b.toolUseId ?? b.tool_call_id ?? b.call_id ?? fr?.id;
190
+ const out = fr ? fr.response : b.content ?? b.output ?? b.run?.result ?? b.result;
191
+ const err = b.is_error || b.isError || b.run?.status === 'error' || b.status === 'error';
192
+ return void attach(id, fr?.name ?? b.name, resultText(out), err, t);
193
+ }
194
+ if (type === 'image' || type === 'image_url' || b.inlineData) return text('[image]', role, t);
195
+ if (type === 'step-start' || type === 'step-finish' || type === 'snapshot' || type === 'patch' || type === 'compaction') return;
196
+ if (b.synthetic) return;
197
+ const tx = b.text ?? b.content ?? b.value;
198
+ if (typeof tx === 'string') return text(tx, role, t);
199
+ if (tx && typeof tx === 'object') return handleBlock(tx, role, t);
200
+ }
201
+
202
+ function text(raw, role, t) {
203
+ let tx = stripHarnessTags(String(raw))
204
+ .replace(/<environment_details>[\s\S]*?<\/environment_details>/g, '')
205
+ .replace(/<\/?task>/g, '')
206
+ .trim();
207
+ if (!tx) return;
208
+ if (role === 'user') {
209
+ // Cline/Roo feed tool results back as user text: "[read_file for 'x'] Result:\n…"
210
+ const r = tx.match(/^\[([\w-]+)(?: for [^\]]*)?\] Result:\s*([\s\S]*)$/);
211
+ if (r && attach(null, r[1], r[2], /^(Error|The tool execution failed)/i.test(r[2].trim()), t)) return;
212
+ if (/^(<command-|<local-command|Caveat: The messages below)/.test(tx)) return;
213
+ // Harness-injected context blocks (<environment_context>…</environment_context> etc.)
214
+ if (/^<([\w-]+)[^>]*>[\s\S]*<\/\1>$/.test(tx)) return;
215
+ return push({ kind: 'user', t, text: tx });
216
+ }
217
+ // Assistants in XML-tool dialects (Cline, Roo, Kilo, older Aider-likes)
218
+ tx = tx.replace(/<thinking>([\s\S]*?)<\/thinking>/g, (_, th) => {
219
+ if (th.trim()) push({ kind: 'thinking', t, text: th.trim() });
220
+ return '';
221
+ });
222
+ const xmlTools = [];
223
+ tx = tx.replace(XML_TOOL_RE, (_, name, inner) => {
224
+ xmlTools.push({ name, input: xmlParams(inner) });
225
+ return '';
226
+ });
227
+ tx = tx.trim();
228
+ if (tx) push({ kind: 'assistant', t, text: tx });
229
+ for (const x of xmlTools) {
230
+ if (x.name === 'attempt_completion' && x.input.result) push({ kind: 'assistant', t, text: x.input.result });
231
+ else toolCall({ name: x.name, input: x.input }, t);
232
+ }
233
+ }
234
+
235
+ function toolCall(tc, t) {
236
+ const fn = tc.function || tc;
237
+ const name = fn.name || tc.name || tc.toolName || tc.tool || 'tool';
238
+ let args = fn.arguments ?? fn.args ?? tc.input ?? tc.args ?? tc.arguments ?? tc.parameters ?? {};
239
+ if (typeof args === 'string') {
240
+ try {
241
+ args = JSON.parse(args);
242
+ } catch {
243
+ /* keep raw string (e.g. a patch) */
244
+ }
245
+ }
246
+ const ev = toolEvent(name, args, t);
247
+ const id = tc.id ?? tc.toolCallId ?? tc.tool_call_id ?? tc.call_id ?? tc.callID ?? fn.id;
248
+ push(ev);
249
+ if (id != null) pending.set(String(id), ev);
250
+ order.push(ev);
251
+ // Gemini CLI stores the result next to the call
252
+ const inline = tc.result ?? tc.output ?? tc.resultDisplay ?? tc.response;
253
+ if (inline !== undefined) {
254
+ ev.output = truncate(resultText(inline), MAX);
255
+ ev.isError = tc.status === 'error' || tc.status === 'failed' || tc.success === false;
256
+ ev.done = true;
257
+ }
258
+ }
259
+
260
+ function opencodeTool(p, t) {
261
+ const st = p.state || {};
262
+ const ev = toolEvent(p.tool || 'tool', st.input || {}, toMs(st.time?.start) || t);
263
+ if (st.status === 'completed' || st.status === 'error' || st.output != null || st.error != null) {
264
+ ev.output = truncate(resultText(st.output ?? st.error ?? ''), MAX);
265
+ ev.isError = st.status === 'error';
266
+ ev.done = true;
267
+ ev.endT = toMs(st.time?.end) || undefined;
268
+ }
269
+ if (st.title && !ev.summary) ev.summary = st.title;
270
+ push(ev);
271
+ if (p.callID) pending.set(String(p.callID), ev);
272
+ }
273
+
274
+ // Fill in missing timestamps so the player still has an order to follow.
275
+ const known = s.events.filter((e) => Number.isFinite(e.t));
276
+ if (known.length < s.events.length) {
277
+ if (!known.length) {
278
+ s.timesSynthetic = true;
279
+ const base = opts.baseTime ?? (opts.file ? safeMtime(opts.file) : Date.now());
280
+ const step = 2500;
281
+ s.events.forEach((e, i) => (e.t = base - (s.events.length - i) * step));
282
+ } else {
283
+ let last = known[0].t;
284
+ for (const e of s.events) {
285
+ if (Number.isFinite(e.t)) last = e.t;
286
+ else e.t = last;
287
+ }
288
+ }
289
+ }
290
+ for (const e of s.events) {
291
+ delete e.done;
292
+ delete e.rawName;
293
+ }
294
+ if (!s.title) {
295
+ const first = s.events.find((e) => e.kind === 'user');
296
+ if (first) s.title = first.text.split('\n')[0].slice(0, 80);
297
+ }
298
+ s.models = [...s.models];
299
+ return s;
300
+ }
301
+
302
+ // ---------------------------------------------------------------------------
303
+ // Pieces
304
+ // ---------------------------------------------------------------------------
305
+
306
+ function blocksOf(m) {
307
+ if (Array.isArray(m.content)) return m.content;
308
+ if (Array.isArray(m.parts)) return m.parts;
309
+ if (typeof m.content === 'string') return [m.content];
310
+ if (m.content && typeof m.content === 'object') return [m.content];
311
+ if (typeof m.text === 'string') return [m.text];
312
+ if (typeof m.message === 'string') return [m.message];
313
+ return [];
314
+ }
315
+
316
+ function modelOf(m) {
317
+ const v = m.model ?? m.modelID ?? m.model_id ?? m.modelId ?? m.usage?.model ?? m.metadata?.model;
318
+ if (!v) return null;
319
+ if (typeof v === 'string') return v;
320
+ return v.modelID || v.id || v.name || null;
321
+ }
322
+
323
+ const num = (...vals) => {
324
+ for (const v of vals) if (typeof v === 'number' && Number.isFinite(v)) return v;
325
+ return 0;
326
+ };
327
+
328
+ /** Token usage in any of the common spellings. */
329
+ export function readUsage(u) {
330
+ if (!u || typeof u !== 'object') return null;
331
+ const cacheRead = num(u.cache_read_input_tokens, u.cacheReadInputTokens, u.cache?.read, u.cacheRead, u.cacheReads, u.cached, u.cachedContentTokenCount, u.cached_input_tokens, u.prompt_tokens_details?.cached_tokens, u.input_tokens_details?.cached_tokens);
332
+ const cacheWrite = num(u.cache_creation_input_tokens, u.cacheCreationInputTokens, u.cache?.write, u.cacheWrite, u.cacheWrites);
333
+ let input = num(u.input_tokens, u.inputTokens, u.input, u.prompt_tokens, u.promptTokens, u.promptTokenCount, u.tokensIn, u.prompt);
334
+ const output = num(u.output_tokens, u.outputTokens, u.output, u.completion_tokens, u.completionTokens, u.candidatesTokenCount, u.tokensOut, u.completion) + num(u.reasoning, u.thoughts, u.thoughtsTokenCount);
335
+ // OpenAI and Gemini count cached tokens inside the prompt total.
336
+ const cachedInsidePrompt = u.prompt_tokens != null || u.promptTokenCount != null || u.cached != null;
337
+ if (cachedInsidePrompt && cacheRead && input >= cacheRead) input -= cacheRead;
338
+ if (!input && !output && !cacheRead && !cacheWrite) return null;
339
+ return { input, output, cacheRead, cacheWrite, cacheWrite1h: 0 };
340
+ }
341
+
342
+ function resultText(v) {
343
+ if (v == null) return '';
344
+ if (typeof v === 'string') return v;
345
+ if (Array.isArray(v)) return v.map(resultText).filter(Boolean).join('\n');
346
+ if (typeof v === 'object') {
347
+ if (v.functionResponse) return resultText(v.functionResponse.response);
348
+ for (const k of ['output', 'text', 'content', 'result', 'stdout', 'error', 'message']) {
349
+ if (v[k] != null && (typeof v[k] === 'string' || typeof v[k] === 'object')) {
350
+ const r = resultText(v[k]);
351
+ if (r) return r;
352
+ }
353
+ }
354
+ return JSON.stringify(v, null, 2);
355
+ }
356
+ return String(v);
357
+ }
358
+
359
+ const XML_TOOL_RE = /<(read_file|write_to_file|replace_in_file|apply_diff|insert_content|search_and_replace|execute_command|search_files|list_files|list_code_definition_names|browser_action|use_mcp_tool|access_mcp_resource|ask_followup_question|attempt_completion|new_task|switch_mode|codebase_search|fetch_instructions|plan_mode_respond|edit_file|new_rule|web_fetch)>([\s\S]*?)<\/\1>/g;
360
+
361
+ function xmlParams(inner) {
362
+ const out = {};
363
+ const re = /<(\w+)>([\s\S]*?)<\/\1>/g;
364
+ let m;
365
+ while ((m = re.exec(inner))) out[m[1]] = m[2].replace(/^\n/, '').replace(/\n$/, '');
366
+ if (!Object.keys(out).length && inner.trim()) out.input = inner.trim();
367
+ return out;
368
+ }
369
+
370
+ const EDIT_NAME = /edit|write|replace|patch|create_file|str_replace|insert|apply_diff|search_and_replace|multiedit/i;
371
+ const PATH_KEYS = ['file_path', 'filePath', 'path', 'target_file', 'targetFile', 'file', 'filename', 'absolute_path', 'notebook_path'];
372
+
373
+ /** Normalized tool event, with a diff when the call edits a file. */
374
+ export function toolEvent(name, args, t) {
375
+ const ev = { kind: 'tool', t, name: prettyName(name), rawName: name, summary: '', input: null, output: '', isError: false };
376
+ const a = args && typeof args === 'object' ? args : {};
377
+ const raw = typeof args === 'string' ? args : null;
378
+
379
+ const patchText = raw?.includes('*** Begin Patch') ? raw : typeof a.input === 'string' && a.input.includes('*** Begin Patch') ? a.input : typeof a.patch === 'string' && a.patch.includes('*** Begin Patch') ? a.patch : null;
380
+ if (patchText) return Object.assign(ev, parsePatch(patchText, MAX));
381
+
382
+ const file = PATH_KEYS.map((k) => a[k]).find((v) => typeof v === 'string');
383
+ if (EDIT_NAME.test(name) && file) {
384
+ let diff = null;
385
+ const oldS = a.old_string ?? a.oldString ?? a.old_str ?? a.search ?? a.old_text ?? a.oldText;
386
+ const newS = a.new_string ?? a.newString ?? a.new_str ?? a.replace ?? a.new_text ?? a.newText;
387
+ if (typeof oldS === 'string' || typeof newS === 'string') diff = [{ old: oldS || '', new: newS || '' }];
388
+ else if (Array.isArray(a.edits)) diff = a.edits.map((e) => ({ old: e.old_string ?? e.oldString ?? e.oldText ?? '', new: e.new_string ?? e.newString ?? e.newText ?? '' }));
389
+ else if (typeof a.diff === 'string' && parseSearchReplace(a.diff).length) diff = parseSearchReplace(a.diff);
390
+ else {
391
+ const content = a.content ?? a.file_text ?? a.contents ?? a.new_content ?? a.code_edit ?? a.text;
392
+ if (typeof content === 'string') {
393
+ diff = [{ old: '', new: content }];
394
+ ev.created = /write|create/i.test(name);
395
+ }
396
+ }
397
+ if (diff) {
398
+ ev.file = file;
399
+ ev.summary = file;
400
+ ev.lines = diff.reduce((acc, d) => {
401
+ const x = lineDelta(d.old, d.new);
402
+ return { added: acc.added + x.added, removed: acc.removed + x.removed };
403
+ }, { added: 0, removed: 0 });
404
+ ev.diff = diff.map((d) => ({ old: truncate(d.old, MAX), new: truncate(d.new, MAX) }));
405
+ return ev;
406
+ }
407
+ }
408
+
409
+ ev.summary = summaryOf(a, raw);
410
+ ev.input = truncate(raw ?? JSON.stringify(a, null, 2), MAX);
411
+ return ev;
412
+ }
413
+
414
+ const SUMMARY_KEYS = ['description', 'command', 'cmd', 'query', 'pattern', 'regex', 'file_path', 'filePath', 'path', 'target_file', 'url', 'name', 'title', 'prompt', 'question', 'code', 'text'];
415
+ const ID_LIKE = /^[0-9a-f]{8}-[0-9a-f]{4}-|^[0-9a-f]{16,}$/i;
416
+
417
+ function summaryOf(a, raw) {
418
+ if (raw) return raw.split('\n')[0].slice(0, 200);
419
+ for (const k of SUMMARY_KEYS) {
420
+ const v = a[k];
421
+ if (typeof v === 'string' && v.trim()) return v.trim().split('\n')[0].slice(0, 200);
422
+ if (Array.isArray(v) && v.every((x) => typeof x === 'string')) return v.join(' ').slice(0, 200);
423
+ }
424
+ const s = Object.values(a).find((v) => typeof v === 'string' && v.trim() && !ID_LIKE.test(v.trim()));
425
+ return s ? s.trim().split('\n')[0].slice(0, 200) : '';
426
+ }
427
+
428
+ /** mcp__server__tool → "server · tool" */
429
+ export function prettyName(name) {
430
+ return String(name).replace(/^mcp__(.+?)__(.+)$/, (_, s, t) => `${s.replace(/_/g, ' ')} · ${t}`);
431
+ }
432
+
433
+ function safeMtime(f) {
434
+ try {
435
+ return fs.statSync(f).mtimeMs;
436
+ } catch {
437
+ return Date.now();
438
+ }
439
+ }
440
+
441
+ // ---------------------------------------------------------------------------
442
+ // Entry points
443
+ // ---------------------------------------------------------------------------
444
+
445
+ /** Does this file contain something we can replay? */
446
+ export function detect(file) {
447
+ try {
448
+ const { doc, lines } = readJsonAny(file);
449
+ return extractMessages(doc ?? lines).length > 0;
450
+ } catch {
451
+ return false;
452
+ }
453
+ }
454
+
455
+ /** Replay any JSON / JSONL chat log. */
456
+ export function parse(file, opts = {}) {
457
+ const { doc, lines } = readJsonAny(file);
458
+ const root = doc ?? lines;
459
+ const meta = doc && !Array.isArray(doc) ? doc : (lines || []).find((l) => l && (l.sessionId || l.session_id || l.title || l.cwd)) || {};
460
+ return buildSession(extractMessages(root), {
461
+ agent: opts.agent || 'AI agent',
462
+ id: meta.sessionId || meta.session_id || meta.id || path.basename(file).replace(/\.(jsonl?|json)$/, ''),
463
+ title: meta.title || meta.summary || meta.name || null,
464
+ cwd: meta.cwd || meta.directory || meta.projectPath || null,
465
+ file,
466
+ });
467
+ }