@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/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,64 @@
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: session.reportedCost ?? estimateCost(session.usageByModel, pricing),
61
+ costReported: session.reportedCost != null,
62
+ timesSynthetic: !!session.timesSynthetic,
63
+ };
64
+ }
@@ -0,0 +1,356 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>__TITLE__</title>
7
+ <style>
8
+ :root {
9
+ --bg: #f7f7f5; --panel: #ffffff; --ink: #1d1d1b; --muted: #6b6b66; --line: #e4e3df;
10
+ --accent: #d97745; --accent-ink: #ffffff; --user: #eef3ff; --user-line: #cfdcff;
11
+ --ok: #2f8a4e; --err: #c8412f; --add-bg: #e6f6ea; --add: #1f7a3c; --del-bg: #fdecea; --del: #b3261e;
12
+ --code-bg: #f1f0ec; --think: #8a8780; --shadow: 0 1px 2px rgba(0,0,0,.04), 0 4px 16px rgba(0,0,0,.04);
13
+ --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
14
+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, sans-serif;
15
+ }
16
+ @media (prefers-color-scheme: dark) {
17
+ :root:not([data-theme="light"]) {
18
+ --bg: #141413; --panel: #1d1d1b; --ink: #ecebe6; --muted: #9b9a94; --line: #2f2e2b;
19
+ --user: #1e2638; --user-line: #2e3b57; --ok: #58c27d; --err: #ff7a66;
20
+ --add-bg: #14301e; --add: #7fdc9b; --del-bg: #3a1916; --del: #ff9a8c; --code-bg: #262522; --think: #8f8c84;
21
+ --shadow: none;
22
+ }
23
+ }
24
+ :root[data-theme="dark"] {
25
+ --bg: #141413; --panel: #1d1d1b; --ink: #ecebe6; --muted: #9b9a94; --line: #2f2e2b;
26
+ --user: #1e2638; --user-line: #2e3b57; --ok: #58c27d; --err: #ff7a66;
27
+ --add-bg: #14301e; --add: #7fdc9b; --del-bg: #3a1916; --del: #ff9a8c; --code-bg: #262522; --think: #8f8c84;
28
+ --shadow: none;
29
+ }
30
+ * { box-sizing: border-box; }
31
+ html, body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.55 var(--sans); }
32
+ a { color: var(--accent); }
33
+ code, pre { font-family: var(--mono); font-size: 13px; }
34
+ .wrap { max-width: 1180px; margin: 0 auto; padding: 24px 16px 120px; }
35
+
36
+ /* ---------- summary card ---------- */
37
+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 22px 24px; box-shadow: var(--shadow); }
38
+ .card-top { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; color: var(--muted); font-size: 13px; }
39
+ .badge { background: var(--accent); color: var(--accent-ink); font-weight: 600; padding: 2px 10px; border-radius: 99px; font-size: 12px; }
40
+ .card h1 { font-size: 26px; line-height: 1.25; margin: 10px 0 18px; letter-spacing: -.01em; overflow-wrap: anywhere; }
41
+ .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; }
42
+ .tile { background: var(--bg); border-radius: 12px; padding: 10px 14px; }
43
+ .tile b { display: block; font-size: 22px; font-variant-numeric: tabular-nums; letter-spacing: -.01em; }
44
+ .tile span { color: var(--muted); font-size: 12px; }
45
+ .tile .add { color: var(--add); } .tile .del { color: var(--del); }
46
+
47
+ /* ---------- layout ---------- */
48
+ .layout { display: grid; grid-template-columns: minmax(0, 1fr) 300px; gap: 20px; margin-top: 20px; align-items: start; }
49
+ @media (max-width: 900px) { .layout { grid-template-columns: minmax(0, 1fr); } .side { order: 2; } }
50
+ .side { position: sticky; top: 16px; display: grid; gap: 14px; }
51
+ .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px; }
52
+ .panel h3 { margin: 0 0 10px; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); }
53
+ .files li, .toolbars li { list-style: none; display: flex; justify-content: space-between; gap: 8px; font-size: 13px; padding: 3px 0; }
54
+ .files, .toolbars { margin: 0; padding: 0; }
55
+ .side > * { min-width: 0; }
56
+ .files .name { font-family: var(--mono); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
57
+ .files .name i { color: var(--muted); font-style: normal; }
58
+ .files .n { white-space: nowrap; font-variant-numeric: tabular-nums; }
59
+ .bar { height: 6px; background: var(--accent); border-radius: 3px; opacity: .8; }
60
+ .toolbars li { display: grid; grid-template-columns: minmax(0, 1.1fr) 1fr 32px; gap: 8px; align-items: center; }
61
+ .toolbars .tn { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
62
+ .toolbars .tc { text-align: right; color: var(--muted); font-variant-numeric: tabular-nums; }
63
+ .muted { color: var(--muted); }
64
+
65
+ /* ---------- feed ---------- */
66
+ .feed { display: flex; flex-direction: column; gap: 10px; }
67
+ .ev { animation: in .25s ease-out; scroll-margin: 80px; }
68
+ @keyframes in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
69
+ .ev.user { align-self: flex-end; max-width: 85%; background: var(--user); border: 1px solid var(--user-line); border-radius: 14px 14px 4px 14px; padding: 10px 14px; white-space: pre-wrap; overflow-wrap: anywhere; }
70
+ .ev.assistant { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 12px 16px; overflow-wrap: anywhere; }
71
+ .ev.assistant p { margin: 0 0 8px; } .ev.assistant p:last-child { margin: 0; }
72
+ .ev.assistant pre { background: var(--code-bg); padding: 10px 12px; border-radius: 8px; overflow-x: auto; }
73
+ .ev.assistant :not(pre) > code { background: var(--code-bg); padding: 1px 5px; border-radius: 4px; }
74
+ .ev.thinking { color: var(--think); font-style: italic; font-size: 14px; padding: 2px 4px 2px 14px; border-left: 2px solid var(--line); white-space: pre-wrap; max-height: 7.5em; overflow: hidden; cursor: pointer; }
75
+ .ev.thinking.open { max-height: none; }
76
+ .ev.tool { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; font-size: 13px; }
77
+ .ev.tool.err { border-color: var(--err); }
78
+ .tool-head { display: flex; gap: 10px; align-items: center; padding: 8px 12px; cursor: pointer; user-select: none; }
79
+ .tool-head .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ok); flex: none; }
80
+ .ev.tool.err .dot { background: var(--err); }
81
+ .ev.tool.pending .dot { background: var(--muted); animation: pulse 1s infinite; }
82
+ @keyframes pulse { 50% { opacity: .3; } }
83
+ .tool-head .tname { font-weight: 600; flex: none; }
84
+ .tool-head .tsum { color: var(--muted); font-family: var(--mono); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
85
+ .tool-head .tlines { font-family: var(--mono); font-size: 12px; flex: none; }
86
+ .tlines .a { color: var(--add); } .tlines .d { color: var(--del); }
87
+ .tool-body { display: none; border-top: 1px solid var(--line); padding: 10px 12px; }
88
+ .ev.tool.open .tool-body { display: block; }
89
+ .tool-body pre { margin: 0 0 8px; background: var(--code-bg); padding: 8px 10px; border-radius: 6px; overflow: auto; max-height: 360px; white-space: pre-wrap; overflow-wrap: anywhere; }
90
+ .tool-body .lbl { font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 4px 0; }
91
+ .tool-body .lbl.path { text-transform: none; letter-spacing: 0; font-family: var(--mono); overflow-wrap: anywhere; }
92
+ .diff { font-family: var(--mono); font-size: 12px; border-radius: 6px; overflow: auto; max-height: 420px; margin-bottom: 8px; background: var(--code-bg); }
93
+ .diff div { padding: 0 10px; white-space: pre-wrap; overflow-wrap: anywhere; }
94
+ .diff .a { background: var(--add-bg); color: var(--add); }
95
+ .diff .d { background: var(--del-bg); color: var(--del); }
96
+ .diff .f { color: var(--muted); padding-top: 6px; }
97
+ .ev.edit.flash { box-shadow: 0 0 0 2px var(--add); transition: box-shadow .6s; }
98
+
99
+ /* ---------- player ---------- */
100
+ .player { position: fixed; left: 0; right: 0; bottom: 0; background: color-mix(in srgb, var(--panel) 92%, transparent); backdrop-filter: blur(10px); border-top: 1px solid var(--line); z-index: 10; }
101
+ .player-in { max-width: 1180px; margin: 0 auto; padding: 10px 16px; display: flex; gap: 12px; align-items: center; }
102
+ .btn { background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 99px; width: 40px; height: 40px; font-size: 16px; cursor: pointer; flex: none; display: grid; place-items: center; }
103
+ .btn.ghost { background: transparent; color: var(--ink); border: 1px solid var(--line); width: auto; padding: 0 12px; height: 32px; font-size: 13px; }
104
+ .track { position: relative; flex: 1; height: 28px; cursor: pointer; min-width: 60px; }
105
+ .track .rail { position: absolute; top: 12px; left: 0; right: 0; height: 4px; background: var(--line); border-radius: 2px; }
106
+ .track .fill { position: absolute; top: 12px; left: 0; height: 4px; background: var(--accent); border-radius: 2px; }
107
+ .track .mk { position: absolute; top: 8px; width: 2px; height: 12px; border-radius: 1px; opacity: .85; }
108
+ .mk.e { background: var(--add); } .mk.x { background: var(--err); } .mk.u { background: #4f7cff; }
109
+ .clock { font-variant-numeric: tabular-nums; font-size: 13px; color: var(--muted); min-width: 92px; text-align: right; }
110
+ select.btn { appearance: none; text-align: center; }
111
+ @media (max-width: 600px) { .clock { display: none; } .hide-sm { display: none; } .card h1 { font-size: 21px; } }
112
+
113
+ footer { text-align: center; color: var(--muted); font-size: 13px; margin-top: 40px; }
114
+ .redacted { font-size: 12px; color: var(--muted); margin-top: 12px; }
115
+ </style>
116
+ </head>
117
+ <body>
118
+ <div class="wrap">
119
+ <section class="card" id="card"></section>
120
+ <div class="layout">
121
+ <main class="feed" id="feed" aria-live="polite"></main>
122
+ <aside class="side" id="side"></aside>
123
+ </div>
124
+ <footer id="foot"></footer>
125
+ </div>
126
+ <div class="player">
127
+ <div class="player-in">
128
+ <button class="btn" id="play" title="Play / pause (space)" aria-label="Play">▶</button>
129
+ <div class="track" id="track" title="Seek"><div class="rail"></div><div class="fill" id="fill"></div></div>
130
+ <span class="clock" id="clock"></span>
131
+ <select class="btn ghost" id="speed" title="Speed" aria-label="Playback speed">
132
+ <option value="0.5">0.5×</option><option value="1" selected>1×</option><option value="2">2×</option><option value="4">4×</option><option value="10">10×</option>
133
+ </select>
134
+ <button class="btn ghost hide-sm" id="all" title="Show everything (end)">Show all</button>
135
+ <button class="btn ghost hide-sm" id="theme" title="Toggle theme" aria-label="Toggle theme">◐</button>
136
+ </div>
137
+ </div>
138
+ <script id="data" type="application/json">__DATA__</script>
139
+ <script>
140
+ (() => {
141
+ const D = JSON.parse(document.getElementById('data').textContent);
142
+ const S = D.stats;
143
+ const $ = (id) => document.getElementById(id);
144
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
145
+ const num = (n) => n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e4 ? Math.round(n / 1e3) + 'k' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'k' : String(n);
146
+ const dur = (ms) => { const m = Math.round(ms / 60000); return m < 1 ? '<1m' : m < 60 ? m + 'm' : Math.floor(m / 60) + 'h ' + (m % 60) + 'm'; };
147
+ const base = (p) => String(p || '').split(/[\\/]/).pop();
148
+ // "…/hooks/useTheme.ts" with the directory part dimmed
149
+ const shortPath = (p) => {
150
+ const parts = String(p || '').split(/[\\/]/).filter(Boolean);
151
+ const name = parts.pop() || '';
152
+ const dir = parts.slice(-2).join('/');
153
+ return (dir ? `<i>${parts.length > 2 ? '…/' : ''}${esc(dir)}/</i>` : '') + esc(name);
154
+ };
155
+
156
+ /* ---------- summary card ---------- */
157
+ const date = S.start ? new Date(S.start).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : '';
158
+ const tiles = [
159
+ ...(S.timesSynthetic ? [] : [[dur(S.activeMs), 'active time']]),
160
+ [S.prompts, S.prompts === 1 ? 'prompt' : 'prompts'],
161
+ [S.toolCalls, 'tool calls'],
162
+ [S.files.length, 'files changed'],
163
+ [`<span class="add">+${num(S.linesAdded)}</span> <span class="del">−${num(S.linesRemoved)}</span>`, 'lines'],
164
+ [num(S.tokens.total), 'tokens'],
165
+ ];
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
+ $('card').innerHTML = `
168
+ <div class="card-top"><span class="badge">${esc(D.agent)}</span>
169
+ ${D.models.length ? `<span>${esc(D.models.join(', '))}</span>` : ''}
170
+ ${date ? `<span>· ${esc(date)}</span>` : ''}
171
+ ${D.branch && D.branch !== 'HEAD' ? `<span>· ⎇ ${esc(D.branch)}</span>` : ''}
172
+ </div>
173
+ <h1>${esc(D.title)}</h1>
174
+ <div class="tiles">${tiles.map(([b, s]) => `<div class="tile"><b>${b}</b><span>${s}</span></div>`).join('')}</div>`;
175
+
176
+ /* ---------- sidebar ---------- */
177
+ const maxTool = S.byTool.length ? S.byTool[0][1] : 1;
178
+ $('side').innerHTML = `
179
+ ${S.files.length ? `<div class="panel"><h3>Files changed</h3><ul class="files">${S.files.slice(0, 25).map((f) =>
180
+ `<li title="${esc(f.file)}"><span class="name">${shortPath(f.file)}</span><span class="n"><span style="color:var(--add)">+${f.added}</span> <span style="color:var(--del)">−${f.removed}</span></span></li>`).join('')}
181
+ ${S.files.length > 25 ? `<li class="muted">+${S.files.length - 25} more</li>` : ''}</ul></div>` : ''}
182
+ ${S.byTool.length ? `<div class="panel"><h3>Tools used</h3><ul class="toolbars">${S.byTool.slice(0, 12).map(([n, c]) =>
183
+ `<li><span class="tn" title="${esc(n)}">${esc(n.split(' · ').pop())}</span><div class="bar" style="width:${Math.max(4, (c / maxTool) * 100)}%"></div><span class="tc">${c}</span></li>`).join('')}</ul></div>` : ''}
184
+ <div class="panel"><h3>Tokens</h3>
185
+ <ul class="files">
186
+ <li><span>Input</span><span class="n">${num(S.tokens.input)}</span></li>
187
+ <li><span>Output</span><span class="n">${num(S.tokens.output)}</span></li>
188
+ <li><span>Cache read</span><span class="n">${num(S.tokens.cacheRead)}</span></li>
189
+ <li><span>Cache write</span><span class="n">${num(S.tokens.cacheWrite)}</span></li>
190
+ ${S.errors ? `<li><span>Failed tool calls</span><span class="n" style="color:var(--err)">${S.errors}</span></li>` : ''}
191
+ </ul>
192
+ ${S.cost != null && !S.costReported ? '<div class="redacted">Cost is an estimate at public API list prices.</div>' : ''}
193
+ </div>`;
194
+
195
+ const red = D.redactions ? Object.entries(D.redactions) : [];
196
+ const gen = D.generator;
197
+ $('foot').innerHTML = `Made with ${gen.url ? `<a href="${esc(gen.url)}">agentreplay</a>` : 'agentreplay'} v${esc(gen.version)}
198
+ ${red.length ? `<div class="redacted">🔒 Redacted before sharing: ${red.map(([k, v]) => `${v} ${esc(k)}`).join(', ')}</div>` : ''}`;
199
+
200
+ /* ---------- tiny markdown ---------- */
201
+ function md(src) {
202
+ const parts = String(src).split(/```(\w*)\n?([\s\S]*?)```/g);
203
+ let html = '';
204
+ for (let i = 0; i < parts.length; i += 3) {
205
+ html += parts[i].split(/\n{2,}/).filter((p) => p.trim()).map((p) => '<p>' + inline(p).replace(/\n/g, '<br>') + '</p>').join('');
206
+ if (parts[i + 2] !== undefined) html += `<pre><code>${esc(parts[i + 2].replace(/\n$/, ''))}</code></pre>`;
207
+ }
208
+ return html;
209
+ }
210
+ function inline(s) {
211
+ return esc(s)
212
+ .replace(/`([^`]+)`/g, '<code>$1</code>')
213
+ .replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
214
+ .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
215
+ .replace(/^#{1,6} (.+)$/gm, '<b>$1</b>');
216
+ }
217
+ function diffHtml(d) {
218
+ const rows = [];
219
+ for (const h of d) {
220
+ if (h.file && d.length > 1) rows.push(`<div class="f">${esc(h.file)}</div>`);
221
+ if (h.old) for (const l of h.old.split('\n')) rows.push(`<div class="d">- ${esc(l)}</div>`);
222
+ if (h.new) for (const l of h.new.split('\n')) rows.push(`<div class="a">+ ${esc(l)}</div>`);
223
+ }
224
+ return `<div class="diff">${rows.join('')}</div>`;
225
+ }
226
+
227
+ /* ---------- events ---------- */
228
+ const E = D.events;
229
+ function render(e, i) {
230
+ const el = document.createElement('div');
231
+ el.id = 'e' + i;
232
+ if (e.kind === 'user') { el.className = 'ev user'; el.textContent = e.text; }
233
+ else if (e.kind === 'assistant') { el.className = 'ev assistant'; el.innerHTML = md(e.text); }
234
+ else if (e.kind === 'thinking') { el.className = 'ev thinking'; el.textContent = e.text; el.onclick = () => el.classList.toggle('open'); }
235
+ else {
236
+ el.className = 'ev tool' + (e.isError ? ' err' : '') + (e.diff ? ' edit' : '');
237
+ const lines = e.lines ? `<span class="tlines"><span class="a">+${e.lines.added}</span> <span class="d">−${e.lines.removed}</span></span>` : '';
238
+ const sum = e.diff ? base(e.file) + (e.files && e.files.length > 1 ? ` +${e.files.length - 1}` : '') : e.summary;
239
+ el.innerHTML = `<div class="tool-head"><span class="dot"></span><span class="tname">${esc(e.name)}</span><span class="tsum" title="${esc(e.summary)}">${esc(sum)}</span>${lines}</div>
240
+ <div class="tool-body">${e.diff ? (e.file ? `<div class="lbl path">${esc(e.file)}</div>` : '') + diffHtml(e.diff) : ''}
241
+ ${e.input ? `<div class="lbl">Input</div><pre>${esc(e.input)}</pre>` : ''}
242
+ ${e.output ? `<div class="lbl">${e.isError ? 'Error' : 'Output'}</div><pre>${esc(e.output)}</pre>` : ''}</div>`;
243
+ el.querySelector('.tool-head').onclick = () => el.classList.toggle('open');
244
+ if (e.diff || e.isError) el.classList.add('open');
245
+ }
246
+ return el;
247
+ }
248
+
249
+ /* ---------- schedule: condensed time ---------- */
250
+ // Real gaps are squeezed into 0.35–2.5s so a 2-hour session plays in minutes,
251
+ // with a bit of extra hold for long messages so they're readable.
252
+ const sched = [];
253
+ let acc = 0;
254
+ for (let i = 0; i < E.length; i++) {
255
+ if (i > 0) {
256
+ const prev = E[i - 1];
257
+ const gap = (E[i].t && prev.t) ? Math.max(0, E[i].t - prev.t) : 800;
258
+ const read = prev.kind === 'user' || prev.kind === 'assistant' ? Math.min(3000, (prev.text || '').length * 12) : 0;
259
+ acc += Math.min(2500, Math.max(350, gap / 4)) + read;
260
+ }
261
+ sched.push(acc);
262
+ }
263
+ const total = acc + 1200;
264
+
265
+ // Markers on the track
266
+ const track = $('track');
267
+ E.forEach((e, i) => {
268
+ const cls = e.kind === 'user' ? 'u' : e.isError ? 'x' : e.diff ? 'e' : null;
269
+ if (!cls) return;
270
+ const m = document.createElement('div');
271
+ m.className = 'mk ' + cls;
272
+ m.style.left = (sched[i] / total * 100) + '%';
273
+ track.appendChild(m);
274
+ });
275
+
276
+ /* ---------- player ---------- */
277
+ const feed = $('feed');
278
+ let shown = 0, clock = 0, playing = false, last = 0, speed = 1;
279
+
280
+ function showUpTo(n, animate) {
281
+ n = Math.max(0, Math.min(E.length, n));
282
+ if (n < shown) { feed.innerHTML = ''; shown = 0; }
283
+ const frag = document.createDocumentFragment();
284
+ let lastEl = null;
285
+ while (shown < n) { lastEl = render(E[shown], shown); if (!animate) lastEl.style.animation = 'none'; frag.appendChild(lastEl); shown++; }
286
+ if (lastEl) {
287
+ feed.appendChild(frag);
288
+ if (animate) lastEl.scrollIntoView({ behavior: 'smooth', block: 'end' });
289
+ }
290
+ }
291
+ function ui() {
292
+ const p = Math.min(1, clock / total);
293
+ $('fill').style.width = (p * 100) + '%';
294
+ $('clock').textContent = `${shown} / ${E.length} events`;
295
+ $('play').textContent = playing ? '❚❚' : (shown >= E.length ? '↺' : '▶');
296
+ $('play').setAttribute('aria-label', playing ? 'Pause' : 'Play');
297
+ }
298
+ function tick(now) {
299
+ if (!playing) return;
300
+ clock += (now - last) * speed; last = now;
301
+ let n = shown;
302
+ while (n < E.length && sched[n] <= clock) n++;
303
+ if (n !== shown) showUpTo(n, true);
304
+ if (shown >= E.length && clock >= total) { playing = false; }
305
+ ui();
306
+ if (playing) requestAnimationFrame(tick);
307
+ }
308
+ function play() {
309
+ if (shown >= E.length) { clock = 0; showUpTo(0); }
310
+ playing = true; last = performance.now(); requestAnimationFrame(tick); ui();
311
+ }
312
+ function pause() { playing = false; ui(); }
313
+ function seekTo(n) {
314
+ pause();
315
+ showUpTo(n, false);
316
+ clock = n > 0 ? sched[n - 1] : 0;
317
+ const el = $('e' + (n - 1));
318
+ if (el) el.scrollIntoView({ block: 'center' });
319
+ ui();
320
+ }
321
+
322
+ $('play').onclick = () => (playing ? pause() : play());
323
+ $('speed').onchange = (ev) => { speed = Number(ev.target.value); };
324
+ $('all').onclick = () => { seekTo(E.length); clock = total; ui(); };
325
+ $('theme').onclick = () => {
326
+ const r = document.documentElement;
327
+ const dark = r.dataset.theme ? r.dataset.theme === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
328
+ r.dataset.theme = dark ? 'light' : 'dark';
329
+ try { localStorage.setItem('agentreplay-theme', r.dataset.theme); } catch {}
330
+ };
331
+ try { const t = localStorage.getItem('agentreplay-theme'); if (t) document.documentElement.dataset.theme = t; } catch {}
332
+
333
+ track.onclick = (ev) => {
334
+ const r = track.getBoundingClientRect();
335
+ const target = (ev.clientX - r.left) / r.width * total;
336
+ let n = 0; while (n < E.length && sched[n] <= target) n++;
337
+ seekTo(n);
338
+ };
339
+ document.addEventListener('keydown', (ev) => {
340
+ if (ev.target.tagName === 'SELECT') return;
341
+ if (ev.code === 'Space') { ev.preventDefault(); playing ? pause() : play(); }
342
+ else if (ev.key === 'ArrowRight') seekTo(shown + 1);
343
+ else if (ev.key === 'ArrowLeft') seekTo(shown - 1);
344
+ else if (ev.key === 'End') $('all').click();
345
+ else if (ev.key === 'Home') seekTo(0);
346
+ });
347
+
348
+ // Deep link: #e42 opens the replay at event 42. ?static shows everything at once.
349
+ const m = location.hash.match(/^#e(\d+)$/);
350
+ if (m) { seekTo(Number(m[1]) + 1); }
351
+ else if (/[?&]static\b/.test(location.search)) { $('all').click(); }
352
+ else { showUpTo(1, false); clock = sched[0]; ui(); setTimeout(play, 600); }
353
+ })();
354
+ </script>
355
+ </body>
356
+ </html>