@dorywoof/agentreplay 0.3.0 → 0.4.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/README.md CHANGED
@@ -32,6 +32,8 @@ You just watched an AI agent build a feature in 6 minutes. Now you want to show
32
32
  - 🔒 **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.
33
33
  - 📝 **Real diffs.** Edits are shown as red and green diffs with a per-file `+/-` summary: Claude's `Edit`/`Write`, Codex `apply_patch`, Cline/Roo/Aider SEARCH/REPLACE blocks, OpenCode and Gemini edit tools.
34
34
  - 📦 **One file, zero dependencies.** The output is one HTML file that works offline. Host it anywhere: GitHub Pages, a gist, Slack, e-mail.
35
+ - 🌍 **Speaks the viewer's language.** The page follows the browser language (English, Türkçe, Español, Deutsch, Français, Português, Italiano, Русский, 日本語, 中文, 한국어). Add `?lang=xx` to force one.
36
+ - 🧮 **Honest token numbers.** Agents re-send the whole conversation on every request, so summed tokens balloon. The replay leads with the largest single prompt and explains the total, including how much came from cache.
35
37
  - 🌗 Light and dark themes, works on phones, and keyboard shortcuts (`space`, `←` `→`, `Home`, `End`).
36
38
 
37
39
  ## Quick start
@@ -128,7 +130,7 @@ Sessions are found automatically. You can also pass any file directly.
128
130
  --no-open don't open the replay in a browser
129
131
  ```
130
132
 
131
- **URL tricks:** add `#e42` to open a replay at event 42, or `?static` to show the whole session at once with no animation.
133
+ **URL tricks:** add `#e42` to open a replay at event 42, `?static` to show the whole session at once with no animation, or `?lang=de` to pick the interface language.
132
134
 
133
135
  ## Sharing a replay
134
136
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dorywoof/agentreplay",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Turn any AI coding agent session (Claude Code, Codex, Gemini CLI, OpenCode, Cline, Roo, Copilot CLI, Aider, …) into a shareable, video-like HTML replay with cost stats and secret redaction.",
5
5
  "homepage": "https://github.com/dorywoof/agentreplay#readme",
6
6
  "repository": {
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { readJsonl, toText, stripHarnessTags, truncate, lineDelta } from '../util.js';
2
+ import { readJsonl, toText, stripHarnessTags, truncate, lineDelta, trackRequest } from '../util.js';
3
3
 
4
4
  const MAX_OUTPUT = 4000;
5
5
  const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
@@ -102,6 +102,7 @@ function addUsage(session, model, u) {
102
102
  session.usage[k] += add[k];
103
103
  per[k] += add[k];
104
104
  }
105
+ trackRequest(session, add);
105
106
  }
106
107
 
107
108
  function toolEvent(b, ts) {
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { readJsonl, toText, truncate, parsePatch } from '../util.js';
2
+ import { readJsonl, toText, truncate, parsePatch, trackRequest } from '../util.js';
3
3
 
4
4
  const MAX_OUTPUT = 4000;
5
5
 
@@ -48,7 +48,14 @@ export function parse(file) {
48
48
  if (currentModel) session.models.add(currentModel);
49
49
 
50
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
51
+ const tot = p.info.total_token_usage; // cumulative across the session
52
+ const last = p.info.last_token_usage; // this one request
53
+ const changed = !lastTotals || tot.total_tokens !== lastTotals.total_tokens || tot.input_tokens !== lastTotals.input_tokens;
54
+ if (last && changed) {
55
+ const cachedLast = last.cached_input_tokens || 0;
56
+ trackRequest(session, { input: (last.input_tokens || 0) - cachedLast, cacheRead: cachedLast, output: last.output_tokens || 0 });
57
+ }
58
+ lastTotals = tot;
52
59
  continue;
53
60
  }
54
61
  if (r.type !== 'response_item') continue;
package/src/stats.js CHANGED
@@ -56,6 +56,8 @@ export function computeStats(session, pricing) {
56
56
  cacheRead: u.cacheRead,
57
57
  cacheWrite: u.cacheWrite + u.cacheWrite1h,
58
58
  total: u.input + u.output + u.cacheRead + u.cacheWrite + u.cacheWrite1h,
59
+ peakContext: session.peakContext || 0,
60
+ requests: session.requests || 0,
59
61
  },
60
62
  cost: session.reportedCost ?? estimateCost(session.usageByModel, pricing),
61
63
  costReported: session.reportedCost != null,
package/src/template.html CHANGED
@@ -3,136 +3,166 @@
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="color-scheme" content="light dark">
6
7
  <title>__TITLE__</title>
7
8
  <style>
8
9
  :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;
10
+ --bg: #fbfaf7; --ink: #1b1b19; --muted: #6c6a63; --faint: #a3a198; --rule: #e6e4dd; --soft: #f2f1ec;
11
+ --accent: #2a50d8; --add: #1a7f37; --add-bg: #e9f6ec; --del: #c4321f; --del-bg: #fcebe8; --warn: #c4321f;
12
+ --sans: "Inter", "Segoe UI Variable Text", "Segoe UI", -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif;
13
+ --mono: "JetBrains Mono", "SF Mono", ui-monospace, "Cascadia Mono", Consolas, "Liberation Mono", monospace;
15
14
  }
16
15
  @media (prefers-color-scheme: dark) {
17
16
  :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;
17
+ --bg: #111110; --ink: #ecebe5; --muted: #908e86; --faint: #5d5c56; --rule: #262522; --soft: #1a1a18;
18
+ --accent: #86a8ff; --add: #56d364; --add-bg: #12261a; --del: #ff7b72; --del-bg: #2d1514; --warn: #ff7b72;
22
19
  }
23
20
  }
24
21
  :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;
22
+ --bg: #111110; --ink: #ecebe5; --muted: #908e86; --faint: #5d5c56; --rule: #262522; --soft: #1a1a18;
23
+ --accent: #86a8ff; --add: #56d364; --add-bg: #12261a; --del: #ff7b72; --del-bg: #2d1514; --warn: #ff7b72;
29
24
  }
30
25
  * { 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; }
