@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.
@@ -0,0 +1,195 @@
1
+ import path from 'node:path';
2
+ import { readJsonl, toText, truncate } 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
+ /** Turn an apply_patch envelope into the same diff shape the Claude parser uses. */
172
+ function fromPatch(patch) {
173
+ const files = [];
174
+ let cur = null;
175
+ for (const line of patch.split('\n')) {
176
+ const m = line.match(/^\*\*\* (Add|Update|Delete) File: (.+)$/);
177
+ if (m) {
178
+ cur = { file: m[2].trim(), op: m[1], old: [], new: [] };
179
+ files.push(cur);
180
+ continue;
181
+ }
182
+ if (!cur || line.startsWith('***') || line.startsWith('@@')) continue;
183
+ if (line.startsWith('+')) cur.new.push(line.slice(1));
184
+ else if (line.startsWith('-')) cur.old.push(line.slice(1));
185
+ }
186
+ const first = files[0] || { file: '(patch)', old: [], new: [] };
187
+ return {
188
+ file: first.file,
189
+ files: files.map((f) => f.file),
190
+ created: first.op === 'Add',
191
+ summary: files.map((f) => f.file).join(', '),
192
+ diff: files.map((f) => ({ old: truncate(f.old.join('\n'), MAX_OUTPUT), new: truncate(f.new.join('\n'), MAX_OUTPUT), file: f.file })),
193
+ lines: files.reduce((a, f) => ({ added: a.added + f.new.length, removed: a.removed + f.old.length }), { added: 0, removed: 0 }),
194
+ };
195
+ }
package/src/pricing.js ADDED
@@ -0,0 +1,63 @@
1
+ import fs from 'node:fs';
2
+
3
+ /**
4
+ * USD per 1M tokens. Cache writes are priced from the input rate
5
+ * (5-minute writes 1.25x, 1-hour writes 2x); cache reads use `cacheRead`
6
+ * when given, else 0.1x input. These are list prices for the first-party
7
+ * API and are only an estimate of what a session cost — subscription plans
8
+ * are billed differently. Override with --pricing <file.json>.
9
+ *
10
+ * Models are matched by longest prefix.
11
+ */
12
+ export const DEFAULT_PRICING = {
13
+ 'claude-fable-5-2': { input: 8, output: 40, cacheRead: 0.2 },
14
+ 'claude-mythos-5-2': { input: 8, output: 40, cacheRead: 0.2 },
15
+ 'claude-fable-5-1': { input: 10, output: 50 },
16
+ 'claude-mythos-5-1': { input: 10, output: 50 },
17
+ 'claude-fable-5': { input: 10, output: 50 },
18
+ 'claude-opus-5-5': { input: 4, output: 20, cacheRead: 0.2 },
19
+ 'claude-opus-5': { input: 5, output: 25 },
20
+ 'claude-opus-4-8': { input: 5, output: 25 },
21
+ 'claude-opus-4-7': { input: 5, output: 25 },
22
+ 'claude-opus-4-6': { input: 5, output: 25 },
23
+ 'claude-sonnet-5-5': { input: 2, output: 10, cacheRead: 0.1 },
24
+ 'claude-sonnet-5': { input: 2, output: 10 },
25
+ 'claude-sonnet-4-6': { input: 3, output: 15 },
26
+ 'claude-haiku-5-5': { input: 0.1, output: 0.5 },
27
+ 'claude-haiku-4-5': { input: 1, output: 5 },
28
+ };
29
+
30
+ export function loadPricing(file) {
31
+ if (!file) return DEFAULT_PRICING;
32
+ const custom = JSON.parse(fs.readFileSync(file, 'utf8'));
33
+ return { ...DEFAULT_PRICING, ...custom };
34
+ }
35
+
36
+ function rateFor(model, pricing) {
37
+ const keys = Object.keys(pricing)
38
+ .filter((k) => model.startsWith(k))
39
+ .sort((a, b) => b.length - a.length);
40
+ return keys.length ? pricing[keys[0]] : null;
41
+ }
42
+
43
+ /** Returns estimated USD, or null when any used model has no known price. */
44
+ export function estimateCost(usageByModel, pricing) {
45
+ let total = 0;
46
+ let any = false;
47
+ for (const [model, u] of Object.entries(usageByModel)) {
48
+ const tokens = u.input + u.output + u.cacheRead + u.cacheWrite + u.cacheWrite1h;
49
+ if (!tokens) continue;
50
+ const r = rateFor(model, pricing);
51
+ if (!r) return null;
52
+ any = true;
53
+ const cacheRead = r.cacheRead ?? r.input * 0.1;
54
+ total +=
55
+ (u.input * r.input +
56
+ u.output * r.output +
57
+ u.cacheRead * cacheRead +
58
+ u.cacheWrite * r.input * 1.25 +
59
+ u.cacheWrite1h * r.input * 2) /
60
+ 1e6;
61
+ }
62
+ return any ? total : null;
63
+ }
package/src/redact.js ADDED
@@ -0,0 +1,96 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Patterns for secrets that should never end up in a shared replay.
6
+ * Order matters: specific token formats first, generic KEY=value last.
7
+ */
8
+ const SECRET_PATTERNS = [
9
+ ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g],
10
+ ['Anthropic key', /sk-ant-[A-Za-z0-9_-]{20,}/g],
11
+ ['OpenAI key', /sk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{20,}/g],
12
+ ['GitHub token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/g],
13
+ ['AWS key', /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g],
14
+ ['Slack token', /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/g],
15
+ ['Google key', /\bAIza[A-Za-z0-9_-]{35}\b/g],
16
+ ['Stripe key', /\b[rs]k_(?:live|test)_[A-Za-z0-9]{20,}\b/g],
17
+ ['JWT', /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g],
18
+ ['bearer token', /\b(Bearer\s+)[A-Za-z0-9._~+/=-]{16,}/g],
19
+ ['URL credentials', /(\w+:\/\/[^\s:/@]+:)[^\s@/]+(@)/g],
20
+ // Env-style assignments only (UPPER_SNAKE names, case-sensitive) so ordinary
21
+ // code like `local token = entry.Token` is left alone. Value must contain a digit.
22
+ [
23
+ 'assigned secret',
24
+ /\b([A-Z0-9_]*(?:API_?KEY|SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE_KEY|ACCESS_KEY)[A-Z0-9_]*\s*[=:]\s*["']?)(?=[A-Za-z0-9_\-./+=]*\d)[A-Za-z0-9_\-./+=]{8,}/g,
25
+ ],
26
+ ];
27
+
28
+ const EMAIL = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
29
+
30
+ export function createRedactor({ paths = true, emails = true } = {}) {
31
+ const counts = {};
32
+ const home = os.homedir();
33
+ const user = path.basename(home);
34
+ const homeVariants = paths
35
+ ? [...new Set([home, home.replace(/\\/g, '/'), home.replace(/\\/g, '\\\\'), toPosixDrive(home)])].filter(
36
+ (h) => h && h.length > 3,
37
+ )
38
+ : [];
39
+
40
+ function bump(kind) {
41
+ counts[kind] = (counts[kind] || 0) + 1;
42
+ }
43
+
44
+ function redactString(s) {
45
+ for (const [kind, re] of SECRET_PATTERNS) {
46
+ s = s.replace(re, (...m) => {
47
+ bump(kind);
48
+ // keep capture-group prefixes/suffixes (e.g. "API_KEY=" or "Bearer ")
49
+ const groups = m.slice(1, -2).filter((g) => typeof g === 'string');
50
+ if (groups.length === 2) return `${groups[0]}[REDACTED]${groups[1]}`;
51
+ if (groups.length === 1) return `${groups[0]}[REDACTED]`;
52
+ return `[REDACTED ${kind}]`;
53
+ });
54
+ }
55
+ if (emails) {
56
+ s = s.replace(EMAIL, (m) => {
57
+ if (/noreply|example\.(com|org)/i.test(m)) return m;
58
+ bump('email');
59
+ return '[email]';
60
+ });
61
+ }
62
+ for (const h of homeVariants) {
63
+ if (s.includes(h)) {
64
+ bump('home path');
65
+ s = s.split(h).join('~');
66
+ }
67
+ }
68
+ // Claude Code project folder names encode the home path with dashes.
69
+ if (paths && user && user.length > 2) {
70
+ s = s.replace(new RegExp(`\\b[A-Za-z]--Users-${escapeRe(user)}\\b`, 'g'), '~');
71
+ }
72
+ return s;
73
+ }
74
+
75
+ function walk(v) {
76
+ if (typeof v === 'string') return redactString(v);
77
+ if (Array.isArray(v)) return v.map(walk);
78
+ if (v && typeof v === 'object') {
79
+ const out = {};
80
+ for (const [k, val] of Object.entries(v)) out[k] = walk(val);
81
+ return out;
82
+ }
83
+ return v;
84
+ }
85
+
86
+ return { redact: walk, counts };
87
+ }
88
+
89
+ function toPosixDrive(p) {
90
+ const m = p.match(/^([A-Za-z]):\\(.*)$/);
91
+ return m ? `/${m[1].toLowerCase()}/${m[2].replace(/\\/g, '/')}` : null;
92
+ }
93
+
94
+ function escapeRe(s) {
95
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
96
+ }
package/src/render.js ADDED
@@ -0,0 +1,33 @@
1
+ import fs from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const TEMPLATE = fileURLToPath(new URL('./template.html', import.meta.url));
5
+ const LS = new RegExp(String.fromCharCode(0x2028), "g");
6
+ const PS = new RegExp(String.fromCharCode(0x2029), "g");
7
+ const PKG = JSON.parse(fs.readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'));
8
+
9
+ /** Build the self-contained replay HTML for a parsed + redacted session. */
10
+ export function renderHtml(session, stats, { redactions = null } = {}) {
11
+ const data = {
12
+ agent: session.agent,
13
+ title: session.title || 'Untitled session',
14
+ models: session.models,
15
+ branch: session.branch,
16
+ cwd: session.cwd,
17
+ events: session.events.map((e) => ({ ...e, t: e.t ?? null })),
18
+ stats,
19
+ redactions,
20
+ generator: { name: 'agentreplay', version: PKG.version, url: PKG.homepage || null },
21
+ };
22
+ // Escape "<" so session text like "</script>" can't break out of the data block.
23
+ const json = JSON.stringify(data).replace(/</g, '\\u003c').replace(LS, '\\u2028').replace(PS, '\\u2029');
24
+ const title = escapeHtml(`${data.title} · ${data.agent} replay`);
25
+ return fs
26
+ .readFileSync(TEMPLATE, 'utf8')
27
+ .replace('__TITLE__', () => title)
28
+ .replace('__DATA__', () => json);
29
+ }
30
+
31
+ function escapeHtml(s) {
32
+ return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
33
+ }
package/src/stats.js ADDED
@@ -0,0 +1,62 @@
1
+ import { estimateCost } from './pricing.js';
2
+
3
+ const IDLE_CAP_MS = 5 * 60 * 1000;
4
+
5
+ /** Aggregate numbers for the summary card. */
6
+ export function computeStats(session, pricing) {
7
+ const ev = session.events;
8
+ const times = ev.flatMap((e) => [e.t, e.endT]).filter(Number.isFinite);
9
+ const start = times.length ? Math.min(...times) : null;
10
+ const end = times.length ? Math.max(...times) : null;
11
+
12
+ // "Active" time: wall-clock minus long idle gaps (lunch breaks, overnight).
13
+ let active = 0;
14
+ const sorted = [...times].sort((a, b) => a - b);
15
+ for (let i = 1; i < sorted.length; i++) active += Math.min(sorted[i] - sorted[i - 1], IDLE_CAP_MS);
16
+
17
+ const tools = ev.filter((e) => e.kind === 'tool');
18
+ const byTool = {};
19
+ for (const t of tools) byTool[t.name] = (byTool[t.name] || 0) + 1;
20
+
21
+ const files = {};
22
+ for (const t of tools) {
23
+ if (!t.diff) continue;
24
+ const list = t.diff.some((d) => d.file) ? t.diff.map((d) => d.file) : [t.file];
25
+ for (const f of list) {
26
+ if (!f) continue;
27
+ files[f] ||= { added: 0, removed: 0, edits: 0, created: false };
28
+ files[f].edits++;
29
+ if (t.created) files[f].created = true;
30
+ }
31
+ const f = files[list[0]];
32
+ if (f && t.lines) {
33
+ f.added += t.lines.added;
34
+ f.removed += t.lines.removed;
35
+ }
36
+ }
37
+
38
+ const u = session.usage;
39
+ return {
40
+ start,
41
+ end,
42
+ wallMs: start != null ? end - start : 0,
43
+ activeMs: active,
44
+ prompts: ev.filter((e) => e.kind === 'user').length,
45
+ toolCalls: tools.length,
46
+ errors: tools.filter((t) => t.isError).length,
47
+ byTool: Object.entries(byTool).sort((a, b) => b[1] - a[1]),
48
+ files: Object.entries(files)
49
+ .map(([file, s]) => ({ file, ...s }))
50
+ .sort((a, b) => b.added + b.removed - (a.added + a.removed)),
51
+ linesAdded: Object.values(files).reduce((s, f) => s + f.added, 0),
52
+ linesRemoved: Object.values(files).reduce((s, f) => s + f.removed, 0),
53
+ tokens: {
54
+ input: u.input,
55
+ output: u.output,
56
+ cacheRead: u.cacheRead,
57
+ cacheWrite: u.cacheWrite + u.cacheWrite1h,
58
+ total: u.input + u.output + u.cacheRead + u.cacheWrite + u.cacheWrite1h,
59
+ },
60
+ cost: estimateCost(session.usageByModel, pricing),
61
+ };
62
+ }