@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.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/agentreplay.js +162 -0
- package/package.json +50 -4
- package/src/discover.js +109 -0
- package/src/parsers/agents.js +377 -0
- package/src/parsers/claude.js +180 -0
- package/src/parsers/codex.js +173 -0
- package/src/parsers/universal.js +467 -0
- package/src/pricing.js +63 -0
- package/src/redact.js +96 -0
- package/src/render.js +33 -0
- package/src/stats.js +64 -0
- package/src/template.html +356 -0
- package/src/util.js +145 -0
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thin adapters for agents whose logs the universal parser can read once the
|
|
3
|
+
* right files are found and stitched together.
|
|
4
|
+
*/
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { createRequire } from 'node:module';
|
|
9
|
+
import { readJsonAny, toMs, addUsage, lineDelta, truncate, parseSearchReplace } from '../util.js';
|
|
10
|
+
import { buildSession, parse as parseUniversal, extractMessages } from './universal.js';
|
|
11
|
+
|
|
12
|
+
const home = os.homedir();
|
|
13
|
+
const env = process.env;
|
|
14
|
+
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
// filesystem helpers
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
export function walk(dir, depth, match, out = []) {
|
|
20
|
+
let entries;
|
|
21
|
+
try {
|
|
22
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
23
|
+
} catch {
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
for (const e of entries) {
|
|
27
|
+
const p = path.join(dir, e.name);
|
|
28
|
+
if (e.isDirectory() && depth > 0) walk(p, depth - 1, match, out);
|
|
29
|
+
else if (e.isFile() && match(e.name, p)) out.push(p);
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const readJson = (f) => {
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(fs.readFileSync(f, 'utf8').replace(/^/, ''));
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** VS Code-family globalStorage folders on this OS (VS Code, Insiders, VSCodium, Cursor, Windsurf…). */
|
|
43
|
+
function globalStorageRoots() {
|
|
44
|
+
const apps = ['Code', 'Code - Insiders', 'VSCodium', 'Cursor', 'Windsurf', 'Trae', 'Kiro', 'Positron'];
|
|
45
|
+
const base =
|
|
46
|
+
process.platform === 'win32'
|
|
47
|
+
? env.APPDATA || path.join(home, 'AppData', 'Roaming')
|
|
48
|
+
: process.platform === 'darwin'
|
|
49
|
+
? path.join(home, 'Library', 'Application Support')
|
|
50
|
+
: env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
51
|
+
return apps.map((a) => path.join(base, a, 'User', 'globalStorage'));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const dataHome = () =>
|
|
55
|
+
env.XDG_DATA_HOME || (process.platform === 'win32' ? path.join(home, '.local', 'share') : path.join(home, '.local', 'share'));
|
|
56
|
+
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
// Gemini CLI ~/.gemini/tmp/<project>/chats/*.json(l)
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
export const gemini = {
|
|
61
|
+
label: 'Gemini CLI',
|
|
62
|
+
find: () => walk(path.join(env.GEMINI_DIR || path.join(home, '.gemini'), 'tmp'), 3, (n, p) => /\.jsonl?$/.test(n) && /[\\/]chats[\\/]/.test(p)),
|
|
63
|
+
match: (f) => /[\\/]\.gemini[\\/]/.test(f),
|
|
64
|
+
parse: (f) => parseUniversal(f, { agent: 'Gemini CLI' }),
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
// Qwen Code ~/.qwen/projects/<project>/chats/*.jsonl
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
export const qwen = {
|
|
71
|
+
label: 'Qwen Code',
|
|
72
|
+
find: () => walk(path.join(env.QWEN_DATA_DIR || path.join(home, '.qwen'), 'projects'), 3, (n, p) => n.endsWith('.jsonl') && /[\\/]chats[\\/]/.test(p)),
|
|
73
|
+
match: (f) => /[\\/]\.qwen[\\/]/.test(f),
|
|
74
|
+
parse: (f) => parseUniversal(f, { agent: 'Qwen Code' }),
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// Amp ~/.local/share/amp/threads/**/*.json
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
export const amp = {
|
|
81
|
+
label: 'Amp',
|
|
82
|
+
find: () => walk(path.join(env.AMP_DATA_DIR || path.join(dataHome(), 'amp'), 'threads'), 3, (n) => n.endsWith('.json')),
|
|
83
|
+
match: (f) => /[\\/]amp[\\/]threads[\\/]/.test(f),
|
|
84
|
+
parse: (f) => parseUniversal(f, { agent: 'Amp' }),
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// GitHub Copilot CLI ~/.copilot/session-state/**/events.jsonl
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
export const copilot = {
|
|
91
|
+
label: 'Copilot CLI',
|
|
92
|
+
find: () => walk(path.join(env.COPILOT_HOME || path.join(home, '.copilot'), 'session-state'), 2, (n) => n.endsWith('.jsonl')),
|
|
93
|
+
match: (f) => /[\\/]\.copilot[\\/]/.test(f),
|
|
94
|
+
parse: (f) => {
|
|
95
|
+
const s = parseUniversal(f, { agent: 'Copilot CLI' });
|
|
96
|
+
try {
|
|
97
|
+
const ws = fs.readFileSync(path.join(path.dirname(f), 'workspace.yaml'), 'utf8');
|
|
98
|
+
const cwd = ws.match(/^cwd:\s*(.+)$/m);
|
|
99
|
+
if (cwd) s.cwd = cwd[1].trim().replace(/^["']|["']$/g, '');
|
|
100
|
+
} catch {
|
|
101
|
+
/* optional */
|
|
102
|
+
}
|
|
103
|
+
return s;
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// Cline / Roo Code / Kilo Code <globalStorage>/<extension>/tasks/<id>/api_conversation_history.json
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
function clineFamily(label, extIds, extraRoots = []) {
|
|
111
|
+
return {
|
|
112
|
+
label,
|
|
113
|
+
find: () => {
|
|
114
|
+
const roots = [...globalStorageRoots().flatMap((g) => extIds.map((id) => path.join(g, id, 'tasks'))), ...extraRoots];
|
|
115
|
+
return roots.flatMap((r) => walk(r, 1, (n) => n === 'api_conversation_history.json'));
|
|
116
|
+
},
|
|
117
|
+
match: (f) => extIds.some((id) => f.includes(id)) || extraRoots.some((r) => f.startsWith(r)),
|
|
118
|
+
parse: (f) => parseClineTask(f, label),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export const cline = clineFamily('Cline', ['saoudrizwan.claude-dev'], [path.join(home, '.cline', 'data', 'tasks')]);
|
|
123
|
+
export const roo = clineFamily('Roo Code', ['rooveterinaryinc.roo-cline']);
|
|
124
|
+
export const kilo = clineFamily('Kilo Code', ['kilocode.kilo-code']);
|
|
125
|
+
|
|
126
|
+
export function parseClineTask(file, agent = 'Cline') {
|
|
127
|
+
const dir = path.dirname(file);
|
|
128
|
+
const api = readJson(path.join(dir, 'api_conversation_history.json')) || [];
|
|
129
|
+
const ui = readJson(path.join(dir, 'ui_messages.json')) || [];
|
|
130
|
+
const s = buildSession(extractMessages(api), { agent, id: path.basename(dir), file });
|
|
131
|
+
|
|
132
|
+
// ui_messages.json carries the real timestamps and per-request usage.
|
|
133
|
+
const times = ui.map((m) => toMs(m.ts)).filter(Number.isFinite);
|
|
134
|
+
if (times.length && s.events.length) {
|
|
135
|
+
const start = Math.min(...times);
|
|
136
|
+
const end = Math.max(...times);
|
|
137
|
+
const step = s.events.length > 1 ? (end - start) / (s.events.length - 1) : 0;
|
|
138
|
+
s.events.forEach((e, i) => {
|
|
139
|
+
e.t = start + i * step;
|
|
140
|
+
if (e.endT) delete e.endT;
|
|
141
|
+
});
|
|
142
|
+
s.timesSynthetic = false;
|
|
143
|
+
}
|
|
144
|
+
let cost = 0;
|
|
145
|
+
for (const m of ui) {
|
|
146
|
+
if (m.say !== 'api_req_started' || typeof m.text !== 'string') continue;
|
|
147
|
+
try {
|
|
148
|
+
const r = JSON.parse(m.text);
|
|
149
|
+
addUsage(s, null, { input: r.tokensIn, output: r.tokensOut, cacheRead: r.cacheReads, cacheWrite: r.cacheWrites });
|
|
150
|
+
if (typeof r.cost === 'number') cost += r.cost;
|
|
151
|
+
} catch {
|
|
152
|
+
/* not JSON */
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (cost > 0) s.reportedCost = cost;
|
|
156
|
+
const firstTask = ui.find((m) => m.say === 'task' || m.type === 'say');
|
|
157
|
+
if (firstTask?.text && !s.title) s.title = firstTask.text.split('\n')[0].slice(0, 80);
|
|
158
|
+
const meta = readJson(path.join(dir, 'task_metadata.json'));
|
|
159
|
+
const model = meta?.model_usage?.at?.(-1)?.model_id || meta?.model_usage?.at?.(-1)?.model;
|
|
160
|
+
if (model && !s.models.includes(model)) s.models.push(model);
|
|
161
|
+
return s;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ---------------------------------------------------------------------------
|
|
165
|
+
// OpenCode storage/{session,message,part} JSON, opencode.db (SQLite), or `opencode export`
|
|
166
|
+
// ---------------------------------------------------------------------------
|
|
167
|
+
const opencodeRoots = () =>
|
|
168
|
+
[env.XDG_DATA_HOME && path.join(env.XDG_DATA_HOME, 'opencode'), path.join(home, '.local', 'share', 'opencode'), env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, 'opencode'), env.APPDATA && path.join(env.APPDATA, 'opencode')].filter(Boolean);
|
|
169
|
+
|
|
170
|
+
export const opencode = {
|
|
171
|
+
label: 'OpenCode',
|
|
172
|
+
find: () => {
|
|
173
|
+
const out = [];
|
|
174
|
+
for (const r of opencodeRoots()) {
|
|
175
|
+
out.push(...walk(path.join(r, 'storage', 'session'), 2, (n) => n.endsWith('.json')));
|
|
176
|
+
const db = path.join(r, 'opencode.db');
|
|
177
|
+
if (fs.existsSync(db)) out.push(...listOpencodeDb(db));
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
},
|
|
181
|
+
match: (f) => /[\\/]opencode[\\/]/.test(f) || f.includes('opencode.db#'),
|
|
182
|
+
parse: (f) => (f.includes('.db#') ? parseOpencodeDb(f) : parseOpencodeFile(f)),
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
function parseOpencodeFile(file) {
|
|
186
|
+
const doc = readJson(file);
|
|
187
|
+
// `opencode export <id>` → { info, messages: [{ info, parts }] }
|
|
188
|
+
if (doc?.info && Array.isArray(doc.messages)) {
|
|
189
|
+
const msgs = doc.messages.map((m) => ({ ...(m.info || {}), parts: m.parts || [] }));
|
|
190
|
+
return buildSession(msgs, { agent: 'OpenCode', id: doc.info.id, title: doc.info.title, cwd: doc.info.directory, file });
|
|
191
|
+
}
|
|
192
|
+
// storage/session/<project>/<session>.json
|
|
193
|
+
const storage = path.resolve(path.dirname(file), '..', '..');
|
|
194
|
+
const id = doc?.id || path.basename(file, '.json');
|
|
195
|
+
const msgDir = path.join(storage, 'message', id);
|
|
196
|
+
const msgs = walk(msgDir, 0, (n) => n.endsWith('.json'))
|
|
197
|
+
.map(readJson)
|
|
198
|
+
.filter(Boolean)
|
|
199
|
+
.sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0) || String(a.id).localeCompare(String(b.id)));
|
|
200
|
+
for (const m of msgs) {
|
|
201
|
+
m.parts = walk(path.join(storage, 'part', m.id), 0, (n) => n.endsWith('.json'))
|
|
202
|
+
.map(readJson)
|
|
203
|
+
.filter(Boolean)
|
|
204
|
+
.sort((a, b) => String(a.id).localeCompare(String(b.id)));
|
|
205
|
+
}
|
|
206
|
+
return buildSession(msgs, { agent: 'OpenCode', id, title: doc?.title, cwd: doc?.directory, file });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function openSqlite(file) {
|
|
210
|
+
try {
|
|
211
|
+
const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite');
|
|
212
|
+
return new DatabaseSync(file, { readOnly: true });
|
|
213
|
+
} catch {
|
|
214
|
+
return null; // Node < 22.5 has no built-in SQLite
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Row → object, merging any JSON-text column (opencode keeps message bodies in a `data` column). */
|
|
219
|
+
function rowObject(row) {
|
|
220
|
+
const out = { ...row };
|
|
221
|
+
for (const [k, v] of Object.entries(row)) {
|
|
222
|
+
if (typeof v === 'string' && v.startsWith('{')) {
|
|
223
|
+
try {
|
|
224
|
+
Object.assign(out, JSON.parse(v));
|
|
225
|
+
} catch {
|
|
226
|
+
/* plain text */
|
|
227
|
+
}
|
|
228
|
+
} else if (/^time_/.test(k) && typeof v === 'number') {
|
|
229
|
+
out.time ||= {};
|
|
230
|
+
out.time[k.slice(5)] = v;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function listOpencodeDb(db) {
|
|
237
|
+
const d = openSqlite(db);
|
|
238
|
+
if (!d) return [];
|
|
239
|
+
try {
|
|
240
|
+
const rows = d.prepare('SELECT * FROM session').all();
|
|
241
|
+
return rows.filter((r) => !r.parent_id).map((r) => `${db}#${r.id}`);
|
|
242
|
+
} catch {
|
|
243
|
+
return [];
|
|
244
|
+
} finally {
|
|
245
|
+
d.close();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function parseOpencodeDb(ref) {
|
|
250
|
+
const [db, id] = ref.split('#');
|
|
251
|
+
const d = openSqlite(db);
|
|
252
|
+
if (!d) throw new Error('reading opencode.db needs Node 22.5+ (built-in SQLite)');
|
|
253
|
+
try {
|
|
254
|
+
const cols = (t) => d.prepare(`PRAGMA table_info(${t})`).all().map((c) => c.name);
|
|
255
|
+
const sidCol = cols('message').find((c) => /^session_?id$/i.test(c));
|
|
256
|
+
const midCol = cols('part').find((c) => /^message_?id$/i.test(c));
|
|
257
|
+
const sess = rowObject(d.prepare('SELECT * FROM session WHERE id = ?').get(id) || {});
|
|
258
|
+
const msgs = d.prepare(`SELECT * FROM message WHERE ${sidCol} = ? ORDER BY rowid`).all(id).map(rowObject);
|
|
259
|
+
const partStmt = d.prepare(`SELECT * FROM part WHERE ${midCol} = ? ORDER BY rowid`);
|
|
260
|
+
for (const m of msgs) m.parts = partStmt.all(m.id).map(rowObject);
|
|
261
|
+
return buildSession(msgs, { agent: 'OpenCode', id, title: sess.title, cwd: sess.directory, file: db });
|
|
262
|
+
} finally {
|
|
263
|
+
d.close();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
// Aider .aider.chat.history.md (markdown transcript in each project)
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
export const aider = {
|
|
271
|
+
label: 'Aider',
|
|
272
|
+
find: () => [path.join(process.cwd(), '.aider.chat.history.md'), path.join(home, '.aider.chat.history.md')].filter((f) => fs.existsSync(f)),
|
|
273
|
+
match: (f) => f.endsWith('.md'),
|
|
274
|
+
parse: parseAider,
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
export function parseAider(file) {
|
|
278
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
279
|
+
// Use only the most recent chat in the file
|
|
280
|
+
const chats = text.split(/^# aider chat started at /m);
|
|
281
|
+
const last = chats.at(-1);
|
|
282
|
+
const started = toMs(last.split('\n')[0].trim().replace(' ', 'T')) ?? fs.statSync(file).mtimeMs;
|
|
283
|
+
const body = last.split('\n').slice(1).join('\n');
|
|
284
|
+
|
|
285
|
+
const msgs = [];
|
|
286
|
+
let cur = null;
|
|
287
|
+
const flush = () => {
|
|
288
|
+
if (cur && cur.text.trim()) msgs.push(cur);
|
|
289
|
+
cur = null;
|
|
290
|
+
};
|
|
291
|
+
for (const line of body.split('\n')) {
|
|
292
|
+
if (line.startsWith('#### ')) {
|
|
293
|
+
if (cur?.role !== 'user') flush();
|
|
294
|
+
cur ||= { role: 'user', text: '' };
|
|
295
|
+
cur.text += line.slice(5) + '\n';
|
|
296
|
+
} else if (line.startsWith('> ')) {
|
|
297
|
+
if (cur?.role !== 'info') flush();
|
|
298
|
+
cur ||= { role: 'info', text: '' };
|
|
299
|
+
cur.text += line.slice(2) + '\n';
|
|
300
|
+
} else {
|
|
301
|
+
if (cur && cur.role !== 'assistant') {
|
|
302
|
+
if (!line.trim()) continue;
|
|
303
|
+
flush();
|
|
304
|
+
}
|
|
305
|
+
cur ||= { role: 'assistant', text: '' };
|
|
306
|
+
cur.text += line + '\n';
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
flush();
|
|
310
|
+
|
|
311
|
+
const events = [];
|
|
312
|
+
let t = started;
|
|
313
|
+
for (const m of msgs) {
|
|
314
|
+
t += 2500;
|
|
315
|
+
const tx = m.text.trim();
|
|
316
|
+
if (m.role === 'user') events.push({ kind: 'user', t, text: tx });
|
|
317
|
+
else if (m.role === 'info') {
|
|
318
|
+
// aider's own console output ("Applied edit to x.py", test runs …) — attach to the last edit or show as a tool
|
|
319
|
+
const last = [...events].reverse().find((e) => e.kind === 'tool' && !e.output);
|
|
320
|
+
if (last) last.output = truncate(tx, 4000);
|
|
321
|
+
else events.push({ kind: 'tool', t, name: 'aider', summary: tx.split('\n')[0], input: null, output: truncate(tx, 4000), isError: /error|failed/i.test(tx) });
|
|
322
|
+
} else {
|
|
323
|
+
// Pull SEARCH/REPLACE edit blocks out into diff events
|
|
324
|
+
const edits = [];
|
|
325
|
+
const rest = tx.replace(/(^|\n)([^\n`]+)\n```[^\n]*\n([\s\S]*?)```/g, (all, pre, fname, block) => {
|
|
326
|
+
const hunks = parseSearchReplace(block);
|
|
327
|
+
if (!hunks.length) return all;
|
|
328
|
+
edits.push({ file: fname.trim(), hunks });
|
|
329
|
+
return pre;
|
|
330
|
+
}).trim();
|
|
331
|
+
if (rest) events.push({ kind: 'assistant', t, text: rest });
|
|
332
|
+
for (const e of edits) {
|
|
333
|
+
const lines = e.hunks.reduce((a, h) => {
|
|
334
|
+
const x = lineDelta(h.old, h.new);
|
|
335
|
+
return { added: a.added + x.added, removed: a.removed + x.removed };
|
|
336
|
+
}, { added: 0, removed: 0 });
|
|
337
|
+
events.push({ kind: 'tool', t, name: 'edit', file: e.file, summary: e.file, diff: e.hunks, lines, created: e.hunks.every((h) => !h.old), input: null, output: '', isError: false });
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return {
|
|
342
|
+
agent: 'Aider',
|
|
343
|
+
id: path.basename(path.dirname(file)) + '-' + Math.round(started / 1000),
|
|
344
|
+
title: events.find((e) => e.kind === 'user')?.text.split('\n')[0].slice(0, 80) || 'Aider chat',
|
|
345
|
+
cwd: path.dirname(file),
|
|
346
|
+
branch: null,
|
|
347
|
+
models: [],
|
|
348
|
+
events,
|
|
349
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 },
|
|
350
|
+
usageByModel: {},
|
|
351
|
+
reportedCost: null,
|
|
352
|
+
timesSynthetic: true,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ---------------------------------------------------------------------------
|
|
357
|
+
// Anything else: the universal parser on whatever JSON/JSONL file you pass
|
|
358
|
+
// ---------------------------------------------------------------------------
|
|
359
|
+
export const generic = {
|
|
360
|
+
label: 'Chat log',
|
|
361
|
+
find: () => [],
|
|
362
|
+
match: () => true,
|
|
363
|
+
parse: (f) => parseUniversal(f, { agent: guessAgentName(f) }),
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
function guessAgentName(f) {
|
|
367
|
+
try {
|
|
368
|
+
const { doc, lines } = readJsonAny(f);
|
|
369
|
+
const sample = JSON.stringify(doc ?? (lines || []).slice(0, 30)).slice(0, 20000).toLowerCase();
|
|
370
|
+
for (const [needle, name] of [['cursor', 'Cursor'], ['windsurf', 'Windsurf'], ['copilot', 'Copilot'], ['gemini', 'Gemini'], ['claude', 'Claude'], ['gpt-', 'ChatGPT / OpenAI'], ['deepseek', 'DeepSeek'], ['grok', 'Grok'], ['mistral', 'Mistral'], ['llama', 'Llama']]) {
|
|
371
|
+
if (sample.includes(needle)) return name;
|
|
372
|
+
}
|
|
373
|
+
} catch {
|
|
374
|
+
/* unreadable */
|
|
375
|
+
}
|
|
376
|
+
return 'AI agent';
|
|
377
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readJsonl, toText, stripHarnessTags, truncate, lineDelta } from '../util.js';
|
|
3
|
+
|
|
4
|
+
const MAX_OUTPUT = 4000;
|
|
5
|
+
const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
|
|
6
|
+
|
|
7
|
+
/** Does this file look like a Claude Code session log? */
|
|
8
|
+
export function detect(records) {
|
|
9
|
+
return records.some((r) => (r.type === 'assistant' || r.type === 'user') && r.message && !r.message.parts && r.sessionId && ('parentUuid' in r || 'uuid' in r));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Parse a Claude Code session (~/.claude/projects/<project>/<session>.jsonl)
|
|
14
|
+
* into the normalized replay shape shared by every parser.
|
|
15
|
+
*/
|
|
16
|
+
export function parse(file, { includeSidechains = false } = {}) {
|
|
17
|
+
const records = readJsonl(file);
|
|
18
|
+
const session = {
|
|
19
|
+
agent: 'Claude Code',
|
|
20
|
+
id: path.basename(file, '.jsonl'),
|
|
21
|
+
title: null,
|
|
22
|
+
cwd: null,
|
|
23
|
+
branch: null,
|
|
24
|
+
models: new Set(),
|
|
25
|
+
events: [],
|
|
26
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 },
|
|
27
|
+
usageByModel: {},
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const toolById = new Map();
|
|
31
|
+
const seenMessageIds = new Set();
|
|
32
|
+
|
|
33
|
+
for (const r of records) {
|
|
34
|
+
if (r.type === 'ai-title' && r.aiTitle) session.title = r.aiTitle;
|
|
35
|
+
if (r.type === 'summary' && r.summary && !session.title) session.title = r.summary;
|
|
36
|
+
if (r.type !== 'user' && r.type !== 'assistant') continue;
|
|
37
|
+
if (r.isSidechain && !includeSidechains) continue;
|
|
38
|
+
if (!session.cwd && r.cwd) session.cwd = r.cwd;
|
|
39
|
+
if (!session.branch && r.gitBranch) session.branch = r.gitBranch;
|
|
40
|
+
|
|
41
|
+
const ts = Date.parse(r.timestamp);
|
|
42
|
+
const msg = r.message || {};
|
|
43
|
+
const blocks = typeof msg.content === 'string' ? [{ type: 'text', text: msg.content }] : msg.content || [];
|
|
44
|
+
|
|
45
|
+
if (r.type === 'assistant') {
|
|
46
|
+
const model = msg.model && msg.model !== '<synthetic>' ? msg.model : null;
|
|
47
|
+
if (model) session.models.add(model);
|
|
48
|
+
// Claude Code writes one line per content block but repeats the usage of the
|
|
49
|
+
// whole API message on each — count it once per message id.
|
|
50
|
+
if (msg.usage && msg.id && !seenMessageIds.has(msg.id)) {
|
|
51
|
+
seenMessageIds.add(msg.id);
|
|
52
|
+
addUsage(session, model, msg.usage);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
for (const b of blocks) {
|
|
57
|
+
if (r.type === 'user' && b.type === 'tool_result') {
|
|
58
|
+
const ev = toolById.get(b.tool_use_id);
|
|
59
|
+
if (!ev) continue;
|
|
60
|
+
ev.output = truncate(stripHarnessTags(toText(b.content)), MAX_OUTPUT);
|
|
61
|
+
ev.isError = !!b.is_error;
|
|
62
|
+
ev.endT = ts;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (r.type === 'user' && b.type === 'text') {
|
|
66
|
+
if (r.isMeta) continue;
|
|
67
|
+
const text = stripHarnessTags(b.text || '');
|
|
68
|
+
if (!text || /^<(command-|local-command|bash-|user-prompt-submit-hook)/.test(text)) continue;
|
|
69
|
+
if (text.startsWith('Caveat: The messages below')) continue;
|
|
70
|
+
session.events.push({ kind: 'user', t: ts, text });
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (r.type !== 'assistant') continue;
|
|
74
|
+
if (b.type === 'text' && b.text?.trim()) {
|
|
75
|
+
session.events.push({ kind: 'assistant', t: ts, text: b.text.trim() });
|
|
76
|
+
} else if (b.type === 'thinking' && b.thinking?.trim()) {
|
|
77
|
+
session.events.push({ kind: 'thinking', t: ts, text: b.thinking.trim() });
|
|
78
|
+
} else if (b.type === 'tool_use') {
|
|
79
|
+
const ev = toolEvent(b, ts);
|
|
80
|
+
toolById.set(b.id, ev);
|
|
81
|
+
session.events.push(ev);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
session.models = [...session.models];
|
|
87
|
+
return session;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function addUsage(session, model, u) {
|
|
91
|
+
const write1h = u.cache_creation?.ephemeral_1h_input_tokens || 0;
|
|
92
|
+
const add = {
|
|
93
|
+
input: u.input_tokens || 0,
|
|
94
|
+
output: u.output_tokens || 0,
|
|
95
|
+
cacheRead: u.cache_read_input_tokens || 0,
|
|
96
|
+
cacheWrite: (u.cache_creation_input_tokens || 0) - write1h,
|
|
97
|
+
cacheWrite1h: write1h,
|
|
98
|
+
};
|
|
99
|
+
const key = model || 'unknown';
|
|
100
|
+
const per = (session.usageByModel[key] ||= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 });
|
|
101
|
+
for (const k of Object.keys(add)) {
|
|
102
|
+
session.usage[k] += add[k];
|
|
103
|
+
per[k] += add[k];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function toolEvent(b, ts) {
|
|
108
|
+
const input = b.input || {};
|
|
109
|
+
// mcp__Roblox_Studio__execute_luau → "Roblox Studio · execute_luau"
|
|
110
|
+
const name = b.name.replace(/^mcp__(.+?)__(.+)$/, (_, server, tool) => `${server.replace(/_/g, ' ')} · ${tool}`);
|
|
111
|
+
const ev = { kind: 'tool', t: ts, name, summary: summarize(b.name, input), input: null, output: '', isError: false };
|
|
112
|
+
|
|
113
|
+
if (EDIT_TOOLS.has(b.name)) {
|
|
114
|
+
const file = input.file_path || input.notebook_path;
|
|
115
|
+
ev.file = file;
|
|
116
|
+
if (b.name === 'Edit') {
|
|
117
|
+
ev.diff = [{ old: input.old_string || '', new: input.new_string || '' }];
|
|
118
|
+
} else if (b.name === 'MultiEdit') {
|
|
119
|
+
ev.diff = (input.edits || []).map((e) => ({ old: e.old_string || '', new: e.new_string || '' }));
|
|
120
|
+
} else if (b.name === 'Write') {
|
|
121
|
+
ev.diff = [{ old: '', new: input.content || '' }];
|
|
122
|
+
ev.created = true;
|
|
123
|
+
} else {
|
|
124
|
+
ev.diff = [{ old: '', new: input.new_source || '' }];
|
|
125
|
+
}
|
|
126
|
+
ev.lines = ev.diff.reduce(
|
|
127
|
+
(acc, d) => {
|
|
128
|
+
const x = lineDelta(d.old, d.new);
|
|
129
|
+
return { added: acc.added + x.added, removed: acc.removed + x.removed };
|
|
130
|
+
},
|
|
131
|
+
{ added: 0, removed: 0 },
|
|
132
|
+
);
|
|
133
|
+
ev.diff = ev.diff.map((d) => ({ old: truncate(d.old, MAX_OUTPUT), new: truncate(d.new, MAX_OUTPUT) }));
|
|
134
|
+
} else {
|
|
135
|
+
ev.input = truncate(JSON.stringify(input, null, 2), MAX_OUTPUT);
|
|
136
|
+
}
|
|
137
|
+
return ev;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const PREFERRED_KEYS = ['description', 'command', 'query', 'file_path', 'path', 'url', 'name', 'title', 'prompt', 'code', 'text'];
|
|
141
|
+
const ID_LIKE = /^[0-9a-f]{8}-[0-9a-f]{4}-|^[0-9a-f]{16,}$|^[A-Za-z0-9_-]{20,}$/i;
|
|
142
|
+
|
|
143
|
+
/** Best human-readable string from an unknown tool's input (MCP tools etc.). */
|
|
144
|
+
function genericSummary(i) {
|
|
145
|
+
for (const k of PREFERRED_KEYS) {
|
|
146
|
+
if (typeof i[k] === 'string' && i[k].trim()) return i[k].trim().split('\n')[0];
|
|
147
|
+
}
|
|
148
|
+
const strings = Object.values(i).filter((v) => typeof v === 'string' && v.trim() && !ID_LIKE.test(v.trim()));
|
|
149
|
+
return strings.length ? strings[0].trim().split('\n')[0] : '';
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function summarize(name, i) {
|
|
153
|
+
switch (name) {
|
|
154
|
+
case 'Bash':
|
|
155
|
+
case 'PowerShell':
|
|
156
|
+
return i.description || i.command;
|
|
157
|
+
case 'Read':
|
|
158
|
+
case 'Edit':
|
|
159
|
+
case 'Write':
|
|
160
|
+
case 'MultiEdit':
|
|
161
|
+
return i.file_path;
|
|
162
|
+
case 'NotebookEdit':
|
|
163
|
+
return i.notebook_path;
|
|
164
|
+
case 'Glob':
|
|
165
|
+
return i.pattern;
|
|
166
|
+
case 'Grep':
|
|
167
|
+
return `${i.pattern}${i.path ? ' in ' + i.path : ''}`;
|
|
168
|
+
case 'WebSearch':
|
|
169
|
+
return i.query;
|
|
170
|
+
case 'WebFetch':
|
|
171
|
+
return i.url;
|
|
172
|
+
case 'Task':
|
|
173
|
+
case 'Agent':
|
|
174
|
+
return i.description || i.prompt;
|
|
175
|
+
case 'Skill':
|
|
176
|
+
return i.skill;
|
|
177
|
+
default:
|
|
178
|
+
return genericSummary(i);
|
|
179
|
+
}
|
|
180
|
+
}
|