@dorywoof/agentreplay 0.1.0 → 0.3.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,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
+ }
package/src/stats.js CHANGED
@@ -57,6 +57,8 @@ export function computeStats(session, pricing) {
57
57
  cacheWrite: u.cacheWrite + u.cacheWrite1h,
58
58
  total: u.input + u.output + u.cacheRead + u.cacheWrite + u.cacheWrite1h,
59
59
  },
60
- cost: estimateCost(session.usageByModel, pricing),
60
+ cost: session.reportedCost ?? estimateCost(session.usageByModel, pricing),
61
+ costReported: session.reportedCost != null,
62
+ timesSynthetic: !!session.timesSynthetic,
61
63
  };
62
64
  }
package/src/template.html CHANGED
@@ -156,14 +156,14 @@ footer { text-align: center; color: var(--muted); font-size: 13px; margin-top: 4
156
156
  /* ---------- summary card ---------- */
157
157
  const date = S.start ? new Date(S.start).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : '';
158
158
  const tiles = [
159
- [dur(S.activeMs), 'active time'],
159
+ ...(S.timesSynthetic ? [] : [[dur(S.activeMs), 'active time']]),
160
160
  [S.prompts, S.prompts === 1 ? 'prompt' : 'prompts'],
161
161
  [S.toolCalls, 'tool calls'],
162
162
  [S.files.length, 'files changed'],
163
163
  [`<span class="add">+${num(S.linesAdded)}</span> <span class="del">−${num(S.linesRemoved)}</span>`, 'lines'],
164
164
  [num(S.tokens.total), 'tokens'],
165
165
  ];
166
- if (S.cost != null) tiles.push(['$' + (S.cost < 10 ? S.cost.toFixed(2) : Math.round(S.cost)), 'est. API cost']);
166
+ if (S.cost != null) tiles.push(['$' + (S.cost < 10 ? S.cost.toFixed(2) : Math.round(S.cost)), S.costReported ? 'cost' : 'est. API cost']);
167
167
  $('card').innerHTML = `
168
168
  <div class="card-top"><span class="badge">${esc(D.agent)}</span>
169
169
  ${D.models.length ? `<span>${esc(D.models.join(', '))}</span>` : ''}
@@ -189,7 +189,7 @@ footer { text-align: center; color: var(--muted); font-size: 13px; margin-top: 4
189
189
  <li><span>Cache write</span><span class="n">${num(S.tokens.cacheWrite)}</span></li>
190
190
  ${S.errors ? `<li><span>Failed tool calls</span><span class="n" style="color:var(--err)">${S.errors}</span></li>` : ''}
191
191
  </ul>
192
- ${S.cost != null ? '<div class="redacted">Cost is an estimate at public API list prices.</div>' : ''}
192
+ ${S.cost != null && !S.costReported ? '<div class="redacted">Cost is an estimate at public API list prices.</div>' : ''}
193
193
  </div>`;
194
194
 
195
195
  const red = D.redactions ? Object.entries(D.redactions) : [];
package/src/util.js CHANGED
@@ -57,3 +57,89 @@ export function lineDelta(oldStr = '', newStr = '') {
57
57
  }
58
58
  return { added: b.length - common, removed: a.length - common };
59
59
  }
60
+
61
+ /** Read a file that may be one JSON document or JSONL. Returns { doc } or { lines }. */
62
+ export function readJsonAny(file) {
63
+ const raw = fs.readFileSync(file, 'utf8').replace(/^/, '');
64
+ const trimmed = raw.trim();
65
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
66
+ try {
67
+ return { doc: JSON.parse(trimmed) };
68
+ } catch {
69
+ /* fall through to JSONL */
70
+ }
71
+ }
72
+ return { lines: readJsonl(file) };
73
+ }
74
+
75
+ /** Accept ISO strings, epoch seconds or epoch milliseconds. */
76
+ export function toMs(v) {
77
+ if (v == null || v === '') return null;
78
+ if (typeof v === 'number') return v < 1e12 ? v * 1000 : v;
79
+ if (typeof v === 'string' && /^\d+(\.\d+)?$/.test(v)) return toMs(Number(v));
80
+ const t = Date.parse(v);
81
+ return Number.isFinite(t) ? t : null;
82
+ }
83
+
84
+ /** Empty normalized session — every parser fills one of these. */
85
+ export function newSession(agent, id) {
86
+ return {
87
+ agent,
88
+ id: String(id || 'session'),
89
+ title: null,
90
+ cwd: null,
91
+ branch: null,
92
+ models: new Set(),
93
+ events: [],
94
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 },
95
+ usageByModel: {},
96
+ reportedCost: null,
97
+ timesSynthetic: false,
98
+ };
99
+ }
100
+
101
+ /** Add token usage to the session totals and the per-model breakdown. */
102
+ export function addUsage(session, model, u) {
103
+ const key = model || 'unknown';
104
+ const per = (session.usageByModel[key] ||= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 });
105
+ for (const k of ['input', 'output', 'cacheRead', 'cacheWrite', 'cacheWrite1h']) {
106
+ const v = Number(u[k]) || 0;
107
+ session.usage[k] += v;
108
+ per[k] += v;
109
+ }
110
+ }
111
+
112
+ /** Codex / OpenAI apply_patch envelope → diff hunks. */
113
+ export function parsePatch(patch, maxLen = 4000) {
114
+ const files = [];
115
+ let cur = null;
116
+ for (const line of patch.split('\n')) {
117
+ const m = line.match(/^\*\*\* (Add|Update|Delete) File: (.+)$/);
118
+ if (m) {
119
+ cur = { file: m[2].trim(), op: m[1], old: [], new: [] };
120
+ files.push(cur);
121
+ continue;
122
+ }
123
+ if (!cur || line.startsWith('***') || line.startsWith('@@')) continue;
124
+ if (line.startsWith('+')) cur.new.push(line.slice(1));
125
+ else if (line.startsWith('-')) cur.old.push(line.slice(1));
126
+ }
127
+ const first = files[0] || { file: '(patch)', old: [], new: [] };
128
+ return {
129
+ file: first.file,
130
+ files: files.map((f) => f.file),
131
+ created: first.op === 'Add',
132
+ summary: files.map((f) => f.file).join(', '),
133
+ diff: files.map((f) => ({ old: truncate(f.old.join('\n'), maxLen), new: truncate(f.new.join('\n'), maxLen), file: f.file })),
134
+ lines: files.reduce((a, f) => ({ added: a.added + f.new.length, removed: a.removed + f.old.length }), { added: 0, removed: 0 }),
135
+ };
136
+ }
137
+
138
+ /** Cline / Roo / Aider style SEARCH/REPLACE blocks → diff hunks. */
139
+ export function parseSearchReplace(text) {
140
+ const hunks = [];
141
+ const re = /<{5,}\s*SEARCH[^\n]*\n([\s\S]*?)\n?={5,}\n([\s\S]*?)\n?>{5,}\s*REPLACE/g;
142
+ let m;
143
+ while ((m = re.exec(text))) hunks.push({ old: m[1].replace(/^:start_line:\d+\n-+\n/, ''), new: m[2] });
144
+ return hunks;
145
+ }