runa-agent-wrapped 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +18 -3
  2. package/dist/cli.js +2022 -1475
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -4,50 +4,14 @@
4
4
  import { spawn } from "node:child_process";
5
5
  import { homedir } from "node:os";
6
6
 
7
- // src/window.ts
8
- function ymd(d) {
9
- const p = (n) => String(n).padStart(2, "0");
10
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
11
- }
12
- function windowFor(now) {
13
- return { start: `${now.getFullYear()}-01-01`, end: ymd(now) };
14
- }
15
- function bounds(w) {
16
- const [sy, sm, sd] = w.start.split("-").map(Number);
17
- const [ey, em, ed] = w.end.split("-").map(Number);
18
- return { from: new Date(sy, sm - 1, sd), until: new Date(ey, em - 1, ed + 1) };
19
- }
7
+ // src/daily.ts
8
+ import { join as join3 } from "node:path";
9
+ import { existsSync as existsSync3 } from "node:fs";
20
10
 
21
- // src/readers/claude.ts
11
+ // src/readers/backfill.ts
12
+ import { existsSync as existsSync2 } from "node:fs";
22
13
  import { join as join2 } from "node:path";
23
14
 
24
- // src/readers/assemble.ts
25
- var RANK = { ask: 0, auto: 1, bypass: 2 };
26
- function raiseAutonomy(s, a) {
27
- if (RANK[a] > RANK[s.autonomy])
28
- s.autonomy = a;
29
- }
30
- function newSession() {
31
- return { model: null, autonomy: "ask", events: [] };
32
- }
33
- function assemble(harness, sessions, range) {
34
- const out = [];
35
- for (const [sessionId, s] of sessions) {
36
- const inRange = s.events.filter((e) => e.at >= range.from && e.at < range.until);
37
- if (inRange.length === 0)
38
- continue;
39
- const first = inRange.reduce((a, b) => b.at < a.at ? b : a).at;
40
- out.push({ harness, sessionId, at: first, kind: "session", model: s.model, autonomy: s.autonomy });
41
- for (const e of inRange)
42
- out.push({ ...e, harness, sessionId });
43
- }
44
- return out;
45
- }
46
- function connectorOf(tool) {
47
- const m = /^mcp__(.+?)__/.exec(tool);
48
- return m ? m[1] ?? null : null;
49
- }
50
-
51
15
  // src/readers/util.ts
52
16
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
53
17
  import { join } from "node:path";
@@ -126,1526 +90,2095 @@ function parseTime(v) {
126
90
  const d = new Date(v);
127
91
  return Number.isNaN(d.getTime()) ? null : d;
128
92
  }
