k0ntrol-cli 0.1.0__py3-none-any.whl

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.
Files changed (80) hide show
  1. k0ntrol/__init__.py +1 -0
  2. k0ntrol/agents.py +998 -0
  3. k0ntrol/cli.py +190 -0
  4. k0ntrol/config.py +330 -0
  5. k0ntrol/credentials.py +78 -0
  6. k0ntrol/defaults/config.yaml +23 -0
  7. k0ntrol/events.py +838 -0
  8. k0ntrol/frontends/__init__.py +1 -0
  9. k0ntrol/frontends/ask.py +218 -0
  10. k0ntrol/frontends/badges.py +228 -0
  11. k0ntrol/frontends/banner.py +128 -0
  12. k0ntrol/frontends/diffview.py +174 -0
  13. k0ntrol/frontends/editor.py +701 -0
  14. k0ntrol/frontends/klog.html +740 -0
  15. k0ntrol/frontends/klog.py +403 -0
  16. k0ntrol/frontends/logo.py +12 -0
  17. k0ntrol/frontends/mentions.py +29 -0
  18. k0ntrol/frontends/prompt.py +340 -0
  19. k0ntrol/frontends/render.py +485 -0
  20. k0ntrol/frontends/session.py +717 -0
  21. k0ntrol/frontends/setup.py +442 -0
  22. k0ntrol/frontends/terminal.py +396 -0
  23. k0ntrol/frontends/theme.py +24 -0
  24. k0ntrol/helpers.py +108 -0
  25. k0ntrol/init_flow.py +362 -0
  26. k0ntrol/langfuse.py +173 -0
  27. k0ntrol/memory/__init__.py +0 -0
  28. k0ntrol/memory/index.py +235 -0
  29. k0ntrol/memory/layout.py +66 -0
  30. k0ntrol/memory/python_extract.py +189 -0
  31. k0ntrol/memory/reflect.py +366 -0
  32. k0ntrol/memory/refresh.py +21 -0
  33. k0ntrol/memory/scan.py +538 -0
  34. k0ntrol/memory/session.py +145 -0
  35. k0ntrol/otel.py +429 -0
  36. k0ntrol/pricing.py +29 -0
  37. k0ntrol/prompts/chatty.md +17 -0
  38. k0ntrol/prompts/implementer.md +14 -0
  39. k0ntrol/prompts/planner.md +42 -0
  40. k0ntrol/prompts/researcher.md +20 -0
  41. k0ntrol/prompts/reviewer.md +34 -0
  42. k0ntrol/providers.py +718 -0
  43. k0ntrol/search.py +133 -0
  44. k0ntrol/tools/__init__.py +0 -0
  45. k0ntrol/tools/bulk_read.py +93 -0
  46. k0ntrol/tools/errors.py +50 -0
  47. k0ntrol/tools/fetch_url.py +212 -0
  48. k0ntrol/tools/net.py +317 -0
  49. k0ntrol/tools/path_guard.py +45 -0
  50. k0ntrol/tools/read.py +174 -0
  51. k0ntrol/tools/run_tests.py +66 -0
  52. k0ntrol/tools/runner.py +177 -0
  53. k0ntrol/tools/search_memory.py +32 -0
  54. k0ntrol/tools/slice_guard.py +166 -0
  55. k0ntrol/tools/slice_journal.py +481 -0
  56. k0ntrol/tools/tracker.py +115 -0
  57. k0ntrol/tools/web_search.py +199 -0
  58. k0ntrol/tools/write.py +123 -0
  59. k0ntrol/tracker/__init__.py +31 -0
  60. k0ntrol/tracker/github.py +371 -0
  61. k0ntrol/tracker/local_files.py +241 -0
  62. k0ntrol/tracker/protocol.py +210 -0
  63. k0ntrol/workflow/__init__.py +29 -0
  64. k0ntrol/workflow/change.py +605 -0
  65. k0ntrol/workflow/ci_gate.py +96 -0
  66. k0ntrol/workflow/context.py +137 -0
  67. k0ntrol/workflow/implement.py +1150 -0
  68. k0ntrol/workflow/nodes.py +331 -0
  69. k0ntrol/workflow/plan.py +675 -0
  70. k0ntrol/workflow/qa.py +98 -0
  71. k0ntrol/workflow/research.py +533 -0
  72. k0ntrol/workflow/routers.py +273 -0
  73. k0ntrol/workflow/run.py +1165 -0
  74. k0ntrol/workflow/state.py +146 -0
  75. k0ntrol/workflow/triage.py +269 -0
  76. k0ntrol_cli-0.1.0.dist-info/METADATA +154 -0
  77. k0ntrol_cli-0.1.0.dist-info/RECORD +80 -0
  78. k0ntrol_cli-0.1.0.dist-info/WHEEL +4 -0
  79. k0ntrol_cli-0.1.0.dist-info/entry_points.txt +2 -0
  80. k0ntrol_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,740 @@