26
+ html, body { margin: 0; background: var(--bg); color: var(--ink); }
27
+ body { font: 15px/1.6 var(--sans); -webkit-font-smoothing: antialiased; }
28
+ a { color: inherit; text-decoration-color: var(--faint); text-underline-offset: 3px; }
29
+ a:hover { text-decoration-color: currentColor; }
30
+ button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
31
+ code, pre, .mono { font-family: var(--mono); }
32
+ .wrap { max-width: 1120px; margin: 0 auto; padding: 48px 24px 140px; }
35
33
 
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); }
34
+ /* ---------- header ---------- */
35
+ .meta { font: 12px/1.4 var(--mono); color: var(--muted); letter-spacing: .02em; display: flex; flex-wrap: wrap; gap: 6px 14px; }
36
+ .meta b { color: var(--ink); font-weight: 600; }
37
+ h1 { font-size: clamp(26px, 4vw, 40px); line-height: 1.12; letter-spacing: -.025em; font-weight: 650; margin: 14px 0 32px; max-width: 28ch; overflow-wrap: anywhere; }
38
+ .figures { display: flex; flex-wrap: wrap; border-top: 1px solid var(--ink); border-bottom: 1px solid var(--rule); }
39
+ .fig { padding: 14px 28px 14px 0; margin-right: 28px; border-right: 1px solid var(--rule); min-width: 92px; }
40
+ .fig:last-child { border-right: 0; margin-right: 0; }
41
+ .fig .n { font: 500 22px/1.2 var(--mono); letter-spacing: -.02em; font-variant-numeric: tabular-nums; white-space: nowrap; }
42
+ .fig .l { font-size: 12px; color: var(--muted); margin-top: 2px; }
43
+ .fig .add { color: var(--add); } .fig .del { color: var(--del); }
46
44
 