129
-
130
- // src/readers/claude.ts
131
- function autonomyOf(mode) {
132
- if (mode === "bypassPermissions")
133
- return "bypass";
134
- if (mode === "acceptEdits" || mode === "auto" || mode === "dontAsk")
135
- return "auto";
136
- return "ask";
137
- }
138
- function promptText(o) {
139
- if (o["isMeta"] === true || o["isCompactSummary"] === true || o["isSidechain"] === true)
140
- return null;
141
- const origin = asObj(o["origin"]);
142
- if (origin && origin["kind"] !== "human")
143
- return null;
144
- const content = asObj(o["message"])?.["content"];
145
- let text = null;
146
- if (typeof content === "string")
147
- text = content;
148
- else if (Array.isArray(content)) {
149
- const parts = content.map(asObj).filter((p) => p?.["type"] === "text").map((p) => str(p?.["text"]) ?? "");
150
- text = parts.join(`
151
- `);
152
- }
153
- if (!text || text.startsWith("<") || text.startsWith("[Request interrupted"))
154
- return null;
155
- return text;
156
- }
157
- function toolPath(input) {
158
- return str(input?.["file_path"]) ?? str(input?.["notebook_path"]) ?? str(input?.["path"]);
93
+ function folderName(cwd) {
94
+ return cwd.split(/[\\/]/).filter(Boolean).pop() ?? null;
159
95
  }
160
- function readClaude(home, range) {
161
- const root = join2(home, ".claude", "projects");
162
- const files = walk(root, (n) => n.endsWith(".jsonl"), 4).sort();
163
- const sessions = new Map;
164
- const seen = new Set;
165
- const cwds = new Set;
166
- for (const file of files) {
167
- const text = readText(file);
168
- if (text === null)
169
- continue;
170
- const stem = file.split("/").pop()?.replace(/\.jsonl$/, "") ?? file;
171
- for (const o of jsonLines(text)) {
172
- const at = parseTime(o["timestamp"]);
173
- const cwd = str(o["cwd"]);
174
- if (cwd)
175
- cwds.add(cwd);
176
- if (!at)
177
- continue;
178
- const uuid = str(o["uuid"]);
179
- if (uuid) {
180
- if (seen.has(uuid))
181
- continue;
182
- seen.add(uuid);
183
- }
184
- const sid = str(o["sessionId"]) ?? stem;
185
- let s = sessions.get(sid);
186
- if (!s)
187
- sessions.set(sid, s = newSession());
188
- const type = o["type"];
189
- if (type === "user") {
190
- const mode = str(o["permissionMode"]);
191
- if (mode)
192
- raiseAutonomy(s, autonomyOf(mode));
193
- const t = promptText(o);
194
- if (t !== null)
195
- s.events.push({ kind: "prompt", at, text: t });
196
- } else if (type === "assistant") {
197
- const msg = asObj(o["message"]);
198
- const rawModel = str(msg?.["model"]);
199
- const model = rawModel && !rawModel.startsWith("<") ? rawModel : null;
200
- if (model && !s.model)
201
- s.model = model;
202
- const content = Array.isArray(msg?.["content"]) ? msg["content"] : [];
203
- for (const item of content) {
204
- const b = asObj(item);
205
- if (!b)
206
- continue;
207
- if (b["type"] === "text" && str(b["text"])) {
208
- s.events.push({ kind: "reply", at, text: b["text"], model });
209
- } else if (b["type"] === "tool_use") {
210
- const name = str(b["name"]);
211
- if (!name)
212
- continue;
213
- const id = str(b["id"]);
214
- if (id) {
215
- if (seen.has(id))
216
- continue;
217
- seen.add(id);
218
- }
219
- const input = asObj(b["input"]);
220
- s.events.push({
221
- kind: "tool",
222
- at,
223
- tool: name,
224
- connector: connectorOf(name),
225
- command: name === "Bash" ? str(input?.["command"]) : null,
226
- path: toolPath(input)
227
- });
228
- }
229
- }
230
- } else if (type === "system" && o["subtype"] === "compact_boundary") {
231
- s.events.push({ kind: "compaction", at });
232
- }
233
- }
234
- }
96
+
97
+ // src/readers/backfill.ts
98
+ var DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
99
+ function isDate(v) {
100
+ if (typeof v !== "string")
101
+ return false;
102
+ const m = DATE.exec(v);
103
+ if (!m)
104
+ return false;
105
+ const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
106
+ return d.getFullYear() === Number(m[1]) && d.getMonth() === Number(m[2]) - 1 && d.getDate() === Number(m[3]);
107
+ }
108
+ var count = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
109
+ function dayTotal(date, toolCalls, sessions) {
110
+ return isDate(date) && count(toolCalls) && count(sessions) ? { date, toolCalls, sessions } : null;
111
+ }
112
+ function readStatsCache(home) {
113
+ const o = readJson(join2(home, ".claude", "stats-cache.json"));
114
+ if (!o)
115
+ return { days: [], first: null };
116
+ const list = Array.isArray(o["dailyActivity"]) ? o["dailyActivity"] : [];
117
+ const days = list.flatMap((e) => {
118
+ const d = asObj(e);
119
+ return d ? dayTotal(d["date"], d["toolCallCount"], d["sessionCount"]) ?? [] : [];
120
+ });
121
+ const first = typeof o["firstSessionDate"] === "string" ? parseTime(o["firstSessionDate"]) : null;
122
+ return { days, first };
123
+ }
124
+ function readDailyFile(home) {
125
+ const path = join2(home, ".agent-wrapped", "daily.json");
126
+ if (!existsSync2(path))
127
+ return { days: [], valid: true };
128
+ const o = readJson(path);
129
+ const days = asObj(o?.["days"]);
130
+ if (!o || o["version"] !== 1 || !days)
131
+ return { days: [], valid: false };
235
132
  return {
236
- events: assemble("claude-code", sessions, range),
237
- allowRules: countAllowRules(home, cwds),
238
- firstStarted: parseTime(readJson(join2(home, ".claude.json"))?.["firstStartTime"]),
239
- found: files.length > 0
133
+ days: Object.entries(days).flatMap(([date, v]) => {
134
+ const d = asObj(v);
135
+ return d ? dayTotal(date, d["toolCalls"], d["sessions"]) ?? [] : [];
136
+ }),
137
+ valid: true
240
138
  };
241
139
  }
242
- function countAllowRules(home, cwds) {
243
- const settings = new Set([join2(home, ".claude", "settings.json")]);
244
- for (const cwd of cwds)
245
- settings.add(join2(cwd, ".claude", "settings.local.json"));
246
- let n = 0;
247
- for (const f of settings) {
248
- const allow = asObj(readJson(f)?.["permissions"])?.["allow"];
249
- if (Array.isArray(allow))
250
- n += allow.length;
251
- }
252
- return n;
253
- }
254
140
 
255
- // src/readers/codex.ts
256
- import { readFileSync as readFileSync2 } from "node:fs";
257
- import * as zlib from "node:zlib";
258
- import { join as join3 } from "node:path";
259
- function readRollout(path) {
260
- if (!path.endsWith(".zst"))
261
- return readText(path);
262
- const z = zlib;
263
- if (!z.zstdDecompressSync)
264
- return null;
265
- try {
266
- return z.zstdDecompressSync(readFileSync2(path)).toString("utf8");
267
- } catch {
268
- return null;
141
+ // src/stats.ts
142
+ import { basename } from "node:path";
143
+
144
+ // src/shell.ts
145
+ var HEREDOC = /<<-?\s*(['"]?)([A-Za-z_][\w]*)\1[^\n]*\n[\s\S]*?(?:\n\s*\2(?=\n|$)|$)/g;
146
+ function split(command) {
147
+ const src = command.replace(HEREDOC, (m) => m.slice(0, m.indexOf(`
148
+ `)));
149
+ const out = [];
150
+ let cur = "";
151
+ let quote = null;
152
+ const flush = (pipe) => {
153
+ if (cur.trim())
154
+ out.push({ text: cur.trim(), pipe });
155
+ cur = "";
156
+ };
157
+ for (let i = 0;i < src.length; i++) {
158
+ const ch = src[i];
159
+ if (quote) {
160
+ cur += ch;
161
+ if (ch === "\\" && quote === '"')
162
+ cur += src[++i] ?? "";
163
+ else if (ch === quote)
164
+ quote = null;
165
+ } else if (ch === '"' || ch === "'") {
166
+ quote = ch;
167
+ cur += ch;
168
+ } else if (ch === "\\") {
169
+ cur += ch + (src[++i] ?? "");
170
+ } else if (ch === "&" && (src[i - 1] === ">" || src[i - 1] === "<" || src[i + 1] === ">")) {
171
+ cur += ch;
172
+ } else if (ch === "|" && src[i + 1] === "|") {
173
+ flush(false);
174
+ i++;
175
+ } else if (ch === "|") {
176
+ if (src[i + 1] === "&")
177
+ i++;
178
+ flush(true);
179
+ } else if (ch === ";" || ch === "&" || ch === `
180
+ `)
181
+ flush(false);
182
+ else
183
+ cur += ch;
269
184
  }
185
+ flush(false);
186
+ return out;
270
187
  }
271
- function autonomyOf2(policy, sandbox) {
272
- if (policy === "never")
273
- return sandbox === "danger-full-access" ? "bypass" : "auto";
274
- if (policy === "on-failure")
275
- return "auto";
276
- if (sandbox === "danger-full-access" && policy !== "untrusted")
277
- return "bypass";
278
- return "ask";
188
+ function shellSegments(command) {
189
+ return split(command).map((p) => p.text);
279
190
  }
280
- function commandOf(args) {
281
- const cmd = args?.["command"] ?? args?.["cmd"];
282
- if (typeof cmd === "string")
283
- return cmd;
284
- if (Array.isArray(cmd)) {
285
- const words = cmd.filter((w) => typeof w === "string");
286
- if (words.length === 3 && words[0].endsWith("sh") && /^-\w*c/.test(words[1]))
287
- return words[2];
288
- return words.join(" ") || null;
191
+ function shellPipelines(command) {
192
+ const out = [];
193
+ let open = false;
194
+ for (const p of split(command)) {
195
+ if (open)
196
+ out[out.length - 1].push(p.text);
197
+ else
198
+ out.push([p.text]);
199
+ open = p.pipe;
289
200
  }
290
- return null;
201
+ return out;
291
202
  }
292
- var SHELL = new Set(["shell", "exec_command", "shell_command", "local_shell", "container.exec", "unified_exec"]);
293
- function readCodex(home, range, codexHome) {
294
- const root = join3(codexHome ?? join3(home, ".codex"), "sessions");
295
- const files = walk(root, (n) => n.startsWith("rollout-") && (n.endsWith(".jsonl") || n.endsWith(".jsonl.zst"))).sort();
296
- const sessions = new Map;
297
- for (const file of files) {
298
- const text = readRollout(file);
299
- if (text === null)
300
- continue;
301
- let sid = file;
302
- let s = newSession();
303
- let policy = null;
304
- let sandbox = null;
305
- for (const o of jsonLines(text)) {
306
- const at = parseTime(o["timestamp"]);
307
- const p = asObj(o["payload"]);
308
- if (!at || !p)
309
- continue;
310
- switch (o["type"]) {
311
- case "session_meta":
312
- sid = str(p["id"]) ?? sid;
313
- break;
314
- case "turn_context": {
315
- s.model ??= str(p["model"]);
316
- policy = str(p["approval_policy"]) ?? policy;
317
- const sb = p["sandbox_policy"];
318
- sandbox = (typeof sb === "string" ? sb : str(asObj(sb)?.["mode"]) ?? str(asObj(sb)?.["type"])) ?? sandbox;
319
- raiseAutonomy(s, autonomyOf2(policy, sandbox));
320
- break;
321
- }
322
- case "compacted":
323
- s.events.push({ kind: "compaction", at });
324
- break;
325
- case "event_msg":
326
- if (p["type"] === "user_message" && str(p["message"]))
327
- s.events.push({ kind: "prompt", at, text: p["message"] });
328
- else if (p["type"] === "agent_message" && str(p["message"]))
329
- s.events.push({ kind: "reply", at, text: p["message"], model: s.model });
330
- break;
331
- case "response_item": {
332
- const kind = p["type"];
333
- if (kind !== "function_call" && kind !== "custom_tool_call" && kind !== "local_shell_call")
334
- break;
335
- const name = kind === "local_shell_call" ? "local_shell" : str(p["name"]) ?? "";
336
- let args = null;
337
- const raw = p["arguments"] ?? p["action"];
338
- if (typeof raw === "string") {
339
- try {
340
- args = asObj(JSON.parse(raw));
341
- } catch {
342
- args = null;
343
- }
344
- } else
345
- args = asObj(raw);
346
- if (SHELL.has(name)) {
347
- s.events.push({ kind: "tool", at, tool: "Bash", connector: null, command: commandOf(args), path: null });
348
- } else if (name === "apply_patch") {
349
- const input = str(p["input"]) ?? "";
350
- const m = /\*\*\* (?:Update|Add|Delete) File: (.+)/.exec(input);
351
- s.events.push({ kind: "tool", at, tool: "Edit", connector: null, command: null, path: m?.[1]?.trim() ?? null });
352
- } else if (name) {
353
- s.events.push({ kind: "tool", at, tool: name, connector: connectorOf(name), command: null, path: null });
354
- }
355
- break;
356
- }
357
- }
358
- }
359
- sessions.set(sid, s);
203
+ var KEYWORDS = new Set(["if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", "esac", "function", "in", "{", "}", "!", "[", "[["]);
204
+ var WRAPPERS = new Set(["sudo", "time", "command", "env", "nohup", "exec", "xargs"]);
205
+ function programOf(segment) {
206
+ const words = segment.split(/\s+/).filter((w) => w && !/^[A-Za-z_]\w*=/.test(w));
207
+ let i = 0;
208
+ while (words[i] && WRAPPERS.has(words[i]))
209
+ i++;
210
+ const w = words[i];
211
+ if (!w || KEYWORDS.has(w) || w === "cd")
212
+ return null;
213
+ const name = w.split("/").pop() ?? "";
214
+ return /^[A-Za-z][\w.+-]*$/.test(name) ? name : null;
215
+ }
216
+
217
+ // src/personality.ts
218
+ var MIN_CALLS = 20;
219
+ var CAP = 3;
220
+ var ratio = (value, bar) => Math.min(value / bar, CAP);
221
+ var busy = (s, score) => s.toolCalls >= MIN_CALLS ? score : 0;
222
+ var ARCHETYPES = [
223
+ {
224
+ score: (s) => s.sessions === 0 ? 0 : Math.max(ratio(s.bypassSessions / s.sessions, 0.2), s.dontAskAgain >= 10 ? ratio(s.dontAskAgain / s.sessions, 0.5) : 0),
225
+ result: { name: "The Intern With Root Access", trustStatus: "It's complicated", genre: "Permission-Prompt Punk" }
226
+ },
227
+ {
228
+ score: (s) => busy(s, ratio(s.nightShare, 0.35)),
229
+ result: { name: "The Night Shift", trustStatus: "Asleep at the wheel, together", genre: "Lo-Fi Beats to Deploy To" }
230
+ },
231
+ {
232
+ score: (s) => busy(s, ratio(s.earlyShare, 0.3)),
233
+ result: { name: "The Early Bird", trustStatus: "Up before the CI is", genre: "Sunrise Standup Soul" }
234
+ },
235
+ {
236
+ score: (s) => busy(s, ratio(s.weekendShare, 0.45)),
237
+ result: { name: "The Weekend Warrior", trustStatus: "Saturday is a work day now", genre: "Sunday Scaries Synthpop" }
238
+ },
239
+ {
240
+ score: (s) => s.compactions >= 3 ? ratio(s.compactions / Math.max(s.sessions, 1), 0.5) : 0,
241
+ result: { name: "The Context Hoarder", trustStatus: "Remembers everything, forgives nothing", genre: "Progressive Rock, 14 Movements" }
242
+ },
243
+ {
244
+ score: (s) => s.sessions < 10 ? 0 : s.agentHours === 0 ? CAP : ratio(0.25, s.agentHours / s.sessions),
245
+ result: { name: "The Speedrunner", trustStatus: "Move fast, ask later", genre: "Speedcore" }
246
+ },
247
+ {
248
+ score: (s) => s.sessions >= 3 ? ratio(s.agentHours / s.sessions, 1.5) : 0,
249
+ result: { name: "The Marathoner", trustStatus: "Till compaction do us part", genre: "Twelve-Hour Drone" }
250
+ },
251
+ {
252
+ score: (s) => s.topHarness === "cursor" ? busy(s, ratio(s.topHarnessShare, 0.5)) : 0,
253
+ result: { name: "The Tab Goblin", trustStatus: "Pressing Tab on faith", genre: "Autocomplete Jazz" }
254
+ },
255
+ {
256
+ score: (s) => busy(s, ratio(s.secondHarnessShare, 0.25)),
257
+ result: { name: "The Agent Juggler", trustStatus: "Seeing other agents", genre: "Split-Screen Ska" }
258
+ },
259
+ {
260
+ score: (s) => busy(s, Math.max(ratio(s.connectorShare, 0.2), ratio(s.connectorCount, 4))),
261
+ result: { name: "The Connector Collector", trustStatus: "Gave it the keys to everything", genre: "Integration Hall of Fame" }
262
+ },
263
+ {
264
+ score: (s) => busy(s, ratio(s.bashShare, 0.55)),
265
+ result: { name: "The Terminal Cowboy", trustStatus: "Shoots first, reads the man page later", genre: "Bash Country" }
266
+ },
267
+ {
268
+ score: (s) => busy(s, ratio(s.webShare, 0.08)),
269
+ result: { name: "The Rabbit-Hole Researcher", trustStatus: "Trust, but cite sources", genre: "Forty-Tab Jazz Odyssey" }
270
+ },
271
+ {
272
+ score: (s) => s.subagentCalls >= 5 ? busy(s, ratio(s.subagentCalls / s.toolCalls, 0.04)) : 0,
273
+ result: { name: "The Middle Manager", trustStatus: "Delegates, then checks nothing", genre: "Org-Chart Orchestral" }
274
+ },
275
+ {
276
+ score: (s) => s.lazyPrompts >= 5 ? ratio(s.lazyPrompts / Math.max(s.sessions, 1), 0.3) : 0,
277
+ result: { name: "The Copy-Paste Debugger", trustStatus: "fix it", genre: "Stack-Trace Screamo" }
278
+ },
279
+ {
280
+ score: (s) => s.reads >= 50 ? ratio(s.reads / Math.max(s.writes, 1), 6) : 0,
281
+ result: { name: "The Archaeologist", trustStatus: "Reads everything, changes nothing", genre: "Ancient Codebase Chants" }
282
+ },
283
+ {
284
+ score: () => 0,
285
+ result: { name: "The Pair Programmer", trustStatus: "Healthy, mostly", genre: "Unplugged Acoustic" }
360
286
  }
361
- return { events: assemble("codex", sessions, range), found: files.length > 0 };
287
+ ];
288
+ function pickArchetype(s) {
289
+ let best = ARCHETYPES[ARCHETYPES.length - 1];
290
+ let bestScore = 0;
291
+ for (const a of ARCHETYPES) {
292
+ const score = a.score(s);
293
+ if (score >= 1 && score > bestScore)
294
+ [best, bestScore] = [a, score];
295
+ }
296
+ return best.result;
297
+ }
298
+ var COMMAND_GENRE = {
299
+ git: "Commit-Core",
300
+ gh: "Pull-Request Pop",
301
+ npm: "Node-Modules Metal",
302
+ npx: "Node-Modules Metal",
303
+ pnpm: "Node-Modules Metal",
304
+ yarn: "Node-Modules Metal",
305
+ node: "Node-Modules Metal",
306
+ bun: "Bun-Fed Breakbeat",
307
+ cargo: "Borrow-Checker Blues",
308
+ rustc: "Borrow-Checker Blues",
309
+ go: "Goroutine Garage Rock",
310
+ python: "Indentation Indie",
311
+ python3: "Indentation Indie",
312
+ pip: "Indentation Indie",
313
+ uv: "Indentation Indie",
314
+ pytest: "Indentation Indie",
315
+ docker: "Container Shoegaze",
316
+ kubectl: "Cluster Ambient",
317
+ helm: "Cluster Ambient",
318
+ terraform: "Infrastructure Industrial",
319
+ curl: "HTTP Hip-Hop",
320
+ wget: "HTTP Hip-Hop",
321
+ rg: "Grep-Hop",
322
+ grep: "Grep-Hop",
323
+ find: "Grep-Hop",
324
+ ls: "Directory Drone",
325
+ pwd: "Directory Drone",
326
+ cat: "Text-Stream Folk",
327
+ head: "Text-Stream Folk",
328
+ tail: "Text-Stream Folk",
329
+ sed: "Text-Stream Folk",
330
+ awk: "Text-Stream Folk",
331
+ echo: "Echo Chamber Pop",
332
+ make: "Makefile Motown",
333
+ psql: "Query Crooner",
334
+ sqlite3: "Query Crooner",
335
+ ssh: "Remote-Server Reggae"
336
+ };
337
+ var capital = (s) => s.charAt(0).toUpperCase() + s.slice(1);
338
+ var CONNECTOR_NAME = { github: "GitHub", gitlab: "GitLab", posthog: "PostHog", hubspot: "HubSpot" };
339
+ var connectorDisplay = (name) => CONNECTOR_NAME[name.toLowerCase()] ?? name.split(/[-_\s]+/).filter(Boolean).map(capital).join(" ");
340
+ function genreOf(topCommand, topConnector, fallback) {
341
+ if (topCommand)
342
+ return COMMAND_GENRE[topCommand] ?? `${capital(topCommand)}core`;
343
+ if (topConnector)
344
+ return `${connectorDisplay(topConnector)} Lounge`;
345
+ return fallback;
362
346
  }
363
347
 
364
- // src/readers/cursor.ts
365
- import { join as join4 } from "node:path";
366
- var SHELL2 = new Set(["Shell", "shell", "run_terminal_cmd", "run_terminal_command", "terminal"]);
367
- var EDIT = new Set(["edit_file", "search_replace", "StrReplace", "Write", "Edit", "MultiEdit", "write"]);
368
- function chatTimes(cursor) {
369
- const out = new Map;
370
- for (const ws of listDir(join4(cursor, "chats"))) {
371
- for (const chat of listDir(join4(cursor, "chats", ws))) {
372
- const meta = readJson(join4(cursor, "chats", ws, chat, "meta.json"));
373
- if (meta)
374
- out.set(chat, { created: parseTime(meta["createdAtMs"]), updated: parseTime(meta["updatedAtMs"]) });
348
+ // src/charges.ts
349
+ var FIX_IT = /^(pls |please )?fix( it| this)?[.!]*$/;
350
+ function isFixIt(prompt) {
351
+ return FIX_IT.test(prompt.trim().toLowerCase());
352
+ }
353
+ var COMMIT_MSG = /^(?:sudo\s+)?git\s+commit\b[^\n]*?(?:\s-[a-zA-Z]*m|\s--message)[\s=]*(?:"([^"]*)"|'([^']*)'|([^\s"']+))/;
354
+ var JUNK_MSG = /^(fix|fixes|fixed|wip)[.!]*$/;
355
+ function isFixCommit(command) {
356
+ const m = COMMIT_MSG.exec(command);
357
+ const msg = (m?.[1] ?? m?.[2] ?? m?.[3] ?? "").trim().toLowerCase();
358
+ return JUNK_MSG.test(msg);
359
+ }
360
+ function isPushToMain(command) {
361
+ return /^(?:sudo\s+)?git\s+push\b[^;&|\n]*(?:^|[\s:])(?:main|master)(?=$|\s)/.test(command);
362
+ }
363
+ var WRAPPERS2 = new Set(["sudo", "time", "command", "env", "nohup", "exec", "xargs"]);
364
+ function wordsOf(segment) {
365
+ const words = segment.split(/\s+/).filter(Boolean).map((w) => w.replace(/^(["'])(.*)\1$/, "$2"));
366
+ let i = 0;
367
+ while (i < words.length && /^[A-Za-z_]\w*=/.test(words[i]))
368
+ i++;
369
+ while (words[i] !== undefined && WRAPPERS2.has(words[i])) {
370
+ i++;
371
+ while (words[i]?.startsWith("-"))
372
+ i++;
373
+ while (i < words.length && /^[A-Za-z_]\w*=/.test(words[i]))
374
+ i++;
375
+ }
376
+ return words.slice(i);
377
+ }
378
+ var programName = (words) => (words[0] ?? "").split("/").pop() ?? "";
379
+ var baseName = (path) => path.split(/[\\/]/).pop() ?? "";
380
+ var ENV_FILE = /^\.env(\..+)?$/;
381
+ var ENV_TEMPLATE = /\.(example|sample|template)$/;
382
+ function isEnvFile(path) {
383
+ const name = baseName(path);
384
+ return ENV_FILE.test(name) && !ENV_TEMPLATE.test(name);
385
+ }
386
+ var FILE_READERS = new Set(["cat", "less", "head", "tail", "more"]);
387
+ function isEnvRead(segment) {
388
+ const words = wordsOf(segment);
389
+ return FILE_READERS.has(programName(words)) && words.slice(1).some((w) => !w.startsWith("-") && isEnvFile(w));
390
+ }
391
+ function isRmRf(segment) {
392
+ const words = wordsOf(segment);
393
+ if (programName(words) !== "rm")
394
+ return false;
395
+ let recursive = false;
396
+ let force = false;
397
+ for (const w of words.slice(1)) {
398
+ if (w === "--")
399
+ break;
400
+ if (w === "--recursive")
401
+ recursive = true;
402
+ else if (w === "--force")
403
+ force = true;
404
+ else if (/^-[A-Za-z]+$/.test(w)) {
405
+ if (/[rR]/.test(w))
406
+ recursive = true;
407
+ if (w.includes("f"))
408
+ force = true;
375
409
  }
376
410
  }
377
- return out;
411
+ return recursive && force;
378
412
  }
379
- function userText(o) {
380
- const content = asObj(o["message"])?.["content"] ?? o["content"];
381
- const raw = typeof content === "string" ? content : Array.isArray(content) ? content.map(asObj).filter((p) => p?.["type"] === "text").map((p) => str(p?.["text"]) ?? "").join(`
382
- `) : "";
383
- const m = /<user_query>([\s\S]*?)<\/user_query>/.exec(raw);
384
- return (m ? m[1] : raw).trim() || null;
413
+ var GIT_OPTS_WITH_VALUE = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace"]);
414
+ function isForcePush(segment) {
415
+ const words = wordsOf(segment);
416
+ if (programName(words) !== "git")
417
+ return false;
418
+ let i = 1;
419
+ while (words[i]?.startsWith("-"))
420
+ i += GIT_OPTS_WITH_VALUE.has(words[i]) ? 2 : 1;
421
+ if (words[i] !== "push")
422
+ return false;
423
+ return words.slice(i + 1).some((w) => w === "--force" || /^-[A-Za-z]*f[A-Za-z]*$/.test(w));
424
+ }
425
+ function isCurlSh(pipeline) {
426
+ return pipeline.some((seg, i) => {
427
+ if (i === 0)
428
+ return false;
429
+ const downloader = programName(wordsOf(pipeline[i - 1]));
430
+ return (downloader === "curl" || downloader === "wget") && ["sh", "bash", "zsh"].includes(programName(wordsOf(seg)));
431
+ });
385
432
  }
386
- function readCursor(home, range) {
387
- const cursor = join4(home, ".cursor");
388
- const times = chatTimes(cursor);
389
- const files = walk(join4(cursor, "projects"), (n) => n.endsWith(".jsonl"), 4).filter((f) => f.includes("agent-transcripts"));
390
- const sessions = new Map;
391
- for (const file of files.sort()) {
392
- const text = readText(file);
393
- if (text === null)
394
- continue;
395
- const parts = file.split("/");
396
- const stem = (parts.pop() ?? "").replace(/\.jsonl$/, "");
397
- const chat = stem;
398
- const meta = times.get(chat);
399
- const lines = jsonLines(text);
400
- const s = newSession();
401
- const created = meta?.created ?? null;
402
- const updated = meta?.updated ?? created;
403
- lines.forEach((o, n) => {
404
- const own = parseTime(o["timestamp"]);
405
- const at = own ?? (created && updated ? new Date(created.getTime() + (updated.getTime() - created.getTime()) * n / Math.max(lines.length - 1, 1)) : null);
406
- if (!at)
407
- return;
408
- const role = o["role"];
409
- if (role === "user") {
410
- const t = userText(o);
411
- if (t)
412
- s.events.push({ kind: "prompt", at, text: t });
413
- return;
414
- }
415
- if (role !== "assistant")
416
- return;
417
- const content = asObj(o["message"])?.["content"] ?? o["content"];
418
- for (const item of Array.isArray(content) ? content : []) {
419
- const b = asObj(item);
420
- if (!b)
421
- continue;
422
- if (b["type"] === "text" && str(b["text"]))
423
- s.events.push({ kind: "reply", at, text: b["text"], model: null });
424
- else if (b["type"] === "tool_use") {
425
- const name = str(b["name"]);
426
- if (!name)
427
- continue;
428
- const input = asObj(b["input"]);
429
- const path = str(input?.["path"]) ?? str(input?.["file_path"]) ?? str(input?.["target_file"]);
430
- if (SHELL2.has(name))
431
- s.events.push({ kind: "tool", at, tool: "Bash", connector: null, command: str(input?.["command"]), path: null });
432
- else if (EDIT.has(name))
433
- s.events.push({ kind: "tool", at, tool: "Edit", connector: null, command: null, path });
434
- else
435
- s.events.push({ kind: "tool", at, tool: name, connector: connectorOf(name), command: null, path });
436
- }
437
- }
438
- });
439
- sessions.set(chat, s);
433
+ var ERROR_WORD = /error|exception|traceback|panic|fatal|^\s*at .+:\d+/i;
434
+ var TRACE_LINE = /^\s+\S|^\s*at\s|^\s*File ".+", line \d+|:\d+(:\d+)?\)?\s*$|^\s*[\^~]+\s*$|^\s*\d+\s*[|│]|^\s*(caused by|npm ERR|warn|fail|exit|command failed)/i;
435
+ function isPastedError(prompt) {
436
+ const lines = prompt.split(`
437
+ `).filter((l) => l.trim() !== "");
438
+ if (lines.length < 2 || !lines.some((l) => ERROR_WORD.test(l)))
439
+ return false;
440
+ return lines.every((l) => ERROR_WORD.test(l) || TRACE_LINE.test(l));
441
+ }
442
+ function count2(f, kind, pred) {
443
+ let n = 0;
444
+ for (const e of f.events)
445
+ if (e.kind === kind && pred(e))
446
+ n++;
447
+ return n;
448
+ }
449
+ var sessionsWith = (f, a) => [...f.sessions.values()].filter((s) => s.autonomy === a).length;
450
+ var bash = (f, pred) => f.events.reduce((n, e) => e.kind === "tool" && e.command !== null ? n + shellSegments(e.command).filter(pred).length : n, 0);
451
+ var pipelines = (f, pred) => f.events.reduce((n, e) => e.kind === "tool" && e.command !== null ? n + shellPipelines(e.command).filter(pred).length : n, 0);
452
+ var CHARGES = [
453
+ { id: "fixIt", label: "typed just “fix it”", count: (f) => count2(f, "prompt", (e) => isFixIt(e.text)) },
454
+ { id: "fixCommits", label: "commits named just “fix”", count: (f) => bash(f, isFixCommit) },
455
+ { id: "pushMain", label: "pushed straight to main", count: (f) => bash(f, isPushToMain) },
456
+ {
457
+ id: "readEnv",
458
+ label: "read your .env",
459
+ count: (f) => count2(f, "tool", (e) => e.tool === "Read" && e.path !== null && isEnvFile(e.path)) + bash(f, isEnvRead)
460
+ },
461
+ { id: "rmRf", label: "ran rm -rf", count: (f) => bash(f, isRmRf) },
462
+ { id: "forcePush", label: "force-pushed", count: (f) => bash(f, isForcePush) },
463
+ { id: "curlSh", label: "piped curl into a shell", count: (f) => pipelines(f, isCurlSh) },
464
+ {
465
+ id: "dontAskAgain",
466
+ label: "said “Yes, don’t ask again”",
467
+ count: (f) => f.approvals.claudeAllowRules + sessionsWith(f, "bypass")
468
+ },
469
+ { id: "pastedError", label: "pasted an error and nothing else", count: (f) => count2(f, "prompt", (e) => isPastedError(e.text)) }
470
+ ];
471
+ var ABSOLUTELY_RIGHT = /you['’]re absolutely right/i;
472
+ var INSTRUCTION_FILE = /(^|[\\/])(CLAUDE|AGENTS)\.md$/;
473
+ var WRITE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
474
+ var TRACKS = [
475
+ { id: "absolutelyRight", title: "You’re Absolutely Right", mix: "Acoustic", plays: (f) => count2(f, "reply", (e) => ABSOLUTELY_RIGHT.test(e.text)) },
476
+ { id: "acceptAll", title: "Accept All", mix: "Taylor’s Version", plays: (f) => sessionsWith(f, "auto") },
477
+ { id: "skipPermissions", title: "Skip Permissions", mix: "Radio Edit", plays: (f) => sessionsWith(f, "bypass") },
478
+ { id: "contextLeft", title: "Context Left: 2%", mix: "Live", plays: (f) => count2(f, "compaction", () => true) },
479
+ {
480
+ id: "claudeMd",
481
+ title: "Bohemian Rhapsody in CLAUDE.md",
482
+ mix: "Demo",
483
+ plays: (f) => count2(f, "tool", (e) => WRITE_TOOLS.has(e.tool) && e.path !== null && INSTRUCTION_FILE.test(e.path))
440
484
  }
441
- return { events: assemble("cursor", sessions, range), found: files.length > 0 };
485
+ ];
486
+ function computeCharges(f) {
487
+ return CHARGES.map((c) => ({ id: c.id, label: c.label, count: c.count(f) })).filter((c) => c.count > 0);
442
488
  }
443
-
444
- // src/readers/index.ts
445
- function readAll(home, now, codexHome = process.env["CODEX_HOME"]) {
446
- const range = { from: bounds(windowFor(now)).from, until: now };
447
- const found = [];
448
- const events = [];
449
- let claudeAllowRules = 0;
450
- let firstStarted = null;
451
- const attempts = [
452
- [
453
- "claude-code",
454
- () => {
455
- const r = readClaude(home, range);
456
- claudeAllowRules = r.allowRules;
457
- firstStarted = r.firstStarted;
458
- return r;
459
- }
460
- ],
461
- ["codex", () => readCodex(home, range, codexHome)],
462
- ["cursor", () => readCursor(home, range)]
489
+ function computeTracks(f, topCommand, topConnector) {
490
+ const own = [
491
+ ...topCommand ? [{ id: "topCommand", title: `${topCommand.name} on Repeat`, mix: "Extended Mix", plays: topCommand.count }] : [],
492
+ ...topConnector ? [{ id: "topConnector", title: `Hotline ${connectorDisplay(topConnector.name)}`, mix: "Club Mix", plays: topConnector.count }] : []
463
493
  ];
464
- for (const [harness, run] of attempts) {
465
- try {
466
- const r = run();
467
- if (r.found)
468
- found.push(harness);
469
- events.push(...r.events);
470
- } catch {}
471
- }
472
- return { events, approvals: { claudeAllowRules }, found, firstStarted };
494
+ return [...TRACKS.map((t) => ({ id: t.id, title: t.title, mix: t.mix, plays: t.plays(f) })), ...own].filter((t) => t.plays > 0).sort((a, b) => b.plays - a.plays).slice(0, 5);
473
495
  }
474
496
 
475
- // src/server.ts
476
- import { createServer } from "node:http";
477
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
478
- import { dirname, join as join5 } from "node:path";
479
- import { fileURLToPath } from "node:url";
480
-
481
- // src/fonts.ts
482
- var FONT_FILES = [
483
- { pkg: "fraunces", family: "Fraunces", weight: 300, style: "normal", file: "fraunces-latin-300-normal.woff2" },
484
- { pkg: "fraunces", family: "Fraunces", weight: 300, style: "italic", file: "fraunces-latin-300-italic.woff2" },
485
- ...[400, 600, 700, 800].map((weight) => ({ pkg: "manrope", family: "Manrope", weight, style: "normal", file: `manrope-latin-${weight}-normal.woff2` })),
486
- ...[400, 500].map((weight) => ({ pkg: "dm-mono", family: "DM Mono", weight, style: "normal", file: `dm-mono-latin-${weight}-normal.woff2` }))
487
- ];
488
- var fontFaceCss = () => FONT_FILES.map((f) => `@font-face{font-family:'${f.family}';font-weight:${f.weight};font-style:${f.style};font-display:swap;src:url(/fonts/${f.file}) format('woff2')}`).join("");
489
-
490
- // src/brand.ts
491
- var BRAND = {
492
- forest: "#1E5A3C",
493
- mist: "#F8FBF8",
494
- "mist-2": "#E8F1E9",
495
- ink: "#12241A",
496
- "ink-dark": "#071A13",
497
- sage: "#389560",
498
- rose: "#C05B6B",
499
- blush: "#EEB2B8",
500
- "rose-tint": "#FFEDEE",
501
- border: "#DDE3DE",
502
- muted: "#5A675F",
503
- white: "#FFFFFF"
504
- };
505
- var brandCss = () => `:root{${Object.entries(BRAND).map(([k, v]) => `--${k}:${v}`).join(";")}}`;
506
- var MARK_PATH = "M11 5V27M11 6L21 12L11 18M15 18L22 27";
507
- var markSvg = (size, color = "var(--forest)") => `<svg class="mark" width="${size}" height="${size}" viewBox="0 0 32 32" fill="none" stroke="${color}" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${MARK_PATH}"/></svg>`;
508
-
509
- // src/config.ts
510
- var API_BASE = "https://agent-wrapped.trappetarn.workers.dev";
511
- var SHARE_URL = "https://github.com/Trappetarn/agent-wrapped";
512
- var SHARE_TARGETS = [
513
- { id: "x", label: "X", url: "https://x.com/intent/post?text={text}&url={url}" },
514
- { id: "linkedin", label: "LinkedIn", url: "https://www.linkedin.com/sharing/share-offsite/?url={url}" },
515
- { id: "reddit", label: "Reddit", url: "https://www.reddit.com/submit?url={url}&title={text}" },
516
- { id: "bluesky", label: "Bluesky", url: "https://bsky.app/intent/compose?text={text}%20{url}" }
517
- ];
518
- var CAL_URL = "https://cal.com/lisa-buerger/15min";
519
- var TEAM_SIZES = ["Just me", "2–20", "21–200", "200+"];
497
+ // src/types.ts
498
+ var HARNESS_NAME = { "claude-code": "Claude Code", codex: "Codex", cursor: "Cursor" };
520
499
 
521
- // src/client.ts
522
- var CLIENT_SCRIPT = String.raw`
523
- (function () {
524
- var D = JSON.parse(document.getElementById("data").textContent);
525
- var W = D.wrapped, B = D.brand;
526
- var $ = function (id) { return document.getElementById(id); };
527
- var num = function (n) { return n.toLocaleString("en-US"); };
500
+ // src/window.ts
501
+ function ymd(d) {
502
+ const p = (n) => String(n).padStart(2, "0");
503
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
504
+ }
505
+ function windowFor(now) {
506
+ return { start: `${now.getFullYear()}-01-01`, end: ymd(now) };
507
+ }
508
+ function bounds(w) {
509
+ const [sy, sm, sd] = w.start.split("-").map(Number);
510
+ const [ey, em, ed] = w.end.split("-").map(Number);
511
+ return { from: new Date(sy, sm - 1, sd), until: new Date(ey, em - 1, ed + 1) };
512
+ }
528
513
 
529
- function wire(openId, dlgId, onOpen) {
530
- $(openId).addEventListener("click", function () { if (onOpen) onOpen(); $(dlgId).showModal(); });
514
+ // src/stats.ts
515
+ var WEB_TOOLS = new Set(["WebFetch", "WebSearch"]);
516
+ var SUBAGENT_TOOLS = new Set(["Task", "Agent"]);
517
+ var WRITE_TOOLS2 = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
518
+ var GAP_CAP_MS = 30 * 60 * 1000;
519
+ var DAY_MS = 86400000;
520
+ var WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
521
+ var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
522
+ function ranked(counts, limit) {
523
+ return [...counts].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)).slice(0, limit);
524
+ }
525
+ function bump(m, k) {
526
+ m.set(k, (m.get(k) ?? 0) + 1);
527
+ }
528
+ function modelFamily(id) {
529
+ const m = id.toLowerCase();
530
+ if (m.startsWith("<"))
531
+ return null;
532
+ for (const f of ["opus", "sonnet", "haiku"])
533
+ if (m.includes(f))
534
+ return f[0].toUpperCase() + f.slice(1);
535
+ const gpt = /gpt-?(\d+)/.exec(m);
536
+ if (gpt)
537
+ return `GPT-${gpt[1]}`;
538
+ if (/^o\d/.test(m))
539
+ return "o-series";
540
+ if (m.includes("gemini"))
541
+ return "Gemini";
542
+ if (m.includes("grok"))
543
+ return "Grok";
544
+ if (m.includes("composer"))
545
+ return "Composer";
546
+ return id;
547
+ }
548
+ var UUID_LIKE = /^[0-9a-f]{8}-[0-9a-f]{4}-/i;
549
+ function userConnector(server) {
550
+ const name = server.replace(/^claude_ai_/i, "");
551
+ if (/^ccd_/i.test(name) || /^claude/i.test(name) || UUID_LIKE.test(name) || name === "")
552
+ return null;
553
+ return name;
554
+ }
555
+ function programsOf(command) {
556
+ return shellSegments(command).flatMap((seg) => programOf(seg) ?? []);
557
+ }
558
+ function shortName(name, max = 22) {
559
+ if (name.length <= max)
560
+ return name;
561
+ const tail = Math.ceil((max - 1) * 0.65);
562
+ return `${name.slice(0, max - 1 - tail)}…${name.slice(name.length - tail)}`;
563
+ }
564
+ function hourLabel(h) {
565
+ const suffix = h < 12 ? "a.m." : "p.m.";
566
+ return `${h % 12 === 0 ? 12 : h % 12} ${suffix}`;
567
+ }
568
+ function hangoutOf(tools) {
569
+ const reads = tools.filter((t) => t.path !== null && t.tool === "Read");
570
+ const pool = reads.length > 0 ? reads : tools.filter((t) => t.path !== null);
571
+ const byFile = new Map;
572
+ for (const t of pool)
573
+ bump(byFile, basename(t.path));
574
+ const top = ranked(byFile, 1)[0];
575
+ const hours = new Array(24).fill(0);
576
+ for (const t of pool)
577
+ if (top && basename(t.path) === top.name)
578
+ hours[t.at.getHours()]++;
579
+ const peak = hours.indexOf(Math.max(...hours));
580
+ const where = !top ? "terminal" : top.name.startsWith(".env") ? `${top.name} file` : shortName(top.name);
581
+ return `Your ${where}, at ${hourLabel(top ? peak : peakHour(tools))}`;
582
+ }
583
+ function peakHour(tools) {
584
+ const hours = new Array(24).fill(0);
585
+ for (const t of tools)
586
+ hours[t.at.getHours()]++;
587
+ return hours.indexOf(Math.max(...hours));
588
+ }
589
+ var hasActivity = (d) => d.toolCalls > 0 || d.sessions > 0;
590
+ function parseYmd(s) {
591
+ const [y, m, d] = s.split("-").map(Number);
592
+ return new Date(y, m - 1, d);
593
+ }
594
+ function longestStreak(dayIndexes, startMs) {
595
+ const days = [...new Set(dayIndexes)].sort((a, b) => a - b);
596
+ let best = null;
597
+ let from = 0;
598
+ for (let i = 1;i <= days.length; i++) {
599
+ if (i < days.length && days[i] === days[i - 1] + 1)
600
+ continue;
601
+ if (days.length > 0 && (!best || i - from > best[1] - best[0] + 1))
602
+ best = [from, i - 1];
603
+ from = i;
531
604
  }
532
- document.querySelectorAll("[data-close]").forEach(function (b) {
533
- b.addEventListener("click", function () { b.closest("dialog").close(); });
534
- });
535
- document.querySelectorAll("dialog").forEach(function (d) {
536
- d.addEventListener("click", function (e) { if (e.target === d) d.close(); });
537
- });
538
-
539
- function post(path, body) {
540
- return fetch(D.api + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })
541
- .then(function (r) { if (!r.ok) throw new Error("status " + r.status); });
605
+ if (!best)
606
+ return null;
607
+ const at = (i) => ymd(new Date(startMs.getFullYear(), startMs.getMonth(), startMs.getDate() + days[i]));
608
+ return { days: best[1] - best[0] + 1, start: at(best[0]), end: at(best[1]) };
609
+ }
610
+ var sortedDays = (m) => [...m.values()].sort((a, b) => a.date.localeCompare(b.date));
611
+ function mergeDays(days) {
612
+ const out = new Map;
613
+ for (const d of days) {
614
+ const o = out.get(d.date);
615
+ out.set(d.date, o ? { date: d.date, toolCalls: Math.max(o.toolCalls, d.toolCalls), sessions: Math.max(o.sessions, d.sessions) } : d);
542
616
  }
543
- function status(el, text, bad) { el.textContent = text; el.className = "status" + (bad ? " err" : ""); }
544
- var FRIENDLY = "Could not reach the server just now. Nothing was sent. Try again later.";
545
-
546
- // Waitlist: only the form fields are sent.
547
- $("waitlist").addEventListener("submit", function (e) {
548
- e.preventDefault();
549
- var f = e.target, st = $("wl-status");
550
- status(st, "Sending...", false);
551
- post("/waitlist", { email: f.email.value.trim(), teamSize: f.teamSize.value })
552
- .then(function () { status(st, "You're on the list. We'll email you when team Wrapped is ready.", false); f.reset(); })
553
- .catch(function () { status(st, FRIENDLY, true); });
554
- });
555
-
556
- wire("open-team", "team");
557
-
558
- // ---- Share cards: drawn natively on a 1080x1920 canvas from the card list in D.cards. ----
559
- var SANS = "Manrope, system-ui, sans-serif", SERIF = "Fraunces, Georgia, serif", MONO = "'DM Mono', ui-monospace, monospace";
560
- var MINT = "#BFE3C8", SAGE_LIGHT = "#9FD0B0", GRID = 48;
561
- var THEMES = {
562
- dark: { bg: B["ink-dark"], grid: "rgba(248,251,248,0.022)", body: B.mist, eyebrow: "rgba(248,251,248,0.62)", rule: "rgba(248,251,248,0.14)", sub: "rgba(248,251,248,0.62)",
563
- heroText: B.ink, heroWord: B.forest, heroEyebrow: "rgba(18,36,26,0.78)", heroMark: "rgba(30,90,60,0.12)", heroMarkSmall: B.forest, accent: { forest: SAGE_LIGHT, rose: B.blush }, footMark: B.mist, site: "rgba(248,251,248,0.62)" },
564
- light: { bg: B.mist, grid: "rgba(30,90,60,0.045)", body: B.ink, eyebrow: B.muted, rule: "rgba(18,36,26,0.12)", sub: B.muted,
565
- heroText: B.mist, heroWord: MINT, heroEyebrow: "rgba(248,251,248,0.78)", heroMark: "rgba(248,251,248,0.12)", heroMarkSmall: B["mist-2"], accent: { forest: B.forest, rose: B.rose }, footMark: B.forest, site: B.muted }
617
+ return sortedDays(out);
618
+ }
619
+ function transcriptDays(events, window) {
620
+ const { from, until } = bounds(window);
621
+ const days = new Map;
622
+ const day = (at) => {
623
+ const date = ymd(at);
624
+ return days.get(date) ?? { date, toolCalls: 0, sessions: 0 };
566
625
  };
567
-
568
- function glow(c, x, y, r, rgb, a) {
569
- var g = c.createRadialGradient(x, y, 0, x, y, r);
570
- g.addColorStop(0, "rgba(" + rgb + "," + a + ")"); g.addColorStop(1, "rgba(" + rgb + ",0)");
571
- c.fillStyle = g; c.fillRect(x - r, y - r, r * 2, r * 2);
572
- }
573
- function grid(c, x0, y0, w, h, color) {
574
- c.save(); c.beginPath(); c.rect(x0, y0, w, h); c.clip();
575
- c.strokeStyle = color; c.lineWidth = 2; c.beginPath();
576
- for (var x = x0 - (x0 % GRID); x <= x0 + w; x += GRID) { c.moveTo(x, y0); c.lineTo(x, y0 + h); }
577
- for (var y = y0 - (y0 % GRID); y <= y0 + h; y += GRID) { c.moveTo(x0, y); c.lineTo(x0 + w, y); }
578
- c.stroke(); c.restore();
579
- }
580
- // The rune on a 32-unit grid; px is the stroke width in canvas pixels.
581
- function mark(c, x, y, size, color, px) {
582
- c.save(); c.translate(x, y); c.scale(size / 32, size / 32);
583
- c.strokeStyle = color; c.lineWidth = px / (size / 32); c.lineCap = "round"; c.lineJoin = "round";
584
- c.stroke(new Path2D("M11 5V27M11 6L21 12L11 18M15 18L22 27")); c.restore();
585
- }
586
- function setFont(c, font) { c.font = font; return c; }
587
- function fontAt(font, size) { return font.replace(/\d+px/, size + "px"); }
588
- // Text with tracking in em, drawn per character so it is measurable and works everywhere.
589
- function spaced(c, s, x, y, font, color, em, align) {
590
- setFont(c, font); c.fillStyle = color; c.textBaseline = "alphabetic"; c.textAlign = "left";
591
- var size = parseFloat(font.match(/(\d+(?:\.\d+)?)px/)[1]), gap = em * size, w = 0, i;
592
- for (i = 0; i < s.length; i++) w += c.measureText(s[i]).width + gap;
593
- w -= gap;
594
- var cx = align === "right" ? x - w : x;
595
- for (i = 0; i < s.length; i++) { c.fillText(s[i], cx, y); cx += c.measureText(s[i]).width + gap; }
596
- return w;
626
+ const starts = new Map;
627
+ for (const e of events) {
628
+ if (e.at < from || e.at >= until)
629
+ continue;
630
+ if (e.kind === "tool") {
631
+ const d = day(e.at);
632
+ days.set(d.date, { ...d, toolCalls: d.toolCalls + 1 });
633
+ }
634
+ const key = `${e.harness}:${e.sessionId}`;
635
+ const s = starts.get(key);
636
+ if (!s || e.at < s)
637
+ starts.set(key, e.at);
597
638
  }
598
- function plain(c, s, x, y, font, color, align) { setFont(c, font); c.fillStyle = color; c.textAlign = align || "left"; c.textBaseline = "alphabetic"; c.fillText(s, x, y); }
599
- function fitFont(c, s, font, maxW, min) {
600
- var size = parseInt(font.match(/(\d+)px/)[1], 10);
601
- while (size > (min || 20)) { setFont(c, fontAt(font, size)); if (c.measureText(s).width <= maxW) break; size -= 2; }
602
- return fontAt(font, size);
639
+ for (const at of starts.values()) {
640
+ const d = day(at);
641
+ days.set(d.date, { ...d, sessions: d.sessions + 1 });
603
642
  }
604
- // Greedy word wrap that measures every line. A word wider than maxW breaks after hyphens, then by character.
605
- function wrapText(c, s, font, maxW) {
606
- setFont(c, font);
607
- var pieces = [];
608
- s.split(" ").forEach(function (word) {
609
- var parts = word.split(/(?<=[A-Za-z0-9]-)(?=[A-Za-z0-9])/);
610
- parts.forEach(function (p, i) {
611
- if (c.measureText(p).width <= maxW) { pieces.push({ t: p, sp: i === 0 }); return; }
612
- var cur = "", first = i === 0;
613
- for (var k = 0; k < p.length; k++) {
614
- if (cur && c.measureText(cur + p[k]).width > maxW) { pieces.push({ t: cur, sp: first }); first = false; cur = ""; }
615
- cur += p[k];
616
- }
617
- if (cur) pieces.push({ t: cur, sp: first });
618
- });
619
- });
620
- var lines = [], line = "";
621
- pieces.forEach(function (p) {
622
- var next = line ? line + (p.sp ? " " : "") + p.t : p.t;
623
- if (line && c.measureText(next).width > maxW) { lines.push(line); line = p.t; } else line = next;
624
- });
625
- if (line) lines.push(line);
626
- return lines;
643
+ return sortedDays(days);
644
+ }
645
+ function highlightsOf(tools, sessions) {
646
+ const byDay = new Map;
647
+ for (const t of tools)
648
+ bump(byDay, ymd(t.at));
649
+ const busiest = [...byDay].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
650
+ let longest = null;
651
+ for (const s of sessions.values()) {
652
+ const ts = s.at.map((d) => d.getTime()).sort((a, b) => a - b);
653
+ let ms = 0;
654
+ for (let i = 1;i < ts.length; i++)
655
+ ms += Math.min(ts[i] - ts[i - 1], GAP_CAP_MS);
656
+ const minutes = Math.round(ms / 60000);
657
+ if (minutes > 0 && (!longest || minutes > longest.minutes || minutes === longest.minutes && s.start < longest.start))
658
+ longest = { minutes, start: s.start };
627
659
  }
628
-
629
- function background(c, th, dark) {
630
- c.fillStyle = th.bg; c.fillRect(0, 0, 1080, 1920);
631
- if (dark) { glow(c, 120, 80, 620, "30,90,60", 0.42); glow(c, 1020, 760, 520, "30,90,60", 0.3); glow(c, 300, 1500, 700, "30,90,60", 0.2); }
632
- else { glow(c, 0, 420, 520, "30,90,60", 0.13); glow(c, 1080, 760, 520, "192,91,107", 0.1); }
633
- grid(c, 0, 0, 1080, 1920, th.grid);
660
+ const projects = new Map;
661
+ for (const t of tools) {
662
+ const project = sessions.get(`${t.harness}:${t.sessionId}`)?.project;
663
+ if (project)
664
+ bump(projects, project);
634
665
  }
635
-
636
- function face(c, th, dark) {
637
- var cx = 700, cy = 330, r = 118;
638
- c.save(); c.beginPath(); c.arc(cx, cy, r, 0, Math.PI * 2); c.clip();
639
- c.fillStyle = B.forest; c.fillRect(cx - r, cy - r, r * 2, r * 2);
640
- c.fillStyle = B.rose; c.fillRect(cx - r, cy - r, r * 2, 40);
641
- plain(c, "sudo", cx, cy - r + 29, "400 24px " + MONO, B.mist, "center");
642
- c.fillStyle = B.mist; c.beginPath(); c.arc(cx - 40, cy - 8, 16, 0, Math.PI * 2); c.arc(cx + 40, cy - 8, 16, 0, Math.PI * 2); c.fill();
643
- c.beginPath(); c.roundRect(cx - 40, cy + 44, 80, 14, 7); c.fill();
644
- c.restore();
666
+ return {
667
+ busiestDay: busiest ? { date: busiest[0], toolCalls: busiest[1] } : null,
668
+ longestSession: longest ? { minutes: longest.minutes, date: ymd(longest.start) } : null,
669
+ topProject: ranked(projects, 1)[0] ?? null
670
+ };
671
+ }
672
+ function tokensOf(events) {
673
+ const usage = events.filter((e) => e.kind === "usage");
674
+ if (usage.length === 0)
675
+ return null;
676
+ const sum = (f) => usage.reduce((a, u) => a + f(u), 0);
677
+ return { total: sum((u) => u.input + u.output + u.cacheRead + u.cacheWrite), output: sum((u) => u.output) };
678
+ }
679
+ function computeWrapped(result, window) {
680
+ const { from, until } = bounds(window);
681
+ const events = result.events.filter((e) => e.at >= from && e.at < until);
682
+ const tools = events.filter((e) => e.kind === "tool");
683
+ const dayCount = Math.round((until.getTime() - from.getTime()) / DAY_MS);
684
+ const sessions = new Map;
685
+ for (const e of events) {
686
+ const key = `${e.harness}:${e.sessionId}`;
687
+ let s = sessions.get(key);
688
+ if (!s)
689
+ sessions.set(key, s = { autonomy: "ask", project: null, start: e.at, at: [] });
690
+ s.at.push(e.at);
691
+ if (e.at < s.start)
692
+ s.start = e.at;
693
+ if (e.kind === "session") {
694
+ s.autonomy = e.autonomy;
695
+ s.project = e.project;
696
+ }
645
697
  }
646
-
647
- function hero(c, card, th, dark) {
648
- var x = 150, y = 110, w = 780, h = 720, r = 32;
649
- c.save(); c.shadowColor = dark ? "rgba(0,0,0,0.45)" : "rgba(7,26,19,0.28)"; c.shadowBlur = 70; c.shadowOffsetY = 28;
650
- c.fillStyle = dark ? B["mist-2"] : B.forest; c.beginPath(); c.roundRect(x, y, w, h, r); c.fill(); c.restore();
651
- c.save(); c.beginPath(); c.roundRect(x, y, w, h, r); c.clip();
652
- var g = c.createLinearGradient(x, y, x + w, y + h);
653
- if (dark) { g.addColorStop(0, B["mist-2"]); g.addColorStop(1, B.mist); } else { g.addColorStop(0, "#216143"); g.addColorStop(1, "#19492f"); }
654
- c.fillStyle = g; c.fillRect(x, y, w, h);
655
- if (dark) { glow(c, 360, 260, 320, "56,149,96", 0.3); glow(c, 850, 740, 300, "192,91,107", 0.18); grid(c, x, y, w, h, "rgba(18,36,26,0.035)"); }
656
- else { glow(c, 330, 250, 360, "159,208,176", 0.3); glow(c, 860, 790, 340, "7,26,19", 0.4); grid(c, x, y, w, h, "rgba(248,251,248,0.03)"); }
657
- if (card.hero === "face") face(c, th, dark); else mark(c, 481, 364, 516, th.heroMark, 22);
658
- spaced(c, "AGENT ACTIVITY · YEAR IN REVIEW", 204, 179, "400 20px " + MONO, th.heroEyebrow, 0.2);
659
- mark(c, 840, 154, 36, th.heroMarkSmall, 2.6);
660
- var tf = fitFont(c, card.title, "300 150px " + SERIF, 672, 60), size = parseInt(tf.match(/(\d+)px/)[1], 10);
661
- var base = 612;
662
- spaced(c, "2026", 204, base - size * 0.7 - 62, "400 34px " + MONO, th.heroText, 0.2);
663
- plain(c, card.title, 204, base, tf, th.heroText);
664
- plain(c, "Wrapped", 220, 752, "italic 300 150px " + SERIF, th.heroWord);
665
- c.restore();
666
- return size;
698
+ let agentMs = 0;
699
+ for (const s of sessions.values()) {
700
+ const ts = s.at.map((d) => d.getTime()).sort((a, b) => a - b);
701
+ for (let i = 1;i < ts.length; i++)
702
+ agentMs += Math.min(ts[i] - ts[i - 1], GAP_CAP_MS);
667
703
  }
668
-
669
- var COLS = { 1: [[84, 912]], 2: [[84, 400], [536, 460]] };
670
- function header(c, th, label, x, y, w) {
671
- spaced(c, label, x, y, "400 22px " + MONO, th.eyebrow, 0.2);
672
- c.fillStyle = th.rule; c.fillRect(x, y + 26, w, 2);
704
+ const daily = new Array(dayCount).fill(0);
705
+ const hours = new Array(24).fill(0);
706
+ const toolNames = new Map;
707
+ const connectors = new Map;
708
+ const commands = new Map;
709
+ const harnessCalls = new Map;
710
+ for (const t of tools) {
711
+ hours[t.at.getHours()]++;
712
+ if (t.connector) {
713
+ const c = userConnector(t.connector);
714
+ if (c)
715
+ bump(connectors, c);
716
+ } else
717
+ bump(toolNames, t.tool);
718
+ if (t.command)
719
+ for (const p of programsOf(t.command))
720
+ bump(commands, p);
721
+ bump(harnessCalls, HARNESS_NAME[t.harness]);
673
722
  }
674
- // One list column. Returns {h, lines}: h is the height from the header baseline to the last baseline.
675
- function listCol(c, th, accent, col, x, w, y, size) {
676
- header(c, th, col.header, x, y, w);
677
- var font = "500 " + size + "px " + SANS, lh = Math.round(size * 1.13), gap = 15, indent = 46, by = y + 26 + 50, maxLines = 0;
678
- col.items.forEach(function (it, i) {
679
- var rw = 0;
680
- if (it.right) { setFont(c, "400 24px " + MONO); rw = c.measureText(it.right).width + 24; }
681
- var tw = w - indent - rw, lines = wrapText(c, it.text, font, tw), ll;
682
- var tail = [];
683
- if (it.sub) tail.push({ s: it.sub, font: "400 " + size + "px " + SANS, color: th.sub });
684
- if (it.note) tail.push({ s: it.note, font: "400 24px " + MONO, color: th.sub });
685
- var lastX = 0, lastLine;
686
- lines.forEach(function (l, j) { plain(c, l, x + indent, by + j * lh, font, th.body); });
687
- lastLine = lines[lines.length - 1]; setFont(c, font); lastX = c.measureText(lastLine).width;
688
- var ty = by + (lines.length - 1) * lh;
689
- tail.forEach(function (t) {
690
- setFont(c, t.font); var tw2 = c.measureText(t.s).width;
691
- if (lastX + 18 + tw2 > tw) { ty += lh; lastX = 0; lines.push(""); } else lastX += 18;
692
- plain(c, t.s, x + indent + lastX, ty, t.font, t.color); lastX += tw2;
693
- });
694
- maxLines = Math.max(maxLines, lines.length);
695
- plain(c, String(i + 1).padStart(2, "0"), x, by - 2, "400 22px " + MONO, accent);
696
- if (it.right) plain(c, it.right, x + w, by, "400 24px " + MONO, th.sub, "right");
697
- by += (lines.length - 1) * lh + lh + gap;
698
- });
699
- return { h: by - lh - gap - y + 24, lines: maxLines };
723
+ const transcript = new Map(transcriptDays(events, window).map((d) => [d.date, d]));
724
+ const backfill = new Map(mergeDays(result.backfill).map((d) => [d.date, d]));
725
+ let sessionTotal = 0;
726
+ let backfilledDays = 0;
727
+ for (let i = 0;i < dayCount; i++) {
728
+ const date = ymd(new Date(from.getFullYear(), from.getMonth(), from.getDate() + i));
729
+ const t = transcript.get(date);
730
+ const b = backfill.get(date);
731
+ daily[i] = Math.max(t?.toolCalls ?? 0, b?.toolCalls ?? 0);
732
+ sessionTotal += Math.max(t?.sessions ?? 0, b?.sessions ?? 0);
733
+ if (b && (b.toolCalls > (t?.toolCalls ?? 0) || b.sessions > (t?.sessions ?? 0)))
734
+ backfilledDays++;
700
735
  }
701
- function statCol(c, th, accent, col, x, w, y) {
702
- header(c, th, col.label, x, y, w);
703
- var top = y + 26, last;
704
- if (col.kind === "number") {
705
- var f = fitFont(c, col.value, "300 110px " + SERIF, col.unit ? w - 70 : w, 50);
706
- last = top + 113; plain(c, col.value, x, last, f, accent);
707
- if (col.unit) { setFont(c, f); plain(c, col.unit, x + c.measureText(col.value).width + 10, last, "italic 300 56px " + SERIF, accent); }
708
- } else {
709
- var font = col.kind === "display" ? "300 92px " + SERIF : "italic 300 56px " + SERIF, lh = col.kind === "display" ? 96 : 57;
710
- var lines = wrapText(c, col.value, font, w);
711
- lines.forEach(function (l, i) { plain(c, l, x, top + (col.kind === "display" ? 92 : 66) + i * lh, font, accent); });
712
- last = top + (col.kind === "display" ? 92 : 66) + (lines.length - 1) * lh;
713
- }
714
- if (col.caption) {
715
- var cl = wrapText(c, col.caption, "400 28px " + SANS, w), cy = last + (col.kind === "number" ? 48 : 46);
716
- cl.forEach(function (l, i) { plain(c, l, x, cy + i * 33, "400 28px " + SANS, th.body); });
717
- last = cy + (cl.length - 1) * 33;
736
+ let rushHour = null;
737
+ let rushBest = 0;
738
+ for (let h = 0;h < 24; h++) {
739
+ const n = hours[h] + hours[(h + 1) % 24] + hours[(h + 2) % 24];
740
+ if (n > rushBest) {
741
+ rushBest = n;
742
+ rushHour = { from: h, to: (h + 3) % 24 };
718
743
  }
719
- return { h: last - y + 24, lines: 0 };
720
744
  }
721
- // Draws a row with its header baseline at y and returns {h, lines}.
722
- function drawRow(c, th, accent, row, y, size) {
723
- var cols = COLS[row.cols.length], h = 0, lines = 0;
724
- row.cols.forEach(function (col, i) {
725
- var r = row.kind === "lists" ? listCol(c, th, accent, col, cols[i][0], cols[i][1], y, size) : statCol(c, th, accent, col, cols[i][0], cols[i][1], y);
726
- h = Math.max(h, r.h); lines = Math.max(lines, r.lines);
727
- });
728
- return { h: h, lines: lines };
745
+ let latest = null;
746
+ let latestKey = -1;
747
+ for (const s of sessions.values()) {
748
+ const h = s.start.getHours();
749
+ if (h >= 5 && h < 20)
750
+ continue;
751
+ const key = (h < 5 ? 1440 : 0) + h * 60 + s.start.getMinutes();
752
+ if (key > latestKey)
753
+ [latestKey, latest] = [key, s.start];
729
754
  }
730
-
731
- function footer(c, card, th, dark, ft) {
732
- mark(c, 80, ft - 6, 78, th.footMark, 5);
733
- spaced(c, "RUNA", 172, ft + 42, "300 46px " + SERIF, th.body, 0.28);
734
- spaced(c, "npx runa-agent-wrapped", 172, ft + 84, "400 24px " + MONO, th.site, 0.08);
735
- var tf = "italic 300 34px " + SERIF, tl = wrapText(c, card.tagline, tf, 520);
736
- tl.forEach(function (l, i) { plain(c, l, 996, ft + 40 + i * 40, tf, dark ? "rgba(248,251,248,0.85)" : B.ink, "right"); });
737
- return Math.max(ft + 90, ft + 40 + (tl.length - 1) * 40 + 12);
738
- }
739
-
740
- var measureCtx = document.createElement("canvas").getContext("2d");
741
- var FOOT_TOP = 1740, ROWS_TOP = 904, MIN_GAP = 72;
742
- // Lays the rows out between the hero and the footer, spreading the free space evenly.
743
- function drawCard(c, card, size) {
744
- var dark = card.theme === "dark", th = THEMES[card.theme], accent = th.accent[card.accent];
745
- background(c, th, dark);
746
- var heroSize = hero(c, card, th, dark);
747
- var m = card.rows.map(function (row) { return drawRow(measureCtx, th, accent, row, 0, size); });
748
- var lines = Math.max.apply(null, m.map(function (r) { return r.lines; }).concat([0]));
749
- var used = m.reduce(function (s, r) { return s + r.h; }, 0);
750
- var free = FOOT_TOP - 70 - ROWS_TOP - used;
751
- var gap = Math.max(MIN_GAP, Math.min(200, free / (m.length + 0.5)));
752
- var y = ROWS_TOP + (gap > MIN_GAP ? gap * 0.5 - 20 : 0), end = y;
753
- card.rows.forEach(function (row, i) { drawRow(c, th, accent, row, y, size); end = y + m[i].h; y = end + gap; });
754
- var ft = Math.max(1720, Math.min(1780, end + gap + 30));
755
- var bottom = footer(c, card, th, dark, ft);
756
- return { bottom: bottom, end: end, footerTop: ft, lines: lines, heroSize: heroSize };
755
+ const modelCounts = new Map;
756
+ for (const e of events) {
757
+ if (e.kind !== "reply" || !e.model)
758
+ continue;
759
+ const fam = modelFamily(e.model);
760
+ if (fam)
761
+ bump(modelCounts, fam);
757
762
  }
763
+ const facts = { events, approvals: result.approvals, sessions };
764
+ const charges = computeCharges(facts);
765
+ const chargeCount = (id) => charges.find((c) => c.id === id)?.count ?? 0;
766
+ const bypassSessions = [...sessions.values()].filter((s) => s.autonomy === "bypass").length;
767
+ const harnessShare = ranked(harnessCalls, 3);
768
+ const topHarness = Object.keys(HARNESS_NAME).find((h) => HARNESS_NAME[h] === harnessShare[0]?.name) ?? null;
769
+ const agentHours = Math.round(agentMs / 3600000 * 10) / 10;
770
+ const share = (n) => tools.length > 0 ? n / tools.length : 0;
771
+ const callsWhere = (pred) => tools.filter(pred).length;
772
+ const archetype = pickArchetype({
773
+ sessions: sessions.size,
774
+ bypassSessions,
775
+ dontAskAgain: chargeCount("dontAskAgain"),
776
+ compactions: events.filter((e) => e.kind === "compaction").length,
777
+ agentHours,
778
+ toolCalls: tools.length,
779
+ nightShare: share(callsWhere((t) => t.at.getHours() >= 21 || t.at.getHours() < 4)),
780
+ earlyShare: share(callsWhere((t) => t.at.getHours() >= 5 && t.at.getHours() < 9)),
781
+ weekendShare: share(callsWhere((t) => t.at.getDay() === 0 || t.at.getDay() === 6)),
782
+ topHarness,
783
+ topHarnessShare: share(harnessShare[0]?.count ?? 0),
784
+ secondHarnessShare: share(harnessShare[1]?.count ?? 0),
785
+ connectorShare: share(callsWhere((t) => t.connector !== null && userConnector(t.connector) !== null)),
786
+ connectorCount: connectors.size,
787
+ bashShare: share(callsWhere((t) => t.command !== null)),
788
+ webShare: share(callsWhere((t) => WEB_TOOLS.has(t.tool))),
789
+ subagentCalls: callsWhere((t) => SUBAGENT_TOOLS.has(t.tool)),
790
+ reads: callsWhere((t) => t.tool === "Read"),
791
+ writes: callsWhere((t) => WRITE_TOOLS2.has(t.tool)),
792
+ lazyPrompts: chargeCount("fixIt") + chargeCount("pastedError")
793
+ });
794
+ const topCommands = ranked(commands, 5);
795
+ const topConnectors = ranked(connectors, 5);
796
+ const firstEvent = result.events.reduce((m, e) => !m || e.at < m ? e.at : m, null);
797
+ const first = [result.firstStarted, firstEvent, result.claudeHistory?.oldest ?? null, ...result.backfill.filter(hasActivity).map((b) => parseYmd(b.date))].filter((d) => d !== null).sort((a, b) => a.getTime() - b.getTime())[0];
798
+ const agentAgeDays = first ? Math.max(1, Math.floor((until.getTime() - first.getTime()) / DAY_MS)) : null;
799
+ const history = result.claudeHistory;
800
+ const oldest = history?.oldest ?? null;
801
+ const cutOff = history !== null && oldest !== null && until.getTime() - oldest.getTime() <= (history.retentionDays + 1) * DAY_MS && oldest >= from;
802
+ const olderEvidence = [result.firstStarted, firstEvent, ...result.backfill.filter(hasActivity).map((b) => parseYmd(b.date))].some((d) => d !== null && oldest !== null && d < oldest);
803
+ const claudeEvents = events.filter((e) => e.harness === "claude-code");
804
+ const detailSince = claudeEvents.length > 0 ? ymd(claudeEvents.reduce((m, e) => e.at < m ? e.at : m, claudeEvents[0].at)) : null;
805
+ return {
806
+ window,
807
+ harnesses: result.found,
808
+ totals: { toolCalls: daily.reduce((a, b) => a + b, 0), sessions: sessionTotal, agentHours },
809
+ daily,
810
+ longestStreak: longestStreak(daily.flatMap((n, i) => n > 0 ? [i] : []), from),
811
+ topTools: ranked(toolNames, 5),
812
+ topConnectors,
813
+ topCommands,
814
+ harnessShare,
815
+ hours,
816
+ rushHour,
817
+ latestStart: latest ? {
818
+ time: `${String(latest.getHours()).padStart(2, "0")}:${String(latest.getMinutes()).padStart(2, "0")}`,
819
+ weekday: WEEKDAYS[latest.getDay()],
820
+ month: MONTHS[latest.getMonth()]
821
+ } : null,
822
+ topModel: modelCounts.size > 0 ? { models: ranked(modelCounts, 4) } : null,
823
+ charges,
824
+ tracks: computeTracks(facts, topCommands[0], topConnectors[0]),
825
+ personality: { ...archetype, genre: genreOf(topCommands[0]?.name, topConnectors[0]?.name, archetype.genre), agentAgeDays, agentAgeIsMinimum: cutOff && !olderEvidence, hangout: hangoutOf(tools) },
826
+ coverage: { detailSince, backfilledDays, retentionDays: history?.retentionDays ?? null, cutOff },
827
+ tokens: tokensOf(events),
828
+ highlights: highlightsOf(tools, sessions)
829
+ };
830
+ }
758
831
 
759
- var ITEM_SIZES = [30, 28, 26, 24, 22];
760
- var shrunk = [];
761
- function draw(card, canvas) {
762
- var scratch = document.createElement("canvas"); scratch.width = 1080; scratch.height = 1920;
763
- var pick = ITEM_SIZES[ITEM_SIZES.length - 1];
764
- for (var i = 0; i < ITEM_SIZES.length; i++) {
765
- var r = drawCard(scratch.getContext("2d"), card, ITEM_SIZES[i]);
766
- // Lists wrap to at most 3 lines, the last row clears the footer, and the footer stays on the canvas.
767
- if (r.lines <= 3 && r.end + 60 <= r.footerTop && r.bottom <= 1890) { pick = ITEM_SIZES[i]; break; }
768
- }
769
- var out = drawCard(canvas.getContext("2d"), card, pick);
770
- if (pick !== ITEM_SIZES[0]) shrunk.push(card.id + ": items " + pick + "px");
771
- if (out.heroSize < 150) shrunk.push(card.id + ": title " + out.heroSize + "px");
772
- return out;
832
+ // src/write.ts
833
+ import { mkdirSync, renameSync, rmSync, statSync as statSync2, writeFileSync } from "node:fs";
834
+ import { dirname } from "node:path";
835
+ function writeJsonAtomic(path, value) {
836
+ mkdirSync(dirname(path), { recursive: true });
837
+ const tmp = `${path}.${process.pid}.tmp`;
838
+ let mode = 420;
839
+ try {
840
+ mode = statSync2(path).mode & 511;
841
+ } catch {}
842
+ try {
843
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + `
844
+ `, { mode });
845
+ renameSync(tmp, path);
846
+ } catch (err) {
847
+ rmSync(tmp, { force: true });
848
+ throw err;
773
849
  }
774
- window.__cardNotes = shrunk;
850
+ }
775
851
 
776
- // ---- Share: one selected card, shared as a file where supported, else downloaded. ----
777
- var CARDS = D.cards, canvases = {}, chosen = CARDS[0];
778
- var SHARE_TEXT = "My AI agents' " + W.window.end.slice(0, 4) + ", wrapped: I'm " + W.personality.name + ". What's yours? npx runa-agent-wrapped";
779
- function select(card, fig) {
780
- chosen = card;
781
- document.querySelectorAll("#cardgrid figure").forEach(function (f) { f.setAttribute("aria-pressed", String(f === fig)); });
782
- }
783
- function blobOf(cb) { canvases[chosen.id].toBlob(function (b) { if (b) cb(b); }, "image/png"); }
784
- function fileName() { return "agent-wrapped-" + chosen.id + ".png"; }
785
- function download() {
786
- blobOf(function (blob) {
787
- var a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = fileName();
788
- document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
789
- });
790
- }
791
- $("share-download").addEventListener("click", download);
792
- var probe = typeof File === "function" && navigator.canShare && navigator.canShare({ files: [new File([""], "x.png", { type: "image/png" })] });
793
- if (probe) {
794
- $("share-native").hidden = false;
795
- $("share-native").addEventListener("click", function () {
796
- blobOf(function (blob) {
797
- navigator.share({ files: [new File([blob], fileName(), { type: "image/png" })], text: SHARE_TEXT + " " + D.share.url }).catch(function () {});
798
- });
799
- });
852
+ // src/daily.ts
853
+ var dailyPath = (home) => join3(home, ".agent-wrapped", "daily.json");
854
+ function toDailyFile(days) {
855
+ return { version: 1, days: Object.fromEntries(mergeDays(days).map((d) => [d.date, { toolCalls: d.toolCalls, sessions: d.sessions }])) };
856
+ }
857
+ function saveDaily(home, runDays) {
858
+ const existing = readDailyFile(home);
859
+ const path = dailyPath(home);
860
+ if (!existing.valid && existsSync3(path))
861
+ return `Not saving day totals: ${path} is not a valid Agent Wrapped file.`;
862
+ try {
863
+ writeJsonAtomic(path, toDailyFile([...existing.days, ...runDays]));
864
+ return null;
865
+ } catch (err) {
866
+ return `Could not save day totals to ${path}: ${err instanceof Error ? err.message : String(err)}`;
800
867
  }
801
- D.share.targets.forEach(function (t) {
802
- var a = document.createElement("a");
803
- a.className = "link"; a.target = "_blank"; a.rel = "noopener"; a.textContent = t.label;
804
- a.href = t.url.replace("{text}", encodeURIComponent(SHARE_TEXT)).replace("{url}", encodeURIComponent(D.share.url));
805
- a.addEventListener("click", download);
806
- $("share-targets").appendChild(a);
807
- });
808
- $("share-copy").addEventListener("click", function () {
809
- navigator.clipboard.writeText(SHARE_TEXT + " " + D.share.url).then(function () { status($("share-status"), "Copied.", false); }, function () { status($("share-status"), "Could not copy.", true); });
810
- });
811
-
812
- var built = false;
813
- wire("open-cards", "cards", function () {
814
- if (built) return;
815
- built = true;
816
- var fonts = ["300 150px Fraunces", "italic 300 150px Fraunces", "500 30px Manrope", "400 28px Manrope", "400 22px 'DM Mono'"];
817
- Promise.all(fonts.map(function (f) { return document.fonts.load(f).catch(function () {}); })).then(function () { return document.fonts.ready; }).then(function () {
818
- var grid = $("cardgrid"); grid.style.setProperty("--n", String(CARDS.length));
819
- CARDS.forEach(function (card) {
820
- var fig = document.createElement("figure"), cv = document.createElement("canvas");
821
- cv.width = 1080; cv.height = 1920; cv.setAttribute("role", "img"); cv.setAttribute("aria-label", "Share card: " + card.title);
822
- draw(card, cv);
823
- fig.tabIndex = 0; fig.setAttribute("role", "button"); fig.setAttribute("aria-pressed", String(card === CARDS[0]));
824
- fig.addEventListener("click", function () { select(card, fig); });
825
- fig.addEventListener("keydown", function (e) { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); select(card, fig); } });
826
- canvases[card.id] = cv;
827
- fig.appendChild(cv); grid.appendChild(fig);
828
- });
829
- });
830
- });
831
- })();
832
- `;
833
-
834
- // src/cards.ts
835
- var num = (n) => n.toLocaleString("en-US");
836
- var clean = (s) => s.replace(/--/g, "-‌-");
837
- var pairs = (a) => Array.from({ length: Math.ceil(a.length / 2) }, (_, i) => a.slice(i * 2, i * 2 + 2));
838
- var statRows = (cols) => pairs(cols).map((c) => ({ kind: "stats", cols: c }));
839
- function buildCards(w) {
840
- const agent = w.harnessShare[0];
841
- const total = w.harnessShare.reduce((s, h) => s + h.count, 0);
842
- const tagline = "In " + (agent?.name ?? "your agent") + " we trust. In “don’t ask again”, we don’t.";
843
- const ranked = (header, r) => r.length ? [{ header, items: r.map((x) => ({ text: clean(x.name), note: num(x.count) })) }] : [];
844
- const common = { tagline };
845
- const top5Lists = [...ranked("TOP COMMANDS", w.topCommands), ...ranked("TOP CONNECTORS", w.topConnectors)];
846
- const top5 = {
847
- ...common,
848
- id: "top5",
849
- title: "Top 5",
850
- theme: "light",
851
- accent: "forest",
852
- hero: "rune",
853
- rows: [
854
- ...top5Lists.length ? [{ kind: "lists", cols: top5Lists }] : [],
855
- { kind: "stats", cols: [{ label: "TOOL CALLS", kind: "number", value: num(w.totals.toolCalls) }, ...agent ? [{ label: "TOP AGENT", kind: "italic", value: agent.name }] : []] }
856
- ]
857
- };
858
- const command = w.topCommands[0];
859
- const connector = w.topConnectors[0];
860
- const highlights = {
861
- ...common,
862
- id: "highlights",
863
- title: "Highlights",
864
- theme: "dark",
865
- accent: "forest",
866
- hero: "rune",
867
- rows: statRows([
868
- ...agent ? [{ label: "TOP AGENT", kind: "italic", value: agent.name, caption: Math.round(agent.count / total * 100) + "% of tool calls" }] : [],
869
- ...command ? [{ label: "TOP COMMAND", kind: "italic", value: clean(command.name), caption: num(command.count) + " runs" }] : [],
870
- ...connector ? [{ label: "TOP CONNECTOR", kind: "italic", value: clean(connector.name), caption: num(connector.count) + " calls" }] : [],
871
- { label: "AGENT HOURS", kind: "number", value: num(w.totals.agentHours), unit: "h" }
872
- ])
873
- };
874
- const p = w.personality;
875
- const personality = {
876
- ...common,
877
- id: "personality",
878
- title: "Personality",
879
- theme: "dark",
880
- accent: "forest",
881
- hero: "face",
882
- rows: [
883
- { kind: "stats", cols: [...p.agentAgeDays !== null ? [{ label: "AGENT AGE", kind: "number", value: num(p.agentAgeDays), unit: p.agentAgeDays === 1 ? "day" : "days" }] : [], { label: "TRUST STATUS", kind: "italic", value: p.trustStatus }] },
884
- { kind: "stats", cols: [{ label: "PERSONALITY", kind: "display", value: p.name }] },
885
- { kind: "stats", cols: [{ label: "TOP GENRE", kind: "italic", value: p.genre }, { label: "FAVOURITE HANGOUT", kind: "italic", value: p.hangout }] }
886
- ]
887
- };
888
- const tracks = {
889
- ...common,
890
- id: "tracks",
891
- title: "Top tracks",
892
- theme: "light",
893
- accent: "rose",
894
- hero: "rune",
895
- rows: [
896
- ...w.tracks.length ? [{ kind: "lists", cols: [{ header: "YOUR TOP TRACKS", items: w.tracks.map((t) => ({ text: clean(t.title), sub: "(" + clean(t.mix) + ")", right: num(t.plays) })) }] }] : [],
897
- { kind: "stats", cols: [{ label: "TOP GENRE", kind: "italic", value: p.genre }, { label: "PLAYS", kind: "number", value: num(w.totals.toolCalls) }] }
898
- ]
899
- };
900
- return [top5, highlights, personality, tracks];
901
868
  }
902
869
 
903
- // src/types.ts
904
- var HARNESS_NAME = { "claude-code": "Claude Code", codex: "Codex", cursor: "Cursor" };
870
+ // src/readers/claude.ts
871
+ import { join as join4 } from "node:path";
905
872
 
906
- // src/page.ts
907
- var esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
908
- var num2 = (n) => n.toLocaleString("en-US");
909
- var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
910
- var COUNT_WORDS = ["zero", "one", "two", "three", "four", "five"];
911
- function parseYmd(s) {
912
- const [y, m, d] = s.split("-").map(Number);
913
- return new Date(y, m - 1, d);
914
- }
915
- var shortDate = (s) => `${parseYmd(s).getDate()} ${MONTHS[parseYmd(s).getMonth()]}`;
916
- function heatLayout(year) {
917
- const offset = new Date(year, 0, 1).getDay();
918
- const days = Math.round((new Date(year + 1, 0, 1).getTime() - new Date(year, 0, 1).getTime()) / 86400000);
919
- const monthCols = Array.from({ length: 12 }, (_, m) => Math.floor((offset + Math.round((new Date(year, m, 1).getTime() - new Date(year, 0, 1).getTime()) / 86400000)) / 7));
920
- return { offset, days, columns: Math.ceil((offset + days) / 7), monthCols };
873
+ // src/readers/assemble.ts
874
+ var RANK = { ask: 0, auto: 1, bypass: 2 };
875
+ function raiseAutonomy(s, a) {
876
+ if (RANK[a] > RANK[s.autonomy])
877
+ s.autonomy = a;
921
878
  }
922
- var CELL = 10;
923
- var GAP = 3;
924
- function heatmap(w) {
925
- const nonzero = w.daily.filter((n) => n > 0).sort((a, b) => a - b);
926
- const q = (p) => nonzero[Math.min(nonzero.length - 1, Math.floor(nonzero.length * p))] ?? 1;
927
- const [t1, t2] = [q(0.4), q(0.75)];
928
- const start = parseYmd(w.window.start);
929
- const layout = heatLayout(start.getFullYear());
930
- const streak = w.longestStreak;
931
- const cells = Array.from({ length: layout.days }, (_, i) => {
932
- const day = new Date(start.getFullYear(), 0, 1 + i);
933
- const key = `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, "0")}-${String(day.getDate()).padStart(2, "0")}`;
934
- const first = i === 0 ? ` style="grid-row-start:${layout.offset + 1}"` : "";
935
- if (i >= w.daily.length)
936
- return `<i class="d future"${first}></i>`;
937
- const n = w.daily[i];
938
- const level = n === 0 ? 0 : n <= t1 ? 1 : n <= t2 ? 2 : 3;
939
- const inStreak = streak !== null && key >= streak.start && key <= streak.end;
940
- return `<i class="d l${level}${inStreak ? " st" : ""}"${first} title="${key}: ${num2(n)} tool calls"></i>`;
941
- });
942
- const months = layout.monthCols.map((col, m) => `<span style="left:${col * (CELL + GAP)}px">${MONTHS[m]}</span>`).join("");
943
- const width = layout.columns * (CELL + GAP) - GAP;
944
- return `<div class="heat" style="width:${width}px"><div class="heatgrid" role="img" aria-label="Tool calls per day">${cells.join("")}</div><div class="months">${months}</div></div>`;
879
+ function newSession() {
880
+ return { model: null, project: null, autonomy: "ask", events: [] };
945
881
  }
946
- function bigStat(label, value, sub) {
947
- return `<div class="big"><span class="bl">${label}</span><span class="bv">${value}</span><span class="bs">${sub}</span></div>`;
948
- }
949
- function summaryCard(w) {
950
- const s = w.longestStreak;
951
- const streak = s ? bigStat("Longest streak", `${s.days} day${s.days === 1 ? "" : "s"}`, `${shortDate(s.start)} – ${shortDate(s.end)}, outlined`) : "";
952
- return `<section class="card tile summary"><div class="bigs">${bigStat("Tool calls", num2(w.totals.toolCalls), `${num2(w.totals.agentHours)} agent hours · ${num2(w.totals.sessions)} session${w.totals.sessions === 1 ? "" : "s"}`)}${streak}</div>${heatmap(w)}</section>`;
882
+ function assemble(harness, sessions, range) {
883
+ const out = [];
884
+ for (const [sessionId, s] of sessions) {
885
+ const inRange = s.events.filter((e) => e.at >= range.from && e.at < range.until);
886
+ if (inRange.length === 0)
887
+ continue;
888
+ const first = inRange.reduce((a, b) => b.at < a.at ? b : a).at;
889
+ out.push({ harness, sessionId, at: first, kind: "session", model: s.model, project: s.project, autonomy: s.autonomy });
890
+ for (const e of inRange)
891
+ out.push({ ...e, harness, sessionId });
892
+ }
893
+ return out;
953
894
  }
954
- function toolsCard(w) {
955
- if (w.topTools.length === 0)
956
- return "";
957
- const max = w.topTools[0].count;
958
- const rows = w.topTools.map((t) => `<div class="bar"><span class="bn">${esc(t.name)}</span><div class="track"><div style="width:${Math.round(t.count / max * 100)}%"></div></div><span class="bc">${num2(t.count)}</span></div>`).join("");
959
- return `<section class="card tile"><h3 class="eyebrow">Top tools</h3>${rows}</section>`;
895
+ function connectorOf(tool) {
896
+ const m = /^mcp__(.+?)__/.exec(tool);
897
+ return m ? m[1] ?? null : null;
960
898
  }
961
- function connectorsCard(w) {
962
- if (w.topConnectors.length === 0)
963
- return "";
964
- const rows = w.topConnectors.map((c, i) => `<div class="rank"><span class="rn">${i + 1}</span><span class="rname">${esc(c.name)}</span><span class="bc">${num2(c.count)}</span></div>`).join("");
965
- return `<section class="card tile"><h3 class="eyebrow">Top connectors</h3>${rows}</section>`;
899
+
900
+ // src/readers/claude.ts
901
+ var DEFAULT_RETENTION_DAYS = 30;
902
+ function retentionDays(home) {
903
+ const v = readJson(join4(home, ".claude", "settings.json"))?.["cleanupPeriodDays"];
904
+ return typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : DEFAULT_RETENTION_DAYS;
966
905
  }
967
- function chargesCard(w) {
968
- if (w.charges.length === 0)
969
- return "";
970
- const n = w.charges.length;
971
- const title = `Charged with vibe coding, on ${COUNT_WORDS[n] ?? String(n)} ${n === 1 ? "count" : "counts"}`;
972
- const rows = w.charges.map((c) => `<li class="${c.id === "pushMain" ? "risk" : ""}"><span class="cn">${num2(c.count)}×</span><span class="cl">${esc(c.label)}</span></li>`).join("");
973
- return `<section class="card charges"><div class="chead"><span class="eyebrow">The charge sheet</span><span class="stamp" aria-hidden="true">GUILTY</span></div><span class="ctitle">${title}</span><ol class="${n >= 4 ? "many" : ""}">${rows}</ol></section>`;
906
+ function autonomyOf(mode) {
907
+ if (mode === "bypassPermissions")
908
+ return "bypass";
909
+ if (mode === "acceptEdits" || mode === "auto" || mode === "dontAsk")
910
+ return "auto";
911
+ return "ask";
974
912
  }
975
- function hoursCard(w) {
976
- const total = w.hours.reduce((a, b) => a + b, 0);
977
- if (total === 0 || w.rushHour === null)
978
- return "";
979
- const max = Math.max(...w.hours);
980
- const r = w.rushHour;
981
- const inRush = (h) => (h - r.from + 24) % 24 < 3;
982
- const bars = w.hours.map((n, h) => `<i class="${inRush(h) ? "rushbar" : ""}" style="height:${Math.max(2, Math.round(n / max * 100))}%" title="${String(h).padStart(2, "0")}:00: ${num2(n)}"></i>`).join("");
983
- const hh = (h) => `${String(h).padStart(2, "0")}:00`;
984
- const latest = w.latestStart ? `<span class="small">Latest session start: <strong>${esc(w.latestStart.time)}</strong>, a ${esc(w.latestStart.weekday)} in ${esc(w.latestStart.month)}</span>` : "";
985
- return `<section class="card tile hours"><h3 class="eyebrow">When your agents work</h3><span class="rush">Rush hour: ${hh(r.from)}–${hh(r.to)}</span><div class="bars" role="img" aria-label="Tool calls by hour of day">${bars}</div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div>${latest}</section>`;
913
+ function promptText(o) {
914
+ if (o["isMeta"] === true || o["isCompactSummary"] === true || o["isSidechain"] === true)
915
+ return null;
916
+ const origin = asObj(o["origin"]);
917
+ if (origin && origin["kind"] !== "human")
918
+ return null;
919
+ const content = asObj(o["message"])?.["content"];
920
+ let text = null;
921
+ if (typeof content === "string")
922
+ text = content;
923
+ else if (Array.isArray(content)) {
924
+ const parts = content.map(asObj).filter((p) => p?.["type"] === "text").map((p) => str(p?.["text"]) ?? "");
925
+ text = parts.join(`
926
+ `);
927
+ }
928
+ if (!text || text.startsWith("<") || text.startsWith("[Request interrupted"))
929
+ return null;
930
+ return text;
986
931
  }
987
- function personalityCard(w) {
988
- const p = w.personality;
989
- return `<section class="card dark soul"><div class="art" aria-hidden="true"><i class="o1"></i><i class="o2"></i><div class="face"><b class="cap"></b><em>sudo</em><i class="eye e1"></i><i class="eye e2"></i><i class="mouth"></i></div></div>
990
- <dl class="facts">${p.agentAgeDays !== null ? `<div><dt>Agent age</dt><dd class="age">${num2(p.agentAgeDays)}<small> ${p.agentAgeDays === 1 ? "day" : "days"}</small></dd></div>` : ""}<div><dt>Trust status</dt><dd class="trust">${esc(p.trustStatus)}</dd></div>
991
- <div class="wide"><dt>Personality</dt><dd class="pname">${esc(p.name)}</dd></div><div class="wide"><dt>Favourite hangout</dt><dd class="line">${esc(p.hangout)}</dd></div></dl></section>`;
932
+ function toolPath(input) {
933
+ return str(input?.["file_path"]) ?? str(input?.["notebook_path"]) ?? str(input?.["path"]);
992
934
  }
993
- function tracksCard(w) {
994
- if (w.tracks.length === 0)
995
- return "";
996
- const rows = w.tracks.map((t, i) => `<li><span class="tr">${i + 1}</span><span class="tt">${esc(t.title)} <span class="mix">(${esc(t.mix)})</span></span><span class="tn">${num2(t.plays)}</span></li>`).join("");
997
- return `<section class="card dark tracks"><div class="thead"><span>Top tracks</span><span class="mono">plays</span></div><ol>${rows}</ol></section>`;
935
+ function readClaude(home, range) {
936
+ const root = join4(home, ".claude", "projects");
937
+ const files = walk(root, (n) => n.endsWith(".jsonl"), 4).sort();
938
+ const sessions = new Map;
939
+ const seen = new Set;
940
+ const cwds = new Set;
941
+ let oldest = null;
942
+ const usages = new Map;
943
+ for (const file of files) {
944
+ const text = readText(file);
945
+ if (text === null)
946
+ continue;
947
+ const stem = file.split("/").pop()?.replace(/\.jsonl$/, "") ?? file;
948
+ for (const o of jsonLines(text)) {
949
+ const at = parseTime(o["timestamp"]);
950
+ const cwd = str(o["cwd"]);
951
+ if (cwd)
952
+ cwds.add(cwd);
953
+ if (!at)
954
+ continue;
955
+ if (!oldest || at < oldest)
956
+ oldest = at;
957
+ const uuid = str(o["uuid"]);
958
+ if (uuid) {
959
+ if (seen.has(uuid))
960
+ continue;
961
+ seen.add(uuid);
962
+ }
963
+ const sid = str(o["sessionId"]) ?? stem;
964
+ let s = sessions.get(sid);
965
+ if (!s)
966
+ sessions.set(sid, s = newSession());
967
+ if (cwd)
968
+ s.project ??= folderName(cwd);
969
+ const type = o["type"];
970
+ if (type === "user") {
971
+ const mode = str(o["permissionMode"]);
972
+ if (mode)
973
+ raiseAutonomy(s, autonomyOf(mode));
974
+ const t = promptText(o);
975
+ if (t !== null)
976
+ s.events.push({ kind: "prompt", at, text: t });
977
+ } else if (type === "assistant") {
978
+ const msg = asObj(o["message"]);
979
+ const rawModel = str(msg?.["model"]);
980
+ const model = rawModel && !rawModel.startsWith("<") ? rawModel : null;
981
+ if (model && !s.model)
982
+ s.model = model;
983
+ const usage = asObj(msg?.["usage"]);
984
+ if (usage) {
985
+ const n = (k) => typeof usage[k] === "number" && Number.isFinite(usage[k]) ? usage[k] : 0;
986
+ const u = { kind: "usage", at, input: n("input_tokens"), output: n("output_tokens"), cacheRead: n("cache_read_input_tokens"), cacheWrite: n("cache_creation_input_tokens") };
987
+ const usageKey = str(msg?.["id"]) ?? str(o["requestId"]);
988
+ const prev = usageKey ? usages.get(usageKey) : undefined;
989
+ if (prev) {
990
+ prev.input = Math.max(prev.input, u.input);
991
+ prev.output = Math.max(prev.output, u.output);
992
+ prev.cacheRead = Math.max(prev.cacheRead, u.cacheRead);
993
+ prev.cacheWrite = Math.max(prev.cacheWrite, u.cacheWrite);
994
+ } else {
995
+ if (usageKey)
996
+ usages.set(usageKey, u);
997
+ s.events.push(u);
998
+ }
999
+ }
1000
+ const content = Array.isArray(msg?.["content"]) ? msg["content"] : [];
1001
+ for (const item of content) {
1002
+ const b = asObj(item);
1003
+ if (!b)
1004
+ continue;
1005
+ if (b["type"] === "text" && str(b["text"])) {
1006
+ s.events.push({ kind: "reply", at, text: b["text"], model });
1007
+ } else if (b["type"] === "tool_use") {
1008
+ const name = str(b["name"]);
1009
+ if (!name)
1010
+ continue;
1011
+ const id = str(b["id"]);
1012
+ if (id) {
1013
+ if (seen.has(id))
1014
+ continue;
1015
+ seen.add(id);
1016
+ }
1017
+ const input = asObj(b["input"]);
1018
+ s.events.push({
1019
+ kind: "tool",
1020
+ at,
1021
+ tool: name,
1022
+ connector: connectorOf(name),
1023
+ command: name === "Bash" ? str(input?.["command"]) : null,
1024
+ path: toolPath(input)
1025
+ });
1026
+ }
1027
+ }
1028
+ } else if (type === "system" && o["subtype"] === "compact_boundary") {
1029
+ s.events.push({ kind: "compaction", at });
1030
+ }
1031
+ }
1032
+ }
1033
+ return {
1034
+ events: assemble("claude-code", sessions, range),
1035
+ allowRules: countAllowRules(home, cwds),
1036
+ firstStarted: parseTime(readJson(join4(home, ".claude.json"))?.["firstStartTime"]),
1037
+ found: files.length > 0,
1038
+ history: files.length > 0 ? { retentionDays: retentionDays(home), oldest } : null
1039
+ };
998
1040
  }
999
- function midRight(w) {
1000
- const inner = chargesCard(w) + modelCard(w);
1001
- return inner ? `<div class="midr">${inner}</div>` : "";
1041
+ function countAllowRules(home, cwds) {
1042
+ const settings = new Set([join4(home, ".claude", "settings.json")]);
1043
+ for (const cwd of cwds)
1044
+ settings.add(join4(cwd, ".claude", "settings.local.json"));
1045
+ let n = 0;
1046
+ for (const f of settings) {
1047
+ const allow = asObj(readJson(f)?.["permissions"])?.["allow"];
1048
+ if (Array.isArray(allow))
1049
+ n += allow.length;
1050
+ }
1051
+ return n;
1002
1052
  }
1003
- function modelCard(w) {
1004
- if (w.topModel === null)
1005
- return "";
1006
- const models = w.topModel.models;
1007
- const total = models.reduce((a, m) => a + m.count, 0);
1008
- const pct = (n) => Math.round(n / total * 100);
1009
- const segs = models.map((m, i) => `<div class="m${i}" style="width:${m.count / total * 100}%"></div>`).join("");
1010
- const legend = models.map((m) => `<span>${esc(m.name)} ${pct(m.count)}%</span>`).join("");
1011
- const aria = models.map((m) => `${m.name} ${pct(m.count)}%`).join(", ");
1012
- return `<section class="card mint"><div class="mhead"><span>Top model</span><span class="mono big2">${esc(models[0].name)} · ${pct(models[0].count)}%</span></div><div class="segs" role="img" aria-label="${esc(aria)}">${segs}</div><div class="legend">${legend}</div></section>`;
1053
+
1054
+ // src/readers/codex.ts
1055
+ import { readFileSync as readFileSync2 } from "node:fs";
1056
+ import * as zlib from "node:zlib";
1057
+ import { join as join5 } from "node:path";
1058
+ function readRollout(path) {
1059
+ if (!path.endsWith(".zst"))
1060
+ return readText(path);
1061
+ const z = zlib;
1062
+ if (!z.zstdDecompressSync)
1063
+ return null;
1064
+ try {
1065
+ return z.zstdDecompressSync(readFileSync2(path)).toString("utf8");
1066
+ } catch {
1067
+ return null;
1068
+ }
1013
1069
  }
1014
- function dateRange(w) {
1015
- const s = parseYmd(w.window.start);
1016
- const e = parseYmd(w.window.end);
1017
- return `${MONTHS[s.getMonth()]} ${s.getDate()} – ${MONTHS[e.getMonth()]} ${e.getDate()}, ${e.getFullYear()}`;
1070
+ function autonomyOf2(policy, sandbox) {
1071
+ if (policy === "never")
1072
+ return sandbox === "danger-full-access" ? "bypass" : "auto";
1073
+ if (policy === "on-failure")
1074
+ return "auto";
1075
+ if (sandbox === "danger-full-access" && policy !== "untrusted")
1076
+ return "bypass";
1077
+ return "ask";
1018
1078
  }
1019
- var SHARE_ICON = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12M7 8l5-5 5 5M5 13v6h14v-6"/></svg>`;
1020
- var ARROW = `<svg class="arrow" width="22" height="22" viewBox="0 0 22 22" fill="none" aria-hidden="true"><circle cx="11" cy="11" r="11" fill="var(--white)"/><path d="M6.5 11h9M11.5 7l4 4-4 4" stroke="var(--forest)" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
1021
- function renderPage(w) {
1022
- const data = JSON.stringify({ wrapped: w, api: API_BASE, share: { url: SHARE_URL, targets: SHARE_TARGETS }, brand: BRAND, cards: buildCards(w) }).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1023
- const harnesses = w.harnesses.map((h) => HARNESS_NAME[h]).join(" · ");
1024
- const empty = w.totals.toolCalls === 0;
1025
- const body = empty ? `<section class="card tile empty"><h3>Nothing to wrap yet</h3><p>No Claude Code, Codex or Cursor history found for ${w.window.start.slice(0, 4)} on this laptop.</p></section>` : `<div class="main"><div class="left">${summaryCard(w)}<div class="mid"><div class="midl"><div class="toprow">${toolsCard(w)}${connectorsCard(w)}</div>${hoursCard(w)}</div>${midRight(w)}</div></div><div class="right">${personalityCard(w)}${tracksCard(w)}</div></div>`;
1026
- const options = TEAM_SIZES.map((t, i) => `<option value="${["1", "2-20", "21-200", "200+"][i]}">${t}</option>`).join("");
1027
- return `<!doctype html>
1028
- <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
1029
- <title>Agent Wrapped ${w.window.end.slice(0, 4)}</title>
1030
- <style>${fontFaceCss()}${CSS}</style></head><body>
1031
- <div class="app">
1032
- <div class="backdrop" aria-hidden="true"></div>
1033
- <nav><span class="navnote">Agent Wrapped · by</span><span class="lockup" aria-label="Runa">${markSvg(20)}<span class="wm" aria-hidden="true">RUNA</span></span></nav>
1034
- <header><div><p class="eyebrow">${dateRange(w)}${harnesses ? ` · ${esc(harnesses)}` : ""}</p><h1>Your agents' ${w.window.end.slice(0, 4)},<br><em>wrapped.</em></h1></div>
1035
- <div class="btns"><button class="pill share" id="open-cards" type="button">${SHARE_ICON}Share</button>
1036
- <button class="pill primary cta" id="open-team" type="button">Talk with us about agent security${ARROW}</button></div></header>
1037
- ${body}
1038
- </div>
1039
- <dialog id="cards"><div class="mh"><h2>Share your Wrapped</h2><button class="x" data-close aria-label="Close">×</button></div>
1040
- <p class="note">Pick a card. Cards are drawn on your laptop; nothing is uploaded until you post it.</p>
1041
- <div class="cardgrid" id="cardgrid"></div>
1042
- <div class="sharebar"><button class="pill primary" id="share-native" type="button" hidden>Share image…</button><button class="pill" id="share-download" type="button">Download image</button><span class="sharevia">or post on</span><span id="share-targets"></span><button class="link" id="share-copy" type="button">Copy text</button><p class="status" id="share-status" role="status"></p></div>
1043
- <p class="fine">X, LinkedIn, Reddit and Bluesky open with your text filled in. Attach the downloaded image there.</p></dialog>
1044
- <dialog id="team"><div class="mh"><h2>You wrapped your year. Do you know what your agent touched?</h2><button class="x" data-close aria-label="Close">×</button></div>
1045
- <p class="note">Runa gives security and compliance teams this view for every agent at work, with rules that stop the risky stuff.</p>
1046
- <form id="waitlist"><label>Work email<input name="email" type="email" required placeholder="you@company.com" autocomplete="email"></label>
1047
- <label>People using AI agents at work<select name="teamSize">${options}</select></label>
1048
- <button class="pill primary" type="submit">Get Wrapped for my team${ARROW}</button><p class="status" id="wl-status" role="status"></p></form>
1049
- <a class="link book" href="${CAL_URL}" target="_blank" rel="noopener">Book a 15-min call</a>
1050
- <p class="fine">We store your email to contact you about Agent Wrapped for teams. Nothing from your report is sent.</p></dialog>
1051
- <script type="application/json" id="data">${data}</script>
1052
- <script>${CLIENT_SCRIPT}</script>
1053
- </body></html>`;
1079
+ function commandOf(args) {
1080
+ const cmd = args?.["command"] ?? args?.["cmd"];
1081
+ if (typeof cmd === "string")
1082
+ return cmd;
1083
+ if (Array.isArray(cmd)) {
1084
+ const words = cmd.filter((w) => typeof w === "string");
1085
+ if (words.length === 3 && words[0].endsWith("sh") && /^-\w*c/.test(words[1]))
1086
+ return words[2];
1087
+ return words.join(" ") || null;
1088
+ }
1089
+ return null;
1054
1090
  }
1055
- var CSS = `${brandCss()}
1056
- .share{gap:8px}
1057
- .pill.cta{height:52px;padding:0 12px 0 24px;font-size:16px}
1058
- .cardgrid figure{cursor:pointer;border-radius:14px;outline:2px solid transparent;outline-offset:4px}
1059
- .cardgrid figure[aria-pressed="true"]{outline-color:var(--forest)}
1060
- .sharebar{display:flex;flex-wrap:wrap;align-items:center;gap:10px 14px;margin-top:14px}
1061
- .sharevia{font-size:13px;color:var(--muted)}#share-targets{display:flex;gap:14px}
1062
- :root{--mono:'DM Mono',ui-monospace,SFMono-Regular,Menlo,monospace}
1063
- *{box-sizing:border-box}body{margin:0;background:var(--mist);color:var(--ink);font-family:Manrope,system-ui,-apple-system,'Segoe UI',sans-serif}
1064
- .app{position:relative;height:100vh;min-height:700px;padding:14px 40px 26px;display:flex;flex-direction:column;gap:12px}
1065
- .backdrop{position:absolute;left:0;right:0;top:0;height:200px;z-index:-1;background:radial-gradient(520px 200px at 12% 0%,color-mix(in srgb,var(--forest),transparent 82%),transparent),radial-gradient(420px 180px at 92% 20%,color-mix(in srgb,var(--rose),transparent 88%),transparent)}
1066
- nav{flex:none;display:flex;justify-content:flex-end;align-items:center;gap:10px;height:28px}.navnote{font-size:12px;color:var(--muted)}
1067
- header{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;flex:none}
1068
- .eyebrow,h3.eyebrow{display:block;margin:0 0 4px;font-family:var(--mono);font-size:11px;font-weight:400;letter-spacing:.2em;text-transform:uppercase;color:var(--forest)}
1069
- h1{margin:0;font-family:Fraunces,Georgia,serif;font-weight:300;font-size:40px;line-height:1.02}h1 em{font-style:italic;color:var(--forest)}
1070
- .btns{display:flex;gap:10px;align-items:center}
1071
- .pill{height:44px;padding:0 18px;border-radius:999px;border:1px solid var(--border);background:var(--white);color:inherit;font:700 14px Manrope,system-ui,sans-serif;cursor:pointer;display:inline-flex;align-items:center;text-decoration:none}
1072
- .pill.primary{gap:12px;padding-right:10px;background:var(--forest);border-color:var(--forest);color:var(--mist)}
1073
- .link{padding:0 2px 3px;border:0;border-bottom:1px solid var(--forest);background:none;color:var(--forest);font:600 14px Manrope,system-ui,sans-serif;cursor:pointer;text-decoration:none}.btns{gap:22px}
1074
- button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--rose);outline-offset:2px}
1075
- .main{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,3fr) minmax(280px,1fr);gap:14px}
1076
- .left,.right{min-height:0;display:flex;flex-direction:column;gap:14px}
1077
- .card{border-radius:22px;padding:18px 20px;min-height:0}
1078
- .tile{background:var(--white);border:1px solid var(--border);display:flex;flex-direction:column;gap:8px}
1079
- .dark{background:var(--ink-dark);color:var(--mist)}
1080
- h3{margin:0;font-size:13px;font-weight:700;color:var(--muted)}
1081
- .summary{flex:none;padding:16px 24px;flex-direction:row;align-items:center;gap:28px}
1082
- .bigs{flex:none;width:210px;display:flex;flex-direction:column;gap:10px}
1083
- .big{display:flex;flex-direction:column;gap:2px}.bl{font-size:13px;font-weight:600;color:var(--muted)}
1084
- .bv{font-family:Fraunces,Georgia,serif;font-weight:300;font-size:42px;line-height:1.05;color:var(--ink)}
1085
- .bs{font-size:12px;color:var(--muted)}
1086
- .heat{flex:none;max-width:100%;display:flex;flex-direction:column;gap:6px;overflow:hidden}
1087
- .heatgrid{display:grid;grid-template-rows:repeat(7,10px);grid-auto-flow:column;grid-auto-columns:10px;gap:3px}
1088
- .d{width:10px;height:10px;border-radius:3px;display:block;background:var(--mist-2)}
1089
- .l1{background:color-mix(in srgb,var(--mist-2),var(--forest) 35%)}.l2{background:color-mix(in srgb,var(--mist-2),var(--forest) 65%)}.l3{background:var(--forest)}
1090
- .d.st{box-shadow:0 0 0 1.5px var(--rose)}
1091
- .months{position:relative;height:14px;font-family:var(--mono);font-size:11px;color:var(--muted)}.months span{position:absolute;top:0}.d.future{background:none;box-shadow:inset 0 0 0 1px var(--border)}
1092
- .mid{flex:1;min-height:0;display:flex;gap:14px}
1093
- .midl{flex:2;min-width:0;display:flex;flex-direction:column;gap:14px}
1094
- .midr{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;gap:14px}
1095
- .toprow{flex:none;display:flex;gap:14px}.toprow .card{flex:1;min-width:0}
1096
- .bar{display:flex;align-items:center;gap:10px;font-family:var(--mono);font-size:13px}
1097
- .bn{width:86px;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.track{flex:1;height:10px;border-radius:999px;background:var(--mist-2)}
1098
- .track div{height:10px;border-radius:999px;background:var(--forest)}.bc{min-width:44px;text-align:right;color:var(--muted);font-family:var(--mono);font-size:13px}
1099
- .rank{display:flex;align-items:center;gap:10px;font-size:14px}.rn{font:300 18px Fraunces,Georgia,serif;width:16px;color:var(--forest)}.rname{flex:1;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1100
- .hours{flex:1}.rush{font:300 20px/1.1 Fraunces,Georgia,serif}
1101
- .bars{flex:1;min-height:40px;display:flex;align-items:flex-end;gap:3px}.bars i{flex:1;border-radius:4px 4px 0 0;background:var(--mist-2)}.bars i.rushbar{background:var(--forest)}
1102
- .axis{display:flex;justify-content:space-between;font-family:var(--mono);font-size:11px;color:var(--muted)}
1103
- .small{font-size:12px;color:var(--muted)}.small strong{color:var(--ink)}
1104
- .charges{flex:1;min-width:0;min-height:0;background:var(--white);border:1px solid var(--border);padding:20px 22px;display:flex;flex-direction:column;gap:10px}
1105
- .chead{display:flex;align-items:center;justify-content:space-between;gap:10px}.chead .eyebrow{margin:0}.ctitle{display:block;font:300 22px/1.15 Fraunces,Georgia,serif}
1106
- .stamp{flex:none;transform:rotate(-8deg);border:2.5px solid var(--forest);color:var(--forest);border-radius:6px;padding:2px 10px;font:500 15px var(--mono);letter-spacing:.12em}
1107
- .charges ol{flex:1;margin:0;padding:0;list-style:none;display:flex;flex-direction:column;justify-content:flex-start}.charges ol.many{justify-content:space-evenly}
1108
- .charges li{display:flex;align-items:baseline;gap:14px;padding:7px 0;border-bottom:1px solid var(--border)}.charges li:last-child{border-bottom:0}.charges li.risk{background:var(--rose-tint);margin:0 -22px;padding-left:22px;padding-right:22px}.cn{color:var(--forest)}
1109
- .cn{font:300 28px/1 Fraunces,Georgia,serif;min-width:72px;color:var(--forest)}.cl{font-size:15px;line-height:1.3}
1110
- .soul{flex:1;padding:0;overflow:hidden;display:flex;flex-direction:column;color:var(--mist-2)}
1111
- .art{flex:1;min-height:100px;position:relative;overflow:hidden;background:color-mix(in srgb,var(--ink-dark),var(--forest) 30%)}
1112
- .art .o1{position:absolute;left:-30px;top:-50px;width:150px;height:150px;border-radius:50%;background:color-mix(in srgb,var(--rose),transparent 30%)}
1113
- .art .o2{position:absolute;right:-30px;top:80px;width:130px;height:130px;border-radius:50%;background:var(--forest)}
1114
- .face{position:absolute;left:50%;top:50%;margin:-60px 0 0 -75px;width:150px;height:150px;border-radius:50%;background:var(--mist-2);overflow:hidden;transform:scale(.7)}
1115
- .face .cap{position:absolute;left:0;top:0;width:150px;height:28px;background:var(--rose)}.face em{position:absolute;left:0;top:6px;width:150px;text-align:center;font:normal 11px var(--mono);color:var(--mist)}
1116
- .face .eye{position:absolute;top:54px;width:22px;height:22px;border-radius:50%;background:var(--ink-dark)}.e1{left:34px}.e2{left:94px}
1117
- .face .mouth{position:absolute;left:46px;top:96px;width:58px;height:11px;border-radius:999px;background:var(--ink)}
1118
- .facts{flex:none;margin:0;padding:16px 20px;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
1119
- .facts>div{display:flex;flex-direction:column;gap:3px}.facts .wide{grid-column:span 2}
1120
- dt{font-size:12px;font-weight:600;color:color-mix(in srgb,var(--mist),transparent 30%)}dd{margin:0;font-weight:800;color:var(--mist)}
1121
- .age{font-size:24px;line-height:1.1}.age small{font-size:14px;color:var(--muted)}.trust{font-size:18px;line-height:1.15}.pname{font:300 24px/1.1 Fraunces,Georgia,serif}.line{font-size:17px;line-height:1.25;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1122
- .tracks{flex:none;padding:18px 20px;display:flex;flex-direction:column;gap:12px;color:var(--mist)}
1123
- .thead{display:flex;justify-content:space-between;align-items:baseline;font-size:13px;font-weight:700;color:var(--blush)}.mono{font-family:var(--mono)}.thead .mono{font-size:11px;font-weight:400;opacity:.6}
1124
- .tracks ol{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:9px}
1125
- .tracks li{display:flex;align-items:baseline;gap:10px}.tr{font:300 16px Fraunces,Georgia,serif;width:12px;color:var(--blush)}
1126
- .tt{flex:1;min-width:0;font-size:13px;line-height:1.3;font-weight:700}.mix{font-weight:400;opacity:.7}.tn{font:12px var(--mono);opacity:.6}
1127
- .mint{flex:none;background:var(--mist-2);padding:14px 20px;display:flex;flex-direction:column;gap:8px}
1128
- .mhead{display:flex;justify-content:space-between;align-items:baseline;font-size:13px;font-weight:700}.big2{font-weight:500;font-size:22px}
1129
- .segs{display:flex;height:10px;border-radius:999px;overflow:hidden}.m0{background:var(--ink-dark)}.m1{background:var(--forest)}.m2{background:var(--sage)}.m3{background:var(--white)}
1130
- .legend{display:flex;justify-content:space-between;gap:6px;font:11px var(--mono)}
1131
- .empty{max-width:520px}
1132
- dialog{border:1px solid color-mix(in srgb,var(--white),transparent 30%);border-radius:24px;padding:24px 28px;max-width:min(980px,94vw);max-height:92vh;overflow:auto;background:color-mix(in srgb,var(--white),transparent 45%);backdrop-filter:blur(22px) saturate(150%);box-shadow:0 30px 80px -20px color-mix(in srgb,var(--forest),transparent 65%);color:var(--ink)}
1133
- dialog::backdrop{background:color-mix(in srgb,var(--ink-dark),transparent 45%)}
1134
- .mh{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}.mh h2{margin:0;font:300 26px/1.2 Fraunces,Georgia,serif}
1135
- .x{border:0;background:none;font-size:28px;line-height:1;cursor:pointer;color:var(--muted)}
1136
- .note,.fine{color:var(--muted);font-size:14px;line-height:1.4}.fine{font-size:12px}
1137
- .cardgrid{display:grid;grid-template-columns:repeat(var(--n,4),minmax(0,1fr));gap:16px;width:min(calc(var(--n,4)*225px),86vw)}
1138
- .cardgrid figure{margin:0;display:flex;flex-direction:column;gap:8px}.cardgrid canvas{width:100%;aspect-ratio:9/16;border-radius:16px;background:var(--ink-dark)}
1139
- .cardgrid .pill{height:38px;justify-content:center;font-size:13px}
1140
- #team{width:min(520px,94vw)}form{display:flex;flex-direction:column;gap:12px;margin:14px 0}label{display:flex;flex-direction:column;gap:5px;font-size:13px;font-weight:700}
1141
- input,select{height:42px;border-radius:12px;border:1px solid var(--border);padding:0 12px;font:500 15px Manrope,system-ui,sans-serif;background:var(--white)}
1142
- .book{margin:2px 0 10px}.status{margin:0;font-size:13px;min-height:1em}.status.err{color:var(--rose)}
1143
- pre{background:var(--white);border:1px solid var(--border);border-radius:12px;padding:12px;font:13px var(--mono);overflow:auto;max-height:50vh}.row{display:flex;gap:14px;align-items:center}
1144
- .by{margin:8px 0 0;display:flex;align-items:center;gap:8px;font-size:13px;color:var(--muted)}.lockup{display:inline-flex;align-items:center;gap:6px;color:var(--forest)}
1145
- .wm{font:300 15px Fraunces,Georgia,serif;letter-spacing:.42em;margin-right:-.42em;color:var(--ink)}
1146
- @keyframes settle{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
1147
- .card{animation:settle .8s ease-out both}.right .card{animation-delay:.1s}
1148
- @media (prefers-reduced-motion:reduce){.card{animation:none}*{transition:none!important}}
1149
- @media (max-width:1100px),(max-height:700px){.app{height:auto;padding:20px}header{flex-direction:column;align-items:flex-start}.btns{flex-wrap:wrap}.main{display:flex;flex-direction:column}.summary{flex-direction:column;align-items:flex-start}.mid,.toprow{flex-direction:column}.cardgrid{grid-template-columns:repeat(2,minmax(0,1fr))}.soul .art{min-height:180px}}
1150
- `;
1151
-
1152
- // src/server.ts
1153
- var FONT_DIR = [join5(dirname(fileURLToPath(import.meta.url)), "fonts"), join5(dirname(fileURLToPath(import.meta.url)), "../dist/fonts")].find(existsSync2);
1154
- var FONT_NAMES = new Set(FONT_FILES.map((f) => f.file));
1155
- function serve(wrapped, port = 4747) {
1156
- const html = renderPage(wrapped);
1157
- const server = createServer((req, res) => {
1158
- const host = (req.headers.host ?? "").replace(/:\d+$/, "");
1159
- if (host !== "127.0.0.1" && host !== "localhost") {
1160
- res.writeHead(403).end("Forbidden");
1161
- return;
1162
- }
1163
- if (req.method === "GET" && (req.url === "/" || req.url?.startsWith("/?"))) {
1164
- res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(html);
1165
- } else if (req.method === "GET" && req.url?.startsWith("/fonts/") && FONT_DIR && FONT_NAMES.has(req.url.slice(7))) {
1166
- res.writeHead(200, { "content-type": "font/woff2", "cache-control": "public, max-age=31536000, immutable" }).end(readFileSync3(join5(FONT_DIR, req.url.slice(7))));
1167
- } else {
1168
- res.writeHead(404).end("Not found");
1091
+ var SHELL = new Set(["shell", "exec_command", "shell_command", "local_shell", "container.exec", "unified_exec"]);
1092
+ function readCodex(home, range, codexHome) {
1093
+ const root = join5(codexHome ?? join5(home, ".codex"), "sessions");
1094
+ const files = walk(root, (n) => n.startsWith("rollout-") && (n.endsWith(".jsonl") || n.endsWith(".jsonl.zst"))).sort();
1095
+ const sessions = new Map;
1096
+ for (const file of files) {
1097
+ const text = readRollout(file);
1098
+ if (text === null)
1099
+ continue;
1100
+ let sid = file;
1101
+ let s = newSession();
1102
+ let policy = null;
1103
+ let sandbox = null;
1104
+ for (const o of jsonLines(text)) {
1105
+ const at = parseTime(o["timestamp"]);
1106
+ const p = asObj(o["payload"]);
1107
+ if (!at || !p)
1108
+ continue;
1109
+ switch (o["type"]) {
1110
+ case "session_meta":
1111
+ sid = str(p["id"]) ?? sid;
1112
+ s.project ??= folderName(str(p["cwd"]) ?? "");
1113
+ break;
1114
+ case "turn_context": {
1115
+ s.model ??= str(p["model"]);
1116
+ policy = str(p["approval_policy"]) ?? policy;
1117
+ const sb = p["sandbox_policy"];
1118
+ sandbox = (typeof sb === "string" ? sb : str(asObj(sb)?.["mode"]) ?? str(asObj(sb)?.["type"])) ?? sandbox;
1119
+ raiseAutonomy(s, autonomyOf2(policy, sandbox));
1120
+ break;
1121
+ }
1122
+ case "compacted":
1123
+ s.events.push({ kind: "compaction", at });
1124
+ break;
1125
+ case "event_msg":
1126
+ if (p["type"] === "user_message" && str(p["message"]))
1127
+ s.events.push({ kind: "prompt", at, text: p["message"] });
1128
+ else if (p["type"] === "agent_message" && str(p["message"]))
1129
+ s.events.push({ kind: "reply", at, text: p["message"], model: s.model });
1130
+ break;
1131
+ case "response_item": {
1132
+ const kind = p["type"];
1133
+ if (kind !== "function_call" && kind !== "custom_tool_call" && kind !== "local_shell_call")
1134
+ break;
1135
+ const name = kind === "local_shell_call" ? "local_shell" : str(p["name"]) ?? "";
1136
+ let args = null;
1137
+ const raw = p["arguments"] ?? p["action"];
1138
+ if (typeof raw === "string") {
1139
+ try {
1140
+ args = asObj(JSON.parse(raw));
1141
+ } catch {
1142
+ args = null;
1143
+ }
1144
+ } else
1145
+ args = asObj(raw);
1146
+ if (SHELL.has(name)) {
1147
+ s.events.push({ kind: "tool", at, tool: "Bash", connector: null, command: commandOf(args), path: null });
1148
+ } else if (name === "apply_patch") {
1149
+ const input = str(p["input"]) ?? "";
1150
+ const m = /\*\*\* (?:Update|Add|Delete) File: (.+)/.exec(input);
1151
+ s.events.push({ kind: "tool", at, tool: "Edit", connector: null, command: null, path: m?.[1]?.trim() ?? null });
1152
+ } else if (name) {
1153
+ s.events.push({ kind: "tool", at, tool: name, connector: connectorOf(name), command: null, path: null });
1154
+ }
1155
+ break;
1156
+ }
1157
+ }
1169
1158
  }
1170
- });
1171
- return new Promise((resolve, reject) => {
1172
- const tryPort = (p, left) => {
1173
- server.once("error", (err) => {
1174
- if (err.code === "EADDRINUSE" && left > 0)
1175
- tryPort(p + 1, left - 1);
1176
- else
1177
- reject(err);
1178
- });
1179
- server.listen(p, "127.0.0.1", () => resolve({ server, port: server.address().port }));
1180
- };
1181
- tryPort(port, 20);
1182
- });
1159
+ sessions.set(sid, s);
1160
+ }
1161
+ return { events: assemble("codex", sessions, range), found: files.length > 0 };
1183
1162
  }
1184
1163
 
1185
- // src/stats.ts
1186
- import { basename } from "node:path";
1187
-
1188
- // src/shell.ts
1189
- var HEREDOC = /<<-?\s*(['"]?)([A-Za-z_][\w]*)\1[^\n]*\n[\s\S]*?(?:\n\s*\2(?=\n|$)|$)/g;
1190
- function shellSegments(command) {
1191
- const src = command.replace(HEREDOC, (m) => m.slice(0, m.indexOf(`
1192
- `)));
1193
- const out = [];
1194
- let cur = "";
1195
- let quote = null;
1196
- for (let i = 0;i < src.length; i++) {
1197
- const ch = src[i];
1198
- if (quote) {
1199
- cur += ch;
1200
- if (ch === "\\" && quote === '"')
1201
- cur += src[++i] ?? "";
1202
- else if (ch === quote)
1203
- quote = null;
1204
- } else if (ch === '"' || ch === "'") {
1205
- quote = ch;
1206
- cur += ch;
1207
- } else if (ch === "\\") {
1208
- cur += ch + (src[++i] ?? "");
1209
- } else if (ch === ";" || ch === "|" || ch === "&" || ch === `
1210
- `) {
1211
- if (cur.trim())
1212
- out.push(cur.trim());
1213
- cur = "";
1214
- } else
1215
- cur += ch;
1164
+ // src/readers/cursor.ts
1165
+ import { join as join6 } from "node:path";
1166
+ var SHELL2 = new Set(["Shell", "shell", "run_terminal_cmd", "run_terminal_command", "terminal"]);
1167
+ var EDIT = new Set(["edit_file", "search_replace", "StrReplace", "Write", "Edit", "MultiEdit", "write"]);
1168
+ function chatTimes(cursor) {
1169
+ const out = new Map;
1170
+ for (const ws of listDir(join6(cursor, "chats"))) {
1171
+ for (const chat of listDir(join6(cursor, "chats", ws))) {
1172
+ const meta = readJson(join6(cursor, "chats", ws, chat, "meta.json"));
1173
+ if (meta)
1174
+ out.set(chat, { created: parseTime(meta["createdAtMs"]), updated: parseTime(meta["updatedAtMs"]) });
1175
+ }
1216
1176
  }
1217
- if (cur.trim())
1218
- out.push(cur.trim());
1219
1177
  return out;
1220
1178
  }
1221
- var KEYWORDS = new Set(["if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", "esac", "function", "in", "{", "}", "!", "[", "[["]);
1222
- var WRAPPERS = new Set(["sudo", "time", "command", "env", "nohup", "exec", "xargs"]);
1223
- function programOf(segment) {
1224
- const words = segment.split(/\s+/).filter((w) => w && !/^[A-Za-z_]\w*=/.test(w));
1225
- let i = 0;
1226
- while (words[i] && WRAPPERS.has(words[i]))
1227
- i++;
1228
- const w = words[i];
1229
- if (!w || KEYWORDS.has(w) || w === "cd")
1230
- return null;
1231
- const name = w.split("/").pop() ?? "";
1232
- return /^[A-Za-z][\w.+-]*$/.test(name) ? name : null;
1179
+ function userText(o) {
1180
+ const content = asObj(o["message"])?.["content"] ?? o["content"];
1181
+ const raw = typeof content === "string" ? content : Array.isArray(content) ? content.map(asObj).filter((p) => p?.["type"] === "text").map((p) => str(p?.["text"]) ?? "").join(`
1182
+ `) : "";
1183
+ const m = /<user_query>([\s\S]*?)<\/user_query>/.exec(raw);
1184
+ return (m ? m[1] : raw).trim() || null;
1185
+ }
1186
+ function readCursor(home, range) {
1187
+ const cursor = join6(home, ".cursor");
1188
+ const times = chatTimes(cursor);
1189
+ const files = walk(join6(cursor, "projects"), (n) => n.endsWith(".jsonl"), 4).filter((f) => f.includes("agent-transcripts"));
1190
+ const sessions = new Map;
1191
+ for (const file of files.sort()) {
1192
+ const text = readText(file);
1193
+ if (text === null)
1194
+ continue;
1195
+ const parts = file.split("/");
1196
+ const stem = (parts.pop() ?? "").replace(/\.jsonl$/, "");
1197
+ const chat = stem;
1198
+ const meta = times.get(chat);
1199
+ const lines = jsonLines(text);
1200
+ const s = newSession();
1201
+ const created = meta?.created ?? null;
1202
+ const updated = meta?.updated ?? created;
1203
+ lines.forEach((o, n) => {
1204
+ const own = parseTime(o["timestamp"]);
1205
+ const at = own ?? (created && updated ? new Date(created.getTime() + (updated.getTime() - created.getTime()) * n / Math.max(lines.length - 1, 1)) : null);
1206
+ if (!at)
1207
+ return;
1208
+ const role = o["role"];
1209
+ if (role === "user") {
1210
+ const t = userText(o);
1211
+ if (t)
1212
+ s.events.push({ kind: "prompt", at, text: t });
1213
+ return;
1214
+ }
1215
+ if (role !== "assistant")
1216
+ return;
1217
+ const content = asObj(o["message"])?.["content"] ?? o["content"];
1218
+ for (const item of Array.isArray(content) ? content : []) {
1219
+ const b = asObj(item);
1220
+ if (!b)
1221
+ continue;
1222
+ if (b["type"] === "text" && str(b["text"]))
1223
+ s.events.push({ kind: "reply", at, text: b["text"], model: null });
1224
+ else if (b["type"] === "tool_use") {
1225
+ const name = str(b["name"]);
1226
+ if (!name)
1227
+ continue;
1228
+ const input = asObj(b["input"]);
1229
+ const path = str(input?.["path"]) ?? str(input?.["file_path"]) ?? str(input?.["target_file"]);
1230
+ if (SHELL2.has(name))
1231
+ s.events.push({ kind: "tool", at, tool: "Bash", connector: null, command: str(input?.["command"]), path: null });
1232
+ else if (EDIT.has(name))
1233
+ s.events.push({ kind: "tool", at, tool: "Edit", connector: null, command: null, path });
1234
+ else
1235
+ s.events.push({ kind: "tool", at, tool: name, connector: connectorOf(name), command: null, path });
1236
+ }
1237
+ }
1238
+ });
1239
+ sessions.set(chat, s);
1240
+ }
1241
+ return { events: assemble("cursor", sessions, range), found: files.length > 0 };
1233
1242
  }
1234
1243
 
1235
- // src/personality.ts
1236
- var MIN_CALLS = 20;
1237
- var CAP = 3;
1238
- var ratio = (value, bar) => Math.min(value / bar, CAP);
1239
- var busy = (s, score) => s.toolCalls >= MIN_CALLS ? score : 0;
1240
- var ARCHETYPES = [
1241
- {
1242
- score: (s) => s.sessions === 0 ? 0 : Math.max(ratio(s.bypassSessions / s.sessions, 0.2), s.dontAskAgain >= 10 ? ratio(s.dontAskAgain / s.sessions, 0.5) : 0),
1243
- result: { name: "The Intern With Root Access", trustStatus: "It's complicated", genre: "Permission-Prompt Punk" }
1244
- },
1245
- {
1246
- score: (s) => busy(s, ratio(s.nightShare, 0.35)),
1247
- result: { name: "The Night Shift", trustStatus: "Asleep at the wheel, together", genre: "Lo-Fi Beats to Deploy To" }
1248
- },
1249
- {
1250
- score: (s) => busy(s, ratio(s.earlyShare, 0.3)),
1251
- result: { name: "The Early Bird", trustStatus: "Up before the CI is", genre: "Sunrise Standup Soul" }
1252
- },
1253
- {
1254
- score: (s) => busy(s, ratio(s.weekendShare, 0.45)),
1255
- result: { name: "The Weekend Warrior", trustStatus: "Saturday is a work day now", genre: "Sunday Scaries Synthpop" }
1256
- },
1257
- {
1258
- score: (s) => s.compactions >= 3 ? ratio(s.compactions / Math.max(s.sessions, 1), 0.5) : 0,
1259
- result: { name: "The Context Hoarder", trustStatus: "Remembers everything, forgives nothing", genre: "Progressive Rock, 14 Movements" }
1260
- },
1261
- {
1262
- score: (s) => s.sessions < 10 ? 0 : s.agentHours === 0 ? CAP : ratio(0.25, s.agentHours / s.sessions),
1263
- result: { name: "The Speedrunner", trustStatus: "Move fast, ask later", genre: "Speedcore" }
1264
- },
1265
- {
1266
- score: (s) => s.sessions >= 3 ? ratio(s.agentHours / s.sessions, 1.5) : 0,
1267
- result: { name: "The Marathoner", trustStatus: "Till compaction do us part", genre: "Twelve-Hour Drone" }
1268
- },
1269
- {
1270
- score: (s) => s.topHarness === "cursor" ? busy(s, ratio(s.topHarnessShare, 0.5)) : 0,
1271
- result: { name: "The Tab Goblin", trustStatus: "Pressing Tab on faith", genre: "Autocomplete Jazz" }
1272
- },
1273
- {
1274
- score: (s) => busy(s, ratio(s.secondHarnessShare, 0.25)),
1275
- result: { name: "The Agent Juggler", trustStatus: "Seeing other agents", genre: "Split-Screen Ska" }
1276
- },
1277
- {
1278
- score: (s) => busy(s, Math.max(ratio(s.connectorShare, 0.2), ratio(s.connectorCount, 4))),
1279
- result: { name: "The Connector Collector", trustStatus: "Gave it the keys to everything", genre: "Integration Hall of Fame" }
1280
- },
1281
- {
1282
- score: (s) => busy(s, ratio(s.bashShare, 0.55)),
1283
- result: { name: "The Terminal Cowboy", trustStatus: "Shoots first, reads the man page later", genre: "Bash Country" }
1284
- },
1285
- {
1286
- score: (s) => busy(s, ratio(s.webShare, 0.08)),
1287
- result: { name: "The Rabbit-Hole Researcher", trustStatus: "Trust, but cite sources", genre: "Forty-Tab Jazz Odyssey" }
1288
- },
1289
- {
1290
- score: (s) => s.subagentCalls >= 5 ? busy(s, ratio(s.subagentCalls / s.toolCalls, 0.04)) : 0,
1291
- result: { name: "The Middle Manager", trustStatus: "Delegates, then checks nothing", genre: "Org-Chart Orchestral" }
1292
- },
1293
- {
1294
- score: (s) => s.lazyPrompts >= 5 ? ratio(s.lazyPrompts / Math.max(s.sessions, 1), 0.3) : 0,
1295
- result: { name: "The Copy-Paste Debugger", trustStatus: "fix it", genre: "Stack-Trace Screamo" }
1296
- },
1297
- {
1298
- score: (s) => s.reads >= 50 ? ratio(s.reads / Math.max(s.writes, 1), 6) : 0,
1299
- result: { name: "The Archaeologist", trustStatus: "Reads everything, changes nothing", genre: "Ancient Codebase Chants" }
1300
- },
1301
- {
1302
- score: () => 0,
1303
- result: { name: "The Pair Programmer", trustStatus: "Healthy, mostly", genre: "Unplugged Acoustic" }
1244
+ // src/readers/index.ts
1245
+ function readAll(home, now, codexHome = process.env["CODEX_HOME"]) {
1246
+ const range = { from: bounds(windowFor(now)).from, until: now };
1247
+ const found = [];
1248
+ const events = [];
1249
+ let claudeAllowRules = 0;
1250
+ let firstStarted = null;
1251
+ let claudeHistory = null;
1252
+ const attempts = [
1253
+ [
1254
+ "claude-code",
1255
+ () => {
1256
+ const r = readClaude(home, range);
1257
+ claudeAllowRules = r.allowRules;
1258
+ firstStarted = r.firstStarted;
1259
+ claudeHistory = r.history;
1260
+ return r;
1261
+ }
1262
+ ],
1263
+ ["codex", () => readCodex(home, range, codexHome)],
1264
+ ["cursor", () => readCursor(home, range)]
1265
+ ];
1266
+ for (const [harness, run] of attempts) {
1267
+ try {
1268
+ const r = run();
1269
+ if (r.found)
1270
+ found.push(harness);
1271
+ events.push(...r.events);
1272
+ } catch {}
1304
1273
  }
1305
- ];
1306
- function pickArchetype(s) {
1307
- let best = ARCHETYPES[ARCHETYPES.length - 1];
1308
- let bestScore = 0;
1309
- for (const a of ARCHETYPES) {
1310
- const score = a.score(s);
1311
- if (score >= 1 && score > bestScore)
1312
- [best, bestScore] = [a, score];
1274
+ const backfill = [];
1275
+ try {
1276
+ const cache = readStatsCache(home);
1277
+ backfill.push(...cache.days);
1278
+ const inWindow = cache.days.some((d) => d.date >= ymd(range.from) && d.date <= ymd(range.until) && (d.toolCalls > 0 || d.sessions > 0));
1279
+ if (inWindow && !found.includes("claude-code"))
1280
+ found.unshift("claude-code");
1281
+ if (cache.first && (!firstStarted || cache.first < firstStarted))
1282
+ firstStarted = cache.first;
1283
+ backfill.push(...readDailyFile(home).days);
1284
+ } catch {}
1285
+ return { events, approvals: { claudeAllowRules }, found, firstStarted, backfill, claudeHistory };
1286
+ }
1287
+
1288
+ // src/server.ts
1289
+ import { createServer } from "node:http";
1290
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
1291
+
1292
+ // src/keepHistory.ts
1293
+ import { lstatSync, readFileSync as readFileSync3, readlinkSync } from "node:fs";
1294
+ import { dirname as dirname2, join as join7, resolve } from "node:path";
1295
+ var KEEP_DAYS = 400;
1296
+ function linkTarget(path, hops = 0) {
1297
+ try {
1298
+ if (hops < 8 && lstatSync(path).isSymbolicLink())
1299
+ return linkTarget(resolve(dirname2(path), readlinkSync(path)), hops + 1);
1300
+ } catch {}
1301
+ return path;
1302
+ }
1303
+ function keepHistory(home) {
1304
+ const path = join7(home, ".claude", "settings.json");
1305
+ const shown = "~/.claude/settings.json";
1306
+ let settings = {};
1307
+ try {
1308
+ let text = null;
1309
+ try {
1310
+ text = readFileSync3(path, "utf8");
1311
+ } catch (err) {
1312
+ if (err.code !== "ENOENT")
1313
+ throw err;
1314
+ }
1315
+ if (text !== null) {
1316
+ let parsed;
1317
+ try {
1318
+ parsed = JSON.parse(text);
1319
+ } catch {
1320
+ parsed = null;
1321
+ }
1322
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1323
+ return { status: 409, body: { error: `${shown} is not valid JSON, so it was left as it is. Fix it, then try again.` } };
1324
+ }
1325
+ settings = parsed;
1326
+ }
1327
+ const current = settings["cleanupPeriodDays"];
1328
+ const existing = typeof current === "number" && Number.isFinite(current) ? current : 0;
1329
+ if (existing >= KEEP_DAYS)
1330
+ return { status: 200, body: { retentionDays: existing } };
1331
+ writeJsonAtomic(linkTarget(path), { ...settings, cleanupPeriodDays: KEEP_DAYS });
1332
+ return { status: 200, body: { retentionDays: KEEP_DAYS } };
1333
+ } catch (err) {
1334
+ return { status: 500, body: { error: `Could not update ${shown}: ${err instanceof Error ? err.message : String(err)}` } };
1313
1335
  }
1314
- return best.result;
1315
1336
  }
1316
- var COMMAND_GENRE = {
1317
- git: "Commit-Core",
1318
- gh: "Pull-Request Pop",
1319
- npm: "Node-Modules Metal",
1320
- npx: "Node-Modules Metal",
1321
- pnpm: "Node-Modules Metal",
1322
- yarn: "Node-Modules Metal",
1323
- node: "Node-Modules Metal",
1324
- bun: "Bun-Fed Breakbeat",
1325
- cargo: "Borrow-Checker Blues",
1326
- rustc: "Borrow-Checker Blues",
1327
- go: "Goroutine Garage Rock",
1328
- python: "Indentation Indie",
1329
- python3: "Indentation Indie",
1330
- pip: "Indentation Indie",
1331
- uv: "Indentation Indie",
1332
- pytest: "Indentation Indie",
1333
- docker: "Container Shoegaze",
1334
- kubectl: "Cluster Ambient",
1335
- helm: "Cluster Ambient",
1336
- terraform: "Infrastructure Industrial",
1337
- curl: "HTTP Hip-Hop",
1338
- wget: "HTTP Hip-Hop",
1339
- rg: "Grep-Hop",
1340
- grep: "Grep-Hop",
1341
- find: "Grep-Hop",
1342
- ls: "Directory Drone",
1343
- pwd: "Directory Drone",
1344
- cat: "Text-Stream Folk",
1345
- head: "Text-Stream Folk",
1346
- tail: "Text-Stream Folk",
1347
- sed: "Text-Stream Folk",
1348
- awk: "Text-Stream Folk",
1349
- echo: "Echo Chamber Pop",
1350
- make: "Makefile Motown",
1351
- psql: "Query Crooner",
1352
- sqlite3: "Query Crooner",
1353
- ssh: "Remote-Server Reggae"
1337
+
1338
+ // src/server.ts
1339
+ import { dirname as dirname3, join as join8 } from "node:path";
1340
+ import { fileURLToPath } from "node:url";
1341
+
1342
+ // src/fonts.ts
1343
+ var FONT_FILES = [
1344
+ { pkg: "fraunces", family: "Fraunces", weight: 300, style: "normal", file: "fraunces-latin-300-normal.woff2" },
1345
+ { pkg: "fraunces", family: "Fraunces", weight: 300, style: "italic", file: "fraunces-latin-300-italic.woff2" },
1346
+ ...[400, 600, 700, 800].map((weight) => ({ pkg: "manrope", family: "Manrope", weight, style: "normal", file: `manrope-latin-${weight}-normal.woff2` })),
1347
+ ...[400, 500].map((weight) => ({ pkg: "dm-mono", family: "DM Mono", weight, style: "normal", file: `dm-mono-latin-${weight}-normal.woff2` }))
1348
+ ];
1349
+ var fontFaceCss = () => FONT_FILES.map((f) => `@font-face{font-family:'${f.family}';font-weight:${f.weight};font-style:${f.style};font-display:swap;src:url(/fonts/${f.file}) format('woff2')}`).join("");
1350
+
1351
+ // src/brand.ts
1352
+ var BRAND = {
1353
+ forest: "#1E5A3C",
1354
+ mist: "#F8FBF8",
1355
+ "mist-2": "#E8F1E9",
1356
+ ink: "#12241A",
1357
+ "ink-dark": "#071A13",
1358
+ sage: "#389560",
1359
+ rose: "#C05B6B",
1360
+ blush: "#EEB2B8",
1361
+ "rose-tint": "#FFEDEE",
1362
+ border: "#DDE3DE",
1363
+ muted: "#5A675F",
1364
+ white: "#FFFFFF"
1354
1365
  };
1355
- var capital = (s) => s.charAt(0).toUpperCase() + s.slice(1);
1356
- var CONNECTOR_NAME = { github: "GitHub", gitlab: "GitLab", posthog: "PostHog", hubspot: "HubSpot" };
1357
- var connectorDisplay = (name) => CONNECTOR_NAME[name.toLowerCase()] ?? name.split(/[-_\s]+/).filter(Boolean).map(capital).join(" ");
1358
- function genreOf(topCommand, topConnector, fallback) {
1359
- if (topCommand)
1360
- return COMMAND_GENRE[topCommand] ?? `${capital(topCommand)}core`;
1361
- if (topConnector)
1362
- return `${connectorDisplay(topConnector)} Lounge`;
1363
- return fallback;
1366
+ var brandCss = () => `:root{${Object.entries(BRAND).map(([k, v]) => `--${k}:${v}`).join(";")}}`;
1367
+ var MARK_PATH = "M11 5V27M11 6L21 12L11 18M15 18L22 27";
1368
+ var markSvg = (size, color = "var(--forest)") => `<svg class="mark" width="${size}" height="${size}" viewBox="0 0 32 32" fill="none" stroke="${color}" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${MARK_PATH}"/></svg>`;
1369
+
1370
+ // src/config.ts
1371
+ var API_BASE = "https://agent-wrapped.trappetarn.workers.dev";
1372
+ var SHARE_URL = "https://github.com/Trappetarn/agent-wrapped";
1373
+ var SHARE_TARGETS = [
1374
+ { id: "x", label: "X", url: "https://x.com/intent/post?text={text}&url={url}" },
1375
+ { id: "linkedin", label: "LinkedIn", url: "https://www.linkedin.com/sharing/share-offsite/?url={url}" },
1376
+ { id: "reddit", label: "Reddit", url: "https://www.reddit.com/submit?url={url}&title={text}" },
1377
+ { id: "bluesky", label: "Bluesky", url: "https://bsky.app/intent/compose?text={text}%20{url}" }
1378
+ ];
1379
+ var CAL = { origin: "https://app.cal.com", script: "https://app.cal.com/embed/embed.js", link: "lisa-buerger/15min", namespace: "15min" };
1380
+ var SAFETY_TOPICS = [
1381
+ "Knowing what agents touched",
1382
+ "Secrets and customer data",
1383
+ "Risky commands: deploys, deletes, pushes",
1384
+ "Audit and compliance",
1385
+ "Which agents and tools people use",
1386
+ "Not sure yet"
1387
+ ];
1388
+ var TEAM_SIZES = ["Just me", "2–20", "21–200", "200+"];
1389
+
1390
+ // src/client.ts
1391
+ var CLIENT_SCRIPT = String.raw`
1392
+ (function () {
1393
+ var D = JSON.parse(document.getElementById("data").textContent);
1394
+ var W = D.wrapped, B = D.brand;
1395
+ var $ = function (id) { return document.getElementById(id); };
1396
+ var num = function (n) { return n.toLocaleString("en-US"); };
1397
+
1398
+ function wire(openId, dlgId, onOpen) {
1399
+ $(openId).addEventListener("click", function () { if (onOpen) onOpen(); $(dlgId).showModal(); });
1400
+ }
1401
+ document.querySelectorAll("[data-close]").forEach(function (b) {
1402
+ b.addEventListener("click", function () { b.closest("dialog").close(); });
1403
+ });
1404
+ document.querySelectorAll("dialog").forEach(function (d) {
1405
+ d.addEventListener("click", function (e) { if (e.target === d) d.close(); });
1406
+ });
1407
+
1408
+ function post(path, body) {
1409
+ return fetch(D.api + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })
1410
+ .then(function (r) { if (!r.ok) throw new Error("status " + r.status); });
1411
+ }
1412
+ function status(el, text, bad) { el.textContent = text; el.className = "status" + (bad ? " err" : ""); }
1413
+ var FRIENDLY = "Could not reach the server just now. Nothing was sent. Try again later.";
1414
+
1415
+ // Waitlist: only the form fields are sent.
1416
+ $("waitlist").addEventListener("submit", function (e) {
1417
+ e.preventDefault();
1418
+ var f = e.target, st = $("wl-status");
1419
+ status(st, "Sending...", false);
1420
+ post("/waitlist", { email: f.email.value.trim(), teamSize: f.teamSize.value })
1421
+ .then(function () { status(st, "You're on the list. We'll email you when team Wrapped is ready.", false); f.reset(); })
1422
+ .catch(function () { status(st, FRIENDLY, true); });
1423
+ });
1424
+
1425
+ wire("open-team", "team");
1426
+
1427
+ // Booking: Cal.com loads only after "Pick a time". It gets the ticked topics as the booking note.
1428
+ function showBooking(on) {
1429
+ $("ask").hidden = on; $("booking").hidden = !on; $("team").classList.toggle("booking", on);
1430
+ }
1431
+ // Cal.com's own inline embed loader (from the Cal.com "inline embed" snippet), started on first click.
1432
+ function calApi() {
1433
+ (function (C, A, L) { var p = function (a, ar) { a.q.push(ar); }; var d = C.document; C.Cal = C.Cal || function () { var cal = C.Cal; var ar = arguments; if (!cal.loaded) { cal.ns = {}; cal.q = cal.q || []; d.head.appendChild(d.createElement("script")).src = A; cal.loaded = true; } if (ar[0] === L) { var api = function () { p(api, arguments); }; var namespace = ar[1]; api.q = api.q || []; if (typeof namespace === "string") { cal.ns[namespace] = cal.ns[namespace] || api; p(cal.ns[namespace], ar); p(cal, ["initNamespace", namespace]); } else p(cal, ar); return; } p(cal, ar); }; })(window, D.cal.script, "init");
1434
+ if (!Cal.ns || !Cal.ns[D.cal.namespace]) {
1435
+ Cal("init", D.cal.namespace, { origin: D.cal.origin });
1436
+ Cal.ns[D.cal.namespace]("ui", { hideEventTypeDetails: false, layout: "month_view", theme: "light", cssVarsPerTheme: { light: { "cal-brand": B.forest } } });
1437
+ }
1438
+ return Cal.ns[D.cal.namespace];
1439
+ }
1440
+ var calNotes = null;
1441
+ $("pick-time").addEventListener("click", function () {
1442
+ var picked = [];
1443
+ document.querySelectorAll("#ask input[name=topic]:checked").forEach(function (c) { picked.push(c.value); });
1444
+ var notes = picked.length ? "What we care about: " + picked.join("; ") : "";
1445
+ showBooking(true);
1446
+ if (notes === calNotes) return;
1447
+ calNotes = notes;
1448
+ $("cal").innerHTML = "";
1449
+ var config = { layout: "month_view", useSlotsViewOnSmallScreen: "true" };
1450
+ if (notes) config.notes = notes;
1451
+ calApi()("inline", { elementOrSelector: "#cal", config: config, calLink: D.cal.link });
1452
+ });
1453
+ $("back-ask").addEventListener("click", function () { showBooking(false); });
1454
+ $("team").addEventListener("close", function () { showBooking(false); });
1455
+
1456
+ // ---- Share cards: drawn natively on a 1080x1920 canvas from the card list in D.cards. ----
1457
+ var SANS = "Manrope, system-ui, sans-serif", SERIF = "Fraunces, Georgia, serif", MONO = "'DM Mono', ui-monospace, monospace";
1458
+ var MINT = "#BFE3C8", SAGE_LIGHT = "#9FD0B0", GRID = 48;
1459
+ var THEMES = {
1460
+ dark: { bg: B["ink-dark"], grid: "rgba(248,251,248,0.022)", body: B.mist, eyebrow: "rgba(248,251,248,0.62)", rule: "rgba(248,251,248,0.14)", sub: "rgba(248,251,248,0.62)",
1461
+ heroText: B.ink, heroWord: B.forest, heroEyebrow: "rgba(18,36,26,0.78)", heroMark: "rgba(30,90,60,0.12)", heroMarkSmall: B.forest, accent: { forest: SAGE_LIGHT, rose: B.blush }, footMark: B.mist, site: "rgba(248,251,248,0.62)" },
1462
+ light: { bg: B.mist, grid: "rgba(30,90,60,0.045)", body: B.ink, eyebrow: B.muted, rule: "rgba(18,36,26,0.12)", sub: B.muted,
1463
+ heroText: B.mist, heroWord: MINT, heroEyebrow: "rgba(248,251,248,0.78)", heroMark: "rgba(248,251,248,0.12)", heroMarkSmall: B["mist-2"], accent: { forest: B.forest, rose: B.rose }, footMark: B.forest, site: B.muted }
1464
+ };
1465
+
1466
+ function glow(c, x, y, r, rgb, a) {
1467
+ var g = c.createRadialGradient(x, y, 0, x, y, r);
1468
+ g.addColorStop(0, "rgba(" + rgb + "," + a + ")"); g.addColorStop(1, "rgba(" + rgb + ",0)");
1469
+ c.fillStyle = g; c.fillRect(x - r, y - r, r * 2, r * 2);
1470
+ }
1471
+ function grid(c, x0, y0, w, h, color) {
1472
+ c.save(); c.beginPath(); c.rect(x0, y0, w, h); c.clip();
1473
+ c.strokeStyle = color; c.lineWidth = 2; c.beginPath();
1474
+ for (var x = x0 - (x0 % GRID); x <= x0 + w; x += GRID) { c.moveTo(x, y0); c.lineTo(x, y0 + h); }
1475
+ for (var y = y0 - (y0 % GRID); y <= y0 + h; y += GRID) { c.moveTo(x0, y); c.lineTo(x0 + w, y); }
1476
+ c.stroke(); c.restore();
1477
+ }
1478
+ // The rune on a 32-unit grid; px is the stroke width in canvas pixels.
1479
+ function mark(c, x, y, size, color, px) {
1480
+ c.save(); c.translate(x, y); c.scale(size / 32, size / 32);
1481
+ c.strokeStyle = color; c.lineWidth = px / (size / 32); c.lineCap = "round"; c.lineJoin = "round";
1482
+ c.stroke(new Path2D("M11 5V27M11 6L21 12L11 18M15 18L22 27")); c.restore();
1483
+ }
1484
+ function setFont(c, font) { c.font = font; return c; }
1485
+ function fontAt(font, size) { return font.replace(/\d+px/, size + "px"); }
1486
+ // Text with tracking in em, drawn per character so it is measurable and works everywhere.
1487
+ function spaced(c, s, x, y, font, color, em, align) {
1488
+ setFont(c, font); c.fillStyle = color; c.textBaseline = "alphabetic"; c.textAlign = "left";
1489
+ var size = parseFloat(font.match(/(\d+(?:\.\d+)?)px/)[1]), gap = em * size, w = 0, i;
1490
+ for (i = 0; i < s.length; i++) w += c.measureText(s[i]).width + gap;
1491
+ w -= gap;
1492
+ var cx = align === "right" ? x - w : x;
1493
+ for (i = 0; i < s.length; i++) { c.fillText(s[i], cx, y); cx += c.measureText(s[i]).width + gap; }
1494
+ return w;
1495
+ }
1496
+ function plain(c, s, x, y, font, color, align) { setFont(c, font); c.fillStyle = color; c.textAlign = align || "left"; c.textBaseline = "alphabetic"; c.fillText(s, x, y); }
1497
+ function fitFont(c, s, font, maxW, min) {
1498
+ var size = parseInt(font.match(/(\d+)px/)[1], 10);
1499
+ while (size > (min || 20)) { setFont(c, fontAt(font, size)); if (c.measureText(s).width <= maxW) break; size -= 2; }
1500
+ return fontAt(font, size);
1501
+ }
1502
+ // Greedy word wrap that measures every line. A word wider than maxW breaks after hyphens, then by character.
1503
+ function wrapText(c, s, font, maxW) {
1504
+ setFont(c, font);
1505
+ var pieces = [];
1506
+ s.split(" ").forEach(function (word) {
1507
+ var parts = word.split(/(?<=[A-Za-z0-9]-)(?=[A-Za-z0-9])/);
1508
+ parts.forEach(function (p, i) {
1509
+ if (c.measureText(p).width <= maxW) { pieces.push({ t: p, sp: i === 0 }); return; }
1510
+ var cur = "", first = i === 0;
1511
+ for (var k = 0; k < p.length; k++) {
1512
+ if (cur && c.measureText(cur + p[k]).width > maxW) { pieces.push({ t: cur, sp: first }); first = false; cur = ""; }
1513
+ cur += p[k];
1514
+ }
1515
+ if (cur) pieces.push({ t: cur, sp: first });
1516
+ });
1517
+ });
1518
+ var lines = [], line = "";
1519
+ pieces.forEach(function (p) {
1520
+ var next = line ? line + (p.sp ? " " : "") + p.t : p.t;
1521
+ if (line && c.measureText(next).width > maxW) { lines.push(line); line = p.t; } else line = next;
1522
+ });
1523
+ if (line) lines.push(line);
1524
+ return lines;
1525
+ }
1526
+
1527
+ function background(c, th, dark) {
1528
+ c.fillStyle = th.bg; c.fillRect(0, 0, 1080, 1920);
1529
+ if (dark) { glow(c, 120, 80, 620, "30,90,60", 0.42); glow(c, 1020, 760, 520, "30,90,60", 0.3); glow(c, 300, 1500, 700, "30,90,60", 0.2); }
1530
+ else { glow(c, 0, 420, 520, "30,90,60", 0.13); glow(c, 1080, 760, 520, "192,91,107", 0.1); }
1531
+ grid(c, 0, 0, 1080, 1920, th.grid);
1532
+ }
1533
+
1534
+ function face(c, th, dark) {
1535
+ var cx = 700, cy = 330, r = 118;
1536
+ c.save(); c.beginPath(); c.arc(cx, cy, r, 0, Math.PI * 2); c.clip();
1537
+ c.fillStyle = B.forest; c.fillRect(cx - r, cy - r, r * 2, r * 2);
1538
+ c.fillStyle = B.rose; c.fillRect(cx - r, cy - r, r * 2, 40);
1539
+ plain(c, "sudo", cx, cy - r + 29, "400 24px " + MONO, B.mist, "center");
1540
+ c.fillStyle = B.mist; c.beginPath(); c.arc(cx - 40, cy - 8, 16, 0, Math.PI * 2); c.arc(cx + 40, cy - 8, 16, 0, Math.PI * 2); c.fill();
1541
+ c.beginPath(); c.roundRect(cx - 40, cy + 44, 80, 14, 7); c.fill();
1542
+ c.restore();
1543
+ }
1544
+
1545
+ function hero(c, card, th, dark) {
1546
+ var x = 150, y = 110, w = 780, h = 720, r = 32;
1547
+ c.save(); c.shadowColor = dark ? "rgba(0,0,0,0.45)" : "rgba(7,26,19,0.28)"; c.shadowBlur = 70; c.shadowOffsetY = 28;
1548
+ c.fillStyle = dark ? B["mist-2"] : B.forest; c.beginPath(); c.roundRect(x, y, w, h, r); c.fill(); c.restore();
1549
+ c.save(); c.beginPath(); c.roundRect(x, y, w, h, r); c.clip();
1550
+ var g = c.createLinearGradient(x, y, x + w, y + h);
1551
+ if (dark) { g.addColorStop(0, B["mist-2"]); g.addColorStop(1, B.mist); } else { g.addColorStop(0, "#216143"); g.addColorStop(1, "#19492f"); }
1552
+ c.fillStyle = g; c.fillRect(x, y, w, h);
1553
+ if (dark) { glow(c, 360, 260, 320, "56,149,96", 0.3); glow(c, 850, 740, 300, "192,91,107", 0.18); grid(c, x, y, w, h, "rgba(18,36,26,0.035)"); }
1554
+ else { glow(c, 330, 250, 360, "159,208,176", 0.3); glow(c, 860, 790, 340, "7,26,19", 0.4); grid(c, x, y, w, h, "rgba(248,251,248,0.03)"); }
1555
+ if (card.hero === "face") face(c, th, dark); else mark(c, 481, 364, 516, th.heroMark, 22);
1556
+ spaced(c, "AGENT ACTIVITY · YEAR IN REVIEW", 204, 179, "400 20px " + MONO, th.heroEyebrow, 0.2);
1557
+ mark(c, 840, 154, 36, th.heroMarkSmall, 2.6);
1558
+ var tf = fitFont(c, card.title, "300 150px " + SERIF, 672, 60), size = parseInt(tf.match(/(\d+)px/)[1], 10);
1559
+ var base = 612;
1560
+ spaced(c, "2026", 204, base - size * 0.7 - 62, "400 34px " + MONO, th.heroText, 0.2);
1561
+ plain(c, card.title, 204, base, tf, th.heroText);
1562
+ plain(c, "Wrapped", 220, 752, "italic 300 150px " + SERIF, th.heroWord);
1563
+ c.restore();
1564
+ return size;
1565
+ }
1566
+
1567
+ var COLS = { 1: [[84, 912]], 2: [[84, 400], [536, 460]] };
1568
+ function header(c, th, label, x, y, w) {
1569
+ spaced(c, label, x, y, "400 22px " + MONO, th.eyebrow, 0.2);
1570
+ c.fillStyle = th.rule; c.fillRect(x, y + 26, w, 2);
1571
+ }
1572
+ // One list column. Returns {h, lines}: h is the height from the header baseline to the last baseline.
1573
+ function listCol(c, th, accent, col, x, w, y, size) {
1574
+ header(c, th, col.header, x, y, w);
1575
+ var font = "500 " + size + "px " + SANS, lh = Math.round(size * 1.13), gap = 15, indent = 46, by = y + 26 + 50, maxLines = 0;
1576
+ col.items.forEach(function (it, i) {
1577
+ var rw = 0;
1578
+ if (it.right) { setFont(c, "400 24px " + MONO); rw = c.measureText(it.right).width + 24; }
1579
+ var tw = w - indent - rw, lines = wrapText(c, it.text, font, tw), ll;
1580
+ var tail = [];
1581
+ if (it.sub) tail.push({ s: it.sub, font: "400 " + size + "px " + SANS, color: th.sub });
1582
+ if (it.note) tail.push({ s: it.note, font: "400 24px " + MONO, color: th.sub });
1583
+ var lastX = 0, lastLine;
1584
+ lines.forEach(function (l, j) { plain(c, l, x + indent, by + j * lh, font, th.body); });
1585
+ lastLine = lines[lines.length - 1]; setFont(c, font); lastX = c.measureText(lastLine).width;
1586
+ var ty = by + (lines.length - 1) * lh;
1587
+ tail.forEach(function (t) {
1588
+ setFont(c, t.font); var tw2 = c.measureText(t.s).width;
1589
+ if (lastX + 18 + tw2 > tw) { ty += lh; lastX = 0; lines.push(""); } else lastX += 18;
1590
+ plain(c, t.s, x + indent + lastX, ty, t.font, t.color); lastX += tw2;
1591
+ });
1592
+ maxLines = Math.max(maxLines, lines.length);
1593
+ plain(c, String(i + 1).padStart(2, "0"), x, by - 2, "400 22px " + MONO, accent);
1594
+ if (it.right) plain(c, it.right, x + w, by, "400 24px " + MONO, th.sub, "right");
1595
+ by += (lines.length - 1) * lh + lh + gap;
1596
+ });
1597
+ return { h: by - lh - gap - y + 24, lines: maxLines };
1598
+ }
1599
+ function statCol(c, th, accent, col, x, w, y) {
1600
+ header(c, th, col.label, x, y, w);
1601
+ var top = y + 26, last;
1602
+ if (col.kind === "number") {
1603
+ var f = fitFont(c, col.value, "300 110px " + SERIF, col.unit ? w - 70 : w, 50);
1604
+ last = top + 113; plain(c, col.value, x, last, f, accent);
1605
+ if (col.unit) { setFont(c, f); plain(c, col.unit, x + c.measureText(col.value).width + 10, last, "italic 300 56px " + SERIF, accent); }
1606
+ } else {
1607
+ var font = col.kind === "display" ? "300 92px " + SERIF : "italic 300 56px " + SERIF, lh = col.kind === "display" ? 96 : 57;
1608
+ var lines = wrapText(c, col.value, font, w);
1609
+ lines.forEach(function (l, i) { plain(c, l, x, top + (col.kind === "display" ? 92 : 66) + i * lh, font, accent); });
1610
+ last = top + (col.kind === "display" ? 92 : 66) + (lines.length - 1) * lh;
1611
+ }
1612
+ if (col.caption) {
1613
+ var cl = wrapText(c, col.caption, "400 28px " + SANS, w), cy = last + (col.kind === "number" ? 48 : 46);
1614
+ cl.forEach(function (l, i) { plain(c, l, x, cy + i * 33, "400 28px " + SANS, th.body); });
1615
+ last = cy + (cl.length - 1) * 33;
1616
+ }
1617
+ return { h: last - y + 24, lines: 0 };
1618
+ }
1619
+ // Draws a row with its header baseline at y and returns {h, lines}.
1620
+ function drawRow(c, th, accent, row, y, size) {
1621
+ var cols = COLS[row.cols.length], h = 0, lines = 0;
1622
+ row.cols.forEach(function (col, i) {
1623
+ var r = row.kind === "lists" ? listCol(c, th, accent, col, cols[i][0], cols[i][1], y, size) : statCol(c, th, accent, col, cols[i][0], cols[i][1], y);
1624
+ h = Math.max(h, r.h); lines = Math.max(lines, r.lines);
1625
+ });
1626
+ return { h: h, lines: lines };
1627
+ }
1628
+
1629
+ function footer(c, card, th, dark, ft) {
1630
+ mark(c, 80, ft - 6, 78, th.footMark, 5);
1631
+ spaced(c, "RUNA", 172, ft + 42, "300 46px " + SERIF, th.body, 0.28);
1632
+ spaced(c, "npx runa-agent-wrapped", 172, ft + 84, "400 24px " + MONO, th.site, 0.08);
1633
+ var tf = "italic 300 34px " + SERIF, tl = wrapText(c, card.tagline, tf, 520);
1634
+ tl.forEach(function (l, i) { plain(c, l, 996, ft + 40 + i * 40, tf, dark ? "rgba(248,251,248,0.85)" : B.ink, "right"); });
1635
+ return Math.max(ft + 90, ft + 40 + (tl.length - 1) * 40 + 12);
1636
+ }
1637
+
1638
+ var measureCtx = document.createElement("canvas").getContext("2d");
1639
+ var FOOT_TOP = 1740, ROWS_TOP = 904, MIN_GAP = 72;
1640
+ // Lays the rows out between the hero and the footer, spreading the free space evenly.
1641
+ function drawCard(c, card, size) {
1642
+ var dark = card.theme === "dark", th = THEMES[card.theme], accent = th.accent[card.accent];
1643
+ background(c, th, dark);
1644
+ var heroSize = hero(c, card, th, dark);
1645
+ var m = card.rows.map(function (row) { return drawRow(measureCtx, th, accent, row, 0, size); });
1646
+ var lines = Math.max.apply(null, m.map(function (r) { return r.lines; }).concat([0]));
1647
+ var used = m.reduce(function (s, r) { return s + r.h; }, 0);
1648
+ var free = FOOT_TOP - 70 - ROWS_TOP - used;
1649
+ var gap = Math.max(MIN_GAP, Math.min(200, free / (m.length + 0.5)));
1650
+ var y = ROWS_TOP + (gap > MIN_GAP ? gap * 0.5 - 20 : 0), end = y;
1651
+ card.rows.forEach(function (row, i) { drawRow(c, th, accent, row, y, size); end = y + m[i].h; y = end + gap; });
1652
+ var ft = Math.max(1720, Math.min(1780, end + gap + 30));
1653
+ var bottom = footer(c, card, th, dark, ft);
1654
+ return { bottom: bottom, end: end, footerTop: ft, lines: lines, heroSize: heroSize };
1655
+ }
1656
+
1657
+ var ITEM_SIZES = [30, 28, 26, 24, 22];
1658
+ var shrunk = [];
1659
+ function draw(card, canvas) {
1660
+ var scratch = document.createElement("canvas"); scratch.width = 1080; scratch.height = 1920;
1661
+ var pick = ITEM_SIZES[ITEM_SIZES.length - 1];
1662
+ for (var i = 0; i < ITEM_SIZES.length; i++) {
1663
+ var r = drawCard(scratch.getContext("2d"), card, ITEM_SIZES[i]);
1664
+ // Lists wrap to at most 3 lines, the last row clears the footer, and the footer stays on the canvas.
1665
+ if (r.lines <= 3 && r.end + 60 <= r.footerTop && r.bottom <= 1890) { pick = ITEM_SIZES[i]; break; }
1666
+ }
1667
+ var out = drawCard(canvas.getContext("2d"), card, pick);
1668
+ if (pick !== ITEM_SIZES[0]) shrunk.push(card.id + ": items " + pick + "px");
1669
+ if (out.heroSize < 150) shrunk.push(card.id + ": title " + out.heroSize + "px");
1670
+ return out;
1671
+ }
1672
+ window.__cardNotes = shrunk;
1673
+
1674
+ // ---- Share: one selected card, shared as a file where supported, else downloaded. ----
1675
+ var CARDS = D.cards, canvases = {}, chosen = CARDS[0];
1676
+ var SHARE_TEXT = "My AI agents' " + W.window.end.slice(0, 4) + ", wrapped: I'm " + W.personality.name + ". What's yours? npx runa-agent-wrapped";
1677
+ function select(card, fig) {
1678
+ chosen = card;
1679
+ document.querySelectorAll("#cardgrid figure").forEach(function (f) { f.setAttribute("aria-pressed", String(f === fig)); });
1680
+ }
1681
+ function blobOf(cb) { canvases[chosen.id].toBlob(function (b) { if (b) cb(b); }, "image/png"); }
1682
+ function fileName() { return "agent-wrapped-" + chosen.id + ".png"; }
1683
+ function download() {
1684
+ blobOf(function (blob) {
1685
+ var a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = fileName();
1686
+ document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
1687
+ });
1688
+ }
1689
+ $("share-download").addEventListener("click", download);
1690
+ var probe = typeof File === "function" && navigator.canShare && navigator.canShare({ files: [new File([""], "x.png", { type: "image/png" })] });
1691
+ if (probe) {
1692
+ $("share-native").hidden = false;
1693
+ $("share-native").addEventListener("click", function () {
1694
+ blobOf(function (blob) {
1695
+ navigator.share({ files: [new File([blob], fileName(), { type: "image/png" })], text: SHARE_TEXT + " " + D.share.url }).catch(function () {});
1696
+ });
1697
+ });
1698
+ }
1699
+ D.share.targets.forEach(function (t) {
1700
+ var a = document.createElement("a");
1701
+ a.className = "link"; a.target = "_blank"; a.rel = "noopener"; a.textContent = t.label;
1702
+ a.href = t.url.replace("{text}", encodeURIComponent(SHARE_TEXT)).replace("{url}", encodeURIComponent(D.share.url));
1703
+ a.addEventListener("click", download);
1704
+ $("share-targets").appendChild(a);
1705
+ });
1706
+ $("share-copy").addEventListener("click", function () {
1707
+ navigator.clipboard.writeText(SHARE_TEXT + " " + D.share.url).then(function () { status($("share-status"), "Copied.", false); }, function () { status($("share-status"), "Could not copy.", true); });
1708
+ });
1709
+
1710
+ // The keep-history button: the only write the page can ask for. Nothing happens until the click.
1711
+ var keep = $("keep-history");
1712
+ if (keep) keep.addEventListener("click", function () {
1713
+ var st = $("keep-status");
1714
+ keep.disabled = true;
1715
+ fetch("/keep-history", { method: "POST", headers: { "x-agent-wrapped": "1" } })
1716
+ .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { return { ok: r.ok, body: j }; }); })
1717
+ .then(function (r) {
1718
+ if (!r.ok) throw new Error(r.body && r.body.error ? r.body.error : "Could not update the setting.");
1719
+ st.className = ""; st.textContent = "Done. Claude Code now keeps " + num(r.body.retentionDays) + " days.";
1720
+ keep.hidden = true;
1721
+ })
1722
+ .catch(function (err) {
1723
+ keep.disabled = false;
1724
+ st.className = "err"; st.textContent = err && err.message ? err.message : "Could not update the setting.";
1725
+ });
1726
+ });
1727
+
1728
+ var built = false;
1729
+ wire("open-cards", "cards", function () {
1730
+ if (built) return;
1731
+ built = true;
1732
+ var fonts = ["300 150px Fraunces", "italic 300 150px Fraunces", "500 30px Manrope", "400 28px Manrope", "400 22px 'DM Mono'"];
1733
+ Promise.all(fonts.map(function (f) { return document.fonts.load(f).catch(function () {}); })).then(function () { return document.fonts.ready; }).then(function () {
1734
+ var grid = $("cardgrid"); grid.style.setProperty("--n", String(CARDS.length));
1735
+ CARDS.forEach(function (card) {
1736
+ var fig = document.createElement("figure"), cv = document.createElement("canvas");
1737
+ cv.width = 1080; cv.height = 1920; cv.setAttribute("role", "img"); cv.setAttribute("aria-label", "Share card: " + card.title);
1738
+ draw(card, cv);
1739
+ fig.tabIndex = 0; fig.setAttribute("role", "button"); fig.setAttribute("aria-pressed", String(card === CARDS[0]));
1740
+ fig.addEventListener("click", function () { select(card, fig); });
1741
+ fig.addEventListener("keydown", function (e) { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); select(card, fig); } });
1742
+ canvases[card.id] = cv;
1743
+ fig.appendChild(cv); grid.appendChild(fig);
1744
+ });
1745
+ });
1746
+ });
1747
+ })();
1748
+ `;
1749
+
1750
+ // src/cards.ts
1751
+ var num = (n) => n.toLocaleString("en-US");
1752
+ var clean = (s) => s.replace(/--/g, "-‌-");
1753
+ var pairs = (a) => Array.from({ length: Math.ceil(a.length / 2) }, (_, i) => a.slice(i * 2, i * 2 + 2));
1754
+ var statRows = (cols) => pairs(cols).map((c) => ({ kind: "stats", cols: c }));
1755
+ function buildCards(w) {
1756
+ const agent = w.harnessShare[0];
1757
+ const total = w.harnessShare.reduce((s, h) => s + h.count, 0);
1758
+ const tagline = "In " + (agent?.name ?? "your agent") + " we trust. In “don’t ask again”, we don’t.";
1759
+ const ranked = (header, r) => r.length ? [{ header, items: r.map((x) => ({ text: clean(x.name), note: num(x.count) })) }] : [];
1760
+ const common = { tagline };
1761
+ const top5Lists = [...ranked("TOP COMMANDS", w.topCommands), ...ranked("TOP CONNECTORS", w.topConnectors)];
1762
+ const top5 = {
1763
+ ...common,
1764
+ id: "top5",
1765
+ title: "Top 5",
1766
+ theme: "light",
1767
+ accent: "forest",
1768
+ hero: "rune",
1769
+ rows: [
1770
+ ...top5Lists.length ? [{ kind: "lists", cols: top5Lists }] : [],
1771
+ { kind: "stats", cols: [{ label: "TOOL CALLS", kind: "number", value: num(w.totals.toolCalls) }, ...agent ? [{ label: "TOP AGENT", kind: "italic", value: agent.name }] : []] }
1772
+ ]
1773
+ };
1774
+ const command = w.topCommands[0];
1775
+ const connector = w.topConnectors[0];
1776
+ const highlights = {
1777
+ ...common,
1778
+ id: "highlights",
1779
+ title: "Highlights",
1780
+ theme: "dark",
1781
+ accent: "forest",
1782
+ hero: "rune",
1783
+ rows: statRows([
1784
+ ...agent ? [{ label: "TOP AGENT", kind: "italic", value: agent.name, caption: Math.round(agent.count / total * 100) + "% of tool calls" }] : [],
1785
+ ...command ? [{ label: "TOP COMMAND", kind: "italic", value: clean(command.name), caption: num(command.count) + " runs" }] : [],
1786
+ ...connector ? [{ label: "TOP CONNECTOR", kind: "italic", value: clean(connector.name), caption: num(connector.count) + " calls" }] : [],
1787
+ { label: "AGENT HOURS", kind: "number", value: num(w.totals.agentHours), unit: "h" }
1788
+ ])
1789
+ };
1790
+ const p = w.personality;
1791
+ const personality = {
1792
+ ...common,
1793
+ id: "personality",
1794
+ title: "Personality",
1795
+ theme: "dark",
1796
+ accent: "forest",
1797
+ hero: "face",
1798
+ rows: [
1799
+ { kind: "stats", cols: [...p.agentAgeDays !== null ? [{ label: "AGENT AGE", kind: "number", value: num(p.agentAgeDays) + (p.agentAgeIsMinimum ? "+" : ""), unit: p.agentAgeDays === 1 && !p.agentAgeIsMinimum ? "day" : "days" }] : [], { label: "TRUST STATUS", kind: "italic", value: p.trustStatus }] },
1800
+ { kind: "stats", cols: [{ label: "PERSONALITY", kind: "display", value: p.name }] },
1801
+ { kind: "stats", cols: [{ label: "TOP GENRE", kind: "italic", value: p.genre }, { label: "FAVOURITE HANGOUT", kind: "italic", value: p.hangout }] }
1802
+ ]
1803
+ };
1804
+ const tracks = {
1805
+ ...common,
1806
+ id: "tracks",
1807
+ title: "Top tracks",
1808
+ theme: "light",
1809
+ accent: "rose",
1810
+ hero: "rune",
1811
+ rows: [
1812
+ ...w.tracks.length ? [{ kind: "lists", cols: [{ header: "YOUR TOP TRACKS", items: w.tracks.map((t) => ({ text: clean(t.title), sub: "(" + clean(t.mix) + ")", right: num(t.plays) })) }] }] : [],
1813
+ { kind: "stats", cols: [{ label: "TOP GENRE", kind: "italic", value: p.genre }, { label: "PLAYS", kind: "number", value: num(w.totals.toolCalls) }] }
1814
+ ]
1815
+ };
1816
+ return [top5, highlights, personality, tracks];
1364
1817
  }
1365
1818
 
1366
- // src/charges.ts
1367
- var FIX_IT = /^(pls |please )?fix( it| this)?[.!]*$/;
1368
- function isFixIt(prompt) {
1369
- return FIX_IT.test(prompt.trim().toLowerCase());
1819
+ // src/page.ts
1820
+ var esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
1821
+ var num2 = (n) => n.toLocaleString("en-US");
1822
+ var MONTHS2 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1823
+ var COUNT_WORDS = ["zero", "one", "two", "three", "four", "five"];
1824
+ function parseYmd2(s) {
1825
+ const [y, m, d] = s.split("-").map(Number);
1826
+ return new Date(y, m - 1, d);
1370
1827
  }
1371
- var COMMIT_MSG = /^(?:sudo\s+)?git\s+commit\b[^\n]*?(?:\s-[a-zA-Z]*m|\s--message)[\s=]*(?:"([^"]*)"|'([^']*)'|([^\s"']+))/;
1372
- var JUNK_MSG = /^(fix|fixes|fixed|wip)[.!]*$/;
1373
- function isFixCommit(command) {
1374
- const m = COMMIT_MSG.exec(command);
1375
- const msg = (m?.[1] ?? m?.[2] ?? m?.[3] ?? "").trim().toLowerCase();
1376
- return JUNK_MSG.test(msg);
1828
+ var shortDate = (s) => `${parseYmd2(s).getDate()} ${MONTHS2[parseYmd2(s).getMonth()]}`;
1829
+ function heatLayout(year) {
1830
+ const offset = new Date(year, 0, 1).getDay();
1831
+ const days = Math.round((new Date(year + 1, 0, 1).getTime() - new Date(year, 0, 1).getTime()) / 86400000);
1832
+ const monthCols = Array.from({ length: 12 }, (_, m) => Math.floor((offset + Math.round((new Date(year, m, 1).getTime() - new Date(year, 0, 1).getTime()) / 86400000)) / 7));
1833
+ return { offset, days, columns: Math.ceil((offset + days) / 7), monthCols };
1377
1834
  }
1378
- function isPushToMain(command) {
1379
- return /^(?:sudo\s+)?git\s+push\b[^;&|\n]*(?:^|[\s:])(?:main|master)(?=$|\s)/.test(command);
1835
+ function coverageRow(w) {
1836
+ const c = w.coverage;
1837
+ const line = c.cutOff && c.detailSince !== null && c.retentionDays !== null ? `<span id="coverage">Detailed history starts ${shortDate(c.detailSince)}. Claude Code deletes logs older than ${num2(c.retentionDays)} days.</span>` : "";
1838
+ const button = c.cutOff || c.retentionDays !== null && c.retentionDays < 366 ? `<button class="mini" id="keep-history" type="button">Keep a year of history</button><span id="keep-status" role="status"></span>` : "";
1839
+ return line || button ? `<p class="cov">${line}${button}</p>` : "";
1380
1840
  }
1381
- var ERROR_WORD = /error|exception|traceback|panic|fatal|^\s*at .+:\d+/i;
1382
- var TRACE_LINE = /^\s+\S|^\s*at\s|^\s*File ".+", line \d+|:\d+(:\d+)?\)?\s*$|^\s*[\^~]+\s*$|^\s*\d+\s*[|│]|^\s*(caused by|npm ERR|warn|fail|exit|command failed)/i;
1383
- function isPastedError(prompt) {
1384
- const lines = prompt.split(`
1385
- `).filter((l) => l.trim() !== "");
1386
- if (lines.length < 2 || !lines.some((l) => ERROR_WORD.test(l)))
1387
- return false;
1388
- return lines.every((l) => ERROR_WORD.test(l) || TRACE_LINE.test(l));
1841
+ function heatmap(w) {
1842
+ const nonzero = w.daily.filter((n) => n > 0).sort((a, b) => a - b);
1843
+ const q = (p) => nonzero[Math.min(nonzero.length - 1, Math.floor(nonzero.length * p))] ?? 1;
1844
+ const [t1, t2] = [q(0.4), q(0.75)];
1845
+ const start = parseYmd2(w.window.start);
1846
+ const layout = heatLayout(start.getFullYear());
1847
+ const streak = w.longestStreak;
1848
+ const cells = Array.from({ length: layout.days }, (_, i) => {
1849
+ const day = new Date(start.getFullYear(), 0, 1 + i);
1850
+ const key = `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, "0")}-${String(day.getDate()).padStart(2, "0")}`;
1851
+ const first = i === 0 ? ` style="grid-row-start:${layout.offset + 1}"` : "";
1852
+ if (i >= w.daily.length)
1853
+ return `<i class="d future"${first}></i>`;
1854
+ const n = w.daily[i];
1855
+ const level = n === 0 ? 0 : n <= t1 ? 1 : n <= t2 ? 2 : 3;
1856
+ const inStreak = streak !== null && key >= streak.start && key <= streak.end;
1857
+ return `<i class="d l${level}${inStreak ? " st" : ""}"${first} title="${key}: ${num2(n)} tool calls"></i>`;
1858
+ });
1859
+ const months = layout.monthCols.map((col, m) => `<span style="left:calc(${col} * var(--step))">${MONTHS2[m]}</span>`).join("");
1860
+ return `<div class="heat" style="width:calc(${layout.columns} * var(--step) - var(--gap))"><div class="heatgrid" role="img" aria-label="Tool calls per day">${cells.join("")}</div><div class="months">${months}</div>${coverageRow(w)}</div>`;
1389
1861
  }
1390
- function count(f, kind, pred) {
1391
- let n = 0;
1392
- for (const e of f.events)
1393
- if (e.kind === kind && pred(e))
1394
- n++;
1395
- return n;
1862
+ var head = (left, right = "") => `<h3 class="thead"><span>${left}</span>${right ? `<span>${right}</span>` : ""}</h3>`;
1863
+ var rank = (i) => `<span class="tr">${String(i + 1).padStart(2, "0")}</span>`;
1864
+ var plural = (n, word) => `${num2(n)}<small> ${word}${n === 1 ? "" : "s"}</small>`;
1865
+ function ranked2(rows) {
1866
+ return `<ol class="ranks">${rows.map((r, i) => `<li>${rank(i)}<span class="tt">${esc(r.name)}</span><span class="tn">${num2(r.count)}</span></li>`).join("")}</ol>`;
1396
1867
  }
1397
- var sessionsWith = (f, a) => [...f.sessions.values()].filter((s) => s.autonomy === a).length;
1398
- var bash = (f, pred) => f.events.reduce((n, e) => e.kind === "tool" && e.command !== null ? n + shellSegments(e.command).filter(pred).length : n, 0);
1399
- var CHARGES = [
1400
- { id: "fixIt", label: "typed just “fix it”", count: (f) => count(f, "prompt", (e) => isFixIt(e.text)) },
1401
- { id: "fixCommits", label: "commits named just “fix”", count: (f) => bash(f, isFixCommit) },
1402
- { id: "pushMain", label: "pushed straight to main", count: (f) => bash(f, isPushToMain) },
1403
- {
1404
- id: "dontAskAgain",
1405
- label: "said “Yes, don’t ask again”",
1406
- count: (f) => f.approvals.claudeAllowRules + sessionsWith(f, "bypass")
1407
- },
1408
- { id: "pastedError", label: "pasted an error and nothing else", count: (f) => count(f, "prompt", (e) => isPastedError(e.text)) }
1409
- ];
1410
- var ABSOLUTELY_RIGHT = /you['’]re absolutely right/i;
1411
- var INSTRUCTION_FILE = /(^|[\\/])(CLAUDE|AGENTS)\.md$/;
1412
- var WRITE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
1413
- var TRACKS = [
1414
- { id: "absolutelyRight", title: "You’re Absolutely Right", mix: "Acoustic", plays: (f) => count(f, "reply", (e) => ABSOLUTELY_RIGHT.test(e.text)) },
1415
- { id: "acceptAll", title: "Accept All", mix: "Taylor’s Version", plays: (f) => sessionsWith(f, "auto") },
1416
- { id: "skipPermissions", title: "Skip Permissions", mix: "Radio Edit", plays: (f) => sessionsWith(f, "bypass") },
1417
- { id: "contextLeft", title: "Context Left: 2%", mix: "Live", plays: (f) => count(f, "compaction", () => true) },
1418
- {
1419
- id: "claudeMd",
1420
- title: "Bohemian Rhapsody in CLAUDE.md",
1421
- mix: "Demo",
1422
- plays: (f) => count(f, "tool", (e) => WRITE_TOOLS.has(e.tool) && e.path !== null && INSTRUCTION_FILE.test(e.path))
1868
+ function bigStat(label, value, sub) {
1869
+ return `<div class="big">${head(label)}<span class="bv">${value}</span><span class="bs">${sub}</span></div>`;
1870
+ }
1871
+ function compact(n) {
1872
+ if (n < 1000)
1873
+ return String(Math.round(n));
1874
+ const units = [[1000, "K"], [1e6, "M"], [1e9, "B"]];
1875
+ for (const [size, suffix] of units) {
1876
+ const v = Math.round(n / size * 10) / 10;
1877
+ if (v < 1000 || suffix === "B")
1878
+ return `${v}${suffix}`;
1423
1879
  }
1424
- ];
1425
- function computeCharges(f) {
1426
- return CHARGES.map((c) => ({ id: c.id, label: c.label, count: c.count(f) })).filter((c) => c.count > 0);
1427
- }
1428
- function computeTracks(f, topCommand, topConnector) {
1429
- const own = [
1430
- ...topCommand ? [{ id: "topCommand", title: `${topCommand.name} on Repeat`, mix: "Extended Mix", plays: topCommand.count }] : [],
1431
- ...topConnector ? [{ id: "topConnector", title: `Hotline ${connectorDisplay(topConnector.name)}`, mix: "Club Mix", plays: topConnector.count }] : []
1432
- ];
1433
- return [...TRACKS.map((t) => ({ id: t.id, title: t.title, mix: t.mix, plays: t.plays(f) })), ...own].filter((t) => t.plays > 0).sort((a, b) => b.plays - a.plays).slice(0, 5);
1434
- }
1435
-
1436
- // src/stats.ts
1437
- var WEB_TOOLS = new Set(["WebFetch", "WebSearch"]);
1438
- var SUBAGENT_TOOLS = new Set(["Task", "Agent"]);
1439
- var WRITE_TOOLS2 = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
1440
- var GAP_CAP_MS = 30 * 60 * 1000;
1441
- var DAY_MS = 86400000;
1442
- var WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
1443
- var MONTHS2 = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
1444
- function ranked(counts, limit) {
1445
- return [...counts].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)).slice(0, limit);
1880
+ return String(Math.round(n));
1446
1881
  }
1447
- function bump(m, k) {
1448
- m.set(k, (m.get(k) ?? 0) + 1);
1882
+ function summaryCard(w) {
1883
+ const s = w.longestStreak;
1884
+ const streak = s ? bigStat("Longest streak", plural(s.days, "day"), `${shortDate(s.start)} – ${shortDate(s.end)}, outlined`) : "";
1885
+ return `<section class="card sheet summary"><div class="bigs">${bigStat("Tool calls", num2(w.totals.toolCalls), `${num2(w.totals.agentHours)} agent hours · ${num2(w.totals.sessions)} session${w.totals.sessions === 1 ? "" : "s"}${w.tokens ? ` · ${compact(w.tokens.total)} tokens` : ""}`)}${streak}</div>${heatmap(w)}</section>`;
1449
1886
  }
1450
- function modelFamily(id) {
1451
- const m = id.toLowerCase();
1452
- if (m.startsWith("<"))
1453
- return null;
1454
- for (const f of ["opus", "sonnet", "haiku"])
1455
- if (m.includes(f))
1456
- return f[0].toUpperCase() + f.slice(1);
1457
- const gpt = /gpt-?(\d+)/.exec(m);
1458
- if (gpt)
1459
- return `GPT-${gpt[1]}`;
1460
- if (/^o\d/.test(m))
1461
- return "o-series";
1462
- if (m.includes("gemini"))
1463
- return "Gemini";
1464
- if (m.includes("grok"))
1465
- return "Grok";
1466
- if (m.includes("composer"))
1467
- return "Composer";
1468
- return id;
1887
+ function toolsCard(w) {
1888
+ if (w.topTools.length === 0)
1889
+ return "";
1890
+ return `<section class="card sheet">${head("Top tools", "Calls")}${ranked2(w.topTools)}</section>`;
1469
1891
  }
1470
- function programsOf(command) {
1471
- return shellSegments(command).flatMap((seg) => programOf(seg) ?? []);
1892
+ function connectorsCard(w) {
1893
+ if (w.topConnectors.length === 0)
1894
+ return "";
1895
+ return `<section class="card sheet">${head("Top connectors", "Calls")}${ranked2(w.topConnectors)}</section>`;
1472
1896
  }
1473
- function shortName(name, max = 22) {
1474
- if (name.length <= max)
1475
- return name;
1476
- const tail = Math.ceil((max - 1) * 0.65);
1477
- return `${name.slice(0, max - 1 - tail)}…${name.slice(name.length - tail)}`;
1897
+ var RISK_CHARGES = new Set(["pushMain", "readEnv", "rmRf", "forcePush", "curlSh"]);
1898
+ var MAX_CHARGES = 5;
1899
+ function chargesCard(w) {
1900
+ if (w.charges.length === 0)
1901
+ return "";
1902
+ const shown = [...w.charges].sort((a, b) => b.count - a.count).slice(0, MAX_CHARGES);
1903
+ const n = shown.length;
1904
+ const title = `Charged with vibe coding, on ${COUNT_WORDS[n] ?? String(n)} ${n === 1 ? "count" : "counts"}`;
1905
+ const rows = shown.map((c) => `<li${RISK_CHARGES.has(c.id) ? ' class="risk"' : ""}><span class="cn">${num2(c.count)}<small>×</small></span><span class="cl">${esc(c.label)}</span></li>`).join("");
1906
+ return `<section class="card sheet charges"><span class="stamp" aria-hidden="true">GUILTY</span>${head("The charge sheet")}<span class="ctitle">${title}</span><ol class="${n >= 4 ? "many" : ""}">${rows}</ol></section>`;
1907
+ }
1908
+ function duration(minutes) {
1909
+ const h = Math.floor(minutes / 60);
1910
+ const m = minutes % 60;
1911
+ return h === 0 ? `${m} min` : m === 0 ? `${h} h` : `${h} h ${m} min`;
1912
+ }
1913
+ function highlightsRow(w) {
1914
+ const { busiestDay: b, longestSession: l, topProject: p } = w.highlights;
1915
+ const items = [
1916
+ b ? `<span>Busiest day <strong>${esc(shortDate(b.date))}</strong>, ${num2(b.toolCalls)} calls</span>` : "",
1917
+ l ? `<span>Longest session <strong>${esc(duration(l.minutes))}</strong></span>` : "",
1918
+ p ? `<span class="proj">Top project <strong>${esc(p.name)}</strong></span>` : ""
1919
+ ].filter(Boolean);
1920
+ return items.length ? `<div class="bs hl">${items.join("<i> · </i>")}</div>` : "";
1478
1921
  }
1479
- function hourLabel(h) {
1480
- const suffix = h < 12 ? "a.m." : "p.m.";
1481
- return `${h % 12 === 0 ? 12 : h % 12} ${suffix}`;
1922
+ function hoursCard(w) {
1923
+ const total = w.hours.reduce((a, b) => a + b, 0);
1924
+ if (total === 0 || w.rushHour === null)
1925
+ return "";
1926
+ const max = Math.max(...w.hours);
1927
+ const r = w.rushHour;
1928
+ const inRush = (h) => (h - r.from + 24) % 24 < 3;
1929
+ const bars = w.hours.map((n, h) => `<i class="${inRush(h) ? "rushbar" : ""}" style="height:${Math.max(2, Math.round(n / max * 100))}%" title="${String(h).padStart(2, "0")}:00: ${num2(n)}"></i>`).join("");
1930
+ const hh = (h) => `${String(h).padStart(2, "0")}:00`;
1931
+ const latest = w.latestStart ? `<span class="bs">Latest session start: <strong>${esc(w.latestStart.time)}</strong>, a ${esc(w.latestStart.weekday)} in ${esc(w.latestStart.month)}</span>` : "";
1932
+ return `<section class="card sheet hours">${head("When your agents work")}<span class="rush">${hh(r.from)}–${hh(r.to)}<small> rush hour</small></span><div class="bars" role="img" aria-label="Tool calls by hour of day">${bars}</div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div>${latest}${highlightsRow(w)}</section>`;
1482
1933
  }
1483
- function hangoutOf(tools) {
1484
- const reads = tools.filter((t) => t.path !== null && t.tool === "Read");
1485
- const pool = reads.length > 0 ? reads : tools.filter((t) => t.path !== null);
1486
- const byFile = new Map;
1487
- for (const t of pool)
1488
- bump(byFile, basename(t.path));
1489
- const top = ranked(byFile, 1)[0];
1490
- const hours = new Array(24).fill(0);
1491
- for (const t of pool)
1492
- if (top && basename(t.path) === top.name)
1493
- hours[t.at.getHours()]++;
1494
- const peak = hours.indexOf(Math.max(...hours));
1495
- const where = !top ? "terminal" : top.name.startsWith(".env") ? `${top.name} file` : shortName(top.name);
1496
- return `Your ${where}, at ${hourLabel(top ? peak : peakHour(tools))}`;
1934
+ function personalityCard(w) {
1935
+ const p = w.personality;
1936
+ const fact = (label, value, cls, wide = false) => `<div${wide ? ' class="wide"' : ""}><dt>${label}</dt><dd class="${cls}">${value}</dd></div>`;
1937
+ const age = p.agentAgeDays !== null ? fact("Agent age", `${num2(p.agentAgeDays)}${p.agentAgeIsMinimum ? "+" : ""}<small> ${p.agentAgeDays === 1 && !p.agentAgeIsMinimum ? "day" : "days"}</small>`, "age") : "";
1938
+ return `<section class="card soul"><div class="hero" aria-hidden="true"><span class="hyear">${esc(w.window.end.slice(0, 4))}</span><span class="htitle">Personality <em>Wrapped</em></span><div class="face"><b class="cap"><em>sudo</em></b><i class="eye e1"></i><i class="eye e2"></i><i class="mouth"></i></div></div>
1939
+ <dl class="facts">${age}${fact("Trust status", esc(p.trustStatus), "trust")}${fact("Personality", esc(p.name), "pname", true)}${fact("Favourite hangout", esc(p.hangout), "line", true)}</dl></section>`;
1497
1940
  }
1498
- function peakHour(tools) {
1499
- const hours = new Array(24).fill(0);
1500
- for (const t of tools)
1501
- hours[t.at.getHours()]++;
1502
- return hours.indexOf(Math.max(...hours));
1941
+ function tracksCard(w) {
1942
+ if (w.tracks.length === 0)
1943
+ return "";
1944
+ const rows = w.tracks.map((t, i) => `<li>${rank(i)}<span class="tt">${esc(t.title)} <span class="mix">(${esc(t.mix)})</span></span><span class="tn">${num2(t.plays)}</span></li>`).join("");
1945
+ return `<section class="card sheet tracks">${head("Your top tracks", "Plays")}<ol class="ranks">${rows}</ol></section>`;
1503
1946
  }
1504
- function longestStreak(dayIndexes, startMs) {
1505
- const days = [...new Set(dayIndexes)].sort((a, b) => a - b);
1506
- let best = null;
1507
- let from = 0;
1508
- for (let i = 1;i <= days.length; i++) {
1509
- if (i < days.length && days[i] === days[i - 1] + 1)
1510
- continue;
1511
- if (days.length > 0 && (!best || i - from > best[1] - best[0] + 1))
1512
- best = [from, i - 1];
1513
- from = i;
1514
- }
1515
- if (!best)
1516
- return null;
1517
- const at = (i) => ymd(new Date(startMs.getFullYear(), startMs.getMonth(), startMs.getDate() + days[i]));
1518
- return { days: best[1] - best[0] + 1, start: at(best[0]), end: at(best[1]) };
1947
+ function midRight(w) {
1948
+ const inner = chargesCard(w) + modelCard(w);
1949
+ return inner ? `<div class="midr">${inner}</div>` : "";
1519
1950
  }
1520
- function computeWrapped(result, window) {
1521
- const { from, until } = bounds(window);
1522
- const events = result.events.filter((e) => e.at >= from && e.at < until);
1523
- const tools = events.filter((e) => e.kind === "tool");
1524
- const dayCount = Math.round((until.getTime() - from.getTime()) / DAY_MS);
1525
- const dayOf = (d) => Math.floor((new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() - from.getTime()) / DAY_MS + 0.5);
1526
- const sessions = new Map;
1527
- for (const e of events) {
1528
- const key = `${e.harness}:${e.sessionId}`;
1529
- let s = sessions.get(key);
1530
- if (!s)
1531
- sessions.set(key, s = { autonomy: "ask", start: e.at, at: [] });
1532
- s.at.push(e.at);
1533
- if (e.at < s.start)
1534
- s.start = e.at;
1535
- if (e.kind === "session")
1536
- s.autonomy = e.autonomy;
1537
- }
1538
- let agentMs = 0;
1539
- for (const s of sessions.values()) {
1540
- const ts = s.at.map((d) => d.getTime()).sort((a, b) => a - b);
1541
- for (let i = 1;i < ts.length; i++)
1542
- agentMs += Math.min(ts[i] - ts[i - 1], GAP_CAP_MS);
1543
- }
1544
- const daily = new Array(dayCount).fill(0);
1545
- const hours = new Array(24).fill(0);
1546
- const toolNames = new Map;
1547
- const connectors = new Map;
1548
- const commands = new Map;
1549
- const harnessCalls = new Map;
1550
- for (const t of tools) {
1551
- const d = dayOf(t.at);
1552
- if (d >= 0 && d < dayCount)
1553
- daily[d]++;
1554
- hours[t.at.getHours()]++;
1555
- if (t.connector)
1556
- bump(connectors, t.connector);
1557
- else
1558
- bump(toolNames, t.tool);
1559
- if (t.command)
1560
- for (const p of programsOf(t.command))
1561
- bump(commands, p);
1562
- bump(harnessCalls, HARNESS_NAME[t.harness]);
1563
- }
1564
- let rushHour = null;
1565
- let rushBest = 0;
1566
- for (let h = 0;h < 24; h++) {
1567
- const n = hours[h] + hours[(h + 1) % 24] + hours[(h + 2) % 24];
1568
- if (n > rushBest) {
1569
- rushBest = n;
1570
- rushHour = { from: h, to: (h + 3) % 24 };
1951
+ function modelCard(w) {
1952
+ if (w.topModel === null)
1953
+ return "";
1954
+ const models = w.topModel.models;
1955
+ const total = models.reduce((a, m) => a + m.count, 0);
1956
+ const pct = (n) => n > 0 && n / total * 100 < 1 ? "<1" : String(Math.round(n / total * 100));
1957
+ const segs = models.map((m, i) => `<div class="m${i}" style="width:${m.count / total * 100}%"></div>`).join("");
1958
+ const legend = models.map((m, i) => `<span><i class="m${i}"></i>${esc(m.name)} ${pct(m.count)}%</span>`).join("");
1959
+ const aria = models.map((m) => `${m.name} ${pct(m.count)}%`).join(", ");
1960
+ return `<section class="card sheet model">${head("Top model")}<span class="mval">${esc(models[0].name)}<small>${pct(models[0].count)}%</small></span><div class="segs" role="img" aria-label="${esc(aria)}">${segs}</div><div class="legend">${legend}</div></section>`;
1961
+ }
1962
+ function dateRange(w) {
1963
+ const s = parseYmd2(w.window.start);
1964
+ const e = parseYmd2(w.window.end);
1965
+ return `${MONTHS2[s.getMonth()]} ${s.getDate()} – ${MONTHS2[e.getMonth()]} ${e.getDate()}, ${e.getFullYear()}`;
1966
+ }
1967
+ var SHARE_ICON = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12M7 8l5-5 5 5M5 13v6h14v-6"/></svg>`;
1968
+ var ARROW = `<svg class="arrow" width="22" height="22" viewBox="0 0 22 22" fill="none" aria-hidden="true"><circle cx="11" cy="11" r="11" fill="var(--white)"/><path d="M6.5 11h9M11.5 7l4 4-4 4" stroke="var(--forest)" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
1969
+ function renderPage(w) {
1970
+ const data = JSON.stringify({ wrapped: w, api: API_BASE, cal: CAL, share: { url: SHARE_URL, targets: SHARE_TARGETS }, brand: BRAND, cards: buildCards(w) }).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1971
+ const harnesses = w.harnesses.map((h) => HARNESS_NAME[h]).join(" · ");
1972
+ const empty = w.totals.toolCalls === 0;
1973
+ const body = empty ? `<section class="card sheet empty">${head("Nothing to wrap yet")}<p class="ctitle">No Claude Code, Codex or Cursor history found for ${w.window.start.slice(0, 4)} on this laptop.</p></section>` : `<div class="main"><div class="left">${summaryCard(w)}<div class="mid"><div class="midl"><div class="toprow">${toolsCard(w)}${connectorsCard(w)}</div>${hoursCard(w)}</div>${midRight(w)}</div></div><div class="right">${personalityCard(w)}${tracksCard(w)}</div></div>`;
1974
+ const topics = SAFETY_TOPICS.map((t) => `<label class="chip"><input type="checkbox" name="topic" value="${esc(t)}">${esc(t)}</label>`).join("");
1975
+ const options = TEAM_SIZES.map((t, i) => `<option value="${["1", "2-20", "21-200", "200+"][i]}">${t}</option>`).join("");
1976
+ return `<!doctype html>
1977
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
1978
+ <title>Agent Wrapped ${w.window.end.slice(0, 4)}</title>
1979
+ <style>${fontFaceCss()}${CSS}</style></head><body>
1980
+ <div class="app">
1981
+ <div class="backdrop" aria-hidden="true"></div>
1982
+ <nav><span class="navnote scope">Counts this computer only. Cloud sessions and other computers are not included.</span><span class="navnote">Agent Wrapped · by</span><span class="lockup" aria-label="Runa">${markSvg(20)}<span class="wm" aria-hidden="true">RUNA</span></span></nav>
1983
+ <header><div><p class="eyebrow">${dateRange(w)}${harnesses ? ` · ${esc(harnesses)}` : ""}</p><h1>Your agents' ${w.window.end.slice(0, 4)},<br><em>wrapped.</em></h1></div>
1984
+ <div class="btns"><button class="pill share" id="open-cards" type="button">${SHARE_ICON}Share</button>
1985
+ <button class="pill primary cta" id="open-team" type="button">Talk agent safety with us${ARROW}</button></div></header>
1986
+ ${body}
1987
+ </div>
1988
+ <dialog id="cards"><div class="mh"><h2>Share your Wrapped</h2><button class="x" data-close aria-label="Close">×</button></div>
1989
+ <p class="note">Pick a card. Cards are drawn on your laptop; nothing is uploaded until you post it.</p>
1990
+ <div class="cardgrid" id="cardgrid"></div>
1991
+ <div class="sharebar"><button class="pill primary" id="share-native" type="button" hidden>Share image…</button><button class="pill" id="share-download" type="button">Download image</button><span class="sharevia">or post on</span><span id="share-targets"></span><button class="link" id="share-copy" type="button">Copy text</button><p class="status" id="share-status" role="status"></p></div>
1992
+ <p class="fine">X, LinkedIn, Reddit and Bluesky open with your text filled in. Attach the downloaded image there.</p></dialog>
1993
+ <dialog id="team"><div class="mh"><h2>That was your year. Now help us learn how teams keep agents safe.</h2><button class="x" data-close aria-label="Close">×</button></div>
1994
+ <p class="note">We're talking to people who use AI agents at work about what their company actually cares about, what worries them, and what's missing. 15 minutes, no sales pitch.</p>
1995
+ <div id="ask"><fieldset class="topics"><legend>What does your company care about most?</legend><div class="chips">${topics}</div></fieldset>
1996
+ <button class="pill primary" id="pick-time" type="button">Pick a time${ARROW}</button>
1997
+ <p class="fine">Picking a time loads Cal.com's scheduler here. It receives only the topics you ticked, as a note on the booking. Nothing from your report is sent.</p></div>
1998
+ <div id="booking" hidden><button class="link" id="back-ask" type="button">← Back</button><div id="cal" aria-label="Book a 15-minute call"></div></div>
1999
+ <details class="later"><summary>Not now? Leave your email instead</summary>
2000
+ <form id="waitlist"><label>Work email<input name="email" type="email" required placeholder="you@company.com" autocomplete="email"></label>
2001
+ <label>People using AI agents at work<select name="teamSize">${options}</select></label>
2002
+ <button class="pill primary" type="submit">Keep me posted${ARROW}</button><p class="status" id="wl-status" role="status"></p></form>
2003
+ <p class="fine">We store your email to contact you about Agent Wrapped for teams. Nothing from your report is sent.</p></details></dialog>
2004
+ <script type="application/json" id="data">${data}</script>
2005
+ <script>${CLIENT_SCRIPT}</script>
2006
+ </body></html>`;
2007
+ }
2008
+ var CSS = `${brandCss()}
2009
+ .share{gap:8px}
2010
+ .pill.cta{height:52px;padding:0 12px 0 24px;font-size:16px}
2011
+ /* The two header buttons use Fraunces, Runa's wordmark and headline face. Only Light (300) is bundled. */
2012
+ header .pill{font:300 18px/1 Fraunces,Georgia,serif}header .pill.cta{font-size:20px}
2013
+ .cardgrid figure{cursor:pointer;border-radius:14px;outline:2px solid transparent;outline-offset:4px}
2014
+ .cardgrid figure[aria-pressed="true"]{outline-color:var(--forest)}
2015
+ .sharebar{display:flex;flex-wrap:wrap;align-items:center;gap:10px 14px;margin-top:14px}
2016
+ .sharevia{font-size:13px;color:var(--muted)}#share-targets{display:flex;gap:14px}
2017
+ :root{--mono:'DM Mono',ui-monospace,SFMono-Regular,Menlo,monospace}
2018
+ *{box-sizing:border-box}body{--pad:clamp(20px,calc(17.5vh - 110px),40px);margin:0;background:var(--mist);color:var(--ink);font-family:Manrope,system-ui,-apple-system,'Segoe UI',sans-serif}
2019
+ /* Why: the date line and byline are 28px rows with 11–12px text, so their ink starts 6px below the row top. Pulling the top padding up by that 6px makes the visible gap at the top match the left, right and bottom. */
2020
+ .app{position:relative;height:100vh;min-height:700px;padding:calc(var(--pad) - 6px) var(--pad) var(--pad);display:flex;flex-direction:column;gap:12px}
2021
+ .backdrop{position:absolute;left:0;right:0;top:0;height:200px;z-index:-1;background:radial-gradient(520px 200px at 12% 0%,color-mix(in srgb,var(--forest),transparent 82%),transparent),radial-gradient(420px 180px at 92% 20%,color-mix(in srgb,var(--rose),transparent 88%),transparent)}
2022
+ /* Why: the byline sits in the top-right corner on the same line as the date eyebrow, not on a row of its own. Both are 28px tall and start at the same top, so their centres line up. */
2023
+ nav{position:absolute;top:calc(var(--pad) - 6px);right:var(--pad);z-index:1;display:flex;justify-content:flex-end;align-items:center;gap:10px;height:28px}
2024
+ header .eyebrow{line-height:28px}.navnote{font-size:12px;color:var(--muted)}
2025
+ .navnote.scope{margin-right:14px}
2026
+ .cov{margin:0;display:flex;flex-wrap:wrap;align-items:center;gap:2px 10px;font-size:12px;color:var(--muted)}
2027
+ .mini{height:24px;padding:0 10px;border-radius:999px;border:1px solid var(--border);background:var(--white);color:var(--forest);font:700 12px Manrope,system-ui,sans-serif;cursor:pointer}
2028
+ #keep-status.err{color:var(--rose)}
2029
+ header{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;flex:none}
2030
+ .eyebrow{display:block;margin:0 0 4px;font-family:var(--mono);font-size:11px;font-weight:400;letter-spacing:.2em;text-transform:uppercase;color:var(--forest)}
2031
+ h1{margin:0;font-family:Fraunces,Georgia,serif;font-weight:300;font-size:40px;line-height:1.02}h1 em{font-style:italic;color:var(--forest)}
2032
+ .btns{display:flex;gap:10px;align-items:center}
2033
+ .pill{height:44px;padding:0 18px;border-radius:999px;border:1px solid var(--border);background:var(--white);color:inherit;font:700 14px Manrope,system-ui,sans-serif;cursor:pointer;display:inline-flex;align-items:center;text-decoration:none}
2034
+ .pill.primary{gap:12px;padding-right:10px;background:var(--forest);border-color:var(--forest);color:var(--mist)}
2035
+ .link{padding:0 2px 3px;border:0;border-bottom:1px solid var(--forest);background:none;color:var(--forest);font:600 14px Manrope,system-ui,sans-serif;cursor:pointer;text-decoration:none}.btns{gap:22px}
2036
+ button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--rose);outline-offset:2px}
2037
+ .main{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,3fr) minmax(280px,1fr);gap:14px}
2038
+ .left,.right{min-height:0;display:flex;flex-direction:column;gap:14px}
2039
+ .card{border-radius:22px;padding:18px 20px;min-height:0}
2040
+ h3{margin:0;font-size:13px;font-weight:700;color:var(--muted)}
2041
+ .sheet.summary{flex:none;padding:16px 24px;flex-direction:row;align-items:center;gap:28px}
2042
+ .bigs{flex:none;min-width:210px;display:flex;flex-direction:column;gap:10px}.bigs .bs{white-space:nowrap}
2043
+ .heat{--cell:10px;--gap:3px;--step:calc(var(--cell) + var(--gap));flex:none;max-width:100%;display:flex;flex-direction:column;gap:6px;overflow:hidden}
2044
+ .heatgrid{display:grid;grid-template-rows:repeat(7,var(--cell));grid-auto-flow:column;grid-auto-columns:var(--cell);gap:var(--gap)}
2045
+ .d{width:var(--cell);height:var(--cell);border-radius:3px;display:block;background:var(--mist-2)}
2046
+ .l1{background:color-mix(in srgb,var(--mist-2),var(--forest) 35%)}.l2{background:color-mix(in srgb,var(--mist-2),var(--forest) 65%)}.l3{background:var(--forest)}
2047
+ .d.st{box-shadow:0 0 0 1.5px var(--rose)}
2048
+ .months{position:relative;height:14px;font-family:var(--mono);font-size:11px;color:var(--muted)}.months span{position:absolute;top:0}.d.future{background:none;box-shadow:inset 0 0 0 1px var(--border)}
2049
+ .mid{flex:1;min-height:0;display:flex;gap:14px}
2050
+ .midl{flex:2;min-width:0;display:flex;flex-direction:column;gap:14px}
2051
+ .midr{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;gap:14px}
2052
+ .toprow{flex:none;display:flex;gap:14px}.toprow .card{flex:1;min-width:0}
2053
+ .axis{display:flex;justify-content:space-between;font-family:var(--mono);font-size:11px;color:var(--muted)}
2054
+ .hl{display:flex;white-space:nowrap}.hl span{flex:none}.hl i{font-style:normal;white-space:pre}.hl .proj{flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis}
2055
+ .empty{max-width:520px}
2056
+ dialog{border:1px solid color-mix(in srgb,var(--white),transparent 30%);border-radius:24px;padding:24px 28px;max-width:min(980px,94vw);max-height:92vh;overflow:auto;background:color-mix(in srgb,var(--white),transparent 45%);backdrop-filter:blur(22px) saturate(150%);box-shadow:0 30px 80px -20px color-mix(in srgb,var(--forest),transparent 65%);color:var(--ink)}
2057
+ dialog::backdrop{background:color-mix(in srgb,var(--ink-dark),transparent 45%)}
2058
+ .mh{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}.mh h2{margin:0;font:300 26px/1.2 Fraunces,Georgia,serif}
2059
+ .x{border:0;background:none;font-size:28px;line-height:1;cursor:pointer;color:var(--muted)}
2060
+ .note,.fine{color:var(--muted);font-size:14px;line-height:1.4}.fine{font-size:12px}
2061
+ .cardgrid{display:grid;grid-template-columns:repeat(var(--n,4),minmax(0,1fr));gap:16px;width:min(calc(var(--n,4)*225px),86vw)}
2062
+ .cardgrid figure{margin:0;display:flex;flex-direction:column;gap:8px}.cardgrid canvas{width:100%;aspect-ratio:9/16;border-radius:16px;background:var(--ink-dark)}
2063
+ .cardgrid .pill{height:38px;justify-content:center;font-size:13px}
2064
+ #team{width:min(520px,94vw)}form{display:flex;flex-direction:column;gap:12px;margin:14px 0}label{display:flex;flex-direction:column;gap:5px;font-size:13px;font-weight:700}
2065
+ input,select{height:42px;border-radius:12px;border:1px solid var(--border);padding:0 12px;font:500 15px Manrope,system-ui,sans-serif;background:var(--white)}
2066
+ .topics{border:0;margin:16px 0 14px;padding:0}.topics legend{font-size:13px;font-weight:700;margin-bottom:8px;padding:0}
2067
+ .chips{display:flex;flex-wrap:wrap;gap:8px}.chip{flex-direction:row;align-items:center;gap:0;font-weight:500;font-size:14px;padding:8px 14px;border:1px solid var(--border);border-radius:999px;background:var(--white);cursor:pointer}
2068
+ .chip input{position:absolute;opacity:0;width:1px;height:1px}.chip:has(input:checked){background:var(--forest);border-color:var(--forest);color:var(--mist)}.chip:has(input:focus-visible){outline:2px solid var(--forest);outline-offset:2px}
2069
+ #team.booking{width:min(960px,94vw)}#team.booking .later{display:none}#cal{width:100%;height:min(640px,70vh);overflow:auto;border-radius:16px;margin-top:8px}
2070
+ .later{margin-top:14px;border-top:1px solid var(--border);padding-top:12px}.later summary{cursor:pointer;font-size:14px;color:var(--muted)}
2071
+ .status{margin:0;font-size:13px;min-height:1em}.status.err{color:var(--rose)}
2072
+ pre{background:var(--white);border:1px solid var(--border);border-radius:12px;padding:12px;font:13px var(--mono);overflow:auto;max-height:50vh}.row{display:flex;gap:14px;align-items:center}
2073
+ .by{margin:8px 0 0;display:flex;align-items:center;gap:8px;font-size:13px;color:var(--muted)}.lockup{display:inline-flex;align-items:center;gap:6px;color:var(--forest)}
2074
+ .wm{font:300 15px Fraunces,Georgia,serif;letter-spacing:.42em;margin-right:-.42em;color:var(--ink)}
2075
+ @keyframes settle{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
2076
+ .card{animation:settle .8s ease-out both}.right .card{animation-delay:.1s}
2077
+ .soul{flex:1;padding:12px;overflow:hidden;display:flex;flex-direction:column;gap:12px;color:var(--mist);background:radial-gradient(120% 60% at 0% 0%,color-mix(in srgb,var(--forest),transparent 55%),transparent 70%),var(--ink-dark)}
2078
+ .hero{flex:1;min-height:96px;position:relative;overflow:hidden;border-radius:16px;padding:12px 14px;display:flex;flex-direction:column;justify-content:flex-end;gap:4px;color:var(--ink);background:linear-gradient(135deg,var(--mist-2),var(--mist));box-shadow:0 12px 28px rgb(0 0 0 / .35)}
2079
+ .hyear{position:absolute;left:14px;top:12px;font:400 11px var(--mono);letter-spacing:.2em;color:rgb(18 36 26 / .78)}
2080
+ .htitle{font:300 28px/1 Fraunces,Georgia,serif}
2081
+ .htitle em{color:var(--forest);font-style:italic}
2082
+ .face{position:absolute;right:16px;top:12px;width:64px;height:64px;border-radius:50%;overflow:hidden;background:var(--forest)}
2083
+ .face .cap{position:absolute;left:0;top:0;right:0;height:13px;background:var(--rose);display:flex;justify-content:center;align-items:center}
2084
+ .face .cap em{font:normal 7px var(--mono);color:var(--mist)}
2085
+ .face .eye{position:absolute;top:26px;width:9px;height:9px;border-radius:50%;background:var(--mist)}
2086
+ .face .e1{left:18px}.face .e2{right:18px}
2087
+ .face .mouth{position:absolute;left:24px;top:43px;width:16px;height:4px;border-radius:2px;background:var(--mist)}
2088
+ .facts{flex:none;margin:0;padding:0 8px 8px;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px 18px}
2089
+ .facts>div{min-width:0;display:flex;flex-direction:column}
2090
+ .facts .wide{grid-column:span 2}
2091
+ dt{font:400 10px var(--mono);letter-spacing:.2em;text-transform:uppercase;color:rgb(248 251 248 / .62);padding-bottom:5px;margin-bottom:6px;border-bottom:1px solid rgb(248 251 248 / .14)}
2092
+ dd{margin:0;color:#9FD0B0;font-family:Fraunces,Georgia,serif;font-weight:300}
2093
+ .age{font-size:30px;line-height:1}
2094
+ .age small{font-size:16px;font-style:italic}
2095
+ .trust{font-size:18px;line-height:1.15;font-style:italic}
2096
+ .pname{font-size:26px;line-height:1.05}
2097
+ .line{font-size:17px;line-height:1.25;font-style:italic;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
2098
+ .mix{color:var(--sub,var(--muted));font-weight:400}
2099
+ /* The light share card: mist on a faint forest grid, mono eyebrows over hairlines, forest accent. */
2100
+ .sheet{--accent:var(--forest);--rule:rgb(18 36 26 / .12);display:flex;flex-direction:column;gap:8px;color:var(--ink);border:1px solid var(--border);background:linear-gradient(rgb(30 90 60 / .045) 1px,transparent 1px) 0 0/24px 24px,linear-gradient(90deg,rgb(30 90 60 / .045) 1px,transparent 1px) 0 0/24px 24px,var(--mist)}
2101
+ .thead{margin:0;display:flex;justify-content:space-between;align-items:baseline;gap:10px;font:400 10px var(--mono);letter-spacing:.2em;text-transform:uppercase;color:var(--sub,var(--muted));padding-bottom:6px;border-bottom:1px solid var(--rule)}
2102
+ .ranks{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:8px}
2103
+ .ranks li{display:flex;align-items:baseline;gap:10px}
2104
+ .tr{font:400 11px var(--mono);color:var(--accent);flex:none}
2105
+ /* Why: Manrope's standard ligature draws "--" as one dash, which would misspell CLI flags in names. */
2106
+ .tt{flex:1;min-width:0;font-size:13px;line-height:1.3;font-weight:500;overflow-wrap:anywhere;font-variant-ligatures:no-common-ligatures}
2107
+ .tn{font:12px var(--mono);color:var(--sub,var(--muted))}
2108
+ .big{display:flex;flex-direction:column}
2109
+ .bv{font:300 40px/1.05 Fraunces,Georgia,serif;color:var(--accent);margin-top:4px}.bv small,.rush small{font-size:.5em;font-style:italic}.cn small{font-size:.75em}
2110
+ .bs{font-size:12px;line-height:1.35;color:var(--ink)}.bs strong{font-weight:700}
2111
+ .hours{flex:1}.rush{font:italic 300 22px/1.1 Fraunces,Georgia,serif;color:var(--accent)}
2112
+ .bars{flex:1;min-height:16px;display:flex;align-items:flex-end;gap:3px}.bars i{flex:1;border-radius:4px 4px 0 0;background:rgb(30 90 60 / .12)}.bars i.rushbar{background:var(--forest)}
2113
+ .charges{position:relative;flex:1;min-width:0;padding:18px 20px}
2114
+ .ctitle{display:block;font:300 22px/1.15 Fraunces,Georgia,serif}
2115
+ .stamp{position:absolute;right:16px;top:12px;transform:rotate(-8deg);border:2px solid var(--rose);color:var(--rose);background:var(--mist);border-radius:6px;padding:1px 9px;font:500 13px var(--mono);letter-spacing:.12em}
2116
+ .charges ol{flex:1;margin:0;padding:0;list-style:none;display:flex;flex-direction:column;justify-content:flex-start}.charges ol.many{justify-content:space-evenly}
2117
+ .charges li{display:flex;align-items:baseline;gap:14px;padding:7px 0;border-bottom:1px solid var(--rule)}.charges li:last-child{border-bottom:0}
2118
+ .charges li.risk{background:var(--rose-tint);margin:0 -20px;padding-left:20px;padding-right:20px}.charges li.risk .cn{color:var(--rose)}
2119
+ .cn{font:300 28px/1 Fraunces,Georgia,serif;min-width:72px;color:var(--accent)}.cl{font-size:14px;line-height:1.3}
2120
+ .model{flex:none;padding:12px 20px;gap:6px}
2121
+ .mval{font:italic 300 22px/1.1 Fraunces,Georgia,serif;color:var(--accent);display:flex;align-items:baseline;justify-content:space-between;gap:10px}.mval small{font:400 12px var(--mono);font-style:normal;color:var(--muted)}
2122
+ .segs{display:flex;height:8px;border-radius:999px;overflow:hidden;background:rgb(30 90 60 / .12)}.m0{background:var(--forest)}.m1{background:var(--sage)}.m2{background:#9FD0B0}.m3{background:var(--blush)}
2123
+ .legend{display:flex;flex-wrap:wrap;gap:4px 12px;font:10px var(--mono);color:var(--muted)}.legend i{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:5px}
2124
+ /* Top tracks takes the dark card theme, like Personality: mist text, blush ranks, light hairlines. */
2125
+ .tracks{--accent:var(--blush);--rule:rgb(248 251 248 / .14);--sub:rgb(248 251 248 / .62);flex:none;padding:16px 20px;gap:8px;color:var(--mist);border-color:var(--ink-dark);background:linear-gradient(rgb(248 251 248 / .022) 1px,transparent 1px) 0 0/24px 24px,linear-gradient(90deg,rgb(248 251 248 / .022) 1px,transparent 1px) 0 0/24px 24px,radial-gradient(120% 80% at 100% 100%,color-mix(in srgb,var(--forest),transparent 55%),transparent 70%),var(--ink-dark)}
2126
+ /* Short windows: the charge sheet tightens so all its counts stay inside the tile. */
2127
+ @media (max-height:860px){.charges{gap:6px;padding:14px 20px}.ctitle{font-size:19px}.charges li{padding:4px 0}.cn{font-size:22px;min-width:60px}.cl{font-size:13px}}
2128
+ @media (max-width:1360px){.heat{--cell:9px;--gap:2px}}
2129
+ /* Five charges (the cap) on a short window: tighter rows so the count stays inside the tile. */
2130
+ @media (max-height:800px){.charges ol.many li{padding:2px 0}.charges ol.many .cn{font-size:19px;min-width:52px}}
2131
+ @media (prefers-reduced-motion:reduce){.card{animation:none}*{transition:none!important}}
2132
+ @media (max-width:1100px),(max-height:700px){.app{height:auto;padding:14px 20px 20px}nav{position:static}header{flex-direction:column;align-items:flex-start}.btns{flex-wrap:wrap}.main{display:flex;flex-direction:column}.sheet.summary{flex-direction:column;align-items:flex-start}.mid,.toprow{flex-direction:column}.cardgrid{grid-template-columns:repeat(2,minmax(0,1fr))}}
2133
+ `;
2134
+
2135
+ // src/server.ts
2136
+ var FONT_DIR = [join8(dirname3(fileURLToPath(import.meta.url)), "fonts"), join8(dirname3(fileURLToPath(import.meta.url)), "../dist/fonts")].find(existsSync4);
2137
+ var FONT_NAMES = new Set(FONT_FILES.map((f) => f.file));
2138
+ function serve(wrapped, home, port = 4747) {
2139
+ const html = renderPage(wrapped);
2140
+ let boundPort = 0;
2141
+ const server = createServer((req, res) => {
2142
+ const host = (req.headers.host ?? "").replace(/:\d+$/, "");
2143
+ if (host !== "127.0.0.1" && host !== "localhost") {
2144
+ res.writeHead(403).end("Forbidden");
2145
+ return;
2146
+ }
2147
+ if (req.url === "/keep-history") {
2148
+ const origin = req.headers.origin;
2149
+ const own = origin === `http://localhost:${boundPort}` || origin === `http://127.0.0.1:${boundPort}`;
2150
+ if (req.method !== "POST" || !own || req.headers["x-agent-wrapped"] !== "1") {
2151
+ res.writeHead(403).end("Forbidden");
2152
+ return;
2153
+ }
2154
+ req.resume();
2155
+ const r = keepHistory(home);
2156
+ res.writeHead(r.status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(r.body));
2157
+ return;
2158
+ }
2159
+ if (req.method === "GET" && (req.url === "/" || req.url?.startsWith("/?"))) {
2160
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(html);
2161
+ } else if (req.method === "GET" && req.url?.startsWith("/fonts/") && FONT_DIR && FONT_NAMES.has(req.url.slice(7))) {
2162
+ res.writeHead(200, { "content-type": "font/woff2", "cache-control": "public, max-age=31536000, immutable" }).end(readFileSync4(join8(FONT_DIR, req.url.slice(7))));
2163
+ } else {
2164
+ res.writeHead(404).end("Not found");
1571
2165
  }
1572
- }
1573
- let latest = null;
1574
- let latestKey = -1;
1575
- for (const s of sessions.values()) {
1576
- const h = s.start.getHours();
1577
- if (h >= 5 && h < 20)
1578
- continue;
1579
- const key = (h < 5 ? 1440 : 0) + h * 60 + s.start.getMinutes();
1580
- if (key > latestKey)
1581
- [latestKey, latest] = [key, s.start];
1582
- }
1583
- const modelCounts = new Map;
1584
- for (const e of events) {
1585
- if (e.kind !== "reply" || !e.model)
1586
- continue;
1587
- const fam = modelFamily(e.model);
1588
- if (fam)
1589
- bump(modelCounts, fam);
1590
- }
1591
- const facts = { events, approvals: result.approvals, sessions };
1592
- const charges = computeCharges(facts);
1593
- const chargeCount = (id) => charges.find((c) => c.id === id)?.count ?? 0;
1594
- const bypassSessions = [...sessions.values()].filter((s) => s.autonomy === "bypass").length;
1595
- const harnessShare = ranked(harnessCalls, 3);
1596
- const topHarness = Object.keys(HARNESS_NAME).find((h) => HARNESS_NAME[h] === harnessShare[0]?.name) ?? null;
1597
- const agentHours = Math.round(agentMs / 3600000 * 10) / 10;
1598
- const share = (n) => tools.length > 0 ? n / tools.length : 0;
1599
- const callsWhere = (pred) => tools.filter(pred).length;
1600
- const archetype = pickArchetype({
1601
- sessions: sessions.size,
1602
- bypassSessions,
1603
- dontAskAgain: chargeCount("dontAskAgain"),
1604
- compactions: events.filter((e) => e.kind === "compaction").length,
1605
- agentHours,
1606
- toolCalls: tools.length,
1607
- nightShare: share(callsWhere((t) => t.at.getHours() >= 21 || t.at.getHours() < 4)),
1608
- earlyShare: share(callsWhere((t) => t.at.getHours() >= 5 && t.at.getHours() < 9)),
1609
- weekendShare: share(callsWhere((t) => t.at.getDay() === 0 || t.at.getDay() === 6)),
1610
- topHarness,
1611
- topHarnessShare: share(harnessShare[0]?.count ?? 0),
1612
- secondHarnessShare: share(harnessShare[1]?.count ?? 0),
1613
- connectorShare: share(callsWhere((t) => t.connector !== null)),
1614
- connectorCount: connectors.size,
1615
- bashShare: share(callsWhere((t) => t.command !== null)),
1616
- webShare: share(callsWhere((t) => WEB_TOOLS.has(t.tool))),
1617
- subagentCalls: callsWhere((t) => SUBAGENT_TOOLS.has(t.tool)),
1618
- reads: callsWhere((t) => t.tool === "Read"),
1619
- writes: callsWhere((t) => WRITE_TOOLS2.has(t.tool)),
1620
- lazyPrompts: chargeCount("fixIt") + chargeCount("pastedError")
1621
2166
  });
1622
- const topCommands = ranked(commands, 5);
1623
- const topConnectors = ranked(connectors, 5);
1624
- const firstEvent = result.events.reduce((m, e) => !m || e.at < m ? e.at : m, null);
1625
- const first = [result.firstStarted, firstEvent].filter((d) => d !== null).sort((a, b) => a.getTime() - b.getTime())[0];
1626
- const agentAgeDays = first ? Math.max(1, Math.floor((until.getTime() - first.getTime()) / DAY_MS)) : null;
1627
- return {
1628
- window,
1629
- harnesses: result.found,
1630
- totals: { toolCalls: tools.length, sessions: sessions.size, agentHours },
1631
- daily,
1632
- longestStreak: longestStreak(daily.flatMap((n, i) => n > 0 ? [i] : []), from),
1633
- topTools: ranked(toolNames, 5),
1634
- topConnectors,
1635
- topCommands,
1636
- harnessShare,
1637
- hours,
1638
- rushHour,
1639
- latestStart: latest ? {
1640
- time: `${String(latest.getHours()).padStart(2, "0")}:${String(latest.getMinutes()).padStart(2, "0")}`,
1641
- weekday: WEEKDAYS[latest.getDay()],
1642
- month: MONTHS2[latest.getMonth()]
1643
- } : null,
1644
- topModel: modelCounts.size > 0 ? { models: ranked(modelCounts, 4) } : null,
1645
- charges,
1646
- tracks: computeTracks(facts, topCommands[0], topConnectors[0]),
1647
- personality: { ...archetype, genre: genreOf(topCommands[0]?.name, topConnectors[0]?.name, archetype.genre), agentAgeDays, hangout: hangoutOf(tools) }
1648
- };
2167
+ return new Promise((resolve, reject) => {
2168
+ const tryPort = (p, left) => {
2169
+ server.once("error", (err) => {
2170
+ if (err.code === "EADDRINUSE" && left > 0)
2171
+ tryPort(p + 1, left - 1);
2172
+ else
2173
+ reject(err);
2174
+ });
2175
+ server.listen(p, "127.0.0.1", () => {
2176
+ boundPort = server.address().port;
2177
+ resolve({ server, port: boundPort });
2178
+ });
2179
+ };
2180
+ tryPort(port, 20);
2181
+ });
1649
2182
  }
1650
2183
 
1651
2184
  // src/cli.ts
@@ -1662,22 +2195,36 @@ function openBrowser(url) {
1662
2195
  }
1663
2196
  async function main() {
1664
2197
  if (flag("--help") || flag("-h")) {
1665
- console.log(`runa-agent-wrapped [--no-open] [--json]
1666
- Reads local Claude Code, Codex and Cursor history and opens a report on http://localhost:4747.`);
2198
+ console.log([
2199
+ "runa-agent-wrapped [--no-open] [--json] [--no-save]",
2200
+ " Reads local Claude Code, Codex and Cursor history and opens a report on http://localhost:4747.",
2201
+ " --no-open print the URL, do not open a browser",
2202
+ " --json print the computed report as JSON and exit",
2203
+ " --no-save do not write ~/.agent-wrapped/daily.json (dates and counts per day, kept for next year's report)"
2204
+ ].join(`
2205
+ `));
1667
2206
  return;
1668
2207
  }
1669
2208
  const now = new Date;
1670
2209
  const home = (homeArg >= 0 ? args[homeArg + 1] : undefined) ?? homedir();
1671
- const wrapped = computeWrapped(readAll(home, now), windowFor(now));
2210
+ const window = windowFor(now);
2211
+ const read = readAll(home, now);
2212
+ const wrapped = computeWrapped(read, window);
1672
2213
  if (flag("--json")) {
1673
2214
  console.log(JSON.stringify(wrapped, null, 2));
1674
2215
  return;
1675
2216
  }
2217
+ const days = [...transcriptDays(read.events, window), ...read.backfill];
2218
+ if (!flag("--no-save") && days.length > 0) {
2219
+ const problem = saveDaily(home, days);
2220
+ if (problem)
2221
+ console.log(problem);
2222
+ }
1676
2223
  const { totals, personality, harnesses } = wrapped;
1677
2224
  console.log(`Agent Wrapped ${wrapped.window.start.slice(0, 4)}: ${harnesses.length ? harnesses.map((h) => HARNESS_NAME[h]).join(", ") : "no agent history found"}`);
1678
2225
  console.log(`${totals.toolCalls.toLocaleString("en-US")} tool calls, ${totals.sessions.toLocaleString("en-US")} ${totals.sessions === 1 ? "session" : "sessions"}, ${totals.agentHours} agent hours`);
1679
2226
  console.log(`You are ${personality.name}. Everything stays on this laptop.`);
1680
- const { port } = await serve(wrapped);
2227
+ const { port } = await serve(wrapped, home);
1681
2228
  const url = `http://localhost:${port}`;
1682
2229
  console.log(`Report: ${url} (Ctrl-C to stop)`);
1683
2230
  if (!flag("--no-open"))