wrapped-agents 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs CHANGED
@@ -23,6 +23,8 @@ usage: npx wrapped-agents [options]
23
23
  --json build wrapped.json only and print its path (for agents)
24
24
  --from <file> render from an existing wrapped.json instead of reading logs
25
25
  --roast "<line>" your agent's roast (≤ 12 words, numbers from this wrap)
26
+ --quip "<line>" your agent's funny line for the tokens slide (numbers from compare.options)
27
+ --day "<line>" your agent's guess at what happened on your busiest day
26
28
  --roast-by <name> who wrote it, e.g. "Claude Code" (shown under the roast)
27
29
  --no-roast no roast slide
28
30
  --show-projects show project names (hidden by default)
@@ -44,6 +46,8 @@ function args(argv) {
44
46
  else if (k === '--roast') a.roast = v();
45
47
  else if (k === '--no-roast') a.roast = '';
46
48
  else if (k === '--roast-by') a.roastBy = v();
49
+ else if (k === '--quip') a.quip = v();
50
+ else if (k === '--day') a.day = v();
47
51
  else if (k === '--show-projects') a.showProjects = true;
48
52
  else if (k === '--no-git') a.git = false;
49
53
  else if (k === '--no-open') a.open = false;
@@ -66,11 +70,11 @@ function openFile(file) {
66
70
  try { spawn(cmd[0], cmd[1], { detached: true, stdio: 'ignore' }).unref(); return true; } catch { return false; }
67
71
  }
68
72
 
69
- function cleanRoast(s) {
73
+ function cleanRoast(s, max = 14) {
70
74
  const r = String(s || '').replace(/\s+/g, ' ').trim();
71
75
  if (!r) return null;
72
76
  const words = r.split(' ');
73
- return words.length > 14 ? words.slice(0, 14).join(' ') + '…' : r;
77
+ return words.length > max ? words.slice(0, max).join(' ') + '…' : r;
74
78
  }
75
79
 
76
80
  async function main() {
@@ -99,6 +103,7 @@ async function main() {
99
103
  log(` done in ${((Date.now() - t0) / 1000).toFixed(1)} s`);
100
104
  }
101
105
 
106
+ delete wrapped.letter; // retired: no agent letter slide
102
107
  if (a.handle) wrapped.handle = { ...(wrapped.handle || {}), github: a.handle, display: a.handle };
103
108
  if (a.skin) wrapped.theme = { ...(wrapped.theme || {}), skin: a.skin };
104
109
  if (a.roast !== undefined) {
@@ -107,6 +112,17 @@ async function main() {
107
112
  // every number in the roast must exist in this wrap (agents sometimes reuse numbers from an older run)
108
113
  if (wrapped.roast && !roastNumbersOk(wrapped, wrapped.roast)) log(`warning: the roast cites numbers that aren't in this wrap; please re-write it from wrapped-${wrapped.year}.json`);
109
114
  }
115
+ if (a.quip !== undefined && wrapped.compare) {
116
+ const q = cleanRoast(a.quip, 18);
117
+ if (q && !roastNumbersOk(wrapped, q)) log(`warning: the quip cites numbers that aren't in this wrap (use compare.options); please re-write it`);
118
+ if (q) { wrapped.compare.text = q; wrapped.compare.by = a.roastBy || 'your agent'; }
119
+ }
120
+ for (const [key, val, max] of [['dayLine', a.day, 20]]) {
121
+ if (val === undefined) continue;
122
+ const t = String(val).replace(/\s+/g, ' ').trim(), words = t.split(' ');
123
+ wrapped[key] = t ? (words.length > max ? words.slice(0, max).join(' ') + '…' : t) : null;
124
+ if (wrapped[key] && !roastNumbersOk(wrapped, wrapped[key])) log(`warning: --${key === 'dayLine' ? 'day' : key} cites numbers that aren't in this wrap; please re-write it`);
125
+ }
110
126
  if (a.showProjects) wrapped.privacy = { ...(wrapped.privacy || {}), projectsHidden: false };
111
127
 
112
128
  fs.mkdirSync(a.out, { recursive: true });
@@ -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
+ }