47
45
  /* ---------- 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); }
46
+ .cols { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: 56px; margin-top: 40px; align-items: start; }
47
+ @media (max-width: 920px) { .cols { grid-template-columns: minmax(0, 1fr); gap: 40px; } .side { order: 2; } }
48
+ .side { position: sticky; top: 24px; font-size: 13px; }
49
+ @media (max-width: 920px) { .side { position: static; } }
50
+ .side section { padding: 14px 0 18px; border-top: 1px solid var(--rule); }
51
+ .side section:first-child { border-top-color: var(--ink); }
52
+ .side h2 { font: 600 11px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 0 0 12px; }
53
+ .rows { list-style: none; margin: 0; padding: 0; }
54
+ .rows li { display: flex; justify-content: space-between; gap: 12px; padding: 3px 0; }
55
+ .rows .k { color: var(--muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
56
+ .rows .v { font-family: var(--mono); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
57
+ .rows .file { font-family: var(--mono); font-size: 12px; color: var(--ink); }
58
+ .rows .file i { color: var(--faint); font-style: normal; }
59
+ .rows .strong .k, .rows .strong .v { color: var(--ink); font-weight: 600; }
60
+ .note { color: var(--muted); font-size: 12px; line-height: 1.5; margin: 10px 0 0; }
61
+ .bar { display: inline-block; height: 2px; background: var(--ink); vertical-align: middle; margin-right: 8px; opacity: .55; }
64
62
 
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; }
63
+ /* ---------- transcript ---------- */
64
+ .log { min-width: 0; }
65
+ .ev { display: grid; grid-template-columns: 52px minmax(0, 1fr); gap: 0 16px; padding: 10px 0; scroll-margin: 120px; }
66
+ .ev + .ev { border-top: 1px solid transparent; }
67
+ .ev.turn { border-top: 1px solid var(--rule); margin-top: 14px; padding-top: 22px; }
68
+ .ev.turn:first-child { border-top: 0; margin-top: 0; padding-top: 4px; }
69
+ .t { font: 11px/22px var(--mono); color: var(--faint); font-variant-numeric: tabular-nums; text-align: right; }
70
+ .who { font: 600 11px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 4px 0 8px; }
71
+ .ev.new { animation: rise .28s ease-out; }
72
+ @keyframes rise { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
73
+ @media (prefers-reduced-motion: reduce) { .ev.new { animation: none; } }
74
+
75
+ .user .body { font-size: 17px; line-height: 1.5; font-weight: 500; white-space: pre-wrap; overflow-wrap: anywhere; border-left: 2px solid var(--accent); padding-left: 14px; }
76
+ .user .who { color: var(--accent); }
77
+ .say .body { overflow-wrap: anywhere; max-width: 68ch; }
78
+ .say .body p { margin: 0 0 10px; } .say .body p:last-child { margin-bottom: 0; }
79
+ .say .body ul, .say .body ol { margin: 0 0 10px; padding-left: 20px; }
80
+ .say .body pre { background: var(--soft); padding: 12px 14px; overflow-x: auto; font-size: 12.5px; line-height: 1.55; margin: 0 0 10px; border-left: 2px solid var(--rule); }
81
+ .say .body :not(pre) > code { font-size: .88em; background: var(--soft); padding: 1px 5px; }
82
+ .think .body { color: var(--muted); font-style: italic; font-size: 14px; white-space: pre-wrap; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; cursor: pointer; }
83
+ .think.open .body { display: block; }
84
+
85
+ .tool { padding: 3px 0; }
86
+ .tool .line { display: flex; align-items: baseline; gap: 10px; min-width: 0; cursor: pointer; font-size: 13.5px; padding: 3px 0; }
87
+ .tool .line:hover .nm { text-decoration: underline; text-decoration-color: var(--faint); text-underline-offset: 3px; }
88
+ .tool .g { font: 12px var(--mono); width: 12px; flex: none; color: var(--add); }
89
+ .tool.err .g { color: var(--warn); }
90
+ .tool .nm { font: 500 13px var(--mono); flex: none; }
91
+ .tool .sum { color: var(--muted); font: 12.5px var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
92
+ .tool .dl { font: 12px var(--mono); flex: none; }
93
+ .dl .a { color: var(--add); } .dl .d { color: var(--del); }
94
+ .tool .detail { display: none; margin: 6px 0 8px 22px; border-left: 1px solid var(--rule); padding-left: 14px; }
95
+ .tool.open .detail { display: block; }
96
+ .detail .lbl { font: 600 10.5px var(--mono); text-transform: uppercase; letter-spacing: .08em; color: var(--faint); margin: 10px 0 4px; }
97
+ .detail .lbl:first-child { margin-top: 0; }
98
+ .detail .path { font: 12px var(--mono); color: var(--muted); overflow-wrap: anywhere; margin-bottom: 6px; }
99
+ .detail pre { margin: 0; background: var(--soft); padding: 10px 12px; font-size: 12px; line-height: 1.55; overflow: auto; max-height: 340px; white-space: pre-wrap; overflow-wrap: anywhere; }
100
+ .diff { font: 12px/1.55 var(--mono); overflow: auto; max-height: 420px; background: var(--soft); }
101
+ .diff div { padding: 0 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
94
102
  .diff .a { background: var(--add-bg); color: var(--add); }
95
103
  .diff .d { background: var(--del-bg); color: var(--del); }
96
104
  .diff .f { color: var(--muted); padding-top: 6px; }
97
- .ev.edit.flash { box-shadow: 0 0 0 2px var(--add); transition: box-shadow .6s; }
105
+ @media (max-width: 600px) {
106
+ .wrap { padding: 28px 16px 140px; }
107
+ .ev { grid-template-columns: minmax(0, 1fr); }
108
+ .t { text-align: left; line-height: 1; margin-bottom: 2px; }
109
+ .ev:not(.turn) .t { display: none; }
110
+ .fig { padding-right: 18px; margin-right: 18px; min-width: 0; }
111
+ .fig .n { font-size: 18px; }
112
+ }
98
113
 
99
114
  /* ---------- 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; } }
115
+ .player { position: fixed; inset: auto 0 0 0; background: var(--bg); border-top: 1px solid var(--rule); z-index: 10; }
116
+ .pin { max-width: 1120px; margin: 0 auto; padding: 12px 24px; display: flex; align-items: center; gap: 18px; }
117
+ .play { width: 34px; height: 34px; display: grid; place-items: center; border: 1px solid var(--ink); flex: none; }
118
+ .play:hover { background: var(--ink); color: var(--bg); }
119
+ .play svg { width: 14px; height: 14px; fill: currentColor; }
120
+ .track { position: relative; flex: 1; height: 26px; cursor: pointer; min-width: 80px; touch-action: none; }
121
+ .track .rail { position: absolute; left: 0; right: 0; top: 12px; height: 2px; background: var(--rule); }
122
+ .track .fill { position: absolute; left: 0; top: 12px; height: 2px; background: var(--ink); }
123
+ .track .head { position: absolute; top: 8px; width: 2px; height: 10px; background: var(--ink); transform: translateX(-1px); }
124
+ .track .mk { position: absolute; top: 18px; width: 1px; height: 5px; background: var(--faint); }
125
+ .mk.u { background: var(--accent); height: 7px; top: 17px; width: 2px; }
126
+ .mk.x { background: var(--warn); }
127
+ .mk.e { background: var(--add); }
128
+ .count { font: 12px var(--mono); color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; min-width: 64px; text-align: right; }
129
+ .speeds { display: flex; font: 12px var(--mono); border: 1px solid var(--rule); }
130
+ .speeds button { padding: 5px 8px; color: var(--muted); border-left: 1px solid var(--rule); }
131
+ .speeds button:first-child { border-left: 0; }
132
+ .speeds button[aria-pressed="true"] { color: var(--bg); background: var(--ink); }
133
+ .speeds button:not([aria-pressed="true"]):hover { color: var(--ink); }
134
+ .txt { font: 12px var(--mono); color: var(--muted); white-space: nowrap; }
135
+ .txt:hover { color: var(--ink); }
136
+ .icon svg { width: 16px; height: 16px; stroke: currentColor; fill: none; stroke-width: 1.6; display: block; }
137
+ .icon { color: var(--muted); } .icon:hover { color: var(--ink); }
138
+ @media (max-width: 700px) {
139
+ .pin { padding: 10px 16px; gap: 12px; }
140
+ .speeds button:not([aria-pressed="true"]) { display: none; }
141
+ .speeds button { border-left: 0; }
142
+ .count, .hide-sm { display: none; }
143
+ }
144
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
112
145
 
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; }
146
+ footer { margin-top: 64px; padding-top: 16px; border-top: 1px solid var(--rule); font: 12px/1.6 var(--mono); color: var(--muted); display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px 24px; }
115
147
  </style>
116
148
  </head>
117
149
  <body>
118
150
  <div class="wrap">
119
- <section class="card" id="card"></section>
120
- <div class="layout">
121
- <main class="feed" id="feed" aria-live="polite"></main>
151
+ <header id="head"></header>
152
+ <div class="cols">
153
+ <main class="log" id="log" aria-live="polite"></main>
122
154
  <aside class="side" id="side"></aside>
123
155
  </div>
124
156
  <footer id="foot"></footer>
125
157
  </div>
126
158
  <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>
159
+ <div class="pin">
160
+ <button class="play" id="play"></button>
161
+ <div class="track" id="track"><div class="rail"></div><div class="fill" id="fill"></div><div class="head" id="phead"></div></div>
162
+ <span class="count" id="count"></span>
163
+ <div class="speeds" id="speeds" role="group"></div>
164
+ <button class="txt hide-sm" id="all"></button>
165
+ <button class="icon" id="theme"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.2"/><path d="M12 2.5v2.2M12 19.3v2.2M4.6 4.6l1.6 1.6M17.8 17.8l1.6 1.6M2.5 12h2.2M19.3 12h2.2M4.6 19.4l1.6-1.6M17.8 6.2l1.6-1.6"/></svg></button>
136
166
  </div>
137
167
  </div>
138
168
  <script id="data" type="application/json">__DATA__</script>
@@ -141,69 +171,104 @@ footer { text-align: center; color: var(--muted); font-size: 13px; margin-top: 4
141
171
  const D = JSON.parse(document.getElementById('data').textContent);
142
172
  const S = D.stats;
143
173
  const $ = (id) => document.getElementById(id);
174
+
175
+ /* ---------- language ---------- */
176
+ const I18N = {
177
+ en: { you: 'You', thinking: 'Thinking', activeTime: 'active', prompts: ['prompt', 'prompts'], toolCalls: 'tool calls', filesChanged: 'files changed', lines: 'lines', peak: 'largest prompt', cost: 'cost', estCost: 'est. API cost', files: 'Files', tools: 'Tools', tokens: 'Tokens', output: 'Output', newInput: 'New input', cacheRead: 'Read from cache', cacheWrite: 'Written to cache', requests: 'Requests', totalProcessed: 'Total processed', failed: 'Failed tool calls', tokenNote: 'Every request re-sends the whole conversation, so the total counts the same context again and again. {pct} of it came from cache. The largest single prompt was {peak}.', costNote: 'Estimate at public API list prices.', input: 'Input', error: 'Error', result: 'Output', showAll: 'Show all', play: 'Play', pause: 'Pause', replay: 'Replay from start', theme: 'Switch theme', speed: 'Speed', more: '+{n} more', madeWith: 'Made with', redacted: 'Removed before sharing: {list}', untitled: 'Untitled session', seek: 'Timeline', of: 'of', branch: 'branch' },
178
+ tr: { you: 'Sen', thinking: 'Düşünüyor', activeTime: 'aktif süre', prompts: ['mesaj', 'mesaj'], toolCalls: 'araç çağrısı', filesChanged: 'dosya değişti', lines: 'satır', peak: 'en büyük istem', cost: 'maliyet', estCost: 'tahmini API maliyeti', files: 'Dosyalar', tools: 'Araçlar', tokens: 'Token', output: 'Çıktı', newInput: 'Yeni girdi', cacheRead: 'Önbellekten okunan', cacheWrite: 'Önbelleğe yazılan', requests: 'API isteği', totalProcessed: 'Toplam işlenen', failed: 'Başarısız araç çağrısı', tokenNote: 'Her istekte konuşmanın tamamı yeniden gönderilir, bu yüzden toplam aynı içeriği defalarca sayar. Bunun {pct} kadarı önbellekten geldi. Tek seferdeki en büyük istem {peak} idi.', costNote: 'Herkese açık API liste fiyatlarına göre tahmin.', input: 'Girdi', error: 'Hata', result: 'Çıktı', showAll: 'Tümünü göster', play: 'Oynat', pause: 'Duraklat', replay: 'Baştan oynat', theme: 'Temayı değiştir', speed: 'Hız', more: '+{n} tane daha', madeWith: 'Şununla yapıldı:', redacted: 'Paylaşmadan önce kaldırıldı: {list}', untitled: 'Başlıksız oturum', seek: 'Zaman çizelgesi', of: '/', branch: 'dal' },
179
+ es: { you: 'Tú', thinking: 'Pensando', activeTime: 'activo', prompts: ['instrucción', 'instrucciones'], toolCalls: 'llamadas a herramientas', filesChanged: 'archivos cambiados', lines: 'líneas', peak: 'mayor prompt', cost: 'coste', estCost: 'coste API estimado', files: 'Archivos', tools: 'Herramientas', tokens: 'Tokens', output: 'Salida', newInput: 'Entrada nueva', cacheRead: 'Leído de caché', cacheWrite: 'Escrito en caché', requests: 'Peticiones', totalProcessed: 'Total procesado', failed: 'Llamadas fallidas', tokenNote: 'Cada petición reenvía toda la conversación, así que el total cuenta el mismo contexto una y otra vez. El {pct} vino de la caché. El prompt más grande fue de {peak}.', costNote: 'Estimación con precios de lista de la API.', input: 'Entrada', error: 'Error', result: 'Salida', showAll: 'Ver todo', play: 'Reproducir', pause: 'Pausa', replay: 'Reproducir desde el inicio', theme: 'Cambiar tema', speed: 'Velocidad', more: '+{n} más', madeWith: 'Hecho con', redacted: 'Eliminado antes de compartir: {list}', untitled: 'Sesión sin título', seek: 'Línea de tiempo', of: 'de', branch: 'rama' },
180
+ de: { you: 'Du', thinking: 'Denkt nach', activeTime: 'aktiv', prompts: ['Prompt', 'Prompts'], toolCalls: 'Tool-Aufrufe', filesChanged: 'Dateien geändert', lines: 'Zeilen', peak: 'größter Prompt', cost: 'Kosten', estCost: 'geschätzte API-Kosten', files: 'Dateien', tools: 'Tools', tokens: 'Tokens', output: 'Ausgabe', newInput: 'Neue Eingabe', cacheRead: 'Aus Cache gelesen', cacheWrite: 'In Cache geschrieben', requests: 'Anfragen', totalProcessed: 'Insgesamt verarbeitet', failed: 'Fehlgeschlagene Aufrufe', tokenNote: 'Jede Anfrage sendet das ganze Gespräch erneut, daher zählt die Summe denselben Kontext immer wieder. {pct} davon kamen aus dem Cache. Der größte einzelne Prompt hatte {peak}.', costNote: 'Schätzung nach öffentlichen API-Listenpreisen.', input: 'Eingabe', error: 'Fehler', result: 'Ausgabe', showAll: 'Alles zeigen', play: 'Abspielen', pause: 'Pause', replay: 'Von vorn abspielen', theme: 'Design wechseln', speed: 'Tempo', more: '+{n} weitere', madeWith: 'Erstellt mit', redacted: 'Vor dem Teilen entfernt: {list}', untitled: 'Unbenannte Sitzung', seek: 'Zeitleiste', of: 'von', branch: 'Branch' },
181
+ fr: { you: 'Vous', thinking: 'Réflexion', activeTime: 'actif', prompts: ['prompt', 'prompts'], toolCalls: 'appels d’outils', filesChanged: 'fichiers modifiés', lines: 'lignes', peak: 'plus grand prompt', cost: 'coût', estCost: 'coût API estimé', files: 'Fichiers', tools: 'Outils', tokens: 'Tokens', output: 'Sortie', newInput: 'Nouvelle entrée', cacheRead: 'Lu depuis le cache', cacheWrite: 'Écrit en cache', requests: 'Requêtes', totalProcessed: 'Total traité', failed: 'Appels échoués', tokenNote: 'Chaque requête renvoie toute la conversation : le total compte donc le même contexte encore et encore. {pct} provenait du cache. Le plus grand prompt faisait {peak}.', costNote: 'Estimation aux prix publics de l’API.', input: 'Entrée', error: 'Erreur', result: 'Sortie', showAll: 'Tout afficher', play: 'Lire', pause: 'Pause', replay: 'Rejouer depuis le début', theme: 'Changer de thème', speed: 'Vitesse', more: '+{n} autres', madeWith: 'Fait avec', redacted: 'Retiré avant partage : {list}', untitled: 'Session sans titre', seek: 'Chronologie', of: 'sur', branch: 'branche' },
182
+ pt: { you: 'Você', thinking: 'Pensando', activeTime: 'ativo', prompts: ['prompt', 'prompts'], toolCalls: 'chamadas de ferramentas', filesChanged: 'arquivos alterados', lines: 'linhas', peak: 'maior prompt', cost: 'custo', estCost: 'custo de API estimado', files: 'Arquivos', tools: 'Ferramentas', tokens: 'Tokens', output: 'Saída', newInput: 'Entrada nova', cacheRead: 'Lido do cache', cacheWrite: 'Gravado no cache', requests: 'Requisições', totalProcessed: 'Total processado', failed: 'Chamadas com falha', tokenNote: 'Cada requisição reenvia a conversa inteira, então o total conta o mesmo contexto várias vezes. {pct} veio do cache. O maior prompt teve {peak}.', costNote: 'Estimativa com preços públicos da API.', input: 'Entrada', error: 'Erro', result: 'Saída', showAll: 'Mostrar tudo', play: 'Reproduzir', pause: 'Pausar', replay: 'Reproduzir do início', theme: 'Mudar tema', speed: 'Velocidade', more: '+{n} mais', madeWith: 'Feito com', redacted: 'Removido antes de compartilhar: {list}', untitled: 'Sessão sem título', seek: 'Linha do tempo', of: 'de', branch: 'branch' },
183
+ it: { you: 'Tu', thinking: 'Ragionamento', activeTime: 'attivo', prompts: ['prompt', 'prompt'], toolCalls: 'chiamate a strumenti', filesChanged: 'file modificati', lines: 'righe', peak: 'prompt più grande', cost: 'costo', estCost: 'costo API stimato', files: 'File', tools: 'Strumenti', tokens: 'Token', output: 'Output', newInput: 'Input nuovo', cacheRead: 'Letto dalla cache', cacheWrite: 'Scritto in cache', requests: 'Richieste', totalProcessed: 'Totale elaborato', failed: 'Chiamate fallite', tokenNote: 'Ogni richiesta reinvia l’intera conversazione, quindi il totale conta lo stesso contesto più volte. Il {pct} proveniva dalla cache. Il prompt più grande era di {peak}.', costNote: 'Stima ai prezzi di listino dell’API.', input: 'Input', error: 'Errore', result: 'Output', showAll: 'Mostra tutto', play: 'Riproduci', pause: 'Pausa', replay: 'Riproduci dall’inizio', theme: 'Cambia tema', speed: 'Velocità', more: '+{n} altri', madeWith: 'Creato con', redacted: 'Rimosso prima della condivisione: {list}', untitled: 'Sessione senza titolo', seek: 'Timeline', of: 'di', branch: 'branch' },
184
+ ru: { you: 'Вы', thinking: 'Размышление', activeTime: 'активно', prompts: ['запрос', 'запросов'], toolCalls: 'вызовов инструментов', filesChanged: 'файлов изменено', lines: 'строк', peak: 'крупнейший промпт', cost: 'стоимость', estCost: 'оценка стоимости API', files: 'Файлы', tools: 'Инструменты', tokens: 'Токены', output: 'Вывод', newInput: 'Новый ввод', cacheRead: 'Из кэша', cacheWrite: 'Записано в кэш', requests: 'Запросы к API', totalProcessed: 'Всего обработано', failed: 'Неудачные вызовы', tokenNote: 'Каждый запрос заново отправляет весь диалог, поэтому сумма много раз считает один и тот же контекст. {pct} пришло из кэша. Самый большой промпт — {peak}.', costNote: 'Оценка по публичным ценам API.', input: 'Ввод', error: 'Ошибка', result: 'Вывод', showAll: 'Показать всё', play: 'Воспроизвести', pause: 'Пауза', replay: 'С начала', theme: 'Сменить тему', speed: 'Скорость', more: 'ещё {n}', madeWith: 'Сделано с помощью', redacted: 'Удалено перед публикацией: {list}', untitled: 'Сессия без названия', seek: 'Шкала времени', of: 'из', branch: 'ветка' },
185
+ ja: { you: 'あなた', thinking: '思考中', activeTime: '作業時間', prompts: ['プロンプト', 'プロンプト'], toolCalls: 'ツール呼び出し', filesChanged: '変更ファイル', lines: '行', peak: '最大プロンプト', cost: 'コスト', estCost: 'API 推定コスト', files: 'ファイル', tools: 'ツール', tokens: 'トークン', output: '出力', newInput: '新規入力', cacheRead: 'キャッシュ読込', cacheWrite: 'キャッシュ書込', requests: 'リクエスト数', totalProcessed: '処理合計', failed: '失敗した呼び出し', tokenNote: 'リクエストごとに会話全体が再送されるため、合計には同じ文脈が何度も含まれます。そのうち {pct} はキャッシュからでした。1 回あたりの最大プロンプトは {peak} です。', costNote: '公開 API 価格による推定です。', input: '入力', error: 'エラー', result: '出力', showAll: 'すべて表示', play: '再生', pause: '一時停止', replay: '最初から再生', theme: 'テーマ切替', speed: '速度', more: 'ほか {n} 件', madeWith: '作成:', redacted: '共有前に削除:{list}', untitled: '無題のセッション', seek: 'タイムライン', of: '/', branch: 'ブランチ' },
186
+ zh: { you: '你', thinking: '思考中', activeTime: '活跃时长', prompts: ['条提示', '条提示'], toolCalls: '次工具调用', filesChanged: '个文件改动', lines: '行', peak: '最大提示', cost: '费用', estCost: '估算 API 费用', files: '文件', tools: '工具', tokens: 'Token', output: '输出', newInput: '新输入', cacheRead: '缓存读取', cacheWrite: '缓存写入', requests: '请求次数', totalProcessed: '累计处理', failed: '失败的调用', tokenNote: '每次请求都会重新发送整个对话,所以累计值会反复计算同样的上下文。其中 {pct} 来自缓存。单次最大提示为 {peak}。', costNote: '按公开 API 价格估算。', input: '输入', error: '错误', result: '输出', showAll: '显示全部', play: '播放', pause: '暂停', replay: '从头播放', theme: '切换主题', speed: '速度', more: '还有 {n} 个', madeWith: '制作工具:', redacted: '分享前已移除:{list}', untitled: '未命名会话', seek: '时间轴', of: '/', branch: '分支' },
187
+ ko: { you: '나', thinking: '생각 중', activeTime: '작업 시간', prompts: ['프롬프트', '프롬프트'], toolCalls: '도구 호출', filesChanged: '변경된 파일', lines: '줄', peak: '가장 큰 프롬프트', cost: '비용', estCost: '예상 API 비용', files: '파일', tools: '도구', tokens: '토큰', output: '출력', newInput: '새 입력', cacheRead: '캐시 읽기', cacheWrite: '캐시 쓰기', requests: '요청 수', totalProcessed: '총 처리량', failed: '실패한 호출', tokenNote: '요청할 때마다 대화 전체를 다시 보내므로 합계에는 같은 맥락이 여러 번 포함됩니다. 그중 {pct}는 캐시에서 왔습니다. 한 번에 가장 큰 프롬프트는 {peak}였습니다.', costNote: '공개 API 가격 기준 추정치입니다.', input: '입력', error: '오류', result: '출력', showAll: '모두 보기', play: '재생', pause: '일시정지', replay: '처음부터 재생', theme: '테마 전환', speed: '속도', more: '+{n}개 더', madeWith: '제작 도구:', redacted: '공유 전 제거됨: {list}', untitled: '제목 없는 세션', seek: '타임라인', of: '/', branch: '브랜치' },
188
+ };
189
+ const qs = new URLSearchParams(location.search);
190
+ const wanted = [qs.get('lang'), ...(navigator.languages || [navigator.language || 'en'])].filter(Boolean);
191
+ const lang = wanted.map((l) => l.toLowerCase().split('-')[0]).find((l) => I18N[l]) || 'en';
192
+ const L = I18N[lang];
193
+ document.documentElement.lang = lang;
194
+ const tr = (k, vars = {}) => String(L[k] ?? I18N.en[k]).replace(/\{(\w+)\}/g, (_, v) => vars[v] ?? '');
195
+ const plural = (k, n) => { const f = L[k] || I18N.en[k]; return Array.isArray(f) ? f[n === 1 ? 0 : 1] : f; };
196
+ const nf = new Intl.NumberFormat(lang);
197
+ const cf = (() => { try { return new Intl.NumberFormat(lang, { notation: 'compact', maximumFractionDigits: 1 }); } catch { return null; } })();
198
+
199
+ /* ---------- helpers ---------- */
144
200
  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'; };
201
+ const num = (n) => (n >= 1e6 && cf ? cf.format(n) : nf.format(n));
202
+ const dur = (ms) => { const m = Math.round(ms / 60000); if (m < 1) return '<1 min'; if (m < 60) return m + ' min'; return Math.floor(m / 60) + ' h ' + (m % 60) + ' min'; };
203
+ const clock = (ms) => { const s = Math.max(0, Math.round(ms / 1000)); const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), x = s % 60; return (h ? h + ':' + String(m).padStart(2, '0') : String(m).padStart(2, '0')) + ':' + String(x).padStart(2, '0'); };
147
204
  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);
205
+ const shortPath = (p) => { const parts = String(p || '').split(/[\\/]/).filter(Boolean); const name = parts.pop() || ''; const dir = parts.slice(-2).join('/'); return (dir ? `<i>${parts.length > 2 ? '…/' : ''}${esc(dir)}/</i>` : '') + esc(name); };
206
+ const money = (c) => { try { return new Intl.NumberFormat(lang, { style: 'currency', currency: 'USD', maximumFractionDigits: c < 10 ? 2 : 0 }).format(c); } catch { return '$' + c.toFixed(2); } };
207
+ const ICON = {
208
+ play: '<svg viewBox="0 0 16 16"><path d="M4 2.5v11l9-5.5z"/></svg>',
209
+ pause: '<svg viewBox="0 0 16 16"><path d="M4 2.5h3v11H4zM9 2.5h3v11H9z"/></svg>',
210
+ again: '<svg viewBox="0 0 16 16"><path d="M8 2.5a5.5 5.5 0 1 0 5.4 6.5h-1.6A4 4 0 1 1 8 4v2.2L11.2 3.3 8 .5z"/></svg>',
154
211
  };
155
212
 
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>`;
213
+ /* ---------- header ---------- */
214
+ const date = S.start ? new Date(S.start).toLocaleDateString(lang, { year: 'numeric', month: 'short', day: 'numeric' }) : '';
215
+ const meta = [`<b>${esc(D.agent)}</b>`];
216
+ if (D.models.length) meta.push(esc(D.models.join(', ')));
217
+ if (date) meta.push(esc(date));
218
+ if (D.branch && D.branch !== 'HEAD') meta.push(`${esc(tr('branch'))} ${esc(D.branch)}`);
219
+ const figs = [];
220
+ if (!S.timesSynthetic) figs.push([dur(S.activeMs), tr('activeTime')]);
221
+ figs.push([nf.format(S.prompts), plural('prompts', S.prompts)]);
222
+ figs.push([nf.format(S.toolCalls), tr('toolCalls')]);
223
+ figs.push([nf.format(S.files.length), tr('filesChanged')]);
224
+ if (S.linesAdded || S.linesRemoved) figs.push([`<span class="add">+${num(S.linesAdded)}</span> <span class="del">−${num(S.linesRemoved)}</span>`, tr('lines')]);
225
+ if (S.tokens.peakContext) figs.push([num(S.tokens.peakContext), tr('peak')]);
226
+ if (S.cost != null) figs.push([money(S.cost), S.costReported ? tr('cost') : tr('estCost')]);
227
+ $('head').innerHTML = `<div class="meta">${meta.join('<span>·</span>')}</div>
228
+ <h1>${esc(D.title || tr('untitled'))}</h1>
229
+ <div class="figures">${figs.map(([n, l]) => `<div class="fig"><div class="n">${n}</div><div class="l">${esc(l)}</div></div>`).join('')}</div>`;
175
230
 
176
231
  /* ---------- sidebar ---------- */
232
+ const T = S.tokens;
177
233
  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>`;
234
+ const totalIn = T.input + T.cacheRead + T.cacheWrite;
235
+ const pct = totalIn ? Math.round((T.cacheRead / totalIn) * 100) + '%' : '0%';
236
+ let side = '';
237
+ if (S.files.length) side += `<section><h2>${esc(tr('files'))}</h2><ul class="rows">${S.files.slice(0, 20).map((f) =>
238
+ `<li title="${esc(f.file)}"><span class="k file">${shortPath(f.file)}</span><span class="v"><span style="color:var(--add)">+${f.added}</span> <span style="color:var(--del)">−${f.removed}</span></span></li>`).join('')}
239
+ ${S.files.length > 20 ? `<li><span class="k">${esc(tr('more', { n: S.files.length - 20 }))}</span></li>` : ''}</ul></section>`;
240
+ if (S.byTool.length) side += `<section><h2>${esc(tr('tools'))}</h2><ul class="rows">${S.byTool.slice(0, 10).map(([n, c]) =>
241
+ `<li title="${esc(n)}"><span class="k">${esc(n.split(' · ').pop())}</span><span class="v"><span class="bar" style="width:${Math.max(3, (c / maxTool) * 56)}px"></span>${c}</span></li>`).join('')}</ul></section>`;
242
+ if (T.total) side += `<section><h2>${esc(tr('tokens'))}</h2><ul class="rows">
243
+ <li><span class="k">${esc(tr('output'))}</span><span class="v">${nf.format(T.output)}</span></li>
244
+ <li><span class="k">${esc(tr('newInput'))}</span><span class="v">${nf.format(T.input)}</span></li>
245
+ ${T.cacheRead ? `<li><span class="k">${esc(tr('cacheRead'))}</span><span class="v">${nf.format(T.cacheRead)}</span></li>` : ''}
246
+ ${T.cacheWrite ? `<li><span class="k">${esc(tr('cacheWrite'))}</span><span class="v">${nf.format(T.cacheWrite)}</span></li>` : ''}
247
+ ${T.requests ? `<li><span class="k">${esc(tr('requests'))}</span><span class="v">${nf.format(T.requests)}</span></li>` : ''}
248
+ <li class="strong"><span class="k">${esc(tr('totalProcessed'))}</span><span class="v">${nf.format(T.total)}</span></li>
249
+ ${S.errors ? `<li><span class="k">${esc(tr('failed'))}</span><span class="v" style="color:var(--warn)">${S.errors}</span></li>` : ''}
250
+ </ul>${T.requests > 1 && T.peakContext ? `<p class="note">${esc(tr('tokenNote', { pct, peak: num(T.peakContext) }))}</p>` : ''}
251
+ ${S.cost != null && !S.costReported ? `<p class="note">${esc(tr('costNote'))}</p>` : ''}</section>`;
252
+ $('side').innerHTML = side;
194
253
 
195
254
  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>` : ''}`;
255
+ const g = D.generator;
256
+ $('foot').innerHTML = `<span>${esc(tr('madeWith'))} ${g.url ? `<a href="${esc(g.url)}">agentreplay</a>` : 'agentreplay'} ${esc(g.version)}</span>
257
+ ${red.length ? `<span>${esc(tr('redacted', { list: red.map(([k, v]) => `${v} × ${k}`).join(', ') }))}</span>` : ''}`;
199
258
 
200
- /* ---------- tiny markdown ---------- */
259
+ /* ---------- markdown (small, safe) ---------- */
201
260
  function md(src) {
202
- const parts = String(src).split(/```(\w*)\n?([\s\S]*?)```/g);
261
+ const parts = String(src).split(/```[\w+-]*\n?([\s\S]*?)```/g);
203
262
  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>`;
263
+ for (let i = 0; i < parts.length; i++) {
264
+ if (i % 2) { html += `<pre><code>${esc(parts[i].replace(/\n$/, ''))}</code></pre>`; continue; }
265
+ for (const block of parts[i].split(/\n{2,}/)) {
266
+ if (!block.trim()) continue;
267
+ const lines = block.split('\n');
268
+ if (lines.every((l) => /^\s*[-*•] /.test(l))) html += '<ul>' + lines.map((l) => `<li>${inline(l.replace(/^\s*[-*•] /, ''))}</li>`).join('') + '</ul>';
269
+ else if (lines.every((l) => /^\s*\d+[.)] /.test(l))) html += '<ol>' + lines.map((l) => `<li>${inline(l.replace(/^\s*\d+[.)] /, ''))}</li>`).join('') + '</ol>';
270
+ else html += '<p>' + inline(block).replace(/\n/g, '<br>') + '</p>';
271
+ }
207
272
  }
208
273
  return html;
209
274
  }
@@ -226,118 +291,143 @@ footer { text-align: center; color: var(--muted); font-size: 13px; margin-top: 4
226
291
 
227
292
  /* ---------- events ---------- */
228
293
  const E = D.events;
294
+ const t0 = E.length && E[0].t ? E[0].t : 0;
229
295
  function render(e, i) {
230
296
  const el = document.createElement('div');
231
297
  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>` : '';
298
+ const prev = E[i - 1];
299
+ const newTurn = e.kind === 'user' || (prev && prev.kind === 'user');
300
+ const time = !S.timesSynthetic && e.t && t0 ? clock(e.t - t0) : '';
301
+ const gutter = `<div class="t">${time}</div>`;
302
+ if (e.kind === 'user') {
303
+ el.className = 'ev user turn';
304
+ el.innerHTML = `${gutter}<div><div class="who">${esc(tr('you'))}</div><div class="body"></div></div>`;
305
+ el.querySelector('.body').textContent = e.text;
306
+ } else if (e.kind === 'assistant') {
307
+ el.className = 'ev say' + (newTurn ? ' turn' : '');
308
+ el.innerHTML = `${gutter}<div>${newTurn ? `<div class="who">${esc(D.agent)}</div>` : ''}<div class="body">${md(e.text)}</div></div>`;
309
+ } else if (e.kind === 'thinking') {
310
+ el.className = 'ev think' + (newTurn ? ' turn' : '');
311
+ el.innerHTML = `${gutter}<div>${newTurn ? `<div class="who">${esc(D.agent)}</div>` : ''}<div class="body" title="${esc(tr('thinking'))}"></div></div>`;
312
+ el.querySelector('.body').textContent = e.text;
313
+ el.querySelector('.body').onclick = () => el.classList.toggle('open');
314
+ } else {
315
+ el.className = 'ev tool' + (e.isError ? ' err' : '') + (newTurn ? ' turn' : '');
316
+ const lines = e.lines ? `<span class="dl"><span class="a">+${e.lines.added}</span> <span class="d">−${e.lines.removed}</span></span>` : '';
238
317
  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');
318
+ const name = String(e.name).split(' · ').pop();
319
+ el.innerHTML = `${gutter}<div>${newTurn ? `<div class="who">${esc(D.agent)}</div>` : ''}
320
+ <div class="line" role="button" tabindex="0" aria-expanded="false"><span class="g">${e.isError ? '✕' : '✓'}</span><span class="nm" title="${esc(e.name)}">${esc(name)}</span><span class="sum" title="${esc(e.summary)}">${esc(sum)}</span>${lines}</div>
321
+ <div class="detail">${e.diff ? (e.file ? `<div class="path">${esc(e.file)}</div>` : '') + diffHtml(e.diff) : ''}
322
+ ${e.input ? `<div class="lbl">${esc(tr('input'))}</div><pre>${esc(e.input)}</pre>` : ''}
323
+ ${e.output ? `<div class="lbl">${esc(e.isError ? tr('error') : tr('result'))}</div><pre>${esc(e.output)}</pre>` : ''}</div></div>`;
324
+ const line = el.querySelector('.line');
325
+ const toggle = () => { el.classList.toggle('open'); line.setAttribute('aria-expanded', el.classList.contains('open')); };
326
+ line.onclick = toggle;
327
+ line.onkeydown = (ev) => { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); toggle(); } };
328
+ if (e.isError || (e.diff && e.lines && e.lines.added + e.lines.removed <= 40)) { el.classList.add('open'); line.setAttribute('aria-expanded', 'true'); }
245
329
  }
