myaiwrapped 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/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # myaiwrapped
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
+ Spotify Wrapped for your AI coding agents.
4
+
5
+ ```bash
6
+ npx myaiwrapped
7
+ ```
8
+
9
+ It reads the history that **Claude Code**, **Codex**, **OpenCode** and **Cursor** already keep on your computer and turns your year into a story: prompts, hours, tokens, top models, languages, your peak hour, your longest streak, a vibe check and your AI coding personality. It ends on three swipeable share cards (Your Year in AI, Your AI Self, Your Numbers) with a generative holographic texture that's unique to your stats. Save or copy any card as a 1080×1920 image and post it anywhere.
10
+
11
+ ## Privacy
12
+
13
+ - Everything is read and computed on your machine. Nothing is uploaded.
14
+ - The share cards never show project names or anything you typed.
15
+
16
+ ## Options
17
+
18
+ ```
19
+ npx myaiwrapped --year 2025 # wrap a specific year (default: this year)
20
+ npx myaiwrapped --all # your whole history
21
+ npx myaiwrapped --json # print the stats instead of opening the story
22
+ npx myaiwrapped --no-open # don't open the browser
23
+ ```
24
+
25
+ ## Where the data comes from
26
+
27
+ | Agent | Location |
28
+ |---|---|
29
+ | Claude Code | `~/.claude/projects/**/*.jsonl` |
30
+ | Codex | `~/.codex/sessions/**/*.jsonl`, `~/.codex/archived_sessions/*.jsonl(.zst)` |
31
+ | OpenCode | `~/.local/share/opencode/opencode.db` (or the older `storage/` JSON) |
32
+ | Cursor | `Cursor/User/globalStorage/state.vscdb` + `workspaceStorage/*/state.vscdb` |
33
+
34
+ Respects `CLAUDE_CONFIG_DIR`, `CODEX_HOME` and `XDG_DATA_HOME`. No dependencies; Node 18+ (22.5+ recommended for built-in SQLite, otherwise the `sqlite3` CLI is used).
@@ -0,0 +1,138 @@
1
+ #!/usr/bin/env node
2
+ import http from 'node:http';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { spawn } from 'node:child_process';
7
+ import { Collector } from '../src/collector.js';
8
+ import { computeStats } from '../src/stats.js';
9
+ import * as claude from '../src/adapters/claude.js';
10
+ import * as codex from '../src/adapters/codex.js';
11
+ import * as opencode from '../src/adapters/opencode.js';
12
+ import * as cursor from '../src/adapters/cursor.js';
13
+
14
+ const ADAPTERS = [claude, codex, opencode, cursor];
15
+ const WEB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'web');
16
+
17
+ const args = process.argv.slice(2);
18
+ const flag = (f) => args.includes(f);
19
+ const opt = (f) => { const i = args.indexOf(f); return i >= 0 ? args[i + 1] : undefined; };
20
+
21
+ if (flag('-h') || flag('--help')) {
22
+ console.log(`
23
+ myaiwrapped: your year with AI coding agents
24
+
25
+ Usage: npx myaiwrapped [options]
26
+
27
+ --year <yyyy> Wrap a specific year (default: this year)
28
+ --all Wrap your whole history
29
+ --json Print the stats as JSON instead of opening the story
30
+ --no-open Don't open the browser automatically
31
+ --port <n> Port for the local story page
32
+
33
+ Reads Claude Code, Codex, OpenCode and Cursor history from this computer.
34
+ Nothing is uploaded. Save the share cards as images and post them anywhere.
35
+ `);
36
+ process.exit(0);
37
+ }
38
+
39
+ const c = { dim: (s) => `\x1b[2m${s}\x1b[0m`, bold: (s) => `\x1b[1m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m`, pink: (s) => `\x1b[38;5;213m${s}\x1b[0m` };
40
+ const log = (...a) => { if (!flag('--json')) console.log(...a); };
41
+
42
+ log('');
43
+ log(c.pink(c.bold(' ✦ myaiwrapped')) + c.dim(' your year with AI coding agents'));
44
+ log(c.dim(' everything stays on this computer\n'));
45
+
46
+ const now = new Date();
47
+ let range;
48
+ if (flag('--all')) {
49
+ range = { from: 0, to: Date.now() + 86400000, label: 'All time' };
50
+ } else {
51
+ const y = +(opt('--year') || now.getFullYear());
52
+ range = { from: new Date(y, 0, 1).getTime(), to: new Date(y + 1, 0, 1).getTime(), label: String(y) };
53
+ }
54
+
55
+ async function collectAll(since) {
56
+ const col = new Collector();
57
+ for (const a of ADAPTERS) {
58
+ let found = false;
59
+ try { found = a.detect(); } catch {}
60
+ if (!found) { log(c.dim(` · ${a.name.padEnd(12)} not found`)); continue; }
61
+ const count = () => [...col.sessions.values()].filter((x) => x.tool === a.id).length;
62
+ const before = { s: count(), p: col.prompts.length };
63
+ const t0 = Date.now();
64
+ const tty = process.stdout.isTTY && !flag('--json');
65
+ const onProgress = (f) => { if (tty) process.stdout.write(`\r ${c.pink('◌')} ${a.name.padEnd(12)} ${c.dim(`reading… ${Math.round(f * 100)}%`)} `); };
66
+ try {
67
+ await a.collect(col, { since, onProgress });
68
+ if (tty) process.stdout.write('\r\x1b[2K');
69
+ log(` ${c.green('✓')} ${a.name.padEnd(12)} ${c.dim(`${count() - before.s} sessions, ${col.prompts.length - before.p} prompts (${((Date.now() - t0) / 1000).toFixed(1)}s)`)}`);
70
+ } catch (e) {
71
+ if (tty) process.stdout.write('\r\x1b[2K');
72
+ log(` ${c.pink('!')} ${a.name.padEnd(12)} ${c.dim('could not read: ' + (e && e.message ? e.message.split('\n')[0] : e))}`);
73
+ }
74
+ }
75
+ return col;
76
+ }
77
+
78
+ let col = await collectAll(range.from);
79
+ if (!flag('--all') && !opt('--year') && !col.prompts.some((p) => p.ts >= range.from && p.ts < range.to)) {
80
+ log(c.dim(`\n nothing in ${range.label} yet, wrapping all time instead\n`));
81
+ range = { from: 0, to: Date.now() + 86400000, label: 'All time' };
82
+ col = await collectAll(0);
83
+ }
84
+
85
+ const stats = computeStats(col, range);
86
+
87
+ if (flag('--json')) {
88
+ console.log(JSON.stringify(stats, null, 2));
89
+ process.exit(0);
90
+ }
91
+
92
+ if (!stats.totals.prompts && !stats.totals.sessions) {
93
+ log('\n No AI coding sessions found for ' + range.label + '. Try --all.\n');
94
+ process.exit(1);
95
+ }
96
+
97
+ log('');
98
+ log(` ${c.bold(stats.totals.prompts.toLocaleString())} prompts · ${c.bold(stats.totals.hours.toLocaleString())} hours · ${c.bold(fmt(stats.totals.tokens))} tokens`);
99
+ log(` You are ${c.pink(c.bold(stats.persona.title))}`);
100
+
101
+ function fmt(n) {
102
+ if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B';
103
+ if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
104
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
105
+ return String(n);
106
+ }
107
+
108
+ // Serve the story page locally with the stats injected.
109
+ const inject = `<script>window.__AIWRAPPED__=${JSON.stringify(stats).replace(/</g, '\\u003c')};window.__AIWRAPPED_LOCAL__=true;</script>`;
110
+ const page = () => fs.readFileSync(path.join(WEB, 'index.html'), 'utf8').replace('<!--DATA-->', inject);
111
+ const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon' };
112
+ const server = http.createServer((req, res) => {
113
+ const url = decodeURIComponent((req.url || '/').split('?')[0]);
114
+ if (url === '/' || url === '/index.html') {
115
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
116
+ return res.end(page());
117
+ }
118
+ const file = path.join(WEB, path.normalize(url).replace(/^(\.\.[/\\])+/, ''));
119
+ if (file.startsWith(WEB) && fs.existsSync(file) && fs.statSync(file).isFile()) {
120
+ res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream' });
121
+ return fs.createReadStream(file).pipe(res);
122
+ }
123
+ res.writeHead(404); res.end();
124
+ });
125
+
126
+ const port = +(opt('--port') || 0);
127
+ server.listen(port, '127.0.0.1', () => {
128
+ const url = `http://localhost:${server.address().port}`;
129
+ log(`\n ${c.bold('Your Wrapped is ready →')} ${c.pink(url)}`);
130
+ log(c.dim(' press Ctrl+C when you are done\n'));
131
+ if (!flag('--no-open')) openBrowser(url);
132
+ });
133
+
134
+ function openBrowser(url) {
135
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
136
+ const a = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
137
+ try { spawn(cmd, a, { stdio: 'ignore', detached: true }).unref(); } catch {}
138
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "myaiwrapped",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Spotify Wrapped for your AI coding agents. Reads your local Claude Code, Codex, OpenCode and Cursor history and turns it into a shareable story. Nothing leaves your machine.",
5
+ "type": "module",
6
+ "bin": {
7
+ "myaiwrapped": "bin/aiwrapped.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "web"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "keywords": [
18
+ "wrapped",
19
+ "claude-code",
20
+ "codex",
21
+ "opencode",
22
+ "cursor",
23
+ "ai",
24
+ "stats"
25
+ ],
26
+ "license": "MIT"
27
+ }
@@ -0,0 +1,86 @@
1
+ // Claude Code: ~/.claude/projects/<project>/<session>.jsonl (+ <session>/subagents/*.jsonl)
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import fs from 'node:fs';
5
+ import { walk, eachJsonLine, exists, ms } from '../fsutil.js';
6
+ import { isNoisePrompt } from '../collector.js';
7
+ import { parseAll } from '../pool.js';
8
+
9
+ export const id = 'claude';
10
+ export const name = 'Claude Code';
11
+
12
+ function roots() {
13
+ const dirs = [];
14
+ if (process.env.CLAUDE_CONFIG_DIR) {
15
+ for (const d of process.env.CLAUDE_CONFIG_DIR.split(/[,:]/)) dirs.push(path.join(d, 'projects'));
16
+ }
17
+ dirs.push(path.join(os.homedir(), '.claude', 'projects'));
18
+ dirs.push(path.join(os.homedir(), '.config', 'claude', 'projects'));
19
+ return [...new Set(dirs)].filter(exists);
20
+ }
21
+
22
+ export function detect() { return roots().length > 0; }
23
+
24
+ function promptText(content) {
25
+ if (typeof content === 'string') return content;
26
+ if (!Array.isArray(content)) return null;
27
+ if (content.some((c) => c && c.type === 'tool_result')) return null;
28
+ const text = content.filter((c) => c && c.type === 'text').map((c) => c.text).join('\n');
29
+ return text || null;
30
+ }
31
+
32
+ // Runs inside a worker: extract only what we need from one file.
33
+ export async function parseFile(file) {
34
+ const isSub = file.includes(`${path.sep}subagents${path.sep}`);
35
+ const fallbackId = path.basename(file, '.jsonl');
36
+ const out = { prompts: [], turns: [], calls: [], times: [], cwd: {} };
37
+ await eachJsonLine(file, (d) => {
38
+ const ts = ms(d.timestamp);
39
+ if (!ts) return;
40
+ const sid = d.sessionId || fallbackId;
41
+ const m = d.message;
42
+ if (d.cwd && !out.cwd[sid]) out.cwd[sid] = d.cwd;
43
+ if (d.type === 'user' && m && !isSub && !d.isMeta && !d.isSidechain) {
44
+ const text = promptText(m.content);
45
+ if (text && !isNoisePrompt(text)) out.prompts.push([sid, ts, text, d.uuid || '']);
46
+ else out.times.push([sid, ts]);
47
+ } else if (d.type === 'assistant' && m && m.model !== '<synthetic>') {
48
+ const u = m.usage || {};
49
+ out.turns.push([sid, ts, m.id || d.uuid, m.model, u.input_tokens || 0, u.output_tokens || 0, u.cache_read_input_tokens || 0, u.cache_creation_input_tokens || 0]);
50
+ for (const b of Array.isArray(m.content) ? m.content : []) {
51
+ if (!b || b.type !== 'tool_use') continue;
52
+ const inp = b.input || {};
53
+ out.calls.push([sid, ts, b.id, b.name, inp.file_path || inp.notebook_path || inp.path || null]);
54
+ }
55
+ }
56
+ }, { want: (l) => l.includes('"type":"assistant"') || (l.includes('"type":"user"') && !l.includes('"tool_result"')) });
57
+ return out;
58
+ }
59
+
60
+ export async function collect(c, { since = 0, onProgress } = {}) {
61
+ const files = roots().flatMap((r) => walk(r, (p) => p.endsWith('.jsonl')))
62
+ .filter((f) => { try { return fs.statSync(f).mtimeMs >= since; } catch { return false; } });
63
+ const seenMsg = new Set();
64
+ const seenTool = new Set();
65
+ const seenPrompt = new Set();
66
+ await parseAll(new URL(import.meta.url).href, files, (r) => {
67
+ for (const sid in r.cwd) c.session('claude', sid, { project: r.cwd[sid] });
68
+ for (const [sid, ts] of r.times) c.session('claude', sid, { ts });
69
+ for (const [sid, ts, text, uuid] of r.prompts) {
70
+ const k = uuid || `${sid}:${ts}`;
71
+ if (seenPrompt.has(k)) continue;
72
+ seenPrompt.add(k);
73
+ c.prompt('claude', sid, ts, text);
74
+ }
75
+ for (const [sid, ts, mid, model, i, o, cr, cw] of r.turns) {
76
+ if (seenMsg.has(mid)) { c.session('claude', sid, { ts }); continue; }
77
+ seenMsg.add(mid);
78
+ c.turn('claude', sid, ts, model, { input: i, output: o, cacheRead: cr, cacheWrite: cw });
79
+ }
80
+ for (const [sid, ts, tid, nm, file] of r.calls) {
81
+ if (seenTool.has(tid)) continue;
82
+ seenTool.add(tid);
83
+ c.toolCall('claude', sid, ts, nm, file);
84
+ }
85
+ }, onProgress);
86
+ }
@@ -0,0 +1,118 @@
1
+ // Codex: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl and ~/.codex/archived_sessions/*.jsonl(.zst)
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import fs from 'node:fs';
5
+ import { walk, eachJsonLine, exists, ms, safeJson } from '../fsutil.js';
6
+ import { isNoisePrompt } from '../collector.js';
7
+ import { parseAll } from '../pool.js';
8
+
9
+ export const id = 'codex';
10
+ export const name = 'Codex';
11
+
12
+ function home() { return process.env.CODEX_HOME || path.join(os.homedir(), '.codex'); }
13
+
14
+ export function detect() { return exists(path.join(home(), 'sessions')) || exists(path.join(home(), 'archived_sessions')); }
15
+
16
+ const WANT = ['"session_meta"', '"turn_context"', '"user_message"', '"token_count"', '"role":"user"', '"type":"function_call"', '"type":"custom_tool_call"', '"type":"local_shell_call"'];
17
+ const TS = /"timestamp":"([^"]+)"/;
18
+ const PATCH_FILE = /\*\*\* (?:Update|Add|Delete) File: ([^\n\\"]+)/g;
19
+
20
+ function filesFromPatch(s) {
21
+ const out = [];
22
+ if (typeof s !== 'string') return out;
23
+ for (const m of s.matchAll(PATCH_FILE)) out.push(m[1].trim());
24
+ return out;
25
+ }
26
+
27
+ // Runs inside a worker: one rollout file = one thread.
28
+ export async function parseFile(file) {
29
+ let sid = null, cwd = null, model = null, firstTs = 0, lastUsage = null, lastUsageTs = 0;
30
+ const eventPrompts = [], itemPrompts = [], calls = [], times = [];
31
+ const seenCall = new Set();
32
+ await eachJsonLine(file, (d) => {
33
+ const ts = ms(d.timestamp);
34
+ const p = d.payload || {};
35
+ if (ts) { times.push(ts); if (!firstTs) firstTs = ts; }
36
+ switch (d.type) {
37
+ case 'session_meta':
38
+ sid = sid || p.id || p.session_id;
39
+ cwd = cwd || p.cwd;
40
+ break;
41
+ case 'turn_context':
42
+ cwd = cwd || p.cwd;
43
+ if (p.model) model = p.model;
44
+ break;
45
+ case 'event_msg':
46
+ if (p.type === 'user_message' && p.message) eventPrompts.push([ts, p.message]);
47
+ if (p.type === 'token_count' && p.info && p.info.total_token_usage) { lastUsage = p.info.total_token_usage; lastUsageTs = ts; }
48
+ break;
49
+ case 'response_item': {
50
+ if (p.type === 'message' && p.role === 'user') {
51
+ itemPrompts.push([ts, (p.content || []).filter((x) => x && /text/.test(x.type)).map((x) => x.text).join('\n')]);
52
+ } else if (p.type === 'function_call' || p.type === 'custom_tool_call' || p.type === 'local_shell_call') {
53
+ if (p.call_id) { if (seenCall.has(p.call_id)) break; seenCall.add(p.call_id); }
54
+ const nm = p.name || (p.type === 'local_shell_call' ? 'shell' : null);
55
+ const args = p.arguments || p.input || '';
56
+ const argObj = safeJson(args);
57
+ const patchFiles = filesFromPatch(typeof args === 'string' ? args : JSON.stringify(args));
58
+ const cid = p.call_id || p.id || '';
59
+ if (patchFiles.length) patchFiles.forEach((f, i) => calls.push([ts, 'apply_patch', f, cid && `${cid}:${i}`]));
60
+ else calls.push([ts, nm, argObj && (argObj.path || argObj.file_path) || null, cid]);
61
+ }
62
+ break;
63
+ }
64
+ }
65
+ }, {
66
+ want: (l) => WANT.some((w) => l.includes(w)),
67
+ skipped: (l) => { const m = TS.exec(l.slice(0, 80)); if (m) times.push(ms(m[1])); },
68
+ });
69
+ sid = sid || path.basename(file).replace(/\.jsonl(\.zst)?$/, '');
70
+ const prompts = (eventPrompts.length ? eventPrompts : itemPrompts).filter(([, t]) => !isNoisePrompt(t));
71
+ // Keep times compact: only first/last per minute is enough for active-time math
72
+ const compact = [];
73
+ let lastMin = -1;
74
+ for (const t of times.sort((a, b) => a - b)) { const m = Math.floor(t / 60000); if (m !== lastMin) { compact.push(t); lastMin = m; } }
75
+ return { sid, cwd, model, firstTs, lastUsage, lastUsageTs, prompts, calls, times: compact };
76
+ }
77
+
78
+ export async function collect(c, { since = 0, onProgress } = {}) {
79
+ const files = [
80
+ ...walk(path.join(home(), 'sessions'), (p) => /\.jsonl(\.zst)?$/.test(p)),
81
+ ...walk(path.join(home(), 'archived_sessions'), (p) => /\.jsonl(\.zst)?$/.test(p)),
82
+ ].filter((f) => { try { return fs.statSync(f).mtimeMs >= since; } catch { return false; } });
83
+
84
+ const results = [];
85
+ await parseAll(new URL(import.meta.url).href, files, (r) => results.push(r), onProgress);
86
+ // Process oldest threads first so forks (which replay their parent's prompts) are recognised as copies
87
+ results.sort((a, b) => a.firstTs - b.firstTs);
88
+ const seenSessions = new Set();
89
+ const seenSeq = new Set();
90
+ const seenCalls = new Set();
91
+ for (const r of results) {
92
+ if (seenSessions.has(r.sid)) continue; // archived copy of a live session
93
+ seenSessions.add(r.sid);
94
+ c.session('codex', r.sid, { project: r.cwd, model: r.model });
95
+ for (const t of r.times) c.session('codex', r.sid, { ts: t });
96
+ let prev = '';
97
+ for (const [ts, text] of r.prompts) {
98
+ const k = `${prev.slice(0, 120)}\u0000${text.slice(0, 300)}`;
99
+ prev = text;
100
+ if (seenSeq.has(k)) continue; // replayed history from a forked thread
101
+ seenSeq.add(k);
102
+ c.prompt('codex', r.sid, ts, text);
103
+ }
104
+ for (const [ts, nm, f, cid] of r.calls) {
105
+ if (cid) { if (seenCalls.has(cid)) continue; seenCalls.add(cid); }
106
+ c.toolCall('codex', r.sid, ts, nm, f);
107
+ }
108
+ const u = r.lastUsage;
109
+ if (u) {
110
+ const cached = u.cached_input_tokens || 0;
111
+ c.turn('codex', r.sid, r.lastUsageTs || r.firstTs, r.model, {
112
+ input: Math.max(0, (u.input_tokens || 0) - cached), output: u.output_tokens, cacheRead: cached, cacheWrite: u.cache_write_input_tokens,
113
+ });
114
+ } else if (r.model) {
115
+ c.turn('codex', r.sid, r.firstTs, r.model, {});
116
+ }
117
+ }
118
+ }
@@ -0,0 +1,91 @@
1
+ // Cursor: <Cursor User dir>/globalStorage/state.vscdb, table cursorDiskKV
2
+ // composerData:<chatId> one chat (model, lines added/removed)
3
+ // bubbleId:<chatId>:<bubbleId> one message (type 1 = you, type 2 = AI)
4
+ // workspaceStorage/*/state.vscdb maps chats to project folders.
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import fs from 'node:fs';
8
+ import { exists, ms, safeJson } from '../fsutil.js';
9
+ import { openDb, hasSqlite } from '../sqlite.js';
10
+ import { isNoisePrompt } from '../collector.js';
11
+
12
+ export const id = 'cursor';
13
+ export const name = 'Cursor';
14
+
15
+ function userDir() {
16
+ const h = os.homedir();
17
+ if (process.platform === 'darwin') return path.join(h, 'Library', 'Application Support', 'Cursor', 'User');
18
+ if (process.platform === 'win32') return path.join(process.env.APPDATA || path.join(h, 'AppData', 'Roaming'), 'Cursor', 'User');
19
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(h, '.config'), 'Cursor', 'User');
20
+ }
21
+
22
+ const globalDb = () => path.join(userDir(), 'globalStorage', 'state.vscdb');
23
+
24
+ export function detect() { return exists(globalDb()) && hasSqlite(); }
25
+
26
+ function workspaceMap() {
27
+ const map = new Map();
28
+ const ws = path.join(userDir(), 'workspaceStorage');
29
+ let dirs = [];
30
+ try { dirs = fs.readdirSync(ws); } catch { return map; }
31
+ for (const d of dirs) {
32
+ const meta = safeJson(readSafe(path.join(ws, d, 'workspace.json')));
33
+ const folder = meta && (meta.folder || meta.workspace);
34
+ const dbFile = path.join(ws, d, 'state.vscdb');
35
+ if (!folder || !exists(dbFile)) continue;
36
+ try {
37
+ const db = openDb(dbFile);
38
+ const rows = db.all("select value from ItemTable where key = 'composer.composerData'");
39
+ db.close();
40
+ const data = rows[0] && safeJson(rows[0].value);
41
+ for (const comp of (data && data.allComposers) || []) map.set(comp.composerId, folder);
42
+ } catch {}
43
+ }
44
+ return map;
45
+ }
46
+
47
+ function readSafe(f) { try { return fs.readFileSync(f, 'utf8'); } catch { return null; } }
48
+
49
+ function fileFromTool(t) {
50
+ const p = safeJson(t.params) || safeJson(t.rawArgs) || {};
51
+ return p.targetFile || p.target_file || p.relativeWorkspacePath || p.path || p.filePath || p.file_path || null;
52
+ }
53
+
54
+ export async function collect(c) {
55
+ const projects = workspaceMap();
56
+ const db = openDb(globalDb());
57
+ const chatModel = new Map();
58
+ try {
59
+ db.each("select key, value from cursorDiskKV where key like 'composerData:%'", (r) => {
60
+ const d = safeJson(r.value);
61
+ if (!d) return;
62
+ const id = d.composerId || r.key.slice('composerData:'.length);
63
+ const model = d.modelConfig && d.modelConfig.modelName;
64
+ if (model && model !== 'default') chatModel.set(id, model);
65
+ const ts = ms(d.createdAt);
66
+ if (!ts) return;
67
+ c.session('cursor', id, { project: projects.get(id), ts });
68
+ c.lines.added += d.totalLinesAdded || 0;
69
+ c.lines.removed += d.totalLinesRemoved || 0;
70
+ });
71
+ db.each("select key, value from cursorDiskKV where key like 'bubbleId:%'", (r) => {
72
+ const d = safeJson(r.value);
73
+ if (!d) return;
74
+ const chatId = r.key.split(':')[1];
75
+ const ts = ms(d.createdAt);
76
+ if (!ts) return;
77
+ c.session('cursor', chatId, { project: projects.get(chatId) });
78
+ if (d.type === 1) {
79
+ const model = (d.modelInfo && d.modelInfo.modelName) || chatModel.get(chatId);
80
+ if (model && model !== 'default') chatModel.set(chatId, model);
81
+ if (d.text && !isNoisePrompt(d.text)) c.prompt('cursor', chatId, ts, d.text);
82
+ else c.session('cursor', chatId, { ts });
83
+ } else if (d.type === 2) {
84
+ const tk = d.tokenCount || {};
85
+ c.turn('cursor', chatId, ts, chatModel.get(chatId), { input: tk.inputTokens, output: tk.outputTokens });
86
+ const t = d.toolFormerData;
87
+ if (t && t.name) c.toolCall('cursor', chatId, ts, t.name, fileFromTool(t));
88
+ }
89
+ });
90
+ } finally { db.close(); }
91
+ }
@@ -0,0 +1,87 @@
1
+ // OpenCode: ~/.local/share/opencode/opencode.db (SQLite), older versions: ~/.local/share/opencode/storage/*.json
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import fs from 'node:fs';
5
+ import { walk, exists, ms, safeJson } from '../fsutil.js';
6
+ import { openDb, hasSqlite } from '../sqlite.js';
7
+ import { isNoisePrompt } from '../collector.js';
8
+
9
+ export const id = 'opencode';
10
+ export const name = 'OpenCode';
11
+
12
+ function dataDir() {
13
+ const xdg = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share');
14
+ return path.join(xdg, 'opencode');
15
+ }
16
+
17
+ export function detect() {
18
+ const d = dataDir();
19
+ return exists(path.join(d, 'opencode.db')) || exists(path.join(d, 'storage', 'message'));
20
+ }
21
+
22
+ function handle(c, sessions, messages, parts) {
23
+ // sessions: [{id, directory, parent_id}], messages: [{id, session_id, data}], parts: [{message_id, session_id, data}]
24
+ const dirOf = new Map();
25
+ for (const s of sessions) {
26
+ dirOf.set(s.id, s.directory);
27
+ c.session('opencode', s.id, { project: s.directory });
28
+ }
29
+ const msgs = new Map();
30
+ for (const m of messages) {
31
+ const d = safeJson(m.data) || {};
32
+ msgs.set(m.id, { ...d, session_id: m.session_id, created: ms(d.time && d.time.created) || ms(m.time_created) });
33
+ }
34
+ const userText = new Map();
35
+ for (const p of parts) {
36
+ const d = safeJson(p.data) || {};
37
+ const m = msgs.get(p.message_id);
38
+ if (!m) continue;
39
+ if (d.type === 'text' && m.role === 'user' && !d.synthetic) {
40
+ userText.set(p.message_id, (userText.get(p.message_id) || '') + (d.text || ''));
41
+ } else if (d.type === 'tool') {
42
+ const input = (d.state && d.state.input) || {};
43
+ c.toolCall('opencode', m.session_id, m.created, d.tool, input.filePath || input.file_path || input.path);
44
+ }
45
+ }
46
+ for (const [id, m] of msgs) {
47
+ if (m.role === 'user') {
48
+ const t = userText.get(id);
49
+ if (t && !isNoisePrompt(t)) c.prompt('opencode', m.session_id, m.created, t);
50
+ else c.session('opencode', m.session_id, { ts: m.created });
51
+ } else if (m.role === 'assistant') {
52
+ const t = m.tokens || {};
53
+ c.turn('opencode', m.session_id, m.created, m.modelID || (m.model && m.model.modelID), {
54
+ input: t.input, output: (t.output || 0) + (t.reasoning || 0),
55
+ cacheRead: t.cache && t.cache.read, cacheWrite: t.cache && t.cache.write,
56
+ });
57
+ const done = ms(m.time && m.time.completed);
58
+ if (done) c.session('opencode', m.session_id, { ts: done });
59
+ }
60
+ }
61
+ }
62
+
63
+ export async function collect(c) {
64
+ const d = dataDir();
65
+ const dbFile = path.join(d, 'opencode.db');
66
+ if (exists(dbFile) && hasSqlite()) {
67
+ const db = openDb(dbFile);
68
+ try {
69
+ handle(c,
70
+ db.all('select id, directory, parent_id from session'),
71
+ db.all('select id, session_id, time_created, data from message'),
72
+ db.all("select message_id, session_id, data from part where data like '%\"type\":\"text\"%' or data like '%\"type\":\"tool\"%'"),
73
+ );
74
+ } finally { db.close(); }
75
+ return;
76
+ }
77
+ // Legacy JSON storage
78
+ const st = path.join(d, 'storage');
79
+ const read = (f) => safeJson(fs.readFileSync(f, 'utf8'));
80
+ const sessions = walk(path.join(st, 'session'), (p) => p.endsWith('.json')).map(read).filter(Boolean)
81
+ .map((s) => ({ id: s.id, directory: s.directory, parent_id: s.parentID }));
82
+ const messages = walk(path.join(st, 'message'), (p) => p.endsWith('.json')).map(read).filter(Boolean)
83
+ .map((m) => ({ id: m.id, session_id: m.sessionID, data: m }));
84
+ const parts = walk(path.join(st, 'part'), (p) => p.endsWith('.json')).map(read).filter(Boolean)
85
+ .map((p) => ({ message_id: p.messageID, session_id: p.sessionID, data: p }));
86
+ handle(c, sessions, messages, parts);
87
+ }