@shadevkumar/agent-wrapped 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shadev Kumar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ The bundled fonts in src/story/fonts (Geist and Newsreader) are licensed
24
+ separately under the SIL Open Font License 1.1. Their licence texts are in
25
+ that folder.
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # Agent Wrapped
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Your life with AI coding agents, wrapped.
4
+
5
+ ```
6
+ npx @shadevkumar/agent-wrapped
7
+ ```
8
+
9
+ It reads your Claude Code and Codex logs on your computer and turns them into a short animated story made of keyboard keys: your most-typed typo, every way you've spelled "everything", the key you hit when you meant another, your latest prompt after midnight, your streak, and what all that agent work would cost at public API prices. It ends with your personality and a letter from your agents.
10
+
11
+ Then you share it. One link plays your whole story for anyone who opens it, keys and sound included, and ends by showing them how to make their own. You can leave cards out first, or save a video for places that don't take links. While you watch, the buttons fade away so a screenshot shows only the card, and pressing S saves the card on screen.
12
+
13
+ ## What stays private
14
+
15
+ Nothing is uploaded. The story is one HTML file written to your computer's temp folder and opened in your browser.
16
+
17
+ - **Your prompts never leave your computer.** The story only quotes everyday words. A quote with a name, a link, a file path, an email, a key or a word the dictionary doesn't know is left out, and so are your folder, repo and organisation names.
18
+ - **Nothing is shared until you share it.** A share link carries your story inside it, after the `#`, which browsers never send to the server. So the public page that plays it never receives or stores your story. Anyone you give the link to can watch it.
19
+ - **You see the story before you share it,** and a card you leave out is not in the link at all.
20
+ - **The letter** is written by your own `claude` command, if you have one. It gets your numbers and a few quotes that passed the same privacy check as the cards, never your prompts or logs. It doesn't save a session or load any project files. Run with `--no-ai` to use a template letter instead.
21
+
22
+ ## What it reads
23
+
24
+ | Agent | Where | What |
25
+ | --- | --- | --- |
26
+ | Claude Code | `~/.claude/history.jsonl` | the prompts you typed |
27
+ | Claude Code | `~/.claude/projects/**/*.jsonl` | token use and how long each request took |
28
+ | Claude Code | `~/.claude/stats-cache.json` | older token totals |
29
+ | Codex | `~/.codex/thread_history_*.sqlite` | the prompts you typed and how long each request took |
30
+ | Codex | `~/.codex/state_*.sqlite` | token totals per thread |
31
+ | Codex | `~/.codex/sessions/**/*.jsonl` | token splits for recent threads |
32
+
33
+ Everything is opened read-only. Claude Code deletes full transcripts after about 30 days, so older Claude token use can be missing. The prompts themselves go back further.
34
+
35
+ ## How the cost is worked out
36
+
37
+ "At least $X" is what the same tokens would cost on the public Claude and OpenAI APIs, at standard rates.
38
+
39
+ - Tokens with a full split (input, cached, written to cache, output) are priced exactly.
40
+ - Tokens known only as one total, like older Codex threads, are priced as if they were all the cheapest kind. The real cost is higher, which is why it says "at least".
41
+ - Models without a public price are counted but not priced.
42
+
43
+ Prices are in `src/pricing.ts`, with the date they were read and their source pages. Your plan most likely cost far less.
44
+
45
+ ## Options
46
+
47
+ | Flag | What it does |
48
+ | --- | --- |
49
+ | `--no-ai` | Use a template letter instead of asking your `claude` command |
50
+ | `--no-open` | Write the story file without opening it |
51
+ | `--json` | Print the numbers behind the story instead of making it |
52
+
53
+ ## Needs
54
+
55
+ - Node.js 22.13 or newer
56
+ - Claude Code, Codex, or both, used on this computer
57
+ - macOS is where it's tested. It uses the system dictionary in `/usr/share/dict/words` to tell typos from words; without one, quotes are mostly left out.
58
+
59
+ ## Develop
60
+
61
+ ```
62
+ npm install
63
+ npm test
64
+ npm run dev
65
+ npm run build:player # the public page that plays shared stories, in site/
66
+ ```
67
+
68
+ Share links point at `PLAYER_URL` in `src/build.ts`. The `site/` folder is what goes online: the player page, the picture posts show for a link (`og.png`, made from `og.html`), and its headers in `vercel.json`.
69
+
70
+ ## Credits
71
+
72
+ Fonts: [Geist](https://github.com/vercel/geist-font) and [Newsreader](https://github.com/productiontype/Newsreader), both under the SIL Open Font License 1.1.
package/dist/build.js ADDED
@@ -0,0 +1,47 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ const STORY_DIR = join(import.meta.dirname, "story");
4
+ // The public page that plays shared stories.
5
+ export const PLAYER_URL = "https://agent-wrapped.shadev.space/";
6
+ // Only on the public page: how a shared link looks in a post, and Vercel's
7
+ // page counts. The story sits after the "#", which browsers never send to a
8
+ // server; the counts drop it anyway before anything is sent.
9
+ const PUBLIC_HEAD = `<meta name="description" content="A year with AI coding agents, played back in keyboard keys. Tap to watch.">
10
+ <meta property="og:title" content="Agent Wrapped 2026">
11
+ <meta property="og:description" content="A year with AI coding agents, played back in keyboard keys. Tap to watch.">
12
+ <meta property="og:image" content="${PLAYER_URL}og.png">
13
+ <meta property="og:image:width" content="1200">
14
+ <meta property="og:image:height" content="630">
15
+ <meta property="og:url" content="${PLAYER_URL}">
16
+ <meta property="og:type" content="website">
17
+ <meta name="twitter:card" content="summary_large_image">
18
+ <script>
19
+ window.va = window.va || function () { (window.vaq = window.vaq || []).push(arguments); };
20
+ window.va("beforeSend", (event) => {
21
+ const url = new URL(event.url);
22
+ url.hash = "";
23
+ return { ...event, url: url.toString() };
24
+ });
25
+ </script>
26
+ <script defer src="/_vercel/insights/script.js"></script>`;
27
+ // One self-contained HTML file: fonts, script and data inlined, nothing
28
+ // fetched from the internet when it opens. Without data it is the public
29
+ // player, which reads the story from its link.
30
+ export function buildHtml(data, playerUrl = PLAYER_URL) {
31
+ const font = (file) => readFileSync(join(STORY_DIR, "fonts", file)).toString("base64");
32
+ const fonts = [
33
+ ["Geist", "geist-normal.woff2", "normal", "100 900"],
34
+ ["Newsreader", "newsreader-normal.woff2", "normal", "300 700"],
35
+ ["Newsreader", "newsreader-italic.woff2", "italic", "300 700"],
36
+ ]
37
+ .map(([family, file, style, weight]) => `@font-face{font-family:"${family}";src:url(data:font/woff2;base64,${font(file)}) format("woff2");font-style:${style};font-weight:${weight};font-display:block}`)
38
+ .join("\n");
39
+ // Escape "<" so no value can close the script tag it sits in.
40
+ const json = JSON.stringify(data).replace(/</g, "\\u003c");
41
+ return readFileSync(join(STORY_DIR, "index.html"), "utf8")
42
+ .replace("<!--HEAD-->", () => (data ? "" : PUBLIC_HEAD))
43
+ .replace("/*FONTS*/", () => fonts)
44
+ .replace("/*DATA*/", () => json)
45
+ .replace("/*PLAYER_URL*/", () => JSON.stringify(playerUrl).replace(/</g, "\\u003c"))
46
+ .replace("/*SCRIPT*/", () => readFileSync(join(STORY_DIR, "story.js"), "utf8"));
47
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env -S node --disable-warning=ExperimentalWarning
2
+ import { spawn } from "node:child_process";
3
+ import { mkdirSync, writeFileSync } from "node:fs";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { buildHtml } from "./build.js";
7
+ import { localDay } from "./files.js";
8
+ import { templateLetter, writeLetter } from "./letter.js";
9
+ import { computeWrapped } from "./moments.js";
10
+ import { pickPersonality } from "./personality.js";
11
+ import { harvestClaude } from "./sources/claude.js";
12
+ import { harvestCodex } from "./sources/codex.js";
13
+ import { storyData } from "./story.js";
14
+ import { mergeHarvests } from "./types.js";
15
+ const args = new Set(process.argv.slice(2));
16
+ const home = homedir();
17
+ console.log("Reading your Claude Code and Codex logs. Nothing leaves this computer.");
18
+ const wrapped = computeWrapped(mergeHarvests([harvestClaude(home), harvestCodex(home)]));
19
+ if (args.has("--json")) {
20
+ console.log(JSON.stringify(wrapped, null, 2));
21
+ process.exit(0);
22
+ }
23
+ if (wrapped.totals.prompts === 0) {
24
+ console.log("No Claude Code or Codex prompts found on this computer, so there's no story yet.");
25
+ process.exit(1);
26
+ }
27
+ const personality = pickPersonality(wrapped);
28
+ let letter;
29
+ if (args.has("--no-ai")) {
30
+ letter = { text: templateLetter(wrapped, personality), by: "template" };
31
+ }
32
+ else {
33
+ console.log("Asking your Claude to write you a letter. It sees your stats only, never your prompts.");
34
+ letter = writeLetter(wrapped, personality);
35
+ if (letter.by === "template")
36
+ console.log("Claude wasn't available, so your agents wrote a shorter note instead.");
37
+ }
38
+ const dir = join(tmpdir(), "agent-wrapped");
39
+ mkdirSync(dir, { recursive: true });
40
+ const file = join(dir, `agent-wrapped-${localDay(new Date())}.html`);
41
+ writeFileSync(file, buildHtml(storyData(wrapped, personality, letter)));
42
+ console.log(`\nYou are ${personality.name}. ${wrapped.totals.prompts.toLocaleString("en-US")} prompts, ${Math.round(wrapped.totals.agentHours)} hours of agent work.`);
43
+ console.log(`Your story is ready: ${file}`);
44
+ console.log("Watch it, then share it from the last screen. Anyone with your link can watch it play.");
45
+ if (!args.has("--no-open")) {
46
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
47
+ spawn(opener, [file], { detached: true, stdio: "ignore" }).unref();
48
+ }
package/dist/files.js ADDED
@@ -0,0 +1,114 @@
1
+ import { closeSync, existsSync, fstatSync, openSync, readdirSync, readFileSync, readSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ // Parse a JSONL file, skipping malformed lines. A missing file is empty.
4
+ // `keep` skips decoding lines that can't matter, which is most of a big log.
5
+ export function readJsonl(path, keep) {
6
+ if (!existsSync(path))
7
+ return [];
8
+ const rows = [];
9
+ for (const line of readFileSync(path, "utf8").split("\n")) {
10
+ if (!line.trim() || (keep && !keep(line)))
11
+ continue;
12
+ try {
13
+ const row = JSON.parse(line);
14
+ if (row && typeof row === "object")
15
+ rows.push(row);
16
+ }
17
+ catch {
18
+ // A half-written last line is normal while an agent is running.
19
+ }
20
+ }
21
+ return rows;
22
+ }
23
+ // The last line containing `needle` that parses and passes `accept`, read
24
+ // backwards from the end of the file, so a 300 MB log costs one small read.
25
+ export function lastJsonLine(path, needle, accept) {
26
+ if (!existsSync(path))
27
+ return null;
28
+ const fd = openSync(path, "r");
29
+ try {
30
+ const chunk = 1 << 20;
31
+ let end = fstatSync(fd).size;
32
+ let tail = Buffer.alloc(0);
33
+ while (end > 0) {
34
+ const start = Math.max(0, end - chunk);
35
+ const buf = Buffer.alloc(end - start);
36
+ readSync(fd, buf, 0, buf.length, start);
37
+ tail = Buffer.concat([buf, tail]);
38
+ end = start;
39
+ // Until the start of the file, the first line may be cut in half. Split
40
+ // on bytes, so a character cut at the chunk edge is never decoded.
41
+ const firstBreak = end > 0 ? tail.indexOf(0x0a) : -1;
42
+ const lines = tail.subarray(firstBreak + 1).toString("utf8").split("\n");
43
+ for (let i = lines.length - 1; i >= 0; i--) {
44
+ if (!lines[i].includes(needle))
45
+ continue;
46
+ try {
47
+ const row = JSON.parse(lines[i]);
48
+ if (row && accept(row))
49
+ return row;
50
+ }
51
+ catch {
52
+ // A half-written last line while the agent runs.
53
+ }
54
+ }
55
+ tail = firstBreak >= 0 ? tail.subarray(0, firstBreak) : Buffer.alloc(0);
56
+ }
57
+ return null;
58
+ }
59
+ finally {
60
+ closeSync(fd);
61
+ }
62
+ }
63
+ export function readJson(path) {
64
+ if (!existsSync(path))
65
+ return null;
66
+ try {
67
+ return JSON.parse(readFileSync(path, "utf8"));
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ export function findFiles(dir, ext) {
74
+ if (!existsSync(dir))
75
+ return [];
76
+ return readdirSync(dir, { recursive: true, encoding: "utf8" })
77
+ .filter((f) => f.endsWith(ext))
78
+ .map((f) => join(dir, f));
79
+ }
80
+ export function toDate(value) {
81
+ if (value === null || value === undefined || value === "")
82
+ return null;
83
+ const d = new Date(value);
84
+ return Number.isNaN(d.getTime()) ? null : d;
85
+ }
86
+ export function coverage(agent, source, dates) {
87
+ let from = null;
88
+ let to = null;
89
+ for (const d of dates) {
90
+ if (!from || d < from)
91
+ from = d;
92
+ if (!to || d > to)
93
+ to = d;
94
+ }
95
+ return { agent, source, count: dates.length, from, to };
96
+ }
97
+ // Names worth keeping out of quotes: the folder name, written as one word
98
+ // too. `Words` also blocks its dash-separated parts that aren't real words.
99
+ export function namesFromPath(path) {
100
+ const base = basename(path.replace(/\/+$/, "")).toLowerCase();
101
+ if (!base)
102
+ return [];
103
+ return [base, base.replace(/[-_.]/g, "")];
104
+ }
105
+ export function namesFromGitUrl(url) {
106
+ const m = url.match(/[:/]([^/:]+)\/([^/]+?)(?:\.git)?$/);
107
+ return m ? [...namesFromPath(m[1]), ...namesFromPath(m[2])] : [];
108
+ }
109
+ export function localDay(d) {
110
+ const y = d.getFullYear();
111
+ const m = String(d.getMonth() + 1).padStart(2, "0");
112
+ const day = String(d.getDate()).padStart(2, "0");
113
+ return `${y}-${m}-${day}`;
114
+ }
package/dist/letter.js ADDED
@@ -0,0 +1,60 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { tmpdir } from "node:os";
3
+ const SYSTEM = `You write the closing card of "Agent Wrapped", a year-in-review of someone's work with AI coding agents.
4
+ Write a short letter from their agents to them. Rules:
5
+ - 70 to 100 words, plain text, no markdown, no emoji, no greeting line like "Dear".
6
+ - Warm, funny, a little roasting, never mean. Sound like a coworker, not a greeting card.
7
+ - Use two or three of the facts given, quoting their words exactly as given.
8
+ - Never invent numbers, names, projects or events that are not in the facts.
9
+ - End with a short sign-off line from "your agents".`;
10
+ export function factsFor(w, p) {
11
+ const facts = [
12
+ `Their personality: ${p.name}. ${p.line}`,
13
+ `${w.totals.prompts} prompts over ${w.totals.activeDays} days; their agents worked ${Math.round(w.totals.agentHours)} hours.`,
14
+ w.rhythm.lateNight.latest ? `Latest prompt after midnight: ${w.rhythm.lateNight.latest}.` : "",
15
+ w.rhythm.longestStreak ? `Longest streak: ${w.rhythm.longestStreak.days} days in a row.` : "",
16
+ ...w.voice.topPrompts.slice(0, 3).map((t) => `They typed "${t.text}" ${t.count} times.`),
17
+ ...w.voice.catchphrases.slice(0, 2).map((c) => `Catchphrase "${c.text}" in ${c.sessions} sessions.`),
18
+ ...w.voice.typos.slice(0, 2).map((t) => `They spelled "${t.word}" ${t.spellings.length} wrong ways, like "${t.spellings[0]?.spelling}".`),
19
+ ];
20
+ return facts.filter(Boolean).join("\n");
21
+ }
22
+ export function writeLetter(w, p) {
23
+ const run = spawnSync("claude", [
24
+ "-p",
25
+ "--model", "sonnet",
26
+ "--tools", "",
27
+ "--strict-mcp-config",
28
+ "--disable-slash-commands",
29
+ "--no-session-persistence",
30
+ "--setting-sources", "",
31
+ "--system-prompt", SYSTEM,
32
+ ],
33
+ // Run outside any project so no project instructions are loaded.
34
+ { cwd: tmpdir(), input: `Facts:\n${factsFor(w, p)}`, encoding: "utf8", timeout: 90_000 });
35
+ const text = cleanLetter(run.status === 0 ? run.stdout : "");
36
+ return text ? { text, by: "claude" } : { text: templateLetter(w, p), by: "template" };
37
+ }
38
+ function cleanLetter(raw) {
39
+ const text = raw
40
+ .replace(/[*_#`]/g, "")
41
+ .replace(/\n{3,}/g, "\n\n")
42
+ .replace(/"([^"\n]*)"/g, "“$1”")
43
+ .replace(/'/g, "’")
44
+ .trim();
45
+ const words = text.split(/\s+/).length;
46
+ return words >= 30 && words <= 160 ? text : null;
47
+ }
48
+ export function templateLetter(w, p) {
49
+ const top = w.voice.topPrompts[0];
50
+ const typo = w.voice.typos[0];
51
+ const lines = [
52
+ `${w.totals.prompts.toLocaleString("en-US")} prompts. We read every one.`,
53
+ top ? `Some of them just said “${top.text}”. We got it every time.` : "",
54
+ typo ? `We also know what “${typo.spellings[0]?.spelling}” means now. It means ${typo.word}.` : "",
55
+ w.rhythm.lateNight.latest ? `See you at ${w.rhythm.lateNight.latest} again soon.` : "See you tomorrow.",
56
+ "",
57
+ `Yours, from the other side of the prompt, your agents`,
58
+ ];
59
+ return lines.filter((l, i) => l || i === lines.length - 2).join("\n");
60
+ }
@@ -0,0 +1,283 @@
1
+ import { localDay } from "./files.js";
2
+ import { apiCost, PRICES_AS_OF } from "./pricing.js";
3
+ import { usageTokens } from "./types.js";
4
+ import { findTypos, keySlips, tokenize, Words } from "./words.js";
5
+ const LATE_NIGHT_END_HOUR = 5;
6
+ // Repeats under a second apart are the logs writing a message twice, not a person.
7
+ const DOUBLE_SEND_MIN_MS = 1_000;
8
+ const DOUBLE_SEND_MAX_MS = 120_000;
9
+ // The same ten words in a row in three or more prompts is pasted text, not habit.
10
+ const PASTE_WINDOW = 10;
11
+ const PASTE_MIN_PROMPTS = 3;
12
+ const LEXICON = {
13
+ okay: ["okay", "ok"],
14
+ please: ["please", "pls", "plz"],
15
+ thanks: ["thanks", "thank", "thx"],
16
+ sorry: ["sorry"],
17
+ bro: ["bro", "dude", "man"],
18
+ why: ["why"],
19
+ again: ["again"],
20
+ wait: ["wait"],
21
+ perfect: ["perfect", "great", "awesome", "nice"],
22
+ };
23
+ export function computeWrapped(h, words = new Words(h.privateNames)) {
24
+ const prompts = [...h.prompts].sort((a, b) => a.at.getTime() - b.at.getTime());
25
+ const tokenized = prompts.map((p) => tokenize(p.text));
26
+ const counts = new Map();
27
+ for (const toks of tokenized)
28
+ for (const w of toks)
29
+ counts.set(w, (counts.get(w) ?? 0) + 1);
30
+ const { families, canonical } = findTypos(counts, words);
31
+ const canon = (toks) => toks.map((w) => canonical.get(w) ?? w);
32
+ const canonPrompts = tokenized.map(canon);
33
+ const pasted = pastedTokens(canonPrompts);
34
+ const lengths = tokenized.map((t) => t.length).sort((a, b) => a - b);
35
+ const days = [...new Set(prompts.map((p) => localDay(p.at)))].sort();
36
+ const cost = apiCost(h.usage, h.totals);
37
+ const agents = { claude: agentStats("claude", h), codex: agentStats("codex", h) };
38
+ return {
39
+ coverage: h.coverage.map((c) => ({
40
+ agent: c.agent,
41
+ source: c.source,
42
+ count: c.count,
43
+ from: c.from ? localDay(c.from) : null,
44
+ to: c.to ? localDay(c.to) : null,
45
+ })),
46
+ totals: {
47
+ prompts: prompts.length,
48
+ sessions: agents.claude.sessions + agents.codex.sessions,
49
+ activeDays: days.length,
50
+ firstDay: days[0] ?? null,
51
+ lastDay: days.at(-1) ?? null,
52
+ agentHours: round(agents.claude.agentHours + agents.codex.agentHours, 1),
53
+ tokens: agents.claude.tokens + agents.codex.tokens,
54
+ },
55
+ agents,
56
+ cost: { ...cost, pricesAsOf: PRICES_AS_OF },
57
+ rhythm: rhythm(prompts, days),
58
+ voice: {
59
+ topPrompts: topPrompts(canonPrompts, words, canonical),
60
+ catchphrases: catchphrases(prompts, canonPrompts, pasted, words, canonical),
61
+ typos: families.slice(0, 10),
62
+ typoCount: families.reduce((s, f) => s + f.total, 0),
63
+ topTypo: topTypo(families),
64
+ keySlips: keySlips(families),
65
+ shortShare: share(tokenized.filter((t) => t.length > 0 && t.length <= 3).length, prompts.length),
66
+ medianWords: lengths[Math.floor(lengths.length / 2)] ?? 0,
67
+ pastedShare: share(pasted.filter((flags) => flags.some(Boolean)).length, prompts.length),
68
+ doubleSends: doubleSends(prompts),
69
+ lexicon: lexicon(tokenized),
70
+ },
71
+ loyalty: {
72
+ claudeShare: share(agents.claude.prompts, prompts.length),
73
+ codexShare: share(agents.codex.prompts, prompts.length),
74
+ bothAgentDays: bothAgentDays(prompts),
75
+ },
76
+ };
77
+ }
78
+ function agentStats(agent, h) {
79
+ const prompts = h.prompts.filter((p) => p.agent === agent);
80
+ const turns = h.turns.filter((t) => t.agent === agent);
81
+ const byModel = new Map();
82
+ for (const u of h.usage)
83
+ if (u.agent === agent)
84
+ byModel.set(u.model, (byModel.get(u.model) ?? 0) + usageTokens(u));
85
+ for (const t of h.totals)
86
+ if (t.agent === agent)
87
+ byModel.set(t.model, (byModel.get(t.model) ?? 0) + t.tokens);
88
+ const models = [...byModel].map(([model, tokens]) => ({ model, tokens })).sort((a, b) => b.tokens - a.tokens);
89
+ return {
90
+ prompts: prompts.length,
91
+ sessions: new Set(prompts.map((p) => p.session)).size,
92
+ tokens: models.reduce((s, m) => s + m.tokens, 0),
93
+ agentHours: round(turns.reduce((s, t) => s + t.durationMs, 0) / 3_600_000, 1),
94
+ longestTurnMinutes: round(Math.max(0, ...turns.map((t) => t.durationMs)) / 60_000, 1),
95
+ models,
96
+ };
97
+ }
98
+ function rhythm(prompts, days) {
99
+ const byHour = new Array(24).fill(0);
100
+ const byWeekday = new Array(7).fill(0);
101
+ const perDay = new Map();
102
+ let late = 0;
103
+ let latestMinute = -1;
104
+ for (const p of prompts) {
105
+ const hour = p.at.getHours();
106
+ byHour[hour]++;
107
+ byWeekday[p.at.getDay()]++;
108
+ const day = localDay(p.at);
109
+ perDay.set(day, (perDay.get(day) ?? 0) + 1);
110
+ if (hour < LATE_NIGHT_END_HOUR) {
111
+ late++;
112
+ latestMinute = Math.max(latestMinute, hour * 60 + p.at.getMinutes());
113
+ }
114
+ }
115
+ const busiest = [...perDay].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
116
+ return {
117
+ byHour,
118
+ byWeekday,
119
+ busiestDay: busiest ? { day: busiest[0], prompts: busiest[1] } : null,
120
+ longestStreak: longestStreak(days),
121
+ lateNight: {
122
+ prompts: late,
123
+ share: share(late, prompts.length),
124
+ latest: latestMinute < 0 ? null : `${pad(Math.floor(latestMinute / 60))}:${pad(latestMinute % 60)}`,
125
+ },
126
+ };
127
+ }
128
+ // `days` are sorted, unique local days (YYYY-MM-DD).
129
+ export function longestStreak(days) {
130
+ if (days.length === 0)
131
+ return null;
132
+ let best = { days: 1, from: days[0], to: days[0] };
133
+ let run = { days: 1, from: days[0] };
134
+ for (let i = 1; i < days.length; i++) {
135
+ const gap = (Date.parse(days[i]) - Date.parse(days[i - 1])) / 86_400_000;
136
+ run = gap === 1 ? { days: run.days + 1, from: run.from } : { days: 1, from: days[i] };
137
+ if (run.days > best.days)
138
+ best = { days: run.days, from: run.from, to: days[i] };
139
+ }
140
+ return best;
141
+ }
142
+ function topPrompts(canonPrompts, words, typos) {
143
+ const counts = new Map();
144
+ for (const toks of canonPrompts) {
145
+ if (toks.length === 0 || toks.length > 6)
146
+ continue;
147
+ const key = toks.join(" ");
148
+ counts.set(key, (counts.get(key) ?? 0) + 1);
149
+ }
150
+ return [...counts]
151
+ .filter(([, n]) => n >= 3)
152
+ .sort((a, b) => b[1] - a[1])
153
+ .flatMap(([text, count]) => {
154
+ const safe = words.safeQuote(text, typos);
155
+ return safe ? [{ text: safe, count }] : [];
156
+ })
157
+ .slice(0, 8);
158
+ }
159
+ // For each prompt, which words belong to text that was pasted into other prompts.
160
+ export function pastedTokens(canonPrompts) {
161
+ const windowsPerPrompt = canonPrompts.map((toks) => {
162
+ const set = new Set();
163
+ for (let s = 0; s + PASTE_WINDOW <= toks.length; s++)
164
+ set.add(toks.slice(s, s + PASTE_WINDOW).join(" "));
165
+ return set;
166
+ });
167
+ const seenIn = new Map();
168
+ for (const set of windowsPerPrompt)
169
+ for (const w of set)
170
+ seenIn.set(w, (seenIn.get(w) ?? 0) + 1);
171
+ return canonPrompts.map((toks) => {
172
+ const flags = new Array(toks.length).fill(false);
173
+ for (let s = 0; s + PASTE_WINDOW <= toks.length; s++) {
174
+ if ((seenIn.get(toks.slice(s, s + PASTE_WINDOW).join(" ")) ?? 0) >= PASTE_MIN_PROMPTS) {
175
+ flags.fill(true, s, s + PASTE_WINDOW);
176
+ }
177
+ }
178
+ return flags;
179
+ });
180
+ }
181
+ // Phrases of 3-5 words typed in at least three different sessions. Pasted text
182
+ // doesn't count. A longer phrase replaces a shorter one inside it when it
183
+ // explains most of its uses.
184
+ function catchphrases(prompts, canonPrompts, pasted, words, typos) {
185
+ const grams = new Map();
186
+ canonPrompts.forEach((toks, i) => {
187
+ const seen = new Set();
188
+ for (let n = 3; n <= 5; n++) {
189
+ for (let s = 0; s + n <= toks.length; s++) {
190
+ if (pasted[i].slice(s, s + n).some(Boolean))
191
+ continue;
192
+ const g = toks.slice(s, s + n);
193
+ if (words.isStopword(g[0]) || words.isStopword(g.at(-1)))
194
+ continue;
195
+ const key = g.join(" ");
196
+ if (seen.has(key))
197
+ continue;
198
+ seen.add(key);
199
+ const entry = grams.get(key) ?? { n, sessions: new Set(), uses: 0 };
200
+ entry.sessions.add(`${prompts[i].agent}:${prompts[i].session}`);
201
+ entry.uses++;
202
+ grams.set(key, entry);
203
+ }
204
+ }
205
+ });
206
+ const candidates = [...grams]
207
+ .filter(([, g]) => g.sessions.size >= 3 && g.uses >= 4)
208
+ .sort((a, b) => b[1].n - a[1].n);
209
+ const kept = [];
210
+ for (const [text, g] of candidates) {
211
+ const covered = kept.some(([longer, sessions]) => ` ${longer} `.includes(` ${text} `) && sessions >= g.sessions.size * 0.8);
212
+ if (!covered)
213
+ kept.push([text, g.sessions.size]);
214
+ }
215
+ return kept
216
+ .sort((a, b) => b[1] - a[1])
217
+ .flatMap(([text, sessions]) => {
218
+ const safe = words.safeQuote(text, typos);
219
+ return safe ? [{ text: safe, sessions }] : [];
220
+ })
221
+ .slice(0, 10);
222
+ }
223
+ function topTypo(families) {
224
+ let best = null;
225
+ for (const f of families) {
226
+ for (const s of f.spellings)
227
+ if (!best || s.count > best.count)
228
+ best = { spelling: s.spelling, word: f.word, count: s.count };
229
+ }
230
+ return best;
231
+ }
232
+ // The same message sent again in the same session within two minutes.
233
+ export function doubleSends(sorted) {
234
+ const last = new Map();
235
+ let count = 0;
236
+ for (const p of sorted) {
237
+ const key = `${p.agent}:${p.session}`;
238
+ const prev = last.get(key);
239
+ const gap = prev ? p.at.getTime() - prev.at.getTime() : -1;
240
+ if (prev && prev.text.trim() === p.text.trim() && gap >= DOUBLE_SEND_MIN_MS && gap <= DOUBLE_SEND_MAX_MS) {
241
+ count++;
242
+ }
243
+ last.set(key, p);
244
+ }
245
+ return count;
246
+ }
247
+ function lexicon(tokenized) {
248
+ const out = {};
249
+ const lookup = new Map();
250
+ for (const [group, list] of Object.entries(LEXICON)) {
251
+ out[group] = 0;
252
+ for (const w of list)
253
+ lookup.set(w, group);
254
+ }
255
+ for (const toks of tokenized) {
256
+ for (const w of toks) {
257
+ const group = lookup.get(w);
258
+ if (group)
259
+ out[group]++;
260
+ }
261
+ }
262
+ return out;
263
+ }
264
+ function bothAgentDays(prompts) {
265
+ const byDay = new Map();
266
+ for (const p of prompts) {
267
+ const day = localDay(p.at);
268
+ const set = byDay.get(day) ?? new Set();
269
+ set.add(p.agent);
270
+ byDay.set(day, set);
271
+ }
272
+ return [...byDay.values()].filter((s) => s.size === 2).length;
273
+ }
274
+ function share(part, whole) {
275
+ return whole ? round(part / whole, 3) : 0;
276
+ }
277
+ function round(n, digits) {
278
+ const f = 10 ** digits;
279
+ return Math.round(n * f) / f;
280
+ }
281
+ function pad(n) {
282
+ return String(n).padStart(2, "0");
283
+ }