246
330
  return el;
247
331
  }
248
332
 
249
333
  /* ---------- 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
334
  const sched = [];
253
335
  let acc = 0;
254
336
  for (let i = 0; i < E.length; i++) {
255
337
  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;
338
+ const p = E[i - 1];
339
+ const gap = E[i].t && p.t ? Math.max(0, E[i].t - p.t) : 800;
340
+ const read = p.kind === 'user' || p.kind === 'assistant' ? Math.min(3000, (p.text || '').length * 12) : 0;
259
341
  acc += Math.min(2500, Math.max(350, gap / 4)) + read;
260
342
  }
261
343
  sched.push(acc);
262
344
  }
263
345
  const total = acc + 1200;
264
346
 
265
- // Markers on the track
266
347
  const track = $('track');
267
348
  E.forEach((e, i) => {
268
349
  const cls = e.kind === 'user' ? 'u' : e.isError ? 'x' : e.diff ? 'e' : null;
269
350
  if (!cls) return;
270
351
  const m = document.createElement('div');
271
352
  m.className = 'mk ' + cls;
272
- m.style.left = (sched[i] / total * 100) + '%';
353
+ m.style.left = (sched[i] / total) * 100 + '%';
273
354
  track.appendChild(m);
274
355
  });
275
356
 
276
357
  /* ---------- player ---------- */