1
+ <!doctype html>
2
+ <html lang="en" data-theme="dark">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="color-scheme" content="dark light">
7
+ <title>k0 klog</title>
8
+ <script>
9
+ // Dark unless the viewer switched to light before; set before first paint.
10
+ try { if (localStorage.getItem("k0-klog-theme") === "light") document.documentElement.dataset.theme = "light"; } catch (_) { /* storage blocked */ }
11
+ </script>
12
+ <style>
13
+ /* Palette: the terminal theme (frontends/theme.py). Dark is the default;
14
+ light uses darker shades of the same hues so text keeps its contrast. */
15
+ :root, [data-theme="dark"] {
16
+ color-scheme: dark;
17
+ --bg: #0d0f14; --panel: #151820; --raise: #1c2029; --text: #e5e7eb; --dim: #9ca3af; --border: #2a2f3a;
18
+ --accent: #a78bfa; --brand: #5eead4; --ok: #4ade80; --error: #f87171; --warn: #fbbf24;
19
+ --s1: #a78bfa; --s2: #5eead4; --s3: #fbbf24; --s4: #60a5fa; --s5: #f472b6; --s6: #6b7280;
20
+ }
21
+ [data-theme="light"] {
22
+ color-scheme: light;
23
+ --bg: #ffffff; --panel: #f6f7f9; --raise: #eceef2; --text: #111827; --dim: #5b6472; --border: #d9dde3;
24
+ --accent: #6d28d9; --brand: #0f766e; --ok: #15803d; --error: #b91c1c; --warn: #b45309;
25
+ --s1: #7c3aed; --s2: #0d9488; --s3: #d97706; --s4: #2563eb; --s5: #db2777; --s6: #9ca3af;
26
+ }
27
+ :root {
28
+ --font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
29
+ --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
30
+ }
31
+ * { box-sizing: border-box; }
32
+ html { scrollbar-color: var(--border) var(--bg); }
33
+ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.45 var(--font); caret-color: var(--accent); }
34
+ ::selection { background: color-mix(in srgb, var(--accent) 35%, transparent); }
35
+ main { max-width: 1200px; margin: 0 auto; padding: 20px 16px 48px; }
36
+ header { display: flex; align-items: center; gap: 12px; }
37
+ header .title { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 14px; min-width: 0; flex: 1; }
38
+ h1 { margin: 0; font-size: 20px; color: var(--brand); font-family: var(--mono); letter-spacing: -0.01em; }
39
+ .dim { color: var(--dim); }
40
+ .icon-button { display: inline-grid; place-items: center; width: 34px; height: 34px; flex: none; border-radius: 8px;
41
+ background: var(--panel); border: 1px solid var(--border); color: var(--dim); cursor: pointer; }
42
+ .icon-button:hover { color: var(--text); background: var(--raise); }
43
+ .icon-button svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; }
44
+ [data-theme="dark"] .when-light, [data-theme="light"] .when-dark { display: none; }
45
+
46
+ /* totals: one strip, cells divided by rules */
47
+ .totals { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 18px 0 20px;
48
+ border: 1px solid var(--border); border-radius: 8px; background: var(--panel); overflow: hidden; }
49
+ .total { padding: 10px 14px; border-left: 1px solid var(--border); margin-left: -1px; }
50
+ .total b { display: block; font-size: 20px; font-weight: 600; font-variant-numeric: tabular-nums; }
51
+ .total span { display: block; color: var(--dim); font-size: 12px; }
52
+ .total small { display: block; color: var(--dim); font-size: 11px; margin-top: 2px; }
53
+
54
+ nav { display: flex; gap: 2px; border-bottom: 1px solid var(--border); margin-bottom: 16px; overflow-x: auto; }
55
+ nav button { background: none; border: 0; border-bottom: 2px solid transparent; color: var(--dim);
56
+ font: inherit; padding: 8px 14px; cursor: pointer; white-space: nowrap; }
57
+ nav button:hover { color: var(--text); }
58
+ nav button[aria-selected="true"] { color: var(--accent); border-bottom-color: var(--accent); }
59
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
60
+ tr:focus-visible { outline-offset: -2px; }
61
+ input[type="checkbox"] { accent-color: var(--accent); }
62
+
63
+ .scroll { overflow-x: auto; }
64
+ table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
65
+ th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid var(--border); white-space: nowrap; }
66
+ th { color: var(--dim); font-weight: 500; font-size: 12px; }
67
+ td.num, th.num { text-align: right; }
68
+ tr.row { cursor: pointer; }
69
+ tr.row:hover { background: var(--panel); }
70
+ td.clip { max-width: 160px; overflow: hidden; text-overflow: ellipsis; }
71
+ td.wrap { white-space: normal; word-break: break-word; min-width: 240px; }
72
+ .mono { font-family: var(--mono); font-size: 12px; }
73
+ .fail { color: var(--error); }
74
+ .denied { color: var(--warn); }
75
+ .good { color: var(--ok); }
76
+ tr.fail td:first-child { box-shadow: inset 2px 0 var(--error); }
77
+ tr.denied td:first-child { box-shadow: inset 2px 0 var(--warn); }
78
+ .badge { font-family: var(--mono); font-size: 11px; padding: 1px 6px; border: 1px solid var(--border); border-radius: 4px; color: var(--dim); }
79
+ .timeline { background: var(--panel); }
80
+ .timeline td { border-bottom-color: transparent; padding: 3px 10px; }
81
+ pre { margin: 0; white-space: pre-wrap; word-break: break-all; font: 12px/1.4 var(--mono); }
82
+ .filters { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; margin-bottom: 12px; }
83
+ .filters label { display: flex; gap: 6px; align-items: center; color: var(--dim); }
84
+ select, input[type="search"] { background: var(--panel); color: var(--text); border: 1px solid var(--border);
85
+ border-radius: 6px; padding: 5px 8px; font: inherit; min-width: 0; }
86
+ .more { margin: 12px 0; background: var(--panel); color: var(--text); border: 1px solid var(--border);
87
+ border-radius: 6px; padding: 6px 12px; font: inherit; cursor: pointer; }
88
+ .more:hover { background: var(--raise); }
89
+ .empty { color: var(--dim); margin: 0; padding: 20px 0; }
90
+
91
+ /* charts */
92
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 440px), 1fr)); gap: 14px; }
93
+ .card { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 14px 14px 12px; min-width: 0; }
94
+ .card h2 { margin: 0 0 8px; font-size: 13px; font-weight: 600; }
95
+ .legend { display: flex; flex-wrap: wrap; gap: 4px 14px; color: var(--dim); font-size: 12px; margin-bottom: 8px; }
96
+ .sw { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 5px; vertical-align: -1px; }
97
+ .sw.line { width: 14px; height: 0; border-radius: 0; background: none; border-top: 1.5px dashed var(--text); opacity: .75; vertical-align: 3px; }
98
+ .note { color: var(--dim); font-size: 12px; margin: 8px 0 0; }
99
+ .chart { width: 100%; min-width: 0; }
100
+ svg.plot { display: block; overflow: visible; }
101
+ svg text { fill: var(--text); font: 11px var(--font); }
102
+ svg .lbl, svg .tick { fill: var(--dim); }
103
+ svg .val { font-family: var(--mono); }
104
+ svg .gridline { stroke: var(--border); stroke-width: 1; }
105
+ svg .track { fill: var(--dim); opacity: .3; }
106
+ svg .avg { fill: none; stroke: var(--text); stroke-width: 1.5; stroke-dasharray: 4 3; opacity: .75; }
107
+ svg .area { fill: color-mix(in srgb, var(--accent) 22%, transparent); stroke: var(--accent); stroke-width: 1.75; }
108
+ svg .hit { fill: transparent; }
109
+ svg .day.on .hit { fill: var(--text); opacity: .06; }
110
+ .c-accent { fill: var(--accent); background: var(--accent); }
111
+ .c-brand { fill: var(--brand); background: var(--brand); }
112
+ .c-ok { fill: var(--ok); background: var(--ok); }
113
+ .c-error { fill: var(--error); background: var(--error); }
114
+ .c-warn { fill: var(--warn); background: var(--warn); }
115
+ .c-track { fill: var(--dim); background: var(--dim); opacity: .35; }
116
+ .s1 { fill: var(--s1); background: var(--s1); } .s2 { fill: var(--s2); background: var(--s2); }
117
+ .s3 { fill: var(--s3); background: var(--s3); } .s4 { fill: var(--s4); background: var(--s4); }
118
+ .s5 { fill: var(--s5); background: var(--s5); } .s6 { fill: var(--s6); background: var(--s6); }
119
+
120
+ /* spend board */
121
+ .spend-head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 14px; }
122
+ .spend-head h2 { margin: 0; font-size: 15px; font-weight: 600; }
123
+ .segmented { display: inline-flex; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: var(--panel); }
124
+ .segmented button { background: none; border: 0; color: var(--dim); font: inherit; font-size: 13px; padding: 5px 12px; cursor: pointer; }
125
+ .segmented button + button { border-left: 1px solid var(--border); }
126
+ .segmented button:hover { color: var(--text); }
127
+ .segmented button[aria-pressed="true"] { background: var(--raise); color: var(--text); }
128
+ .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 14px 24px; margin-bottom: 18px; }
129
+ .kpi > span { display: block; color: var(--dim); font-size: 12px; }
130
+ .kpi b { display: block; font-size: 24px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; }
131
+ .kpi small { display: block; font-size: 12px; color: var(--dim); }
132
+ .up { color: var(--warn); }
133
+ .down { color: var(--ok); }
134
+ .readout { display: flex; flex-wrap: wrap; gap: 2px 14px; align-items: baseline; min-height: 20px; font-size: 12px; color: var(--dim); margin-bottom: 6px; }
135
+ .readout b { color: var(--text); font-size: 13px; font-variant-numeric: tabular-nums; }
136
+ .spend-trend { margin-bottom: 14px; }
137
+ .wide { grid-column: 1 / -1; }
138
+ </style>
139
+ </head>
140
+ <body>
141
+ <main>
142
+ <header>
143
+ <div class="title">
144
+ <h1>k0 klog</h1>
145
+ <span class="dim" id="generated"></span>
146
+ </div>
147
+ <button class="icon-button" id="theme-toggle" type="button">
148
+ <svg class="when-dark" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>
149
+ <svg class="when-light" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/></svg>
150
+ </button>
151
+ </header>
152
+ <section class="totals" id="stats" aria-label="Totals"></section>
153
+ <nav role="tablist" aria-label="Views">
154
+ <button role="tab" data-tab="runs">Runs</button>
155
+ <button role="tab" data-tab="spend">Spend</button>
156
+ <button role="tab" data-tab="log">Log</button>
157
+ <button role="tab" data-tab="analytics">Analytics</button>
158
+ </nav>
159
+ <section id="runs" role="tabpanel"></section>
160
+ <section id="spend" role="tabpanel" hidden></section>
161
+ <section id="log" role="tabpanel" hidden>
162
+ <div class="filters">
163
+ <label>Kind <select id="f-kind"></select></label>
164
+ <label>Agent / helper <select id="f-who"></select></label>
165
+ <label>Run <input type="search" id="f-run" placeholder="run or chat id" size="22"></label>
166
+ <label><input type="checkbox" id="f-fail"> Failures only</label>
167
+ <span class="dim" id="f-count"></span>
168
+ </div>
169
+ <div class="scroll" id="log-table"></div>
170
+ </section>
171
+ <section id="analytics" role="tabpanel" hidden></section>
172
+ </main>
173
+ <script type="application/json" id="k0-data">__K0_DATA__</script>
174
+ <script>
175
+ "use strict";
176
+ const DATA = JSON.parse(document.getElementById("k0-data").textContent);
177
+ const TOTALS = DATA.analytics.totals;
178
+ const PAGE = { runs: 100, log: 500 };
179
+ const limits = { runs: PAGE.runs, log: PAGE.log };
180
+ const open = new Set();
181
+
182
+ const $ = (selector) => document.querySelector(selector);
183
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g,
184
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
185
+ const clip = (text, max) => (String(text).length > max ? String(text).slice(0, max - 1) + "…" : String(text));
186
+ const sum = (list) => list.reduce((a, b) => a + b, 0);
187
+
188
+ function fmtCost(value, estimated) {
189
+ if (value == null) return "–";
190
+ const text = value < 0.01 && value > 0 ? value.toFixed(4) : value.toFixed(2);
191
+ return (estimated ? "~" : "") + "$" + text;
192
+ }
193
+ function fmtCount(value) {
194
+ if (value >= 1e6) return (value / 1e6).toFixed(1) + "M";
195
+ if (value >= 1e4) return Math.round(value / 1e3) + "k";
196
+ if (value >= 1e3) return (value / 1e3).toFixed(1) + "k";
197
+ return String(value);
198
+ }
199
+ function fmtMs(ms) {
200
+ if (ms == null) return "–";
201
+ if (ms < 1000) return Math.round(ms) + "ms";
202
+ if (ms < 60000) return (ms / 1000).toFixed(1) + "s";
203
+ return Math.floor(ms / 60000) + "m " + String(Math.round((ms % 60000) / 1000)).padStart(2, "0") + "s";
204
+ }
205
+ // "Nov 9 14:03", for tight tables.
206
+ function fmtShort(ts) {
207
+ const date = new Date(ts);
208
+ if (!ts || isNaN(date)) return ts || "–";
209
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" }) + " " + date.toLocaleTimeString([], { hour12: false, hour: "2-digit", minute: "2-digit" });
210
+ }
211
+ function fmtTime(ts, withMs) {
212
+ const date = new Date(ts);
213
+ if (!ts || isNaN(date)) return ts || "–";
214
+ const day = date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
215
+ const time = date.toLocaleTimeString([], { hour12: false });
216
+ return day + " " + time + (withMs ? "." + String(date.getMilliseconds()).padStart(3, "0") : "");
217
+ }
218
+ // "2026-11-09" (UTC day) -> "Nov 9"
219
+ const fmtDay = (day) => new Date(day + "T00:00:00Z").toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" });
220
+ const pct = (part, whole) => (whole > 0 ? Math.round((part / whole) * 100) + "%" : "–");
221
+
222
+ // -- theme -------------------------------------------------------------------
223
+
224
+ function syncThemeButton() {
225
+ const light = document.documentElement.dataset.theme === "light";
226
+ const label = light ? "Switch to dark theme" : "Switch to light theme";
227
+ const button = $("#theme-toggle");
228
+ button.setAttribute("aria-label", label);
229
+ button.title = label;
230
+ }
231
+ function toggleTheme() {
232
+ const next = document.documentElement.dataset.theme === "light" ? "dark" : "light";
233
+ document.documentElement.dataset.theme = next;
234
+ try { localStorage.setItem("k0-klog-theme", next); } catch (_) { /* storage blocked */ }
235
+ syncThemeButton();
236
+ }
237
+
238
+ // -- totals ------------------------------------------------------------------
239
+
240
+ function renderTotals() {
241
+ const t = TOTALS;
242
+ const costNote = [t.cost_estimated ? "estimated from list prices" : "", t.unpriced_calls ? t.unpriced_calls + " calls unpriced" : ""]
243
+ .filter(Boolean).join(" · ") || "logged by the provider";
244
+ const stats = [
245
+ [t.runs + t.chats, "runs and chats", t.runs + " runs · " + t.chats + " chats"],
246
+ [fmtCount(t.model_calls), "model calls", ""],
247
+ [fmtCount(t.tokens_in) + " / " + fmtCount(t.tokens_out), "tokens in / out", ""],
248
+ [fmtCost(t.cost, t.cost_estimated), "spend", costNote],
249
+ [t.failures, "failures", t.denials + " expected denials"],
250
+ ];
251
+ $("#stats").innerHTML = stats.map(([value, label, note]) =>
252
+ `<div class="total"><b>${esc(value)}</b><span>${esc(label)}</span>${note ? `<small>${esc(note)}</small>` : ""}</div>`).join("");
253
+ $("#generated").textContent = "updated " + fmtTime(DATA.generated) + " · run /klog again to refresh";
254
+ }
255
+
256
+ // -- one event, in words -----------------------------------------------------
257
+
258
+ function who(e) { return e.agent || e.helper || ""; }
259
+
260
+ function detail(e) {
261
+ const parts = [];
262
+ if (e.kind === "model") {
263
+ parts.push(who(e) + (e.helper && !e.agent ? " (helper)" : ""), e.model || "");
264
+ if (e.attempt > 1) parts.push("attempt " + e.attempt);
265
+ if (e.tokens_in != null || e.tokens_out != null) parts.push((e.tokens_in ?? 0) + " → " + (e.tokens_out ?? 0) + " tok");
266
+ if (e.cost != null) parts.push(fmtCost(e.cost, e.estimated));
267
+ } else if (e.kind === "tool") {
268
+ parts.push(e.tool || "", e.path || "");
269
+ if (e.denied) parts.push("denied: " + e.denied);
270
+ } else if (e.kind === "gate") {
271
+ parts.push(e.gate + " → " + e.result);
272
+ if (e.redo && e.redo.length) parts.push("redo " + e.redo.join(", "));
273
+ } else if (e.kind === "run_start") {
274
+ parts.push(e.run_kind || "", e.work_item || "", e.branch || "");
275
+ if (e.resumed) parts.push("resumed");
276
+ if (e.session) parts.push("session " + e.session);
277
+ } else if (e.kind === "run_end") {
278
+ parts.push(e.outcome || "");
279
+ if (e.reason) parts.push(e.reason);
280
+ if (e.node) parts.push("at " + e.node);
281
+ } else {
282
+ parts.push(JSON.stringify(e));
283
+ }
284
+ if (e.err) parts.push(e.err);
285
+ return parts.filter(Boolean).join(" · ");
286
+ }
287
+
288
+ const flagClass = (e) => e.flag || "";
289
+ const eventsById = (() => {
290
+ const map = new Map();
291
+ for (const e of DATA.events) {
292
+ const id = e.run || e.chat;
293
+ if (id) (map.get(id) || map.set(id, []).get(id)).push(e);
294
+ }
295
+ return map;
296
+ })();
297
+
298
+ // -- Runs ----------------------------------------------------------------------
299
+
300
+ function timeline(run) {
301
+ const events = eventsById.get(run.id) || [];
302
+ const origin = Date.parse(events[0] && events[0].ts);
303
+ const rows = events.map((e) => {
304
+ const offset = Date.parse(e.ts) - origin;
305
+ return `<tr class="${flagClass(e)}"><td class="mono dim">${isNaN(offset) ? "" : "+" + fmtMs(offset)}</td>
306
+ <td><span class="badge">${esc(e.kind)}</span></td>
307
+ <td class="wrap ${flagClass(e)}">${esc(detail(e))}</td>
308
+ <td class="num mono dim">${e.ms != null ? fmtMs(e.ms) : ""}</td></tr>`;
309
+ });
310
+ return `<tr class="timeline"><td colspan="12"><div class="scroll"><table>${rows.join("")}</table></div></td></tr>`;
311
+ }
312
+
313
+ function runRow(run, withSession) {
314
+ const outcome = run.outcome || "–";
315
+ const outcomeClass = run.outcome === "done" ? "good" : run.flagged ? "fail" : "dim";
316
+ const isOpen = open.has(run.id);
317
+ const head = `<tr class="row ${run.flagged ? "fail" : ""}" tabindex="0" data-run="${esc(run.id)}" aria-expanded="${isOpen}">
318
+ <td>${esc(fmtTime(run.start))}</td>
319
+ <td><span class="badge">${esc(run.kind)}</span></td>
320
+ <td class="clip" title="${esc(run.work_item || "")}">${esc(run.work_item || "–")}</td>
321
+ <td class="clip mono" title="${esc(run.branch || "")}">${esc(run.branch || "–")}</td>
322
+ ${withSession ? `<td class="clip mono" title="${esc(run.session || "")}">${esc(run.session || "–")}</td>` : ""}
323
+ <td class="num">${fmtMs(run.duration_ms)}</td>
324
+ <td class="${outcomeClass}">${esc(outcome)}</td>
325
+ <td class="num">${run.model_calls}</td>
326
+ <td class="num">${fmtCount(run.tokens_in)} / ${fmtCount(run.tokens_out)}</td>
327
+ <td class="num">${fmtCost(run.cost, run.cost_estimated)}</td>
328
+ <td class="num ${run.failures ? "fail" : "dim"}">${run.failures}</td></tr>`;
329
+ return head + (isOpen ? timeline(run) : "");
330
+ }
331
+
332
+ function renderRuns() {
333
+ const runs = DATA.runs;
334
+ if (!runs.length) { $("#runs").innerHTML = '<p class="empty">No runs or chats in the log yet. Start one with /implement, /plan or a question.</p>'; return; }
335
+ const withSession = runs.some((r) => r.session);
336
+ const shown = runs.slice(0, limits.runs);
337
+ const headers = ["Started", "Kind", "Work item", "Branch", withSession ? "Session" : null, "Duration", "Outcome", "Calls", "Tokens in / out", "Cost", "Failures"];
338
+ const numeric = new Set(["Duration", "Calls", "Tokens in / out", "Cost", "Failures"]);
339
+ const head = headers.filter(Boolean).map((h) => `<th class="${numeric.has(h) ? "num" : ""}">${h}</th>`).join("");
340
+ const more = runs.length > shown.length ? `<button class="more" data-more="runs">Show ${Math.min(PAGE.runs, runs.length - shown.length)} more of ${runs.length - shown.length}</button>` : "";
341
+ $("#runs").innerHTML = `<div class="scroll"><table><thead><tr>${head}</tr></thead><tbody>${shown.map((r) => runRow(r, withSession)).join("")}</tbody></table></div>${more}`;
342
+ }
343
+
344
+ function focusRun(id) {
345
+ const row = document.querySelector(`tr.row[data-run="${CSS.escape(id)}"]`);
346
+ if (row) { row.focus(); row.scrollIntoView({ block: "nearest" }); }
347
+ }
348
+
349
+ function toggleRun(id) {
350
+ if (open.has(id)) open.delete(id); else open.add(id);
351
+ renderRuns();
352
+ focusRun(id);
353
+ }
354
+
355
+ function gotoRun(id) {
356
+ const index = DATA.runs.findIndex((r) => r.id === id);
357
+ limits.runs = Math.max(limits.runs, index + 1);
358
+ open.add(id);
359
+ showTab("runs");
360
+ renderRuns();
361
+ focusRun(id);
362
+ }
363
+
364
+ // -- Log -------------------------------------------------------------------------
365
+
366
+ function fillSelect(select, label, values) {
367
+ select.innerHTML = `<option value="">${label}</option>` + values.map((v) => `<option>${esc(v)}</option>`).join("");
368
+ }
369
+
370
+ function initFilters() {
371
+ const unique = (list) => [...new Set(list.filter(Boolean))].sort();
372
+ fillSelect($("#f-kind"), "all", unique(DATA.events.map((e) => e.kind)));
373
+ fillSelect($("#f-who"), "all", unique(DATA.events.map(who)));
374
+ for (const id of ["#f-kind", "#f-who", "#f-run", "#f-fail"]) {
375
+ $(id).addEventListener("input", () => { limits.log = PAGE.log; renderLog(); });
376
+ }
377
+ }
378
+
379
+ function filteredEvents() {
380
+ const kind = $("#f-kind").value, name = $("#f-who").value;
381
+ const run = $("#f-run").value.trim().toLowerCase(), failing = $("#f-fail").checked;
382
+ return DATA.events.filter((e) =>
383
+ (!kind || e.kind === kind) && (!name || who(e) === name) && (!failing || e.flag) &&
384
+ (!run || String(e.run || e.chat || "").toLowerCase().includes(run)));
385
+ }
386
+
387
+ function logRow(e, index) {
388
+ const id = e.run || e.chat || "";
389
+ return `<tr class="row ${flagClass(e)}" tabindex="0" data-raw="${index}">
390
+ <td class="mono">${esc(fmtTime(e.ts, true))}</td>
391
+ <td><span class="badge">${esc(e.kind)}</span></td>
392
+ <td class="mono dim" title="${esc(id)}">${esc(id.slice(0, 8))}</td>
393
+ <td>${esc(who(e))}</td>
394
+ <td class="wrap ${flagClass(e)}">${esc(detail(e))}</td>
395
+ <td class="num mono dim">${e.ms != null ? fmtMs(e.ms) : ""}</td></tr>`;
396
+ }
397
+
398
+ const rawOpen = new Set();
399
+ const eventIndex = new Map(DATA.events.map((e, i) => [e, i]));
400
+
401
+ function renderLog() {
402
+ const matches = filteredEvents().reverse();
403
+ $("#f-count").textContent = matches.length + " of " + DATA.events.length + " events, newest first";
404
+ if (!matches.length) { $("#log-table").innerHTML = '<p class="empty">No events match these filters.</p>'; return; }
405
+ const shown = matches.slice(0, limits.log);
406
+ const rows = shown.map((e) => logRow(e, eventIndex.get(e)) +
407
+ (rawOpen.has(eventIndex.get(e)) ? `<tr class="timeline"><td colspan="6"><pre>${esc(JSON.stringify(e, null, 2))}</pre></td></tr>` : ""));
408
+ const more = matches.length > shown.length ? `<button class="more" data-more="log">Show ${Math.min(PAGE.log, matches.length - shown.length)} more of ${matches.length - shown.length}</button>` : "";
409
+ $("#log-table").innerHTML = `<table><thead><tr><th>Time</th><th>Kind</th><th>Run</th><th>Agent / helper</th><th>Event</th><th class="num">Took</th></tr></thead><tbody>${rows.join("")}</tbody></table>${more}`;
410
+ }
411
+
412
+ function toggleRaw(index) {
413
+ if (rawOpen.has(index)) rawOpen.delete(index); else rawOpen.add(index);
414
+ renderLog();
415
+ }
416
+
417
+ // -- charts: SVG drawn at the container's pixel width, so text stays 11px ----------
418
+
419
+ const legend = (segments) => `<div class="legend">${segments.map((s) => `<span><i class="sw ${s.cls}"></i>${esc(s.name)}</span>`).join("")}</div>`;
420
+ const chartSlot = (id) => `<div class="chart" data-chart="${id}"></div>`;
421
+ const plot = (width, height, label, body) =>
422
+ `<svg class="plot" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${esc(label)}">${body}</svg>`;
423
+
424
+ // The smallest 1, 2 or 5 x 10^n at or above `value`: a round axis top.
425
+ function niceMax(value) {
426
+ if (!(value > 0)) return 1;
427
+ const power = 10 ** Math.floor(Math.log10(value));
428
+ return [1, 2, 5, 10].map((m) => m * power).find((top) => top >= value);
429
+ }
430
+
431
+ // Horizontal bars. rows: [{label, values: [..one per segment], text}].
432
+ // `overlay` draws each segment from zero (largest first) instead of stacking.
433
+ function barChart(width, rows, segments, label, overlay) {
434
+ const labelW = Math.min(170, Math.round(width * 0.32)), rightW = 96, rowH = 20, gap = 7;
435
+ const plotW = Math.max(width - labelW - rightW, 40);
436
+ const total = (r) => (overlay ? Math.max(...r.values) : sum(r.values));
437
+ const max = Math.max(...rows.map(total), 1e-12);
438
+ let body = "";
439
+ rows.forEach((r, i) => {
440
+ const y = i * (rowH + gap);
441
+ let x = labelW;
442
+ body += `<text class="lbl" x="${labelW - 8}" y="${y + rowH / 2 + 4}" text-anchor="end">${esc(clip(r.label, Math.floor(labelW / 7.2)))}<title>${esc(r.label)}</title></text>`;
443
+ r.values.forEach((v, j) => {
444
+ const w = (v / max) * plotW;
445
+ body += `<rect class="${r.cls || segments[j].cls}" x="${overlay ? labelW : x}" y="${y}" width="${Math.max(w, v > 0 ? 1 : 0)}" height="${rowH}" rx="2"><title>${esc(segments[j].name + ": " + v)}</title></rect>`;
446
+ if (!overlay) x += w;
447
+ });
448
+ const end = overlay ? labelW + (total(r) / max) * plotW : x;
449
+ body += `<text class="val" x="${end + 6}" y="${y + rowH / 2 + 4}">${esc(r.text)}</text>`;
450
+ });
451
+ return plot(width, rows.length * (rowH + gap) - gap, label, body);
452
+ }
453
+
454
+ // Y axis gridlines at 0, half and top, labelled in dollars.
455
+ function yGrid(left, right, top, bottom, max) {
456
+ return [0, 0.5, 1].map((f) => {
457
+ const y = bottom - f * (bottom - top);
458
+ return `<line class="gridline" x1="${left}" x2="${right}" y1="${y}" y2="${y}"/><text class="tick" x="${left - 6}" y="${y + 4}" text-anchor="end">${fmtCost(max * f)}</text>`;
459
+ }).join("");
460
+ }
461
+
462
+ // About six evenly spaced day labels under the plot.
463
+ function xTicks(days, xOf, y) {
464
+ const step = Math.max(1, Math.ceil(days.length / 6));
465
+ return days.map((d, i) => (i % step === 0
466
+ ? `<text class="tick" x="${xOf(i)}" y="${y}" text-anchor="middle">${esc(fmtDay(d.day))}</text>` : "")).join("");
467
+ }
468
+
469
+ // -- Spend board ---------------------------------------------------------------------
470
+
471
+ const RANGES = [["7", "7 days"], ["30", "30 days"], ["90", "90 days"], ["all", "All"]];
472
+ const spend = { range: "30", focus: null };
473
+ const today = String(DATA.generated).slice(0, 10);
474
+ const byDay = new Map(DATA.analytics.by_day.map((d) => [d.day, d]));
475
+
476
+ function shiftDay(day, offset) {
477
+ const date = new Date(day + "T00:00:00Z");
478
+ date.setUTCDate(date.getUTCDate() + offset);
479
+ return date.toISOString().slice(0, 10);
480
+ }
481
+ function dayRange(first, last) {
482
+ const days = [];
483
+ for (let day = first; day <= last && days.length < 3660; day = shiftDay(day, 1)) days.push(day);
484
+ return days;
485
+ }
486
+ const dayCost = (day) => (byDay.get(day) || {}).cost || 0;
487
+ const firstDay = DATA.analytics.by_day.length ? DATA.analytics.by_day[0].day : today;
488
+
489
+ // The selected window, every day in it (zero days included), and the one before it.
490
+ function spendWindow() {
491
+ const length = spend.range === "all" ? dayRange(firstDay, today).length : Number(spend.range);
492
+ const start = shiftDay(today, 1 - length);
493
+ return { start, days: dayRange(start, today), previous: spend.range === "all" ? null : dayRange(shiftDay(start, -length), shiftDay(start, -1)) };
494
+ }
495
+
496
+ // Agents ranked by spend in the window; beyond five they share "other".
497
+ function agentSeries(days) {
498
+ const totals = {};
499
+ for (const day of days) for (const [name, cost] of Object.entries((byDay.get(day) || {}).agents || {})) totals[name] = (totals[name] || 0) + cost;
500
+ const ranked = Object.keys(totals).filter((n) => totals[n] > 0).sort((a, b) => totals[b] - totals[a]);
501
+ const named = ranked.slice(0, 5);
502
+ const series = named.map((name, i) => ({ name, cls: "s" + (i + 1), of: (agents) => agents[name] || 0 }));
503
+ if (ranked.length > 5) series.push({ name: "other", cls: "s6", of: (agents) => sum(ranked.slice(5).map((n) => agents[n] || 0)) });
504
+ return { series, totals };
505
+ }
506
+
507
+ function windowRuns(start) {
508
+ return DATA.runs.filter((r) => String(r.start || "").slice(0, 10) >= start && r.cost != null);
509
+ }
510
+
511
+ function trendRows(days) {
512
+ return days.map((day) => {
513
+ const trailing = dayRange(shiftDay(day, -6), day).map(dayCost);
514
+ return { day, total: dayCost(day), avg: sum(trailing) / 7, row: byDay.get(day) || { calls: 0, agents: {} } };
515
+ });
516
+ }
517
+
518
+ function kpis(win, runs) {
519
+ const total = sum(win.days.map(dayCost));
520
+ const kpi = (label, value, note) => `<div class="kpi"><span>${esc(label)}</span><b>${value}</b><small>${note}</small></div>`;
521
+ const items = [kpi("Spend", esc(fmtCost(total, TOTALS.cost_estimated)), esc(win.days.length + " days, " + fmtDay(win.start) + " to " + fmtDay(today)))];
522
+ items.push(kpi("Versus the period before", ...changeVersus(total, win.previous)));
523
+ const active = win.days.filter((d) => dayCost(d) > 0).length;
524
+ items.push(kpi("Per active day", esc(fmtCost(active ? total / active : 0)), esc(active + " of " + win.days.length + " days had spend")));
525
+ items.push(kpi("Per run or chat", esc(fmtCost(runs.length ? total / runs.length : 0)), esc(runs.length + " runs and chats")));
526
+ items.push(kpi("This month", ...monthPace()));
527
+ return `<div class="kpis">${items.join("")}</div>`;
528
+ }
529
+
530
+ function changeVersus(total, previous) {
531
+ if (!previous) return ["–", "no earlier period in view"];
532
+ const before = sum(previous.map(dayCost));
533
+ if (before === 0) return [total > 0 ? "new" : "–", esc("nothing spent in the " + previous.length + " days before")];
534
+ const change = (total - before) / before;
535
+ const arrow = change > 0 ? "↑" : change < 0 ? "↓" : "";
536
+ const cls = change > 0 ? "up" : change < 0 ? "down" : "";
537
+ return [`<span class="${cls}">${arrow} ${Math.abs(Math.round(change * 100))}%</span>`, esc("from " + fmtCost(before))];
538
+ }
539
+
540
+ function monthPace() {
541
+ const month = today.slice(0, 7), dayOfMonth = Number(today.slice(8, 10));
542
+ const spent = sum(DATA.analytics.by_day.filter((d) => d.day.startsWith(month)).map((d) => d.cost));
543
+ const length = new Date(Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5, 7)), 0)).getUTCDate();
544
+ const note = dayOfMonth < 3 ? "too early to project" : "on pace for " + fmtCost((spent / dayOfMonth) * length);
545
+ return [esc(fmtCost(spent)), esc(note)];
546
+ }
547
+
548
+ // Daily spend stacked by agent, with the trailing 7-day average as a dashed line.
549
+ function trendChart(width, rows, series) {
550
+ const H = 230, left = 56, right = width - 8, top = 10, bottom = H - 24;
551
+ const max = niceMax(Math.max(...rows.map((r) => Math.max(r.total, r.avg)), 0));
552
+ const slot = (right - left) / rows.length, barW = Math.max(Math.min(slot * 0.72, 30), 1);
553
+ const xOf = (i) => left + slot * i + slot / 2, yOf = (v) => bottom - (v / max) * (bottom - top);
554
+ let body = yGrid(left, right, top, bottom, max);
555
+ rows.forEach((r, i) => {
556
+ let y = bottom, bars = "";
557
+ for (const s of series) {
558
+ const h = (s.of(r.row.agents) / max) * (bottom - top);
559
+ if (h > 0) { y -= h; bars += `<rect class="${s.cls}" x="${xOf(i) - barW / 2}" y="${y}" width="${barW}" height="${Math.max(h, 1)}"/>`; }
560
+ }
561
+ body += `<g class="day${spend.focus === i ? " on" : ""}" data-i="${i}"><rect class="hit" x="${left + slot * i}" y="${top}" width="${slot}" height="${bottom - top}"/>${bars}<title>${esc(fmtDay(r.day) + ": " + fmtCost(r.total))}</title></g>`;
562
+ });
563
+ if (rows.length > 1) body += `<polyline class="avg" points="${rows.map((r, i) => xOf(i) + "," + yOf(r.avg)).join(" ")}"/>`;
564
+ body += xTicks(rows, xOf, H - 6);
565
+ return plot(width, H, "Daily spend stacked by agent, with the 7-day average", body);
566
+ }
567
+
568
+ // Running total of spend across the window.
569
+ function cumulativeChart(width, rows) {
570
+ const H = 150, left = 56, right = width - 8, top = 10, bottom = H - 24;
571
+ let running = 0;
572
+ const points = rows.map((r) => (running += r.total));
573
+ const max = niceMax(running);
574
+ const step = rows.length > 1 ? (right - left) / (rows.length - 1) : 0;
575
+ const xOf = (i) => (rows.length > 1 ? left + step * i : (left + right) / 2), yOf = (v) => bottom - (v / max) * (bottom - top);
576
+ const line = points.map((v, i) => xOf(i) + "," + yOf(v)).join(" ");
577
+ const area = `<polygon class="area" points="${xOf(0)},${bottom} ${line} ${xOf(points.length - 1)},${bottom}"/>`;
578
+ return plot(width, H, "Running total of spend", yGrid(left, right, top, bottom, max) + area + xTicks(rows, xOf, H - 6));
579
+ }
580
+
581
+ function readout(rows, series) {
582
+ const index = spend.focus ?? rows.length - 1;
583
+ const r = rows[index];
584
+ if (!r) return "";
585
+ const parts = series.map((s) => [s, s.of(r.row.agents)]).filter(([, v]) => v > 0)
586
+ .map(([s, v]) => `<span><i class="sw ${s.cls}"></i>${esc(s.name)} ${esc(fmtCost(v))}</span>`);
587
+ return `<b>${esc(fmtDay(r.day))} · ${esc(fmtCost(r.total))}</b><span>${r.row.calls} calls · 7-day avg ${esc(fmtCost(r.avg))}</span>${parts.join("")}`;
588
+ }
589
+
590
+ // `colors` maps a name to its series class, so agent bars match the trend chart.
591
+ function shareBars(width, totals, label, colors = {}) {
592
+ const whole = sum(Object.values(totals));
593
+ const rows = Object.entries(totals).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]).slice(0, 8)
594
+ .map(([name, v]) => ({ label: name, values: [v], text: fmtCost(v) + " · " + pct(v, whole), cls: colors[name] }));
595
+ return rows.length ? barChart(width, rows, [{ name: "spend", cls: "c-accent" }], label) : "";
596
+ }
597
+
598
+ function modelTotals(days) {
599
+ const totals = {};
600
+ for (const day of days) for (const [name, cost] of Object.entries((byDay.get(day) || {}).models || {})) totals[name] = (totals[name] || 0) + cost;
601
+ return totals;
602
+ }
603
+
604
+ function topRuns(runs, total) {
605
+ const top = [...runs].sort((a, b) => b.cost - a.cost).slice(0, 5);
606
+ if (!top.length) return '<p class="empty">No priced runs in this window.</p>';
607
+ const rows = top.map((r) => `<tr class="row" tabindex="0" data-goto="${esc(r.id)}"><td>${esc(fmtShort(r.start))}</td><td><span class="badge">${esc(r.kind)}</span></td>
608
+ <td>${esc(r.work_item || r.branch || "–")}</td><td class="num">${esc(fmtCost(r.cost, r.cost_estimated))}</td><td class="num dim">${pct(r.cost, total)}</td></tr>`);
609
+ return `<div class="scroll"><table><thead><tr><th>Started</th><th>Kind</th><th>Work item</th><th class="num">Cost</th><th class="num">Share</th></tr></thead><tbody>${rows.join("")}</tbody></table></div>`;
610
+ }
611
+
612
+ function renderSpend() {
613
+ const win = spendWindow(), runs = windowRuns(win.start), rows = trendRows(win.days);
614
+ const { series, totals } = agentSeries(win.days);
615
+ const total = sum(rows.map((r) => r.total));
616
+ const buttons = RANGES.map(([key, name]) => `<button type="button" data-range="${key}" aria-pressed="${spend.range === key}">${name}</button>`).join("");
617
+ const empty = total === 0 ? `<p class="empty">No spend in the last ${win.days.length} days.</p>` : "";
618
+ $("#spend").innerHTML = `<div class="spend-head"><h2>Spend over time</h2><div class="segmented" role="group" aria-label="Time window">${buttons}</div></div>
619
+ ${kpis(win, runs)}
620
+ <div class="card spend-trend"><h2>Daily spend by agent</h2>${empty || legend([...series, { name: "7-day average", cls: "line" }]) + `<div class="readout" id="spend-readout" aria-live="polite">${readout(rows, series)}</div>` + chartSlot("trend")}</div>
621
+ <div class="grid">
622
+ <div class="card"><h2>Running total</h2>${empty || chartSlot("cumulative")}</div>
623
+ <div class="card"><h2>Most expensive runs</h2>${topRuns(runs, total)}</div>
624
+ <div class="card"><h2>Share by agent</h2>${empty || chartSlot("agents")}</div>
625
+ <div class="card"><h2>Share by model</h2>${empty || chartSlot("models")}</div>
626
+ </div>
627
+ ${TOTALS.cost_estimated ? '<p class="note">Days are UTC. Where the provider logged no cost, it is estimated from list prices.</p>' : '<p class="note">Days are UTC.</p>'}`;
628
+ drawCharts("#spend", {
629
+ trend: (w) => trendChart(w, rows, series),
630
+ cumulative: (w) => cumulativeChart(w, rows),
631
+ agents: (w) => shareBars(w, totals, "Spend by agent", Object.fromEntries(series.map((s) => [s.name, s.cls]))),
632
+ models: (w) => shareBars(w, modelTotals(win.days), "Spend by model"),
633
+ });
634
+ spend.rows = rows;
635
+ spend.series = series;
636
+ }
637
+
638
+ function focusDay(index) {
639
+ if (!spend.rows || index == null || index < 0 || index >= spend.rows.length) return;
640
+ spend.focus = index;
641
+ document.querySelectorAll("#spend g.day").forEach((g) => g.classList.toggle("on", Number(g.dataset.i) === index));
642
+ const box = $("#spend-readout");
643
+ if (box) box.innerHTML = readout(spend.rows, spend.series);
644
+ }
645
+
646
+ // -- Analytics ---------------------------------------------------------------------
647
+
648
+ const card = (title, slot, note, emptyText) => `<div class="card"><h2>${esc(title)}</h2>${slot || `<p class="empty">${esc(emptyText)}</p>`}${note ? `<p class="note">${esc(note)}</p>` : ""}</div>`;
649
+ const agentLabel = (r) => r.name + (r.helper ? " (helper)" : "");
650
+
651
+ function renderAnalytics() {
652
+ const a = DATA.analytics;
653
+ const outcomes = ["done", "stuck", "rejected", "running"].filter((k) => a.outcomes[k]);
654
+ const priceNote = TOTALS.cost_estimated ? "Includes costs estimated from list prices." : "";
655
+ const tokenSegments = [{ name: "in", cls: "c-brand" }, { name: "out", cls: "c-accent" }];
656
+ const latencySegments = [{ name: "p95", cls: "c-track" }, { name: "p50", cls: "c-accent" }];
657
+ const toolSegments = [{ name: "ok", cls: "c-ok" }, { name: "failed", cls: "c-error" }, { name: "denied", cls: "c-warn" }];
658
+ const gateSegments = [{ name: "approved", cls: "c-ok" }, { name: "sent back", cls: "c-error" }];
659
+ $("#analytics").innerHTML = `<div class="grid">${[
660
+ card("Cost per agent", a.by_agent.length && chartSlot("cost"), priceNote, "No model calls yet."),
661
+ card("Tokens per agent", a.by_agent.length && legend(tokenSegments) + chartSlot("tokens"), "", "No model calls yet."),
662
+ card("Model latency", a.latency.length && legend(latencySegments) + chartSlot("latency"), "p50 and p95 of successful calls.", "No successful model calls yet."),
663
+ card("Tool calls", a.tools.length && legend(toolSegments) + chartSlot("tools"), "", "No tool calls yet."),
664
+ card("Gate outcomes", a.gates.length && legend(gateSegments) + chartSlot("gates"), "Approve or pass, against reject, retry, stop or fail.", "No gate has been decided yet."),
665
+ card("Run outcomes", outcomes.length && chartSlot("outcomes"), "", "No run has ended yet."),
666
+ ].join("")}</div>`;
667
+ drawCharts("#analytics", {
668
+ cost: (w) => barChart(w, a.by_agent.map((r) => ({ label: agentLabel(r), values: [r.cost], text: fmtCost(r.cost) })), [{ name: "cost", cls: "c-accent" }], "Cost per agent"),
669
+ tokens: (w) => barChart(w, a.by_agent.map((r) => ({ label: agentLabel(r), values: [r.tokens_in, r.tokens_out], text: fmtCount(r.tokens_in) + " / " + fmtCount(r.tokens_out) })), tokenSegments, "Tokens per agent"),
670
+ latency: (w) => barChart(w, a.latency.map((r) => ({ label: r.model, values: [r.p95, r.p50], text: fmtMs(r.p50) + " / " + fmtMs(r.p95) })), latencySegments, "Model latency", true),
671
+ tools: (w) => barChart(w, a.tools.map((r) => ({ label: r.tool, values: [r.calls - r.failed - r.denied, r.failed, r.denied], text: String(r.calls) })), toolSegments, "Tool calls"),
672
+ gates: (w) => barChart(w, a.gates.map((r) => ({ label: r.gate, values: [r.approved, r.sent_back], text: r.approved + " / " + r.sent_back })), gateSegments, "Gate outcomes"),
673
+ outcomes: (w) => barChart(w, outcomes.map((k) => ({ label: k, values: [a.outcomes[k]], text: String(a.outcomes[k]) })), [{ name: "runs", cls: "c-accent" }], "Run outcomes"),
674
+ });
675
+ }
676
+
677
+ // Fill each chart slot under `root` with its drawing at the slot's width.
678
+ function drawCharts(root, drawers) {
679
+ document.querySelectorAll(`${root} [data-chart]`).forEach((slot) => {
680
+ const draw = drawers[slot.dataset.chart];
681
+ if (draw) slot.innerHTML = draw(Math.max(Math.floor(slot.clientWidth), 240));
682
+ });
683
+ }
684
+
685
+ // -- tabs and events ---------------------------------------------------------------
686
+
687
+ const TABS = ["runs", "spend", "log", "analytics"];
688
+ const RENDER = { spend: renderSpend, analytics: renderAnalytics };
689
+ let current = "runs";
690
+ function showTab(tab) {
691
+ if (!TABS.includes(tab)) tab = "runs";
692
+ current = tab;
693
+ for (const name of TABS) {
694
+ $("#" + name).hidden = name !== tab;
695
+ document.querySelector(`nav [data-tab="${name}"]`).setAttribute("aria-selected", String(name === tab));
696
+ }
697
+ if (RENDER[tab]) RENDER[tab]();
698
+ try { history.replaceState(null, "", "#" + tab); } catch (_) { /* file or sandbox */ }
699
+ }
700
+
701
+ document.addEventListener("click", (event) => {
702
+ const target = event.target.closest("[data-tab],[data-run],[data-raw],[data-more],[data-range],[data-goto],#theme-toggle");
703
+ if (!target) return;
704
+ const d = target.dataset;
705
+ if (target.id === "theme-toggle") toggleTheme();
706
+ else if (d.tab) showTab(d.tab);
707
+ else if (d.run) toggleRun(d.run);
708
+ else if (d.raw) toggleRaw(Number(d.raw));
709
+ else if (d.goto) gotoRun(d.goto);
710
+ else if (d.range) { spend.range = d.range; spend.focus = null; renderSpend(); }
711
+ else if (d.more) { limits[d.more] += PAGE[d.more]; (d.more === "runs" ? renderRuns : renderLog)(); }
712
+ });
713
+ document.addEventListener("keydown", (event) => {
714
+ if ((event.key === "Enter" || event.key === " ") && event.target.matches("tr.row")) {
715
+ event.preventDefault();
716
+ event.target.click();
717
+ }
718
+ });
719
+ document.addEventListener("mouseover", (event) => {
720
+ const day = event.target.closest("#spend g.day");
721
+ if (day) focusDay(Number(day.dataset.i));
722
+ });
723
+
724
+ // Redraw the visible charts when the window width changes.
725
+ let lastWidth = window.innerWidth;
726
+ window.addEventListener("resize", () => {
727
+ if (window.innerWidth === lastWidth) return;
728
+ lastWidth = window.innerWidth;
729
+ requestAnimationFrame(() => { if (RENDER[current]) RENDER[current](); });
730
+ });
731
+
732
+ syncThemeButton();
733
+ renderTotals();
734
+ renderRuns();
735
+ initFilters();
736
+ renderLog();
737
+ showTab(location.hash.slice(1));
738
+ </script>
739
+ </body>
740
+ </html>