@dorywoof/agentreplay 0.0.0-stage → 0.1.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 +116 -2
- package/bin/agentreplay.js +148 -0
- package/package.json +39 -4
- package/src/discover.js +74 -0
- package/src/parsers/claude.js +180 -0
- package/src/parsers/codex.js +195 -0
- package/src/pricing.js +63 -0
- package/src/redact.js +96 -0
- package/src/render.js +33 -0
- package/src/stats.js +62 -0
- package/src/template.html +356 -0
- package/src/util.js +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 agentreplay contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,117 @@
|
|
|
1
|
-
|
|
1
|
+
<h1 align="center">agentreplay</h1>
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center">
|
|
4
|
+
<b>Turn any Claude Code or Codex session into a shareable, video-like replay.</b><br>
|
|
5
|
+
One command. One self-contained HTML file. Secrets stripped before you share.
|
|
6
|
+
</p>
|
|
7
|
+
|
|
8
|
+
<p align="center">
|
|
9
|
+
<code>npx @dorywoof/agentreplay</code>
|
|
10
|
+
</p>
|
|
11
|
+
|
|
12
|
+
<p align="center">
|
|
13
|
+
<a href="https://dorywoof.github.io/agentreplay/"><b>▶ Try the live demo</b></a>
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
<p align="center">
|
|
17
|
+
<a href="https://dorywoof.github.io/agentreplay/"><img src="docs/demo.gif" alt="agentreplay playing back a Claude Code session: prompts, tool calls, diffs, a failing test and the fix" width="800"></a>
|
|
18
|
+
</p>
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
You just watched an AI agent build a feature in 6 minutes. Now you want to show someone — but all you have is a 4 MB JSONL file nobody can read.
|
|
23
|
+
|
|
24
|
+
**agentreplay** turns that log into a page that *plays back* the session: prompts, reasoning, every tool call, every diff, with a scrubbable timeline and a summary card that says what it did, how long it took and what it cost.
|
|
25
|
+
|
|
26
|
+
## Features
|
|
27
|
+
|
|
28
|
+
- ▶️ **Plays like a video.** Events appear in order with condensed timing; scrub, skip, pause, or change speed. Edits, errors and prompts are marked on the timeline.
|
|
29
|
+
- 🤝 **Claude Code *and* Codex.** Auto-detects the format. More agents are on the roadmap.
|
|
30
|
+
- 💸 **Cost and token panel.** Input, output and cache tokens, plus an estimated API cost at list prices.
|
|
31
|
+
- 🔒 **Safe to share by default.** API keys, tokens, JWTs, private keys, passwords in env assignments, e-mail addresses and your home directory are redacted *before* the HTML is written. The footer says what was removed.
|
|
32
|
+
- 📝 **Real diffs.** `Edit`, `Write`, `MultiEdit` and Codex `apply_patch` are shown as red and green diffs, with a per-file `+/-` summary.
|
|
33
|
+
- 📦 **One file, zero dependencies.** The output is one HTML file that works offline. Host it anywhere: GitHub Pages, a gist, Slack, e-mail.
|
|
34
|
+
- 🌗 Light and dark themes, works on phones, and keyboard shortcuts (`space`, `←` `→`, `Home`, `End`).
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npx @dorywoof/agentreplay # replays your most recent session and opens it
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npx @dorywoof/agentreplay --list # pick from recent Claude Code / Codex sessions
|
|
44
|
+
npx @dorywoof/agentreplay --pick 3
|
|
45
|
+
npx @dorywoof/agentreplay path/to/session.jsonl -o my-replay.html
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Requires Node 18+. Nothing is uploaded anywhere: everything happens on your machine.
|
|
49
|
+
|
|
50
|
+
### Where sessions live
|
|
51
|
+
|
|
52
|
+
| Agent | Location |
|
|
53
|
+
|---|---|
|
|
54
|
+
| Claude Code | `~/.claude/projects/<project>/<session>.jsonl` |
|
|
55
|
+
| Codex | `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` |
|
|
56
|
+
|
|
57
|
+
`CLAUDE_CONFIG_DIR` and `CODEX_HOME` are respected.
|
|
58
|
+
|
|
59
|
+
## Options
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
-o, --out <file> output HTML path (default: ./replay-<id>.html)
|
|
63
|
+
-a, --agent <name> only look at "claude" or "codex" sessions
|
|
64
|
+
-t, --title <text> override the replay title
|
|
65
|
+
--no-thinking hide thinking / reasoning blocks
|
|
66
|
+
--no-redact keep secrets, e-mails and home paths (not for sharing!)
|
|
67
|
+
--keep-paths redact secrets but keep file paths as-is
|
|
68
|
+
--pricing <file> JSON with custom $/1M token prices per model
|
|
69
|
+
--json print the normalized session JSON instead of HTML
|
|
70
|
+
--no-open don't open the replay in a browser
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
**URL tricks:** add `#e42` to open a replay at event 42, or `?static` to show the whole session at once with no animation.
|
|
74
|
+
|
|
75
|
+
## Sharing a replay
|
|
76
|
+
|
|
77
|
+
The output is a static file, so any of these work:
|
|
78
|
+
|
|
79
|
+
- **GitHub Pages:** commit `replay.html` to a `gh-pages` branch.
|
|
80
|
+
- **Gist:** upload it, then open it through a gist-preview service.
|
|
81
|
+
- **Netlify / Vercel drop:** drag and drop the file.
|
|
82
|
+
|
|
83
|
+
> ⚠️ Redaction catches common secret formats, but it can't know everything that is private to you. Skim the replay before posting it publicly.
|
|
84
|
+
|
|
85
|
+
## About the cost estimate
|
|
86
|
+
|
|
87
|
+
Cost uses public per-token API list prices (including cache reads and writes) for the Claude models it knows about. If you're on a subscription plan, it shows what the session *would* cost on the API. For models it has no price for (for example Codex models), only token counts are shown. You can supply your own prices:
|
|
88
|
+
|
|
89
|
+
```json
|
|
90
|
+
{ "gpt-6.1": { "input": 1.25, "output": 10, "cacheRead": 0.125 } }
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npx @dorywoof/agentreplay --pricing prices.json
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Roadmap
|
|
98
|
+
|
|
99
|
+
- [ ] opencode, Gemini CLI and Cursor agent logs
|
|
100
|
+
- [ ] Export to GIF / MP4 for social posts
|
|
101
|
+
- [ ] Subagent (sidechain) lanes
|
|
102
|
+
- [ ] `agentreplay publish`: one-command upload to a gist
|
|
103
|
+
- [ ] Combine several sessions into one replay
|
|
104
|
+
|
|
105
|
+
Ideas and PRs are welcome. Adding a new agent means writing one parser in `src/parsers/` that returns the shared event shape.
|
|
106
|
+
|
|
107
|
+
## Development
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
npm test # node:test, no dependencies
|
|
111
|
+
node scripts/make-demo.js # regenerate examples/demo-session.jsonl
|
|
112
|
+
npm run demo # render examples/demo.html
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { listSessions, detectAgent, preview, PARSERS } from '../src/discover.js';
|
|
7
|
+
import { createRedactor } from '../src/redact.js';
|
|
8
|
+
import { computeStats } from '../src/stats.js';
|
|
9
|
+
import { loadPricing } from '../src/pricing.js';
|
|
10
|
+
import { renderHtml } from '../src/render.js';
|
|
11
|
+
|
|
12
|
+
const HELP = `
|
|
13
|
+
agentreplay — turn an AI coding session into a shareable replay
|
|
14
|
+
|
|
15
|
+
Usage
|
|
16
|
+
agentreplay replay your most recent session
|
|
17
|
+
agentreplay <session.jsonl> replay a specific log file
|
|
18
|
+
agentreplay --list list recent sessions
|
|
19
|
+
agentreplay --pick 3 replay #3 from --list
|
|
20
|
+
|
|
21
|
+
Options
|
|
22
|
+
-o, --out <file> output HTML path (default: ./replay-<id>.html)
|
|
23
|
+
-a, --agent <name> only look at "claude" or "codex" sessions
|
|
24
|
+
-t, --title <text> override the replay title
|
|
25
|
+
--no-thinking hide thinking / reasoning blocks
|
|
26
|
+
--no-redact keep secrets, e-mails and home paths (not for sharing!)
|
|
27
|
+
--keep-paths redact secrets but keep file paths as-is
|
|
28
|
+
--pricing <file> JSON with custom $/1M token prices per model
|
|
29
|
+
--json print the normalized session JSON instead of HTML
|
|
30
|
+
--no-open don't open the replay in a browser
|
|
31
|
+
-h, --help show this help
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
const { values: opts, positionals } = parseArgs({
|
|
35
|
+
allowPositionals: true,
|
|
36
|
+
options: {
|
|
37
|
+
out: { type: 'string', short: 'o' },
|
|
38
|
+
agent: { type: 'string', short: 'a' },
|
|
39
|
+
title: { type: 'string', short: 't' },
|
|
40
|
+
list: { type: 'boolean', short: 'l' },
|
|
41
|
+
pick: { type: 'string', short: 'p' },
|
|
42
|
+
'no-thinking': { type: 'boolean' },
|
|
43
|
+
'no-redact': { type: 'boolean' },
|
|
44
|
+
'keep-paths': { type: 'boolean' },
|
|
45
|
+
pricing: { type: 'string' },
|
|
46
|
+
json: { type: 'boolean' },
|
|
47
|
+
'no-open': { type: 'boolean' },
|
|
48
|
+
help: { type: 'boolean', short: 'h' },
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const dim = (s) => (process.stdout.isTTY ? `\x1b[2m${s}\x1b[0m` : s);
|
|
53
|
+
const bold = (s) => (process.stdout.isTTY ? `\x1b[1m${s}\x1b[0m` : s);
|
|
54
|
+
|
|
55
|
+
function fail(msg) {
|
|
56
|
+
console.error(`agentreplay: ${msg}`);
|
|
57
|
+
process.exit(1);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function ago(ms) {
|
|
61
|
+
const m = Math.round((Date.now() - ms) / 60000);
|
|
62
|
+
if (m < 60) return `${m}m ago`;
|
|
63
|
+
if (m < 60 * 24) return `${Math.round(m / 60)}h ago`;
|
|
64
|
+
return `${Math.round(m / 1440)}d ago`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function main() {
|
|
68
|
+
if (opts.help) return console.log(HELP);
|
|
69
|
+
if (opts.agent && !PARSERS[opts.agent]) fail(`unknown agent "${opts.agent}" (use claude or codex)`);
|
|
70
|
+
|
|
71
|
+
if (opts.list) {
|
|
72
|
+
const sessions = listSessions({ agent: opts.agent }).slice(0, 20);
|
|
73
|
+
if (!sessions.length) fail('no Claude Code or Codex sessions found on this machine');
|
|
74
|
+
sessions.forEach((s, i) => {
|
|
75
|
+
const tag = s.agent === 'claude' ? 'claude' : 'codex ';
|
|
76
|
+
console.log(`${bold(String(i + 1).padStart(2))} ${tag} ${dim(ago(s.mtime).padEnd(8))} ${preview(s.file)}`);
|
|
77
|
+
});
|
|
78
|
+
console.log(dim('\nReplay one with: agentreplay --pick <n>'));
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let file, agent;
|
|
83
|
+
if (positionals[0]) {
|
|
84
|
+
file = path.resolve(positionals[0]);
|
|
85
|
+
if (!fs.existsSync(file)) fail(`file not found: ${file}`);
|
|
86
|
+
agent = opts.agent || detectAgent(file);
|
|
87
|
+
if (!agent) fail('could not recognise this log format (supported: Claude Code, Codex)');
|
|
88
|
+
} else {
|
|
89
|
+
const sessions = listSessions({ agent: opts.agent });
|
|
90
|
+
if (!sessions.length) fail('no Claude Code or Codex sessions found. Pass a .jsonl file path instead.');
|
|
91
|
+
const idx = opts.pick ? Number(opts.pick) - 1 : 0;
|
|
92
|
+
if (!sessions[idx]) fail(`no session #${opts.pick} — run with --list to see what's available`);
|
|
93
|
+
({ file, agent } = sessions[idx]);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
let session = PARSERS[agent].parse(file);
|
|
97
|
+
if (opts.title) session.title = opts.title;
|
|
98
|
+
if (opts['no-thinking']) session.events = session.events.filter((e) => e.kind !== 'thinking');
|
|
99
|
+
if (!session.events.length) fail('this session has no messages to replay');
|
|
100
|
+
|
|
101
|
+
let redactions = null;
|
|
102
|
+
if (!opts['no-redact']) {
|
|
103
|
+
const r = createRedactor({ paths: !opts['keep-paths'] });
|
|
104
|
+
session = r.redact(session);
|
|
105
|
+
redactions = r.counts;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const stats = computeStats(session, loadPricing(opts.pricing));
|
|
109
|
+
|
|
110
|
+
if (opts.json) {
|
|
111
|
+
process.stdout.write(JSON.stringify({ ...session, stats }, null, 2) + '\n');
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const out = path.resolve(opts.out || `replay-${session.id.slice(0, 8)}.html`);
|
|
116
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
117
|
+
fs.writeFileSync(out, renderHtml(session, stats, { redactions }));
|
|
118
|
+
|
|
119
|
+
const mins = Math.max(1, Math.round(stats.activeMs / 60000));
|
|
120
|
+
const cost = stats.cost != null ? ` · ~$${stats.cost.toFixed(2)}` : '';
|
|
121
|
+
console.log(`${bold('✓')} ${session.agent} · ${session.title || 'Untitled'}`);
|
|
122
|
+
console.log(dim(` ${session.events.length} events · ${stats.toolCalls} tool calls · ${stats.files.length} files · ${mins} min${cost}`));
|
|
123
|
+
if (redactions) {
|
|
124
|
+
const total = Object.values(redactions).reduce((a, b) => a + b, 0);
|
|
125
|
+
if (total) console.log(dim(` redacted: ${Object.entries(redactions).map(([k, v]) => `${v} ${k}`).join(', ')}`));
|
|
126
|
+
} else {
|
|
127
|
+
console.log(' ⚠ redaction is OFF — check the file before sharing it');
|
|
128
|
+
}
|
|
129
|
+
console.log(` → ${out}`);
|
|
130
|
+
|
|
131
|
+
if (!opts['no-open'] && !process.env.CI) openFile(out);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function openFile(file) {
|
|
135
|
+
const [cmd, args] =
|
|
136
|
+
process.platform === 'win32'
|
|
137
|
+
? ['cmd', ['/c', 'start', '""', file]]
|
|
138
|
+
: process.platform === 'darwin'
|
|
139
|
+
? ['open', [file]]
|
|
140
|
+
: ['xdg-open', [file]];
|
|
141
|
+
try {
|
|
142
|
+
spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: process.platform === 'win32' }).unref();
|
|
143
|
+
} catch {
|
|
144
|
+
/* no browser available — the path is already printed */
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dorywoof/agentreplay",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Turn Claude Code and Codex sessions into a shareable, video-like HTML replay — with cost stats and automatic secret redaction.",
|
|
5
|
+
"homepage": "https://github.com/dorywoof/agentreplay#readme",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/dorywoof/agentreplay.git"
|
|
9
|
+
},
|
|
10
|
+
"bugs": {
|
|
11
|
+
"url": "https://github.com/dorywoof/agentreplay/issues"
|
|
12
|
+
},
|
|
13
|
+
"type": "module",
|
|
14
|
+
"bin": {
|
|
15
|
+
"agentreplay": "bin/agentreplay.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"bin",
|
|
19
|
+
"src",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"test": "node --test test/",
|
|
25
|
+
"demo": "node bin/agentreplay.js examples/demo-session.jsonl -o examples/demo.html --no-open"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"claude-code",
|
|
32
|
+
"codex",
|
|
33
|
+
"ai-agent",
|
|
34
|
+
"replay",
|
|
35
|
+
"session",
|
|
36
|
+
"transcript",
|
|
37
|
+
"llm",
|
|
38
|
+
"cli"
|
|
39
|
+
],
|
|
40
|
+
"license": "MIT"
|
|
41
|
+
}
|
package/src/discover.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { readJsonl, stripHarnessTags } from './util.js';
|
|
5
|
+
import * as claude from './parsers/claude.js';
|
|
6
|
+
import * as codex from './parsers/codex.js';
|
|
7
|
+
|
|
8
|
+
export const PARSERS = { claude, codex };
|
|
9
|
+
|
|
10
|
+
function claudeRoot() {
|
|
11
|
+
return path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'projects');
|
|
12
|
+
}
|
|
13
|
+
function codexRoot() {
|
|
14
|
+
return path.join(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), 'sessions');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function walk(dir, depth, out) {
|
|
18
|
+
let entries;
|
|
19
|
+
try {
|
|
20
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
21
|
+
} catch {
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
for (const e of entries) {
|
|
25
|
+
const p = path.join(dir, e.name);
|
|
26
|
+
if (e.isDirectory() && depth > 0) walk(p, depth - 1, out);
|
|
27
|
+
else if (e.isFile() && e.name.endsWith('.jsonl')) out.push(p);
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** All known session files on this machine, newest first. */
|
|
33
|
+
export function listSessions({ agent } = {}) {
|
|
34
|
+
const found = [];
|
|
35
|
+
if (!agent || agent === 'claude') {
|
|
36
|
+
// projects/<project>/<session>.jsonl — skip subagent logs nested deeper
|
|
37
|
+
for (const f of walk(claudeRoot(), 1, [])) found.push({ agent: 'claude', file: f });
|
|
38
|
+
}
|
|
39
|
+
if (!agent || agent === 'codex') {
|
|
40
|
+
for (const f of walk(codexRoot(), 4, [])) found.push({ agent: 'codex', file: f });
|
|
41
|
+
}
|
|
42
|
+
for (const s of found) s.mtime = fs.statSync(s.file).mtimeMs;
|
|
43
|
+
return found.sort((a, b) => b.mtime - a.mtime);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Pick the parser for an arbitrary file by sniffing its first records. */
|
|
47
|
+
export function detectAgent(file) {
|
|
48
|
+
const records = readJsonl(file).slice(0, 50);
|
|
49
|
+
if (codex.detect(records)) return 'codex';
|
|
50
|
+
if (claude.detect(records)) return 'claude';
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Cheap one-line preview for --list without fully parsing. */
|
|
55
|
+
export function preview(file) {
|
|
56
|
+
try {
|
|
57
|
+
const records = readJsonl(file);
|
|
58
|
+
for (const r of records) if (r.type === 'ai-title' && r.aiTitle) return r.aiTitle;
|
|
59
|
+
for (const r of records) {
|
|
60
|
+
if (r.isMeta || r.isSidechain) continue;
|
|
61
|
+
const isUser = r.type === 'user' || (r.payload?.type === 'message' && r.payload.role === 'user');
|
|
62
|
+
if (!isUser) continue;
|
|
63
|
+
const c = r.message?.content ?? r.payload.content;
|
|
64
|
+
const blocks = typeof c === 'string' ? [c] : Array.isArray(c) ? c.map((b) => (b.type === 'tool_result' ? '' : b.text || '')) : [];
|
|
65
|
+
for (const b of blocks) {
|
|
66
|
+
const clean = stripHarnessTags(b);
|
|
67
|
+
if (clean && !clean.startsWith('<')) return clean.split('\n')[0].slice(0, 70);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
} catch {
|
|
71
|
+
/* unreadable */
|
|
72
|
+
}
|
|
73
|
+
return '(no prompt)';
|
|
74
|
+
}
|
|
@@ -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.sessionId);
|
|
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
|
+
}
|