277
- const feed = $('feed');
278
- let shown = 0, clock = 0, playing = false, last = 0, speed = 1;
358
+ const log = $('log');
359
+ let shown = 0, at = 0, playing = false, last = 0, speed = 1;
360
+ const SPEEDS = [0.5, 1, 2, 4, 10];
279
361
 
280
362
  function showUpTo(n, animate) {
281
363
  n = Math.max(0, Math.min(E.length, n));
282
- if (n < shown) { feed.innerHTML = ''; shown = 0; }
364
+ if (n < shown) { log.innerHTML = ''; shown = 0; }
283
365
  const frag = document.createDocumentFragment();
284
366
  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
- }
367
+ while (shown < n) { lastEl = render(E[shown], shown); if (animate) lastEl.classList.add('new'); frag.appendChild(lastEl); shown++; }
368
+ if (lastEl) { log.appendChild(frag); if (animate) lastEl.scrollIntoView({ behavior: 'smooth', block: 'end' }); }
290
369
  }
291
370
  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');
371
+ const p = Math.min(1, at / total);
372
+ $('fill').style.width = p * 100 + '%';
373
+ $('phead').style.left = p * 100 + '%';
374
+ $('count').textContent = `${shown} ${tr('of')} ${E.length}`;
375
+ const done = shown >= E.length && !playing;
376
+ $('play').innerHTML = playing ? ICON.pause : done ? ICON.again : ICON.play;
377
+ $('play').setAttribute('aria-label', playing ? tr('pause') : done ? tr('replay') : tr('play'));
378
+ $('play').title = $('play').getAttribute('aria-label');
297
379
  }
