wrapped-agents 1.0.0 → 1.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/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # Agent Wrapped
2
2
 
3
- **Your year with AI coding agents, wrapped.** A Spotify-Wrapped-style story of your 2026 with Claude Code, Codex, Pi and Mistral Vibe: tokens, harness and model of the year, streaks, how often you said please, how often your agent said "you're right", your agentic age, what it would have cost at API prices, and a roast written by your own agent.
3
+ [![npm](https://img.shields.io/npm/v/wrapped-agents?label=npx%20wrapped-agents&color=d77757)](https://www.npmjs.com/package/wrapped-agents) [![downloads](https://img.shields.io/npm/dw/wrapped-agents?color=d77757)](https://www.npmjs.com/package/wrapped-agents) [![site](https://img.shields.io/badge/site-leonardodaviti.github.io%2Fagent--wrapped-d77757)](https://leonardodaviti.github.io/agent-wrapped/)
4
+
5
+ **Your year with AI coding agents, wrapped.** A Spotify-Wrapped-style story of your 2026 with Claude Code, Codex, Cursor, Gemini CLI, Qwen Code, OpenCode, Pi and Mistral Vibe: tokens, harness and model of the year, streaks, how often you said please, how often your agent said "you're right", your agentic age, what it would have cost at API prices, and a roast written by your own agent.
4
6
 
5
7
  It runs on your computer. **Your usage data never leaves your machine.**
6
8
 
@@ -14,7 +16,7 @@ Run it in a terminal or paste it into Claude Code, Codex, Pi or Mistral Vibe. Ne
14
16
 
15
17
  Paste it into your agent and it adds a one-line roast of your year.
16
18
 
17
- Also available as an [Agent Skill](SKILL.md) (`npx skills add leonardodaviti/agent-wrapped`) and a Claude Code plugin (`claude plugin install agent-wrapped --marketplace leonardodaviti/agent-wrapped`).
19
+ Also available as an [Agent Skill](SKILL.md) (`npx skills add LeonardoDaviti/agent-wrapped`) and a Claude Code plugin (`claude plugin install agent-wrapped --marketplace LeonardoDaviti/agent-wrapped`).
18
20
 
19
21
  It opens a story in your browser. The last slide saves images for Instagram stories (1080×1920), X (1200×1600) and Reddit (1080×1350), and its QR code opens your wrap on your phone.
20
22
 
@@ -24,6 +26,10 @@ It opens a story in your browser. The last slide saves images for Instagram stor
24
26
  |---|---|
25
27
  | Claude Code | `~/.claude` (history.jsonl, stats-cache.json, projects/) |
26
28
  | Codex | `~/.codex` |
29
+ | Cursor *(beta)* | `Cursor/User/globalStorage/state.vscdb`, `~/.cursor/chats` (needs Node 22.5+) |
30
+ | Gemini CLI *(beta)* | `~/.gemini/tmp` |
31
+ | Qwen Code *(beta)* | `~/.qwen/projects` |
32
+ | OpenCode *(beta)* | `~/.local/share/opencode` |
27
33
  | Pi | `~/.pi/agent` |
28
34
  | Mistral Vibe | `~/.vibe` |
29
35
 
@@ -39,4 +45,4 @@ The story wears the brand of the harness you use most, or your own theme from th
39
45
 
40
46
  Zero dependencies, Node ≥ 18. `npm test` · `node src/cli.mjs --no-open` · `node src/render.mjs test/fixtures/sample-wrapped.json`. Data flow and formats: [docs/CONTRACT.md](docs/CONTRACT.md).
41
47
 
42
- MIT · logos are trademarks of their owners, used to name the harnesses.
48
+ [npm](https://www.npmjs.com/package/wrapped-agents) · [site](https://leonardodaviti.github.io/agent-wrapped/) · MIT · logos are trademarks of their owners, used to name the harnesses.
package/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: agent-wrapped
3
- description: Wrapped / year in review / recap / stats of your AI coding agents — Claude Code, Codex, Pi, Mistral Vibe. Builds a Spotify-Wrapped-style story (tokens, harness and model of the year, streak, politeness, "you're right" count, agentic age, spendings, a roast) from local logs and opens it in the browser, with shareable images for X, Instagram and Reddit. Use when the user asks for their wrapped, year in review, recap, or agent/AI coding stats. Runs locally; usage data never leaves the machine.
3
+ description: Wrapped / year in review / recap / stats of your AI coding agents — Claude Code, Codex, Cursor, Gemini CLI, Qwen Code, OpenCode, Pi, Mistral Vibe. Builds a Spotify-Wrapped-style story (tokens, harness and model of the year, streak, politeness, "you're right" count, agentic age, spendings, a roast) from local logs and opens it in the browser, with shareable images for X, Instagram and Reddit. Use when the user asks for their wrapped, year in review, recap, or agent/AI coding stats. Runs locally; usage data never leaves the machine.
4
4
  ---
5
5
 
6
6
  # Agent Wrapped
@@ -12,12 +12,12 @@ Build the user's year with AI coding agents, wrapped. All numbers come from the
12
12
  Run, in a terminal (read-only over the user's agent logs; writes only to the temp folder):
13
13
 
14
14
  ```bash
15
- npx -y wrapped-agents@1.0.0 --json --no-open
15
+ npx -y wrapped-agents@1.1.0 --json --no-open
16
16
  ```
17
17
 
18
- It prints the path of `wrapped-<year>.json`. Before running, tell the user in one sentence: it reads their local agent logs (~/.claude, ~/.codex, ~/.pi, ~/.vibe) read-only and nothing about their usage leaves the machine.
18
+ It prints the path of `wrapped-<year>.json`. Before running, tell the user in one sentence: it reads their local agent logs (~/.claude, ~/.codex, Cursor, ~/.gemini, ~/.qwen, OpenCode, ~/.pi, ~/.vibe) read-only and nothing about their usage leaves the machine.
19
19
 
20
- No Node? Use the first that exists: `bunx wrapped-agents@1.0.0 --json --no-open` · `deno run -A npm:wrapped-agents@1.0.0 --json --no-open` · or `git clone --depth 1 --branch v1.0.0 https://github.com/leonardodaviti/agent-wrapped "$TMPDIR/agent-wrapped" && node "$TMPDIR/agent-wrapped/src/cli.mjs" --json --no-open`. If none works, say so and point to https://leonardodaviti.github.io/agent-wrapped.
20
+ No Node? Use the first that exists: `bunx wrapped-agents@1.1.0 --json --no-open` · `deno run -A npm:wrapped-agents@1.1.0 --json --no-open` · or `git clone --depth 1 --branch v1.1.0 https://github.com/LeonardoDaviti/agent-wrapped "$TMPDIR/agent-wrapped" && node "$TMPDIR/agent-wrapped/src/cli.mjs" --json --no-open`. If none works, say so and point to https://leonardodaviti.github.io/agent-wrapped.
21
21
 
22
22
  If a sandbox blocks reading a folder, ask the user once for read access; otherwise continue and mention which harness was skipped.
23
23
 
@@ -28,7 +28,7 @@ From the printed `wrapped-<year>.json` only, write one roast line: ≤ 12 words,
28
28
  ## 3 · Render and open
29
29
 
30
30
  ```bash
31
- npx -y wrapped-agents@1.0.0 --from "<path to wrapped-<year>.json>" --roast "<your line>" --roast-by "<your harness, e.g. Claude Code>"
31
+ npx -y wrapped-agents@1.1.0 --from "<path to wrapped-<year>.json>" --roast "<your line>" --roast-by "<your harness, e.g. Claude Code>"
32
32
  ```
33
33
 
34
34
  If `handle.github` in the file is null, ask the user for their GitHub username first and add `--handle <name>`. If they ask for a different look, add `--skin <wrapped|anthropic|claude-code|codex|opencode|pi|hermes|mistral-vibe|yours>` (default: their most-used harness and its own theme).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "wrapped-agents",
3
- "version": "1.0.0",
4
- "description": "Your year with AI coding agents, wrapped. Claude Code, Codex, Pi, Mistral Vibe. Runs locally; your usage data never leaves your machine.",
3
+ "version": "1.1.0",
4
+ "description": "Your year with AI coding agents, wrapped. Claude Code, Codex, Cursor, Gemini CLI, Qwen Code, OpenCode, Pi, Mistral Vibe. Runs locally; your usage data never leaves your machine.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "wrapped-agents": "src/cli.mjs",
@@ -26,6 +26,10 @@
26
26
  "year in review",
27
27
  "claude code",
28
28
  "codex",
29
+ "cursor",
30
+ "gemini cli",
31
+ "qwen code",
32
+ "opencode",
29
33
  "pi",
30
34
  "mistral vibe",
31
35
  "ai agents",
@@ -38,5 +42,8 @@
38
42
  "type": "git",
39
43
  "url": "git+https://github.com/LeonardoDaviti/agent-wrapped.git"
40
44
  },
41
- "homepage": "https://leonardodaviti.github.io/agent-wrapped/"
45
+ "homepage": "https://leonardodaviti.github.io/agent-wrapped/",
46
+ "bugs": {
47
+ "url": "https://github.com/LeonardoDaviti/agent-wrapped/issues"
48
+ }
42
49
  }
@@ -0,0 +1,43 @@
1
+ // Read-only SQLite for readers, on Node's built-in node:sqlite (Node ≥ 22.5). No dependencies.
2
+ // On older Node (or Bun/Deno without it) sqlite() resolves to null and readers report it in coverage notes.
3
+ let mod; // undefined = not tried, null = unavailable
4
+
5
+ /** node:sqlite's DatabaseSync, or null; the ExperimentalWarning some Node versions print is kept off stderr */
6
+ export async function sqlite() {
7
+ if (mod !== undefined) return mod;
8
+ const orig = process.emitWarning;
9
+ process.emitWarning = function (w, ...a) {
10
+ if (/sqlite/i.test(String((w && w.message) || w))) return;
11
+ return orig.call(this, w, ...a);
12
+ };
13
+ try { mod = (await import('node:sqlite')).DatabaseSync || null; } catch { mod = null; } finally { process.emitWarning = orig; }
14
+ return mod;
15
+ }
16
+
17
+ export const NEEDS_NODE = 'needs Node 22.5+ to read';
18
+
19
+ /** open a database read-only in place (WAL readers never block the app writing it); null if it can't be opened */
20
+ export async function openRO(file) {
21
+ const DB = await sqlite(); if (!DB) return null;
22
+ try { const db = new DB(file, { readOnly: true }); db.prepare('select 1').get(); return db; } catch { return null; }
23
+ }
24
+
25
+ /** rows of a query, streamed when this Node can (StatementSync.iterate), else all at once */
26
+ export function* rows(db, sql, ...params) {
27
+ let st; try { st = db.prepare(sql); } catch { return; }
28
+ if (typeof st.iterate === 'function') { try { yield* st.iterate(...params); } catch {} return; }
29
+ let all = []; try { all = st.all(...params); } catch {}
30
+ yield* all;
31
+ }
32
+
33
+ export function tables(db) {
34
+ const out = new Set();
35
+ for (const r of rows(db, "select name from sqlite_master where type = 'table'")) out.add(r.name);
36
+ return out;
37
+ }
38
+
39
+ export function close(db) { try { db && db.close(); } catch {} }
40
+
41
+
42
+ /** tests only: pretend node:sqlite is missing (true) or reset detection (false) */
43
+ export function _simulateNoSqlite(on) { mod = on ? null : undefined; }
@@ -2,6 +2,7 @@
2
2
  // Nothing here keeps prompt or response text.
3
3
  import fs from 'node:fs';
4
4
  import fsp from 'node:fs/promises';
5
+ import os from 'node:os';
5
6
  import path from 'node:path';
6
7
  import readline from 'node:readline';
7
8
 
@@ -180,3 +181,23 @@ export function mostResumed(promptsBySession) {
180
181
  for (const [, s] of promptsBySession) if (!best || s.days.size > best.days) best = { days: s.days.size, project: s.project ?? null };
181
182
  return best && best.days ? best : null;
182
183
  }
184
+
185
+ /** an environment variable, only when reading the real home (tests pass a fixture home and must not see the user's env) */
186
+ export function realEnv(env, name) {
187
+ return env.home === os.homedir() && process.env[name] ? process.env[name] : null;
188
+ }
189
+
190
+ /** JSON with comments / trailing commas (VS Code settings, opencode.jsonc), parsed leniently; undefined if unreadable */
191
+ export function parseJSONC(text) {
192
+ if (typeof text !== 'string') return undefined;
193
+ let out = '', i = 0, str = false;
194
+ while (i < text.length) {
195
+ const c = text[i], n = text[i + 1];
196
+ if (str) { out += c; if (c === '\\') { out += n ?? ''; i += 2; continue; } if (c === '"') str = false; i++; continue; }
197
+ if (c === '"') { str = true; out += c; i++; continue; }
198
+ if (c === '/' && n === '/') { while (i < text.length && text[i] !== '\n') i++; continue; }
199
+ if (c === '/' && n === '*') { i += 2; while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++; i += 2; continue; }
200
+ out += c; i++;
201
+ }
202
+ try { return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1')); } catch { return undefined; }
203
+ }
@@ -0,0 +1,325 @@
1
+ // Cursor reader: the IDE's agent/chat ("composer") history and the cursor-agent CLI's chats. Beta: built from public
2
+ // write-ups of Cursor's storage (Cursor is closed source and documents none of it), not yet verified on real data.
3
+ //
4
+ // IDE, User dir: ~/.config/Cursor/User (Linux, $XDG_CONFIG_HOME honoured), ~/Library/Application Support/Cursor/User (macOS),
5
+ // %APPDATA%\Cursor\User (Windows). SQLite globalStorage/state.vscdb, table cursorDiskKV(key, value JSON):
6
+ // composerData:<composerId> { createdAt (ms), modelConfig.modelName, subagentInfo.parentComposerId,
7
+ // workspaceIdentifier.uri.fsPath, trackedGitRepos[].repoPath, conversation[] (older, inline) }
8
+ // bubbleId:<composerId>:<bubbleId> one message: { type: 1 user | 2 assistant, text, createdAt (ISO or ms), timingInfo,
9
+ // tokenCount.{inputTokens,outputTokens} (mostly zero since early 2026), modelInfo.modelName,
10
+ // toolFormerData.{name,status,params,rawArgs}, images[] }
11
+ // table composerHeaders(composerId, workspaceId, isSubagent, createdAt) in newer versions;
12
+ // workspaceStorage/<id>/workspace.json { folder: "file:///…" } and older workspaceStorage/<id>/state.vscdb
13
+ // ItemTable 'composer.composerData' { allComposers: [{ composerId }] } map chats to folders.
14
+ // Sources: https://github.com/Callum-Ward/cursaves/blob/main/docs/how-cursor-stores-chats.md
15
+ // https://github.com/SupermodularAI/agents-wake/issues/95 (field prevalence on a real 6 GB store)
16
+ // https://github.com/SergeyGalaxyOrsik/codewrapped/pull/6 (packages/parser/src/adapters/cursor.ts)
17
+ // https://github.com/f/agentlytics/blob/master/CONTRIBUTING.md
18
+ // ItemTable in the global database holds Cursor's login tokens and is never queried.
19
+ //
20
+ // CLI (cursor-agent): ${CURSOR_CONFIG_DIR:-~/.cursor}/chats/<md5(cwd)>/<chatId>/store.db (+ meta.json { cwd, createdAtMs }):
21
+ // meta(key, value = hex JSON { agentId, createdAt, lastUsedModel, latestRootBlobId, name, mode }), blobs(id, data):
22
+ // the root blob is protobuf whose repeated field 1 lists 32-byte digests of message blobs, each JSON { role, content } in
23
+ // the Vercel AI SDK shape (text / reasoning / tool-call parts). No per-message time is stored: a user turn's
24
+ // <timestamp>…</timestamp> block is used when present, else the chat's start.
25
+ // Sources: https://vshulcz.github.io/deja-vu/registry/cursor , https://github.com/seanthegeek/doubleagent/issues/235
26
+ import path from 'node:path';
27
+ import fsp from 'node:fs/promises';
28
+ import { fileURLToPath } from 'node:url';
29
+ import {
30
+ readJSON, readText, exists, localDate, windowOf, basename, maxConcurrent, gitUndoKinds, emptyUndos, phraseCounts,
31
+ emptyAssistant, addPhrases, inc, addTok, emptyFacts, day, countPromptTime, finishCoverage, longestSession, mostResumed,
32
+ realEnv, parseJSONC, parse,
33
+ } from './_util.mjs';
34
+ import { PromptStats } from './_prompts.mjs';
35
+ import { sqlite, openRO, rows, tables, close, NEEDS_NODE } from './_sqlite.mjs';
36
+
37
+ export const id = 'cursor';
38
+ export const label = 'Cursor';
39
+ export const BETA = "beta reader (built from Cursor's storage as documented by community tools, not yet verified on real data)";
40
+
41
+ const uniq = a => [...new Set(a.filter(Boolean))];
42
+ function userDirs(env) {
43
+ const h = env.home; const xdg = realEnv(env, 'XDG_CONFIG_HOME'); const app = realEnv(env, 'APPDATA');
44
+ return uniq([
45
+ xdg && path.join(xdg, 'Cursor', 'User'), path.join(h, '.config', 'Cursor', 'User'),
46
+ path.join(h, 'Library', 'Application Support', 'Cursor', 'User'),
47
+ app && path.join(app, 'Cursor', 'User'), path.join(h, 'AppData', 'Roaming', 'Cursor', 'User'),
48
+ ]);
49
+ }
50
+ function cliDirs(env) {
51
+ const xdg = realEnv(env, 'XDG_CONFIG_HOME');
52
+ return uniq([realEnv(env, 'CURSOR_CONFIG_DIR'), path.join(env.home, '.cursor'), xdg && path.join(xdg, 'cursor'), path.join(env.home, '.config', 'cursor')]);
53
+ }
54
+
55
+ async function cliStores(env) {
56
+ const out = [];
57
+ for (const d of cliDirs(env)) {
58
+ const chats = path.join(d, 'chats');
59
+ let ws = []; try { ws = await fsp.readdir(chats); } catch { continue; }
60
+ for (const w of ws) {
61
+ let ids = []; try { ids = await fsp.readdir(path.join(chats, w)); } catch { continue; }
62
+ for (const c of ids) { const f = path.join(chats, w, c, 'store.db'); if (await exists(f)) out.push(f); }
63
+ }
64
+ }
65
+ return out;
66
+ }
67
+
68
+ export async function detect(env) {
69
+ const roots = [];
70
+ for (const u of userDirs(env)) if (await exists(path.join(u, 'globalStorage', 'state.vscdb'))) roots.push(path.join(u, 'globalStorage', 'state.vscdb'));
71
+ for (const f of await cliStores(env)) roots.push(path.dirname(path.dirname(path.dirname(f)))); // …/chats
72
+ return { found: roots.length > 0, roots: uniq(roots) };
73
+ }
74
+
75
+ const SHELL = /^(run_terminal_cmd|run_terminal_command(_v\d)?|shell|bash|terminal)$/i;
76
+ const modelName = m => (m === 'default' ? 'cursor-auto' : m || null); // Cursor saves its "Auto" model as "default"
77
+ /** ISO string or epoch ms (Cursor has written both); NaN if unknown */
78
+ const when = v => (typeof v === 'number' ? (v > 1e12 ? v : NaN) : typeof v === 'string' ? (/^\d+$/.test(v) ? +v : Date.parse(v)) : NaN);
79
+ const firstOk = (...v) => { for (const x of v) { const t = when(x); if (Number.isFinite(t)) return t; } return NaN; };
80
+
81
+ function uriPath(u) {
82
+ try { const x = new URL(u); return x.protocol === 'file:' ? fileURLToPath(x) : decodeURIComponent(x.pathname || ''); } catch { return null; }
83
+ }
84
+
85
+ class Acc {
86
+ constructor(w) {
87
+ this.w = w; this.f = emptyFacts(id, label); this.ps = new PromptStats();
88
+ this.sessions = new Map(); this.bySession = new Map(); this.concEv = []; this.undos = emptyUndos(); this.assistant = emptyAssistant();
89
+ this.subs = new Set(); this.tokensSeen = false;
90
+ }
91
+ in(ms) { return ms >= this.w.start && ms < this.w.end; }
92
+ time(sid, proj, ms) { if (!this.in(ms)) return; const s = this.sessions.get(sid) || { t: [], project: proj }; s.t.push(ms); this.sessions.set(sid, s); }
93
+ prompt(sid, proj, ms, text, images) {
94
+ if (!this.in(ms)) return;
95
+ this.ps.add(text, { images }); countPromptTime(this.f, ms); this.concEv.push([ms, sid]); this.time(sid, proj, ms);
96
+ if (proj) inc(this.f.projects, proj);
97
+ const b = this.bySession.get(sid) || { days: new Set(), project: proj }; b.days.add(localDate(ms)); this.bySession.set(sid, b);
98
+ }
99
+ tokens(model, ms, i, o) {
100
+ if (!this.in(ms) || !(i + o)) return;
101
+ this.tokensSeen = true; addTok(this.f.models, model || 'cursor-unknown', ms, i, o, 0, 0); day(this.f, localDate(ms)).tokens += i + o;
102
+ }
103
+ tool(name, cmd) {
104
+ inc(this.f.tools, name);
105
+ if (cmd && SHELL.test(name)) { const u = gitUndoKinds(String(cmd)); if (u) for (const k of u) this.undos[k]++; }
106
+ }
107
+ }
108
+
109
+ // ------------------------------------------------------------------ IDE
110
+ const V = "cast(value as text)";
111
+ const COMPOSERS = `select substr(key, 14) as id, json_extract(v, '$.createdAt') as created, json_extract(v, '$.modelConfig.modelName') as model,
112
+ json_extract(v, '$.subagentInfo.parentComposerId') as parent, json_extract(v, '$.workspaceIdentifier.uri.fsPath') as folder,
113
+ json_extract(v, '$.trackedGitRepos[0].repoPath') as git, json_array_length(v, '$.conversation') as inline
114
+ from (select key, ${V} as v from cursorDiskKV where key >= 'composerData:' and key < 'composerData;') where json_valid(v)`;
115
+ const BUBBLE_COLS = (j) => `json_extract(${j}, '$.type') as type, json_extract(${j}, '$.createdAt') as created, json_extract(${j}, '$.timestamp') as ts,
116
+ json_extract(${j}, '$.timingInfo.clientStartTime') as cst, json_extract(${j}, '$.timingInfo.clientEndTime') as cet,
117
+ json_extract(${j}, '$.tokenCount.inputTokens') as ti, json_extract(${j}, '$.tokenCount.outputTokens') as tout,
118
+ json_extract(${j}, '$.modelInfo.modelName') as model, json_extract(${j}, '$.toolFormerData.name') as tool,
119
+ coalesce(json_extract(${j}, '$.text'), json_extract(${j}, '$.rawText')) as text, json_array_length(${j}, '$.images') as images,
120
+ json_extract(${j}, '$.toolFormerData.params') as params, json_extract(${j}, '$.toolFormerData.rawArgs') as raw`;
121
+ const BUBBLES = `select key, ${BUBBLE_COLS('v')} from (select key, ${V} as v from cursorDiskKV where key >= 'bubbleId:' and key < 'bubbleId;') where json_valid(v) order by key`;
122
+ const INLINE = `select ${BUBBLE_COLS('j.value')} from cursorDiskKV as k, json_each(cast(k.value as text), '$.conversation') as j
123
+ where k.key = ? and json_valid(cast(k.value as text))`;
124
+
125
+ function command(b) {
126
+ for (const s of [b.params, b.raw]) { const o = typeof s === 'string' ? parse(s) : s; if (o && typeof o === 'object' && typeof o.command === 'string') return o.command; }
127
+ return null;
128
+ }
129
+
130
+ async function workspaceFolders(userDir) {
131
+ // workspace id → folder name, and composer id → workspace id from older per-workspace lists
132
+ const root = path.join(userDir, 'workspaceStorage'); const folders = new Map(); const chatWs = new Map();
133
+ let ids = []; try { ids = await fsp.readdir(root); } catch { return { folders, chatWs }; }
134
+ for (const ws of ids) {
135
+ const wj = await readJSON(path.join(root, ws, 'workspace.json'));
136
+ const u = wj && (wj.folder || wj.workspace); if (u) folders.set(ws, basename(uriPath(u) || '').replace(/\.code-workspace$/, '') || null);
137
+ const db = await openRO(path.join(root, ws, 'state.vscdb')); if (!db) continue;
138
+ try {
139
+ for (const r of rows(db, "select cast(value as text) as v from ItemTable where key = 'composer.composerData'")) {
140
+ const o = parse(r.v); for (const c of (o && Array.isArray(o.allComposers) ? o.allComposers : [])) if (c && c.composerId) chatWs.set(c.composerId, ws);
141
+ }
142
+ } finally { close(db); }
143
+ }
144
+ return { folders, chatWs };
145
+ }
146
+
147
+ async function readIDE(acc, file, userDir, seen) {
148
+ const db = await openRO(file); if (!db) { acc.f.coverage.notes.push('could not open Cursor state.vscdb'); return; }
149
+ try {
150
+ const t = tables(db); if (!t.has('cursorDiskKV')) return;
151
+ const comp = new Map(); for (const r of rows(db, COMPOSERS)) comp.set(r.id, r);
152
+ const headers = new Map();
153
+ if (t.has('composerHeaders')) for (const r of rows(db, 'select composerId, workspaceId, isSubagent from composerHeaders')) headers.set(r.composerId, r);
154
+ const { folders, chatWs } = await workspaceFolders(userDir);
155
+ const project = cid => {
156
+ const c = comp.get(cid) || {}; if (c.folder || c.git) return basename(c.folder || c.git);
157
+ const ws = (headers.get(cid) || {}).workspaceId || chatWs.get(cid); return (ws && folders.get(ws)) || null;
158
+ };
159
+ const isSub = cid => !!((comp.get(cid) || {}).parent || (headers.get(cid) || {}).isSubagent);
160
+ let n = 0;
161
+ const handle = (cid, list) => {
162
+ if (seen.has(cid)) return; seen.add(cid);
163
+ const c = comp.get(cid) || {}; const sub = isSub(cid); const proj = project(cid);
164
+ let model = modelName(c.model); const start = when(c.created); let active = false;
165
+ for (const b of list) {
166
+ if (typeof b.type !== 'number') continue; // partial rows (a checkpoint id, a token count alone)
167
+ const ms = firstOk(b.created, b.ts, b.cst, start); if (!Number.isFinite(ms) || !acc.in(ms)) continue;
168
+ active = true;
169
+ if (b.type === 1) {
170
+ model = modelName(b.model) || model;
171
+ if (sub) continue;
172
+ const text = String(b.text || ''); const images = +b.images || 0;
173
+ if (!text.trim() && !images) continue;
174
+ acc.prompt(cid, proj, ms, text, images);
175
+ } else {
176
+ if (!sub) { acc.time(cid, proj, ms); const end = when(b.cet); if (end > ms) acc.time(cid, proj, end); }
177
+ acc.tokens(modelName(b.model) || model, ms, +b.ti || 0, +b.tout || 0);
178
+ if (b.tool) acc.tool(String(b.tool), command(b));
179
+ else if (b.text) addPhrases(acc.assistant, phraseCounts(String(b.text)));
180
+ }
181
+ }
182
+ if (sub && active) acc.subs.add(cid);
183
+ if (active) n++;
184
+ };
185
+ // newer: one row per bubble, keys sorted so a composer's bubbles arrive together
186
+ let cur = null, buf = [];
187
+ for (const r of rows(db, BUBBLES)) {
188
+ const cid = r.key.slice(9, r.key.indexOf(':', 9));
189
+ if (cid !== cur) { if (cur) handle(cur, buf.sort(byTime)); cur = cid; buf = []; }
190
+ buf.push(r);
191
+ }
192
+ if (cur) handle(cur, buf.sort(byTime));
193
+ // older: bubbles inline in composerData.conversation
194
+ for (const [cid, c] of comp) if (c.inline > 0 && !seen.has(cid)) handle(cid, [...rows(db, INLINE, 'composerData:' + cid)]);
195
+ if (n) acc.f.coverage.sources.push('Cursor/User/globalStorage/state.vscdb (composerData, bubbleId)');
196
+ } finally { close(db); }
197
+ }
198
+ const byTime = (a, b) => (firstOk(a.created, a.ts, a.cst) || 0) - (firstOk(b.created, b.ts, b.cst) || 0);
199
+
200
+ // ------------------------------------------------------------------ CLI
201
+ function varint(buf, i) { let v = 0, m = 1, b; do { b = buf[i++]; v += (b & 127) * m; m *= 128; } while (b & 128 && i < buf.length); return [v, i]; }
202
+ /** repeated bytes field 1 of a protobuf message */
203
+ function pbField1(buf) {
204
+ const out = []; let i = 0;
205
+ while (i < buf.length) {
206
+ let tag; [tag, i] = varint(buf, i); const f = Math.floor(tag / 8), wt = tag & 7;
207
+ if (wt === 2) { let len; [len, i] = varint(buf, i); if (f === 1) out.push(buf.subarray(i, i + len)); i += len; }
208
+ else if (wt === 0) [, i] = varint(buf, i);
209
+ else if (wt === 1) i += 8; else if (wt === 5) i += 4; else break;
210
+ }
211
+ return out;
212
+ }
213
+ const MONTHS = { jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5, jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11 };
214
+ /** "<timestamp>Sunday, Jul 26, 2026, 1:06 PM (UTC+3)</timestamp>" → epoch ms */
215
+ export function turnTime(text) {
216
+ const m = /<timestamp>[^<]*?([A-Za-z]{3})[a-z]*\.? (\d{1,2}), (\d{4}),? (\d{1,2}):(\d{2})\s*(AM|PM)?\s*\(UTC([+-]\d{1,2})?(?::?(\d{2}))?\)/i.exec(text);
217
+ if (!m) return NaN;
218
+ const mo = MONTHS[m[1].toLowerCase()]; if (mo == null) return NaN;
219
+ let h = +m[4] % (m[6] ? 12 : 24); if (m[6] && m[6].toUpperCase() === 'PM') h += 12;
220
+ const off = (+(m[7] || 0)) * 60 + Math.sign(+(m[7] || 0) || 1) * (+(m[8] || 0));
221
+ return Date.UTC(+m[3], mo, +m[2], h, +m[5]) - off * 60e3;
222
+ }
223
+ const contentText = c => (typeof c === 'string' ? c : Array.isArray(c) ? c.filter(p => p && p.type === 'text').map(p => p.text || '').join(' ') : '');
224
+ const userQuery = t => { const q = /<user_query>([\s\S]*?)<\/user_query>/.exec(t); return q ? q[1] : t; };
225
+
226
+ async function readCLI(acc, file) {
227
+ const db = await openRO(file); if (!db) return false;
228
+ try {
229
+ const t = tables(db); if (!t.has('blobs')) return false;
230
+ const mj = await readJSON(path.join(path.dirname(file), 'meta.json')) || {};
231
+ let meta = {};
232
+ if (t.has('meta')) for (const r of rows(db, 'select value from meta')) {
233
+ const v = String(r.value || ''); const o = /^[0-9a-f]+$/i.test(v) ? parse(Buffer.from(v, 'hex').toString('utf8')) : parse(v);
234
+ if (o && typeof o === 'object') meta = { ...meta, ...o };
235
+ }
236
+ const sid = meta.agentId || path.basename(path.dirname(file));
237
+ const proj = basename(mj.cwd || meta.cwd);
238
+ const start = firstOk(mj.createdAtMs, meta.createdAt, mj.createdAt);
239
+ const blob = idHex => { for (const r of rows(db, 'select data from blobs where id = ?', idHex)) return r.data; return null; };
240
+ const asMsg = data => { if (!data) return null; const s = Buffer.from(data).toString('utf8'); return s[0] === '{' ? parse(s) : null; };
241
+ let msgs = [];
242
+ const root = meta.latestRootBlobId && blob(meta.latestRootBlobId);
243
+ if (root && !asMsg(root)) for (const d of pbField1(Buffer.from(root))) { const m = asMsg(blob(Buffer.from(d).toString('hex'))); if (m) msgs.push(m); }
244
+ if (!msgs.length) for (const r of rows(db, 'select data from blobs')) { const m = asMsg(r.data); if (m && m.role) msgs.push(m); }
245
+ let last = start;
246
+ for (const m of msgs) {
247
+ if (m.role === 'user') {
248
+ const raw = contentText(m.content); const tt = turnTime(raw); if (Number.isFinite(tt)) last = tt;
249
+ const text = userQuery(raw).replace(/<(user_info|timestamp|system_reminder|attached_files)[^>]*>[\s\S]*?<\/\1>/g, ' ').trim();
250
+ if (!text) continue;
251
+ acc.prompt(sid, proj, last, text, Array.isArray(m.content) ? m.content.filter(p => p && p.type === 'image').length : 0);
252
+ } else if (m.role === 'assistant') {
253
+ acc.time(sid, proj, last);
254
+ for (const p of Array.isArray(m.content) ? m.content : []) {
255
+ if (!p || typeof p !== 'object') continue;
256
+ if (p.type === 'tool-call' && p.toolName) acc.tool(String(p.toolName), (p.args || {}).command);
257
+ else if (p.type === 'text') addPhrases(acc.assistant, phraseCounts(p.text));
258
+ }
259
+ for (const tc of Array.isArray(m.tool_calls) ? m.tool_calls : []) if (tc && tc.function && tc.function.name) acc.tool(String(tc.function.name), (parse(tc.function.arguments) || {}).command);
260
+ }
261
+ }
262
+ const end = firstOk(mj.updatedAtMs); if (acc.sessions.has(sid) && Number.isFinite(end)) acc.time(sid, proj, end);
263
+ return msgs.length > 0;
264
+ } finally { close(db); }
265
+ }
266
+
267
+ // ------------------------------------------------------------------ read
268
+ export async function read(env, opts = {}) {
269
+ const w = windowOf(env, opts); const progress = opts.onProgress || (() => {});
270
+ const acc = new Acc(w); const f = acc.f;
271
+ f.coverage.notes.push(BETA);
272
+ const ides = []; for (const u of userDirs(env)) { const g = path.join(u, 'globalStorage', 'state.vscdb'); if (await exists(g)) ides.push([g, u]); }
273
+ const clis = await cliStores(env);
274
+ f.theme = await readTheme(env);
275
+ if ((ides.length || clis.length) && !(await sqlite())) {
276
+ f.coverage.notes.push(`${NEEDS_NODE} Cursor's database`);
277
+ f.prompts = null; f.sessions.count = null; f.toolCalls = null;
278
+ return finishCoverage(f);
279
+ }
280
+ const seen = new Set();
281
+ for (const [g, u] of ides) { progress('Cursor: state.vscdb'); await readIDE(acc, g, u, seen); }
282
+ let cliN = 0;
283
+ for (const s of clis) if (await readCLI(acc, s)) cliN++;
284
+ if (cliN) { f.coverage.sources.push('~/.cursor/chats/*/*/store.db'); f.coverage.notes.push('cursor-agent CLI keeps no per-message time: prompts are dated by their <timestamp> block or the chat start'); }
285
+
286
+ for (const [, s] of acc.sessions) {
287
+ let mn = Infinity; for (const t of s.t) { if (t < mn) mn = t; day(f, localDate(t)); }
288
+ day(f, localDate(mn)).sessions++; f.sessions.count++;
289
+ }
290
+ f.sessions.longest = longestSession(acc.sessions);
291
+ f.sessions.mostResumed = mostResumed(acc.bySession);
292
+ f.sessions.maxConcurrent = maxConcurrent(acc.concEv);
293
+ f.prompts = acc.ps.toJSON(); f.slash = acc.ps.slash;
294
+ f.subagents = acc.subs.size;
295
+ f.interrupts = null; f.compactions = null; f.rateLimits = null; f.lines = null; f.rewinds = null;
296
+ f.gitUndos = acc.undos; f.assistant = acc.assistant;
297
+ f.projects = Object.fromEntries(Object.entries(f.projects).sort((a, b) => b[1] - a[1]).slice(0, 20));
298
+ if (!acc.tokensSeen && (ides.length || cliN)) f.coverage.notes.push('no token counts: Cursor keeps them locally only on some older chats');
299
+ return finishCoverage(f);
300
+ }
301
+
302
+ // ------------------------------------------------------------------ theme (User/settings.json)
303
+ const BUILTIN = /^(cursor|default|visual studio|dark modern|light modern|dark\+|light\+|dark high contrast|light high contrast|abyss|kimbie|monokai|quiet light|red|solarized|tomorrow night blue)/i;
304
+
305
+ async function readTheme(env) {
306
+ for (const u of userDirs(env)) {
307
+ const s = parseJSONC(await readText(path.join(u, 'settings.json'))); if (!s) continue;
308
+ const name = typeof s['workbench.colorTheme'] === 'string' ? s['workbench.colorTheme'] : null;
309
+ const cc = s['workbench.colorCustomizations'] && typeof s['workbench.colorCustomizations'] === 'object' ? s['workbench.colorCustomizations'] : {};
310
+ const scoped = name && cc[`[${name}]`] && typeof cc[`[${name}]`] === 'object' ? cc[`[${name}]`] : {};
311
+ const all = { ...cc, ...scoped };
312
+ const hex = k => (typeof all[k] === 'string' && /^#[0-9a-f]{3,8}$/i.test(all[k]) ? all[k].toLowerCase() : null);
313
+ const pick = (...ks) => { for (const k of ks) { const c = hex(k); if (c) return c; } return null; };
314
+ const colors = {
315
+ background: pick('editor.background'), foreground: pick('editor.foreground', 'foreground'),
316
+ primary: pick('focusBorder', 'button.background', 'activityBarBadge.background'), accent: pick('activityBarBadge.background', 'textLink.foreground'),
317
+ surface: pick('sideBar.background', 'panel.background'), success: pick('terminal.ansiGreen', 'gitDecoration.addedResourceForeground'),
318
+ };
319
+ const has = Object.values(colors).some(Boolean);
320
+ if (!name && !has) continue;
321
+ const n = name || 'Cursor Dark';
322
+ return { name: n, builtin: BUILTIN.test(n) && !has, colors: has ? colors : null };
323
+ }
324
+ return null;
325
+ }
@@ -0,0 +1,323 @@
1
+ // Gemini CLI reader, plus the shared reader for Qwen Code (qwen-code.mjs). Beta: built from the tools' source, not yet
2
+ // verified on real data. Read from the public repositories only; no Google service or API is used.
3
+ //
4
+ // Gemini CLI (github.com/google-gemini/gemini-cli), runtime dir ~/.gemini (or $GEMINI_CLI_HOME/.gemini):
5
+ // tmp/<project>/chats/session-<time>-<id>.jsonl one session; <project> is a slug (projects.json) or an older sha256 hash
6
+ // tmp/<project>/chats/<parentSessionId>/<id>.jsonl subagent sessions (kind: 'subagent')
7
+ // tmp/<project>/chats/session-*.json older whole-file ConversationRecord
8
+ // tmp/<project>/logs.json [{ sessionId, messageId, timestamp, type: 'user', message }] prompt log
9
+ // JSONL lines: a metadata record { sessionId, projectHash, startTime, kind }, MessageRecord { id, timestamp, type:
10
+ // 'user'|'gemini'|'info'|'error'|'warning', content, displayContent, tokens: { input, output, cached, thoughts, tool, total },
11
+ // model, toolCalls: [{ name, args, status }] } (re-appended with the same id when updated), { $rewindTo }, { $patch }, { $set }.
12
+ // https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingTypes.ts
13
+ // https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/chatRecordingService.ts
14
+ // https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/config/storage.ts
15
+ // tokens.input is promptTokenCount, which includes tokens.cached (Gemini usage metadata), so input = input − cached.
16
+ // Theme: settings.json `ui.theme` (older: top-level `theme`); custom themes in `ui.customThemes` / `customThemes` or ~/.gemini/theme.json.
17
+ // https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/themes.md
18
+ //
19
+ // Qwen Code (github.com/QwenLM/qwen-code) forked Gemini CLI but now writes its own format, ~/.qwen (or $QWEN_HOME):
20
+ // projects/<sanitized-cwd>/chats/<sessionId>.jsonl, one ChatRecord per line: { uuid, parentUuid, sessionId, timestamp,
21
+ // type: 'user'|'assistant'|'tool_result'|'system', subtype?, provenance?, isSidechain?, agentId?, cwd, version, message:
22
+ // { role, parts }, model, usageMetadata: { promptTokenCount, candidatesTokenCount, cachedContentTokenCount,
23
+ // thoughtsTokenCount, toolUsePromptTokenCount }, systemPayload } (system subtypes: chat_compression, slash_command, rewind…)
24
+ // https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/services/chatRecordingService.ts
25
+ // https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/config/storage.ts
26
+ // Older Qwen Code versions wrote the Gemini layout under ~/.qwen/tmp/, which is read the same way as Gemini CLI.
27
+ import path from 'node:path';
28
+ import {
29
+ eachLine, parse, readJSON, isDir, walk, localDate, toMs, windowOf, basename, maxConcurrent, gitUndoKinds,
30
+ emptyUndos, phraseCounts, emptyAssistant, addPhrases, inc, addTok, emptyFacts, day, countPromptTime, finishCoverage,
31
+ longestSession, mostResumed, realEnv,
32
+ } from './_util.mjs';
33
+ import { PromptStats } from './_prompts.mjs';
34
+ import { mapFiles } from './_pool.mjs';
35
+
36
+ const RATE = /\b429\b|rate.?limit|too many requests|quota|resource.?exhausted/i;
37
+ const SHELL = /^(run_shell_command|shell|bash)$/i;
38
+ const IGNORED = /^(<session_context>|<hook_context>|\?)/; // not prompts (sessionUtils.isIgnoredUserContent); '/' kept as slash
39
+
40
+ /** text and image count from a Gemini PartListUnion */
41
+ function partsText(c) {
42
+ if (typeof c === 'string') return { text: c, images: 0 };
43
+ const arr = Array.isArray(c) ? c : c && typeof c === 'object' ? [c] : [];
44
+ let text = '', images = 0, other = false;
45
+ for (const p of arr) {
46
+ if (typeof p === 'string') { text += (text ? ' ' : '') + p; continue; }
47
+ if (!p || typeof p !== 'object') continue;
48
+ if (typeof p.text === 'string' && !p.thought) text += (text ? ' ' : '') + p.text;
49
+ else if (/^image\//.test(String((p.inlineData || p.fileData || {}).mimeType || ''))) images++;
50
+ else if (p.functionResponse || p.functionCall) other = true;
51
+ }
52
+ return { text, images, other };
53
+ }
54
+
55
+ // ------------------------------------------------------------------ Gemini layout (one file, in a worker)
56
+ export async function scanGeminiFile(file, ctx) {
57
+ const win = ms => ms >= ctx.start && ms < ctx.end;
58
+ const msgs = new Map(); let meta = {}; let rewinds = 0;
59
+ const take = m => { if (m && typeof m.id === 'string' && m.type) msgs.set(m.id, m); };
60
+ if (file.endsWith('.json')) {
61
+ const o = await readJSON(file); if (!o || typeof o !== 'object') return null;
62
+ meta = o; for (const m of Array.isArray(o.messages) ? o.messages : []) take(m);
63
+ } else {
64
+ await eachLine(file, line => {
65
+ const o = parse(line); if (!o || typeof o !== 'object') return;
66
+ if (typeof o.$rewindTo === 'string') { rewinds++; return; }
67
+ if (o.$patch) { const p = o.$patch; const ups = [p, ...(Array.isArray(p.updates) ? p.updates : [])];
68
+ for (const u of ups) { const m = u && msgs.get(u.id); if (m && u.content !== undefined) m.content = u.content; } return; }
69
+ if (o.$set && typeof o.$set === 'object') { meta = { ...meta, ...o.$set }; for (const m of Array.isArray(o.$set.messages) ? o.$set.messages : []) take(m); return; }
70
+ if (typeof o.sessionId === 'string' && typeof o.projectHash === 'string') { meta = { ...meta, ...o }; for (const m of Array.isArray(o.messages) ? o.messages : []) take(m); return; }
71
+ take(o); // a message record; a later copy with the same id is the updated one
72
+ });
73
+ }
74
+ const r = { sid: meta.sessionId || path.basename(file).replace(/\.jsonl?$/, ''), sub: meta.kind === 'subagent', t: [], prompts: [], models: [],
75
+ tools: [], undo: [], phr: [], rl: [], rewinds: 0 };
76
+ for (const m of msgs.values()) {
77
+ const ms = toMs(m.timestamp); if (!win(ms)) continue;
78
+ r.t.push(ms);
79
+ if (m.type === 'user') {
80
+ const { text, images, other } = partsText(m.displayContent ?? m.content);
81
+ const t = text.trim();
82
+ if ((!t && !images) || IGNORED.test(t) || (other && !t)) continue;
83
+ r.prompts.push([ms, text, images]);
84
+ } else if (m.type === 'gemini') {
85
+ const k = m.tokens;
86
+ if (k && typeof k === 'object') {
87
+ const cached = +k.cached || 0, inp = Math.max(0, (+k.input || 0) - cached) + (+k.tool || 0);
88
+ r.models.push([m.model || '?', ms, inp, (+k.output || 0) + (+k.thoughts || 0), cached]);
89
+ }
90
+ for (const tc of Array.isArray(m.toolCalls) ? m.toolCalls : []) {
91
+ if (!tc || !tc.name) continue; r.tools.push(String(tc.name));
92
+ if (SHELL.test(tc.name)) { const u = gitUndoKinds(String((tc.args || {}).command || '')); if (u) r.undo.push(u); }
93
+ }
94
+ const pc = phraseCounts(partsText(m.content).text); if (pc) r.phr.push(pc);
95
+ } else if (m.type === 'error') {
96
+ if (RATE.test(partsText(m.content).text)) r.rl.push(ms);
97
+ }
98
+ }
99
+ if (r.t.length) r.rewinds = rewinds;
100
+ return r;
101
+ }
102
+
103
+ // ------------------------------------------------------------------ Qwen Code layout (one file, in a worker)
104
+ export async function scanQwenFile(file, ctx) {
105
+ const win = ms => ms >= ctx.start && ms < ctx.end;
106
+ const r = { sid: path.basename(file, '.jsonl'), cwd: null, version: null, vAt: 0, t: [], prompts: [], models: [], tools: [], undo: [], phr: [],
107
+ rl: [], rewinds: 0, compactions: 0, slash: [], agents: [], uuids: [] };
108
+ await eachLine(file, line => {
109
+ const o = parse(line); if (!o || typeof o !== 'object' || !o.type) return;
110
+ const ms = toMs(o.timestamp);
111
+ if (o.version && ms >= r.vAt) { r.version = String(o.version); r.vAt = ms; }
112
+ if (!win(ms)) return;
113
+ if (o.sessionId) r.sid = o.sessionId;
114
+ if (o.forkedFrom) return; // a /branch copy of a record already counted in its source session
115
+ if (o.uuid) r.uuids.push(o.uuid); // backstop: any other copy with the same uuid is de-duplicated on the main thread
116
+ const k = o.uuid || null; const side = !!o.isSidechain;
117
+ if (!side && o.cwd && !r.cwd) r.cwd = o.cwd;
118
+ if (!side) r.t.push([k, ms]);
119
+ if (side && o.agentId) r.agents.push(String(o.agentId));
120
+ const parts = (o.message && o.message.parts) || [];
121
+ if (o.type === 'user') {
122
+ if (side || (o.provenance && o.provenance !== 'real_user') || (o.subtype && o.subtype !== 'mid_turn_user_message')) return;
123
+ const pt = partsText(parts); const sp = o.systemPayload || {};
124
+ const text = typeof sp.displayText === 'string' && sp.displayText ? sp.displayText : pt.text;
125
+ const t = text.trim();
126
+ if ((!t && !pt.images) || IGNORED.test(t) || (pt.other && !t) || t.startsWith('/')) return; // slash commands come from system records
127
+ r.prompts.push([k, ms, text, pt.images]);
128
+ } else if (o.type === 'assistant') {
129
+ const u = o.usageMetadata;
130
+ if (u && typeof u === 'object') {
131
+ const cached = +u.cachedContentTokenCount || 0;
132
+ r.models.push([k, o.model || '?', ms, Math.max(0, (+u.promptTokenCount || 0) - cached) + (+u.toolUsePromptTokenCount || 0), (+u.candidatesTokenCount || 0) + (+u.thoughtsTokenCount || 0), cached]);
133
+ }
134
+ for (const p of Array.isArray(parts) ? parts : []) {
135
+ const fc = p && p.functionCall; if (!fc || !fc.name) continue;
136
+ r.tools.push([k, String(fc.name)]);
137
+ if (SHELL.test(fc.name)) { const g = gitUndoKinds(String((fc.args || {}).command || '')); if (g) r.undo.push([k, g]); }
138
+ }
139
+ if (!side) { const pc = phraseCounts(partsText(parts).text); if (pc) r.phr.push([k, pc]); }
140
+ } else if (o.type === 'system') {
141
+ const sp = o.systemPayload || {};
142
+ if (o.subtype === 'chat_compression') r.compactions++;
143
+ else if (o.subtype === 'rewind') r.rewinds++;
144
+ else if (o.subtype === 'slash_command' && sp.phase === 'invocation' && typeof sp.rawCommand === 'string' && !side) r.slash.push([k, ms, sp.rawCommand]);
145
+ else if (o.subtype === 'turn_result' && RATE.test(JSON.stringify(sp.error || ''))) r.rl.push(ms);
146
+ }
147
+ });
148
+ return r;
149
+ }
150
+
151
+ // ------------------------------------------------------------------ reader factory
152
+ const BUILTIN = new Set(['ansi', 'atom one', 'ayu', 'default', 'dracula', 'github', 'holiday', 'shades of purple', 'solarized dark', 'tokyo night',
153
+ 'ansi light', 'ayu light', 'default light', 'github light', 'google code', 'solarized light', 'xcode', 'no color', 'qwen dark', 'qwen light',
154
+ 'github dark colorblind', 'github light colorblind']);
155
+
156
+ /** cfg: { id, label, tool, dir: '.gemini', homeEnv: 'GEMINI_CLI_HOME', qwen: bool } */
157
+ export function makeReader(cfg) {
158
+ const BETA = `beta reader (built from ${cfg.tool}'s source, not yet verified on real data)`;
159
+ const base = env => {
160
+ const h = realEnv(env, cfg.homeEnv);
161
+ return cfg.qwen ? (h || path.join(env.home, cfg.dir)) : path.join(h || env.home, cfg.dir);
162
+ };
163
+ // Qwen Code keeps sessions under $QWEN_RUNTIME_DIR when set, settings under $QWEN_HOME
164
+ const runBase = env => (cfg.qwen && realEnv(env, 'QWEN_RUNTIME_DIR')) || base(env);
165
+ const roots = async env => {
166
+ const b = runBase(env); const out = [];
167
+ if (await isDir(path.join(b, 'tmp'))) out.push(path.join(b, 'tmp'));
168
+ if (cfg.qwen && await isDir(path.join(b, 'projects'))) out.push(path.join(b, 'projects'));
169
+ return out;
170
+ };
171
+
172
+ async function detect(env) {
173
+ // tmp/ exists for every install; it is found only when it holds a session or a prompt log
174
+ const out = [];
175
+ for (const r of await roots(env)) {
176
+ const hit = (await walk(r, (n, p) => /\.jsonl?$/.test(n) && (/[\\/]chats[\\/]/.test(p) || n === 'logs.json'))).length > 0;
177
+ if (hit) out.push(r);
178
+ }
179
+ return { found: out.length > 0, roots: out };
180
+ }
181
+
182
+ async function read(env, opts = {}) {
183
+ const w = windowOf(env, opts); const progress = opts.onProgress || (() => {});
184
+ const f = emptyFacts(cfg.id, cfg.label); const ps = new PromptStats(); const b = base(env); const rb = runBase(env);
185
+ f.coverage.notes.push(BETA);
186
+ const sessions = new Map(); const bySession = new Map(); const concEv = [];
187
+ const undos = emptyUndos(); const assistant = emptyAssistant(); const rlDays = new Set();
188
+ let rlHits = 0, subagents = 0, rewinds = 0, compactions = null; const agentIds = new Set();
189
+ const projectName = await projectNames(b);
190
+ const promptAt = (sid, proj, ms, text, images) => {
191
+ ps.add(text, { images }); countPromptTime(f, ms); concEv.push([ms, sid]);
192
+ if (proj) inc(f.projects, proj);
193
+ const s = bySession.get(sid) || { days: new Set(), project: proj }; s.days.add(localDate(ms)); bySession.set(sid, s);
194
+ };
195
+ const times = (sid, proj, list) => { if (!list.length) return; const s = sessions.get(sid) || { t: [], project: proj }; for (const t of list) s.t.push(t); sessions.set(sid, s); };
196
+ const tok = (model, ms, i, o, cr) => { addTok(f.models, model, ms, i, o, cr, 0); day(f, localDate(ms)).tokens += i + o + cr; };
197
+
198
+ // Gemini layout: tmp/<project>/chats/**
199
+ const tmp = path.join(rb, 'tmp');
200
+ const gfiles = (await isDir(tmp)) ? await walk(tmp, (n, p) => /[\\/]chats[\\/]/.test(p) && (/\.jsonl$/.test(n) || /^session-.*\.json$/.test(n))) : [];
201
+ const seenSid = new Set();
202
+ if (gfiles.length) f.coverage.sources.push('tmp/*/chats/*.jsonl');
203
+ progress(`${cfg.label}: ${gfiles.length} session files`);
204
+ await mapFiles(import.meta.url, 'scanGeminiFile', gfiles, { start: w.start, end: w.end }, (r, file) => {
205
+ const rel = path.relative(tmp, file.path).split(/[\\/]/);
206
+ const proj = projectName(rel[0]); const sub = r.sub || rel.length > 3;
207
+ seenSid.add(r.sid);
208
+ if (sub) { if (r.t.length) subagents++; }
209
+ else {
210
+ times(r.sid, proj, r.t);
211
+ for (const [ms, text, images] of r.prompts) promptAt(r.sid, proj, ms, text, images);
212
+ }
213
+ for (const [m, ms, i, o, cr] of r.models) tok(m, ms, i, o, cr);
214
+ for (const n of r.tools) inc(f.tools, n);
215
+ for (const u of r.undo) for (const k of u) undos[k]++;
216
+ for (const c of r.phr) addPhrases(assistant, c);
217
+ for (const ms of r.rl) { rlHits++; rlDays.add(localDate(ms)); }
218
+ rewinds += r.rewinds;
219
+ }, { onProgress: m => progress(`${cfg.label}: ${m}`) });
220
+
221
+ // prompt logs for sessions without a chat file (older versions, or chat recording turned off)
222
+ const logs = (await isDir(tmp)) ? await walk(tmp, n => n === 'logs.json') : [];
223
+ let fromLogs = 0;
224
+ for (const lf of logs) {
225
+ const arr = await readJSON(lf.path); if (!Array.isArray(arr)) continue;
226
+ const proj = projectName(path.relative(tmp, lf.path).split(/[\\/]/)[0]);
227
+ for (const e of arr) {
228
+ if (!e || e.type !== 'user' || seenSid.has(e.sessionId)) continue;
229
+ const ms = toMs(e.timestamp); if (!(ms >= w.start && ms < w.end)) continue;
230
+ const text = String(e.message || ''); if (!text.trim() || IGNORED.test(text.trim())) continue;
231
+ promptAt(e.sessionId || lf.path, proj, ms, text, 0); times(e.sessionId || lf.path, proj, [ms]); fromLogs++;
232
+ }
233
+ }
234
+ if (fromLogs) { f.coverage.sources.push('tmp/*/logs.json'); f.coverage.notes.push(`${fromLogs} prompts from logs.json only (no chat file: prompts and times, no tokens or tools)`); }
235
+
236
+ // Qwen Code layout: projects/<cwd>/chats/<sessionId>.jsonl
237
+ if (cfg.qwen) {
238
+ const pdir = path.join(rb, 'projects');
239
+ const qfiles = (await isDir(pdir)) ? await walk(pdir, (n, p) => n.endsWith('.jsonl') && /[\\/]chats[\\/]/.test(p)) : [];
240
+ if (qfiles.length) { f.coverage.sources.push('projects/*/chats/*.jsonl'); compactions = 0; }
241
+ const seen = new Set();
242
+ let vAt = 0;
243
+ await mapFiles(import.meta.url, 'scanQwenFile', qfiles, { start: w.start, end: w.end }, r => {
244
+ if (r.version && r.vAt >= vAt) { f.version = r.version; vAt = r.vAt; }
245
+ const proj = basename(r.cwd);
246
+ // de-dup across forks: only records whose uuid has not been seen count (order: largest file first)
247
+ const novel = new Set(r.uuids.filter(u => !seen.has(u)));
248
+ const isNew = k => !k || novel.has(k);
249
+ times(r.sid, proj, r.t.filter(([k]) => isNew(k)).map(([, ms]) => ms));
250
+ for (const [k, ms, text, images] of r.prompts) if (isNew(k)) promptAt(r.sid, proj, ms, text, images);
251
+ for (const [k, ms, cmd] of r.slash) if (isNew(k)) promptAt(r.sid, proj, ms, cmd, 0);
252
+ for (const [k, m, ms, i, o, cr] of r.models) if (isNew(k)) tok(m, ms, i, o, cr);
253
+ for (const [k, n] of r.tools) if (isNew(k)) inc(f.tools, n);
254
+ for (const [k, u] of r.undo) if (isNew(k)) for (const x of u) undos[x]++;
255
+ for (const [k, c] of r.phr) if (isNew(k)) addPhrases(assistant, c);
256
+ for (const ms of r.rl) { rlHits++; rlDays.add(localDate(ms)); }
257
+ for (const a of r.agents) agentIds.add(a);
258
+ compactions += r.compactions; rewinds += r.rewinds;
259
+ for (const u of novel) seen.add(u);
260
+ }, { onProgress: m => progress(`${cfg.label}: ${m}`) });
261
+ subagents += agentIds.size;
262
+ }
263
+
264
+ for (const [, s] of sessions) {
265
+ let mn = Infinity; for (const t of s.t) { if (t < mn) mn = t; day(f, localDate(t)); }
266
+ day(f, localDate(mn)).sessions++; f.sessions.count++;
267
+ }
268
+ f.sessions.longest = longestSession(sessions);
269
+ f.sessions.mostResumed = mostResumed(bySession);
270
+ f.sessions.maxConcurrent = maxConcurrent(concEv);
271
+ f.prompts = ps.toJSON(); f.slash = ps.slash;
272
+ f.subagents = subagents; f.interrupts = null; f.compactions = compactions;
273
+ f.rateLimits = { hits: rlHits, days: rlDays.size };
274
+ f.lines = null; f.gitUndos = undos; f.assistant = assistant; f.rewinds = rewinds;
275
+ f.projects = Object.fromEntries(Object.entries(f.projects).sort((a, b) => b[1] - a[1]).slice(0, 20));
276
+ f.theme = await readTheme(env, b, cfg);
277
+ return finishCoverage(f);
278
+ }
279
+
280
+ return { id: cfg.id, label: cfg.label, detect, read };
281
+ }
282
+
283
+ /** tmp/<id> → project folder name: projects.json { projects: { "/abs/path": "slug" } } or tmp/<slug>/.project_root */
284
+ async function projectNames(b) {
285
+ const reg = await readJSON(path.join(b, 'projects.json')); const bySlug = new Map();
286
+ for (const [p, slug] of Object.entries((reg && reg.projects) || {})) bySlug.set(slug, basename(p));
287
+ // a slug is the folder's own name (slugified); older sha256(cwd) directory names can't be turned back into a folder
288
+ return id => (bySlug.has(id) ? bySlug.get(id) : /^[0-9a-f]{64}$/.test(id) ? null : id || null);
289
+ }
290
+
291
+ // ------------------------------------------------------------------ theme
292
+ async function readTheme(env, b, cfg) {
293
+ const settings = await readJSON(path.join(b, 'settings.json')) || {};
294
+ const ui = settings.ui && typeof settings.ui === 'object' ? settings.ui : {};
295
+ const name = typeof ui.theme === 'string' ? ui.theme : typeof settings.theme === 'string' ? settings.theme : null;
296
+ if (!name) return null;
297
+ let def = null;
298
+ if (/\.json$/i.test(name)) def = await readJSON(name.startsWith('~') ? path.join(env.home, name.slice(1)) : path.isAbsolute(name) ? name : path.join(b, name));
299
+ if (!def) {
300
+ const files = [await readJSON(path.join(b, 'theme.json')), await readJSON(path.join(realEnv(env, 'XDG_CONFIG_HOME') || path.join(env.home, '.config'), cfg.qwen ? 'qwen' : 'gemini', 'theme.json'))];
301
+ for (const src of [...files, ui.customThemes, settings.customThemes]) {
302
+ if (!src || typeof src !== 'object') continue;
303
+ if (src[name] && typeof src[name] === 'object') { def = src[name]; break; }
304
+ if (src.name === name && src.type === 'custom') { def = src; break; }
305
+ }
306
+ }
307
+ if (!def) return { name, builtin: BUILTIN.has(name.toLowerCase()), colors: null };
308
+ const hex = v => (typeof v === 'string' && /^#[0-9a-f]{3,8}$/i.test(v) ? v.toLowerCase() : null);
309
+ const g = (...ks) => { for (const k of ks) { const v = k.split('.').reduce((o, x) => (o && typeof o === 'object' ? o[x] : undefined), def); const c = hex(v); if (c) return c; } return null; };
310
+ const colors = {
311
+ background: g('background.primary', 'Background'), foreground: g('text.primary', 'Foreground'),
312
+ primary: g('text.accent', 'AccentBlue', 'text.link'), accent: g('text.link', 'AccentPurple', 'text.accent'),
313
+ surface: g('background.secondary', 'ui.focus', 'DiffAdded'), success: g('status.success', 'AccentGreen'),
314
+ };
315
+ for (const [k, ...src] of [['secondary', 'text.secondary', 'Gray'], ['muted', 'ui.comment', 'Comment'], ['error', 'status.error', 'AccentRed'], ['warning', 'status.warning', 'AccentYellow']]) { const c = g(...src); if (c) colors[k] = c; }
316
+ return { name, builtin: false, colors: Object.values(colors).some(Boolean) ? colors : null };
317
+ }
318
+
319
+ const gemini = makeReader({ id: 'gemini-cli', label: 'Gemini CLI', tool: 'Gemini CLI', dir: '.gemini', homeEnv: 'GEMINI_CLI_HOME', qwen: false });
320
+ export const id = gemini.id;
321
+ export const label = gemini.label;
322
+ export const detect = gemini.detect;
323
+ export const read = gemini.read;
@@ -1,8 +1,12 @@
1
1
  // All harness readers, in display order. Each: { id, label, detect(env), read(env, opts) } (docs/CONTRACT.md §1).
2
2
  import * as claudeCode from './claude-code.mjs';
3
3
  import * as codex from './codex.mjs';
4
+ import * as cursor from './cursor.mjs';
5
+ import * as geminiCli from './gemini-cli.mjs';
6
+ import * as qwenCode from './qwen-code.mjs';
7
+ import * as opencode from './opencode.mjs';
4
8
  import * as pi from './pi.mjs';
5
9
  import * as mistralVibe from './mistral-vibe.mjs';
6
10
 
7
- export const readers = [claudeCode, codex, pi, mistralVibe];
8
- export { claudeCode, codex, pi, mistralVibe };
11
+ export const readers = [claudeCode, codex, cursor, geminiCli, qwenCode, opencode, pi, mistralVibe];
12
+ export { claudeCode, codex, cursor, geminiCli, qwenCode, opencode, pi, mistralVibe };
@@ -0,0 +1,343 @@
1
+ // OpenCode reader (anomalyco/opencode, formerly sst/opencode). Beta: built from OpenCode's source, not yet verified on real data.
2
+ //
3
+ // Data dir = $XDG_DATA_HOME/opencode, else ~/.local/share/opencode on every OS (xdg-basedir / util/global-roots.ts):
4
+ // https://github.com/anomalyco/opencode/blob/dev/packages/util/src/global-roots.ts
5
+ // Three storage generations, read newest first and de-duplicated by session id:
6
+ // 1. opencode.db (or opencode-<channel>.db, opencode-next.db), "v2" tables (2026-06 →):
7
+ // session_v2(id, parent_id, directory, version, summary_additions, summary_deletions, time_created, time_updated, …)
8
+ // session_message(id, session_id, type, seq, time_created, data JSON) type: user | assistant | compaction | idle | skill | …
9
+ // session_part(message_id, session_id, ordinal, type, call_id, time_created, data JSON) assistant content rows (2026-10 →)
10
+ // https://github.com/anomalyco/opencode/blob/dev/packages/core/src/session/sql.ts
11
+ // https://github.com/anomalyco/opencode/blob/dev/packages/schema/src/session-message.ts
12
+ // 2. the same db, "v1" tables (2026-01 →, kept after the v2 migration): session / message / part with `data` JSON
13
+ // https://github.com/anomalyco/opencode/blob/dev/packages/core/src/database/migration/20260127222353_familiar_lady_ursula.ts
14
+ // https://github.com/anomalyco/opencode/blob/dev/packages/schema/src/v1/session.ts
15
+ // 3. JSON files (≤ 2025): storage/session/<projectID>/<sessionID>.json, storage/message/<sessionID>/<msgID>.json,
16
+ // storage/part/<msgID>/<partID>.json — same v1 shapes. https://github.com/anomalyco/opencode/blob/v1.0.0/packages/opencode/src/storage/storage.ts
17
+ // Theme: `theme` (string, or { name, mode }) in ~/.config/opencode/{opencode,tui}.json[c] or ~/.local/state/opencode/kv.json;
18
+ // custom themes are ~/.config/opencode/themes/<name>.json ({ defs, theme: { key: hex | def | { dark, light } } }).
19
+ import path from 'node:path';
20
+ import fsp from 'node:fs/promises';
21
+ import {
22
+ readJSON, readText, isDir, localDate, windowOf, basename, maxConcurrent, gitUndoKinds, emptyUndos, phraseCounts,
23
+ emptyAssistant, addPhrases, inc, addTok, emptyFacts, day, countPromptTime, finishCoverage, longestSession, mostResumed,
24
+ realEnv, parseJSONC, parse,
25
+ } from './_util.mjs';
26
+ import { PromptStats } from './_prompts.mjs';
27
+ import { sqlite, openRO, rows, tables, close, NEEDS_NODE } from './_sqlite.mjs';
28
+
29
+ export const id = 'opencode';
30
+ export const label = 'OpenCode';
31
+ export const BETA = "beta reader (built from OpenCode's source, not yet verified on real data)";
32
+
33
+ const uniq = a => [...new Set(a.filter(Boolean))];
34
+ const dataDirs = env => uniq([realEnv(env, 'XDG_DATA_HOME') && path.join(realEnv(env, 'XDG_DATA_HOME'), 'opencode'), path.join(env.home, '.local', 'share', 'opencode')]);
35
+ const configDirs = env => uniq([realEnv(env, 'OPENCODE_CONFIG_DIR'), realEnv(env, 'XDG_CONFIG_HOME') && path.join(realEnv(env, 'XDG_CONFIG_HOME'), 'opencode'), path.join(env.home, '.config', 'opencode')]);
36
+ const stateDirs = env => uniq([realEnv(env, 'XDG_STATE_HOME') && path.join(realEnv(env, 'XDG_STATE_HOME'), 'opencode'), path.join(env.home, '.local', 'state', 'opencode')]);
37
+
38
+ async function dbFiles(dir) {
39
+ let names = []; try { names = await fsp.readdir(dir); } catch {}
40
+ return names.filter(n => /^opencode(-[\w.-]+)?\.db$/.test(n)).sort((a, b) => (a === 'opencode.db' ? -1 : b === 'opencode.db' ? 1 : a.localeCompare(b))).map(n => path.join(dir, n));
41
+ }
42
+
43
+ export async function detect(env) {
44
+ const roots = [];
45
+ for (const d of dataDirs(env)) {
46
+ for (const f of await dbFiles(d)) roots.push(f);
47
+ if (await isDir(path.join(d, 'storage', 'session'))) roots.push(path.join(d, 'storage'));
48
+ }
49
+ return { found: roots.length > 0, roots };
50
+ }
51
+
52
+ const RATE = /\b429\b|rate.?limit|too many requests|quota|overloaded/i;
53
+ const isImage = m => /^image\//i.test(String(m || ''));
54
+
55
+ /** everything one read collects, shared by the three storage generations */
56
+ class Acc {
57
+ constructor(w) {
58
+ this.w = w; this.f = emptyFacts(id, label); this.ps = new PromptStats();
59
+ this.seen = new Set(); this.sessions = new Map(); this.bySession = new Map(); this.concEv = [];
60
+ this.undos = emptyUndos(); this.assistant = emptyAssistant(); this.lines = { added: 0, removed: 0 };
61
+ this.rlDays = new Set(); this.rlHits = 0; this.interrupts = 0; this.compactions = 0; this.subagents = 0;
62
+ this.version = null; this.versionAt = -Infinity; this.toolKeys = new Set();
63
+ }
64
+ in(ms) { return ms >= this.w.start && ms < this.w.end; }
65
+ /** register a session once (newest storage wins); false if already read from a newer store */
66
+ session(s) {
67
+ if (!s.id || this.seen.has(s.id)) return false;
68
+ this.seen.add(s.id);
69
+ const created = +s.created || 0;
70
+ if (s.version && (+s.updated || created) > this.versionAt) { this.version = String(s.version); this.versionAt = +s.updated || created; }
71
+ if (s.parent) { if (this.in(created)) this.subagents++; }
72
+ else if (this.in(created)) { this.lines.added += +s.additions || 0; this.lines.removed += +s.deletions || 0; }
73
+ this.cur = { id: s.id, child: !!s.parent, project: basename(s.dir) };
74
+ return true;
75
+ }
76
+ time(ms) {
77
+ if (!this.in(ms) || this.cur.child) return;
78
+ const s = this.sessions.get(this.cur.id) || { t: [], project: this.cur.project }; s.t.push(ms); this.sessions.set(this.cur.id, s);
79
+ }
80
+ prompt(ms, text, images) {
81
+ if (!this.in(ms) || this.cur.child) return;
82
+ const sid = this.cur.id, proj = this.cur.project;
83
+ this.ps.add(text, { images }); countPromptTime(this.f, ms); this.concEv.push([ms, sid]); this.time(ms);
84
+ if (proj) inc(this.f.projects, proj);
85
+ const b = this.bySession.get(sid) || { days: new Set(), project: proj }; b.days.add(localDate(ms)); this.bySession.set(sid, b);
86
+ }
87
+ tokens(model, provider, ms, t) {
88
+ if (!this.in(ms) || !t) return;
89
+ const c = t.cache || {};
90
+ const i = +t.input || 0, o = (+t.output || 0) + (+t.reasoning || 0), cr = +c.read || 0, cw = +c.write || 0;
91
+ this.time(ms);
92
+ if (!(i + o + cr + cw)) return;
93
+ const key = model || '?';
94
+ addTok(this.f.models, key, ms, i, o, cr, cw);
95
+ if (provider && !this.f.models[key].provider) this.f.models[key].provider = provider;
96
+ day(this.f, localDate(ms)).tokens += i + o + cr + cw;
97
+ }
98
+ tool(key, name, input) {
99
+ if (key) { if (this.toolKeys.has(key)) return; this.toolKeys.add(key); }
100
+ inc(this.f.tools, name || '?');
101
+ if (/^skill$/i.test(name) && input && typeof input.name === 'string') inc(this.f.skills, input.name);
102
+ if (/^(bash|shell)$/i.test(name) && input) { const u = gitUndoKinds(String(input.command || '')); if (u) for (const k of u) this.undos[k]++; }
103
+ }
104
+ error(ms, err) {
105
+ if (!err || !this.in(ms)) return;
106
+ const s = JSON.stringify(err);
107
+ if (/MessageAbortedError|"aborted"|interrupted/i.test(s)) this.interrupts++;
108
+ else if (RATE.test(s) || err.statusCode === 429 || (err.data && err.data.statusCode === 429)) { this.rlHits++; this.rlDays.add(localDate(ms)); }
109
+ }
110
+ phrases(text) { addPhrases(this.assistant, phraseCounts(text)); }
111
+
112
+ finish() {
113
+ const f = this.f;
114
+ for (const [, s] of this.sessions) {
115
+ let mn = Infinity; for (const t of s.t) { if (t < mn) mn = t; day(f, localDate(t)); }
116
+ day(f, localDate(mn)).sessions++; f.sessions.count++;
117
+ }
118
+ f.sessions.longest = longestSession(this.sessions);
119
+ f.sessions.mostResumed = mostResumed(this.bySession);
120
+ f.sessions.maxConcurrent = maxConcurrent(this.concEv);
121
+ f.prompts = this.ps.toJSON(); f.slash = this.ps.slash;
122
+ f.subagents = this.subagents; f.interrupts = this.interrupts; f.compactions = this.compactions;
123
+ f.rateLimits = { hits: this.rlHits, days: this.rlDays.size };
124
+ f.lines = this.lines; f.gitUndos = this.undos; f.assistant = this.assistant; f.rewinds = null; // no rewind log, only the current revert point
125
+ f.version = this.version;
126
+ f.projects = Object.fromEntries(Object.entries(f.projects).sort((a, b) => b[1] - a[1]).slice(0, 20));
127
+ return f;
128
+ }
129
+ }
130
+
131
+ /** one v1 message (JSON storage or v1 table) with its parts */
132
+ function v1Message(acc, m, parts) {
133
+ const ms = +(m.time && m.time.created) || 0;
134
+ if (m.role === 'user') {
135
+ if (parts.some(p => p.type === 'compaction')) { if (acc.in(ms)) acc.compactions++; return; }
136
+ const texts = parts.filter(p => p.type === 'text' && !p.synthetic && !p.ignored && p.text);
137
+ const images = parts.filter(p => p.type === 'file' && isImage(p.mime)).length;
138
+ if (!texts.length && !images) { acc.time(ms); return; } // subtask-only / synthetic turns are not the user's
139
+ acc.prompt(ms, texts.map(p => p.text).join(' '), images);
140
+ } else if (m.role === 'assistant') {
141
+ const end = +(m.time && m.time.completed) || ms;
142
+ acc.tokens(m.modelID, m.providerID, ms, m.tokens); if (end > ms) acc.time(end);
143
+ acc.error(ms, m.error);
144
+ if (!acc.in(ms)) return;
145
+ for (const p of parts) {
146
+ if (p.type === 'tool') acc.tool(`${m.id}:${p.callID || p.id}`, p.tool, (p.state && p.state.input) || null);
147
+ else if (p.type === 'text' && !m.summary) acc.phrases(p.text);
148
+ }
149
+ }
150
+ }
151
+
152
+ /** v2 session_message row (+ its session_part rows) */
153
+ function v2Message(acc, row, data, parts) {
154
+ const ms = +row.time_created || +(data.time && data.time.created) || 0;
155
+ switch (row.type) {
156
+ case 'user': {
157
+ const images = (Array.isArray(data.files) ? data.files : []).filter(x => x && isImage(x.mime)).length;
158
+ acc.prompt(ms, String(data.text || ''), images); break;
159
+ }
160
+ case 'assistant': {
161
+ const model = data.model || {};
162
+ acc.tokens(model.id, model.providerID, ms, data.tokens);
163
+ const done = +(data.time && data.time.completed) || 0; if (done > ms) acc.time(done);
164
+ acc.error(ms, data.error);
165
+ if (!acc.in(ms)) break;
166
+ const content = [...(Array.isArray(data.content) ? data.content : []), ...parts];
167
+ for (const c of content) {
168
+ if (!c || typeof c !== 'object') continue;
169
+ if (c.type === 'tool') acc.tool(`${row.id}:${c.id}`, c.name, (c.state && c.state.input && typeof c.state.input === 'object') ? c.state.input : null);
170
+ else if (c.type === 'text') acc.phrases(c.text);
171
+ }
172
+ break;
173
+ }
174
+ case 'compaction': if (acc.in(ms) && data.status !== 'failed') acc.compactions++; acc.time(ms); break;
175
+ case 'idle': if (acc.in(ms) && data.outcome === 'interrupted') acc.interrupts++; break;
176
+ case 'skill': if (acc.in(ms) && data.name) inc(acc.f.skills, String(data.name)); break;
177
+ default: break;
178
+ }
179
+ }
180
+
181
+ const json = s => (typeof s === 'string' ? parse(s) : s && typeof s === 'object' ? s : undefined);
182
+
183
+ function readV2(acc, db) {
184
+ const { start, end } = acc.w;
185
+ const sess = new Map();
186
+ for (const r of rows(db, 'select id, parent_id, directory, version, summary_additions, summary_deletions, time_created, time_updated from session_v2')) sess.set(r.id, r);
187
+ const t = tables(db);
188
+ const partsOf = new Map();
189
+ if (t.has('session_part')) {
190
+ for (const p of rows(db, "select message_id, data from session_part where type = 'tool' and time_created >= ? and time_created < ?", start, end)) {
191
+ const d = json(p.data); if (!d) continue;
192
+ const a = partsOf.get(p.message_id) || []; a.push(d); partsOf.set(p.message_id, a);
193
+ }
194
+ }
195
+ let cur = null;
196
+ const order = 'select id, session_id, type, time_created, data from session_message where time_created >= ? and time_created < ? order by session_id, seq';
197
+ for (const r of rows(db, order, start, end)) {
198
+ if (r.session_id !== cur) {
199
+ cur = r.session_id; const s = sess.get(cur);
200
+ if (!s || !acc.session({ id: s.id, parent: s.parent_id, dir: s.directory, version: s.version, created: s.time_created, updated: s.time_updated, additions: s.summary_additions, deletions: s.summary_deletions })) { cur = '\0skip:' + cur; }
201
+ sess.delete(r.session_id);
202
+ }
203
+ if (cur.startsWith('\0skip:')) continue;
204
+ const d = json(r.data); if (!d) continue;
205
+ v2Message(acc, r, d, partsOf.get(r.id) || []);
206
+ }
207
+ // sessions with no message this year still count for version / subagents / lines
208
+ for (const [, s] of sess) acc.session({ id: s.id, parent: s.parent_id, dir: s.directory, version: s.version, created: s.time_created, updated: s.time_updated, additions: s.summary_additions, deletions: s.summary_deletions });
209
+ }
210
+
211
+ function readV1Tables(acc, db) {
212
+ const { start } = acc.w;
213
+ const list = [...rows(db, 'select id, parent_id, directory, version, summary_additions, summary_deletions, time_created, time_updated from session')];
214
+ for (const s of list) {
215
+ if (!acc.session({ id: s.id, parent: s.parent_id, dir: s.directory, version: s.version, created: s.time_created, updated: s.time_updated, additions: s.summary_additions, deletions: s.summary_deletions })) continue;
216
+ if (+s.time_updated < start) continue;
217
+ const parts = new Map();
218
+ for (const p of rows(db, 'select id, message_id, data from part where session_id = ?', s.id)) {
219
+ const d = json(p.data); if (!d) continue; d.id = p.id;
220
+ const a = parts.get(p.message_id) || []; a.push(d); parts.set(p.message_id, a);
221
+ }
222
+ for (const m of rows(db, 'select id, time_created, data from message where session_id = ? order by time_created', s.id)) {
223
+ const d = json(m.data); if (!d) continue; d.id = m.id; d.time = d.time || { created: m.time_created };
224
+ v1Message(acc, d, (parts.get(m.id) || []).sort((a, b) => String(a.id).localeCompare(String(b.id))));
225
+ }
226
+ }
227
+ }
228
+
229
+ async function readJSONStorage(acc, storage) {
230
+ const sdir = path.join(storage, 'session');
231
+ let projects = []; try { projects = await fsp.readdir(sdir); } catch { return 0; }
232
+ let n = 0;
233
+ for (const pid of projects) {
234
+ let files = []; try { files = (await fsp.readdir(path.join(sdir, pid))).filter(x => x.endsWith('.json')); } catch { continue; }
235
+ for (const fn of files) {
236
+ const s = await readJSON(path.join(sdir, pid, fn)); if (!s || !s.id) continue;
237
+ const tm = s.time || {}; const sum = s.summary || {};
238
+ if (!acc.session({ id: s.id, parent: s.parentID, dir: s.directory, version: s.version, created: tm.created, updated: tm.updated, additions: sum.additions, deletions: sum.deletions })) continue;
239
+ n++;
240
+ if ((+tm.updated || +tm.created || 0) < acc.w.start) continue;
241
+ const mdir = path.join(storage, 'message', s.id);
242
+ let mfiles = []; try { mfiles = (await fsp.readdir(mdir)).filter(x => x.endsWith('.json')).sort(); } catch {}
243
+ for (const mf of mfiles) {
244
+ const m = await readJSON(path.join(mdir, mf)); if (!m || !m.role) continue;
245
+ const pdir = path.join(storage, 'part', m.id || mf.slice(0, -5));
246
+ let pfiles = []; try { pfiles = (await fsp.readdir(pdir)).filter(x => x.endsWith('.json')).sort(); } catch {}
247
+ const parts = [];
248
+ for (const pf of pfiles) { const p = await readJSON(path.join(pdir, pf)); if (p) parts.push(p); }
249
+ v1Message(acc, m, parts);
250
+ }
251
+ }
252
+ }
253
+ return n;
254
+ }
255
+
256
+ export async function read(env, opts = {}) {
257
+ const w = windowOf(env, opts); const progress = opts.onProgress || (() => {});
258
+ const acc = new Acc(w); const f = acc.f;
259
+ f.coverage.notes.push(BETA);
260
+ const dirs = dataDirs(env);
261
+ const dbs = []; for (const d of dirs) dbs.push(...await dbFiles(d));
262
+ if (dbs.length && !(await sqlite())) f.coverage.notes.push(`${NEEDS_NODE} OpenCode's database (opencode.db)`);
263
+ else {
264
+ for (const file of dbs) {
265
+ progress(`OpenCode: ${path.basename(file)}`);
266
+ const db = await openRO(file);
267
+ if (!db) { f.coverage.notes.push(`could not open ${path.basename(file)}`); continue; }
268
+ try {
269
+ const t = tables(db);
270
+ if (t.has('session_v2') && t.has('session_message')) { readV2(acc, db); f.coverage.sources.push(path.basename(file) + ' (session_v2)'); }
271
+ if (t.has('session') && t.has('message') && t.has('part')) { readV1Tables(acc, db); f.coverage.sources.push(path.basename(file) + ' (session/message/part)'); }
272
+ } finally { close(db); }
273
+ }
274
+ }
275
+ for (const d of dirs) {
276
+ const storage = path.join(d, 'storage');
277
+ if (await isDir(path.join(storage, 'session'))) {
278
+ progress('OpenCode: storage/*.json');
279
+ const n = await readJSONStorage(acc, storage);
280
+ if (n) f.coverage.sources.push('storage/{session,message,part}/*.json');
281
+ }
282
+ }
283
+ acc.finish();
284
+ const local = await localProviders(env);
285
+ for (const m of Object.values(f.models)) if (m.provider && local(m.provider)) m.local = true;
286
+ f.theme = await readTheme(env);
287
+ f.coverage.notes.push('tokens as OpenCode recorded them (output includes reasoning); lines = session diff summaries');
288
+ return finishCoverage(f);
289
+ }
290
+
291
+ /** provider id -> served on this machine? (config baseURL on localhost, or a known local runtime name) */
292
+ async function localProviders(env) {
293
+ const byUrl = {};
294
+ for (const dir of configDirs(env)) for (const fn of ['opencode.jsonc', 'opencode.json', 'config.json']) {
295
+ const cfg = parseJSONC(await readText(path.join(dir, fn)));
296
+ for (const [name, p] of Object.entries((cfg && cfg.provider) || {})) if (!(name in byUrl)) byUrl[name] = String((p && p.options && (p.options.baseURL || p.options.baseUrl)) || '');
297
+ }
298
+ const LOCAL_URL = /^https?:\/\/(localhost|127\.|0\.0\.0\.0|\[::1\]|192\.168\.|10\.|host\.docker\.internal)/i;
299
+ const LOCAL_NAME = /^(ollama|lmstudio|lm-studio|llama\.?cpp|llamacpp|vllm|mlx|local)/i;
300
+ return prov => (byUrl[prov] ? LOCAL_URL.test(byUrl[prov]) : LOCAL_NAME.test(prov));
301
+ }
302
+
303
+ // ------------------------------------------------------------------ theme
304
+ const BUILTIN = new Set(['system', 'opencode', 'opencode-classic', 'aura', 'ayu', 'carbonfox', 'catppuccin', 'catppuccin-frappe', 'catppuccin-macchiato',
305
+ 'cobalt2', 'cursor', 'dracula', 'everforest', 'flexoki', 'github', 'gruvbox', 'kanagawa', 'lucent-orng', 'material', 'matrix', 'mercury', 'monokai',
306
+ 'nightowl', 'nord', 'one-dark', 'orng', 'osaka-jade', 'palenight', 'rosepine', 'solarized', 'synthwave84', 'tokyonight', 'vercel', 'vesper', 'zenburn']);
307
+
308
+ export async function readTheme(env) {
309
+ let name = null, mode = 'dark';
310
+ for (const dir of configDirs(env)) {
311
+ for (const fn of ['tui.jsonc', 'tui.json', 'opencode.jsonc', 'opencode.json', 'config.json']) {
312
+ const cfg = parseJSONC(await readText(path.join(dir, fn))); const t = cfg && cfg.theme;
313
+ if (typeof t === 'string' && t) { name = t; break; }
314
+ if (t && typeof t === 'object' && typeof t.name === 'string') { name = t.name; if (t.mode === 'light') mode = 'light'; break; }
315
+ }
316
+ if (name) break;
317
+ }
318
+ if (!name) for (const dir of stateDirs(env)) {
319
+ const kv = await readJSON(path.join(dir, 'kv.json'));
320
+ if (kv && typeof kv.theme === 'string') { name = kv.theme; if (kv.theme_mode === 'light') mode = 'light'; break; }
321
+ }
322
+ if (!name) return null;
323
+ let file = null;
324
+ for (const dir of configDirs(env)) { file = await readJSON(path.join(dir, 'themes', name + '.json')); if (file) break; }
325
+ if (!file) return { name, builtin: BUILTIN.has(name), colors: null };
326
+ const defs = file.defs || {}; const th = file.theme || {};
327
+ const resolve = (v, depth = 0) => {
328
+ if (depth > 8 || v == null) return null;
329
+ if (typeof v === 'object') return resolve(v[mode] ?? v.dark ?? v.light, depth + 1);
330
+ if (typeof v !== 'string') return null;
331
+ if (/^#[0-9a-f]{3,8}$/i.test(v)) return v.toLowerCase();
332
+ if (v in defs) return resolve(defs[v], depth + 1);
333
+ if (v in th) return resolve(th[v], depth + 1);
334
+ return null;
335
+ };
336
+ const pick = (...ks) => { for (const k of ks) { const c = resolve(th[k]); if (c) return c; } return null; };
337
+ const colors = {
338
+ background: pick('background'), foreground: pick('text'), primary: pick('primary'), accent: pick('accent', 'primary'),
339
+ surface: pick('backgroundPanel', 'backgroundElement'), success: pick('success'),
340
+ };
341
+ for (const [k, src] of [['secondary', 'secondary'], ['muted', 'textMuted'], ['surfaceAlt', 'backgroundElement'], ['error', 'error'], ['warning', 'warning']]) { const c = pick(src); if (c) colors[k] = c; }
342
+ return { name, builtin: false, colors: Object.values(colors).some(Boolean) ? colors : null };
343
+ }
@@ -0,0 +1,8 @@
1
+ // Qwen Code reader: ~/.qwen (or $QWEN_HOME / $QWEN_RUNTIME_DIR). Shares gemini-cli.mjs, which documents both formats and sources.
2
+ import { makeReader } from './gemini-cli.mjs';
3
+
4
+ const qwen = makeReader({ id: 'qwen-code', label: 'Qwen Code', tool: 'Qwen Code', dir: '.qwen', homeEnv: 'QWEN_HOME', qwen: true });
5
+ export const id = qwen.id;
6
+ export const label = qwen.label;
7
+ export const detect = qwen.detect;
8
+ export const read = qwen.read;
package/src/site.mjs CHANGED
@@ -34,7 +34,7 @@ const page = (id, name, where, note) => `<!doctype html><html lang="en"><head><m
34
34
  <p>Your year with ${name}: prompts, tokens, streak, model of the year, how often you said please and how often it said “you’re right”, your agentic age, and a roast written by your own agent.</p>
35
35
  <p>Run it in a terminal, or paste it into ${name}:</p><code>npx wrapped-agents</code>
36
36
  <p>It reads <b>${where}</b>, read-only. ${note} Your usage data never leaves your machine.</p>
37
- <p><a href="./">See a demo wrap →</a> · <a href="https://github.com/leonardodaviti/agent-wrapped">GitHub</a></p></body></html>`;
37
+ <p><a href="./">See a demo wrap →</a> · <a href="https://github.com/LeonardoDaviti/agent-wrapped">GitHub</a></p></body></html>`;
38
38
  for (const h of HARNESS) fs.writeFileSync(path.join(SITE, `${h[0]}-wrapped.html`), page(...h));
39
39
 
40
40
  fs.writeFileSync(path.join(SITE, 'privacy.html'), `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Privacy · Agent Wrapped</title>
@@ -49,10 +49,11 @@ fs.writeFileSync(path.join(SITE, 'privacy.html'), `<!doctype html><html lang="en
49
49
  fs.writeFileSync(path.join(SITE, 'llms.txt'), `# Agent Wrapped
50
50
  > Year in review ("wrapped") for AI coding agents: Claude Code, Codex, Pi, Mistral Vibe. Runs locally; usage data never leaves the machine.
51
51
 
52
- To make a user's wrapped: run \`npx -y wrapped-agents\` (opens the story in the browser). Agents may write the roast themselves: run \`npx -y wrapped-agents --json --no-open\`, read the printed wrapped-<year>.json, then \`npx -y wrapped-agents --from <file> --roast "<≤12 words citing its numbers>"\`. Skill: https://github.com/leonardodaviti/agent-wrapped/blob/main/SKILL.md
52
+ To make a user's wrapped: run \`npx -y wrapped-agents\` (opens the story in the browser). Agents may write the roast themselves: run \`npx -y wrapped-agents --json --no-open\`, read the printed wrapped-<year>.json, then \`npx -y wrapped-agents --from <file> --roast "<≤12 words citing its numbers>"\`. Skill: https://github.com/LeonardoDaviti/agent-wrapped/blob/main/SKILL.md
53
53
 
54
- - [Repository](https://github.com/leonardodaviti/agent-wrapped)
55
- - [SKILL.md](https://github.com/leonardodaviti/agent-wrapped/blob/main/SKILL.md)
54
+ - [npm package](https://www.npmjs.com/package/wrapped-agents)
55
+ - [Repository](https://github.com/LeonardoDaviti/agent-wrapped)
56
+ - [SKILL.md](https://github.com/LeonardoDaviti/agent-wrapped/blob/main/SKILL.md)
56
57
  - [Privacy](${BASE}privacy.html)
57
58
  `);
58
59
  fs.writeFileSync(path.join(SITE, 'robots.txt'), `User-agent: *\nAllow: /\nSitemap: ${BASE}sitemap.xml\n`);
@@ -5,7 +5,9 @@ import { agenticAge } from './age.mjs';
5
5
  import { agentTwin } from './twin.mjs';
6
6
  import { buildAwards } from './awards.mjs';
7
7
 
8
- export const SKINS = ['wrapped', 'anthropic', 'claude-code', 'codex', 'opencode', 'pi', 'hermes', 'mistral-vibe'];
8
+ export const SKINS = ['wrapped', 'anthropic', 'claude-code', 'codex', 'cursor', 'gemini-cli', 'opencode', 'pi', 'hermes', 'mistral-vibe'];
9
+ /** harnesses that wear another harness's skin (Qwen Code forked Gemini CLI) */
10
+ const SKIN_OF = { 'qwen-code': 'gemini-cli' };
9
11
 
10
12
  const isNum = v => typeof v === 'number' && Number.isFinite(v);
11
13
  /** sum that stays null when every input is unknown */
@@ -117,7 +119,8 @@ export function mergedMedian(facts) {
117
119
  /** default theme rule (CONTRACT §6) + "yours" token mapping (§5) */
118
120
  export function pickTheme(topFacts) {
119
121
  if (!topFacts) return { skin: 'wrapped', yours: null };
120
- const skin = SKINS.includes(topFacts.harness) ? topFacts.harness : 'wrapped';
122
+ const h = SKIN_OF[topFacts.harness] || topFacts.harness;
123
+ const skin = SKINS.includes(h) ? h : 'wrapped';
121
124
  const th = topFacts.theme;
122
125
  if (!th || th.builtin !== false || !th.colors) return { skin, yours: null };
123
126
  const c = th.colors, y = {};