298
380
  function tick(now) {
299
381
  if (!playing) return;
300
- clock += (now - last) * speed; last = now;
382
+ at += (now - last) * speed; last = now;
301
383
  let n = shown;
302
- while (n < E.length && sched[n] <= clock) n++;
384
+ while (n < E.length && sched[n] <= at) n++;
303
385
  if (n !== shown) showUpTo(n, true);
304
- if (shown >= E.length && clock >= total) { playing = false; }
386
+ if (shown >= E.length && at >= total) playing = false;
305
387
  ui();
306
388
  if (playing) requestAnimationFrame(tick);
307
389
  }
308
- function play() {
309
- if (shown >= E.length) { clock = 0; showUpTo(0); }
310
- playing = true; last = performance.now(); requestAnimationFrame(tick); ui();
311
- }
390
+ function play() { if (shown >= E.length) { at = 0; showUpTo(0); } playing = true; last = performance.now(); requestAnimationFrame(tick); ui(); }
312
391
  function pause() { playing = false; ui(); }
313
392
  function seekTo(n) {
314
393
  pause();
315
394
  showUpTo(n, false);
316
- clock = n > 0 ? sched[n - 1] : 0;
395
+ at = n > 0 ? sched[n - 1] : 0;
317
396
  const el = $('e' + (n - 1));
318
397
  if (el) el.scrollIntoView({ block: 'center' });
319
398
  ui();
320
399
  }
321
400
 
322
401
  $('play').onclick = () => (playing ? pause() : play());
323
- $('speed').onchange = (ev) => { speed = Number(ev.target.value); };
324
- $('all').onclick = () => { seekTo(E.length); clock = total; ui(); };
402
+ $('all').textContent = tr('showAll');
403
+ $('all').onclick = () => { seekTo(E.length); at = total; ui(); };
404
+ $('speeds').setAttribute('aria-label', tr('speed'));
405
+ $('speeds').innerHTML = SPEEDS.map((s) => `<button aria-pressed="${s === 1}" data-s="${s}">${s}×</button>`).join('');
406
+ $('speeds').onclick = (ev) => {
407
+ const b = ev.target.closest('button');
408
+ if (!b) return;
409
+ const narrow = matchMedia('(max-width: 700px)').matches;
410
+ speed = narrow && b.getAttribute('aria-pressed') === 'true' ? SPEEDS[(SPEEDS.indexOf(speed) + 1) % SPEEDS.length] : Number(b.dataset.s);
411
+ for (const x of $('speeds').children) x.setAttribute('aria-pressed', Number(x.dataset.s) === speed);
412
+ };
413
+ $('theme').setAttribute('aria-label', tr('theme'));
414
+ $('theme').title = tr('theme');
325
415
  $('theme').onclick = () => {
326
416
  const r = document.documentElement;
327
417
  const dark = r.dataset.theme ? r.dataset.theme === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
328
418
  r.dataset.theme = dark ? 'light' : 'dark';
329
419
  try { localStorage.setItem('agentreplay-theme', r.dataset.theme); } catch {}
330
420
  };
331
- try { const t = localStorage.getItem('agentreplay-theme'); if (t) document.documentElement.dataset.theme = t; } catch {}
421
+ try { const th = localStorage.getItem('agentreplay-theme'); if (th) document.documentElement.dataset.theme = th; } catch {}
332
422
 
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
- };
423
+ track.setAttribute('role', 'slider');
424
+ track.setAttribute('aria-label', tr('seek'));
425
+ track.tabIndex = 0;
426
+ const seekAt = (x) => { const r = track.getBoundingClientRect(); const target = ((x - r.left) / r.width) * total; let n = 0; while (n < E.length && sched[n] <= target) n++; seekTo(n); };
427
+ track.onpointerdown = (ev) => { seekAt(ev.clientX); track.setPointerCapture(ev.pointerId); track.onpointermove = (m) => seekAt(m.clientX); };
428
+ track.onpointerup = () => { track.onpointermove = null; };
339
429
  document.addEventListener('keydown', (ev) => {
340
- if (ev.target.tagName === 'SELECT') return;
430
+ if (ev.target.closest && ev.target.closest('.line')) return;
341
431
  if (ev.code === 'Space') { ev.preventDefault(); playing ? pause() : play(); }
342
432
  else if (ev.key === 'ArrowRight') seekTo(shown + 1);
343
433
  else if (ev.key === 'ArrowLeft') seekTo(shown - 1);
@@ -345,11 +435,11 @@ footer { text-align: center; color: var(--muted); font-size: 13px; margin-top: 4
345
435
  else if (ev.key === 'Home') seekTo(0);
346
436
  });
347
437
 
348
- // Deep link: #e42 opens the replay at event 42. ?static shows everything at once.
438
+ // #e42 opens at event 42; ?static shows everything at once.
349
439
  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); }
440
+ if (m) seekTo(Number(m[1]) + 1);
441
+ else if (qs.has('static')) $('all').click();
442
+ else { showUpTo(1, false); at = sched[0]; ui(); setTimeout(play, 700); }
353
443
  })();
354
444
  </script>
355
445
  </body>
package/src/util.js CHANGED
@@ -107,6 +107,19 @@ export function addUsage(session, model, u) {
107
107
  session.usage[k] += v;
108
108
  per[k] += v;
109
109
  }
110
+ trackRequest(session, u);
111
+ }
112
+
113
+ /**
114
+ * One API request: count it and remember the biggest prompt. Agents re-send the
115
+ * whole conversation on every request, so summed tokens grow quadratically —
116
+ * the peak prompt is the honest "how big was this conversation" number.
117
+ */
118
+ export function trackRequest(session, u) {
119
+ const ctx = (Number(u.input) || 0) + (Number(u.cacheRead) || 0) + (Number(u.cacheWrite) || 0) + (Number(u.cacheWrite1h) || 0);
120
+ if (!ctx && !u.output) return;
121
+ session.requests = (session.requests || 0) + 1;
122
+ session.peakContext = Math.max(session.peakContext || 0, ctx);
110
123
  }
111
124
 
112
125
  /** Codex / OpenAI apply_patch envelope → diff hunks. */