chompyy 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +14 -1
  2. package/dist/advice.js +98 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/approvals.js +129 -0
  6. package/dist/appstate.js +73 -3
  7. package/dist/away.js +48 -5
  8. package/dist/blueprint.js +3 -7
  9. package/dist/board.js +1 -0
  10. package/dist/cli.js +343 -18
  11. package/dist/codexquota.js +106 -0
  12. package/dist/codexusage.js +10 -0
  13. package/dist/config.js +2 -0
  14. package/dist/context.js +30 -0
  15. package/dist/costs.js +41 -2
  16. package/dist/demon.js +20 -0
  17. package/dist/detect.js +38 -6
  18. package/dist/didwork.js +26 -0
  19. package/dist/label.js +33 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +72 -0
  22. package/dist/nudge.js +70 -24
  23. package/dist/pacing.js +16 -1
  24. package/dist/punchcard.js +39 -0
  25. package/dist/questions.js +71 -0
  26. package/dist/recap.js +74 -0
  27. package/dist/receipt.js +48 -0
  28. package/dist/recipe.js +79 -0
  29. package/dist/savings.js +111 -0
  30. package/dist/stamps.js +14 -0
  31. package/dist/suggest.js +15 -5
  32. package/dist/triggers.js +5 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6955 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/dist/wastechecks.js +233 -0
  162. package/package.json +1 -1
@@ -0,0 +1,1163 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { existsSync, readdirSync, readFileSync, statSync } from 'fs';
3
+ import { join } from 'path';
4
+ import { homedir } from 'os';
5
+ import { getEditorDataDir } from '../editor-data-dir.js';
6
+ import { calculateCost, ownValue } from '../models.js';
7
+ import { extractBashCommands } from '../bash-utils.js';
8
+ import { readCachedResults, readFirstSeen, writeCachedResults, writeFirstSeen } from '../cursor-cache.js';
9
+ import { importSource, importSourceParser } from '../cursor-import.js';
10
+ import { isSqliteAvailable, isSqliteBusyError, getSqliteLoadError, openDatabase, blobToText, isSqliteReadonlyError, warnSqliteReadonlyOnce, } from '../sqlite.js';
11
+ import { estimateTokensFromChars } from '../token-estimate.js';
12
+ /** Matches cli-date.ts "all" period cap (6 months). */
13
+ const CURSOR_MAX_LOOKBACK_MONTHS = 6;
14
+ export function getCursorTimeFloor(dateRange) {
15
+ const now = new Date();
16
+ const maxStart = new Date(now.getFullYear(), now.getMonth() - CURSOR_MAX_LOOKBACK_MONTHS, now.getDate());
17
+ const start = dateRange?.start ?? maxStart;
18
+ const effective = start < maxStart ? maxStart : start;
19
+ return effective.toISOString();
20
+ }
21
+ const CURSOR_COST_MODEL = 'claude-sonnet-4-5';
22
+ const modelDisplayNames = {
23
+ 'claude-4.5-opus-high-thinking': 'Opus 4.5 (Thinking)',
24
+ 'claude-4-opus': 'Opus 4',
25
+ 'claude-4-sonnet-thinking': 'Sonnet 4 (Thinking)',
26
+ 'claude-4.5-sonnet-thinking': 'Sonnet 4.5 (Thinking)',
27
+ 'claude-4.6-sonnet': 'Sonnet 4.6',
28
+ 'composer-1': 'Composer 1',
29
+ 'grok-code-fast-1': 'Grok Code Fast',
30
+ 'gemini-3-pro': 'Gemini 3 Pro',
31
+ 'gpt-5.2-low': 'GPT-5.2 Low',
32
+ 'gpt-5.2': 'GPT-5.2',
33
+ 'gpt-5.1-codex-high': 'GPT-5.1 Codex',
34
+ 'gpt-5': 'GPT-5',
35
+ 'gpt-4.1': 'GPT-4.1',
36
+ 'cursor-auto': 'Cursor (auto)',
37
+ };
38
+ // SQLITE_BUSY must reach parser.ts, whose busy path skips the source without
39
+ // caching; swallowing it here would stamp a silently degraded parse into the
40
+ // results cache under an unchanged DB fingerprint (Cursor writes via WAL, so
41
+ // contention does not change the main file's stat).
42
+ function rethrowBusy(err) {
43
+ if (isSqliteBusyError(err))
44
+ throw err;
45
+ }
46
+ export function getCursorDbPath() {
47
+ return join(getEditorDataDir('Cursor', homedir(), process.platform), 'User', 'globalStorage', 'state.vscdb');
48
+ }
49
+ function getCursorWorkspaceStorageDir(globalDbPath) {
50
+ // Sibling of globalStorage. Cursor lays out User/{globalStorage,workspaceStorage}/.
51
+ // We derive the workspaceStorage path from the global DB path so a test or
52
+ // override can supply both consistently from one root.
53
+ // globalDbPath = .../User/globalStorage/state.vscdb
54
+ // workspaceStorage = .../User/workspaceStorage
55
+ const userDir = join(globalDbPath, '..', '..');
56
+ return join(userDir, 'workspaceStorage');
57
+ }
58
+ const ORPHAN_TAG = '__orphan__';
59
+ // Catch-all project label for composers that did not register against any
60
+ // workspace. When the user has no workspaces at all this is the only label
61
+ // shown, matching the pre-PR `cursor` project so legacy installs are not
62
+ // renamed by the breakdown change.
63
+ const ORPHAN_PROJECT = 'cursor';
64
+ function sanitizeWorkspaceUri(uri) {
65
+ // Mirrors Claude's slug convention so two providers reporting the same
66
+ // project path produce identical project keys for cross-provider rollup.
67
+ // file:///Users/me/myproject → -Users-me-myproject
68
+ // vscode-remote://wsl+Ubuntu/home/me/proj → -wsl-Ubuntu-home-me-proj
69
+ let path;
70
+ if (uri.startsWith('file://')) {
71
+ path = uri.slice('file://'.length);
72
+ }
73
+ else {
74
+ // Other URI schemes (vscode-remote://, ssh+remote://, etc.): swap "://"
75
+ // for a leading "/" so the slugifier produces a predictable shape.
76
+ path = uri.replace(/^[^:]+:\/\//, '/').replace(/\+/g, '-');
77
+ }
78
+ try {
79
+ path = decodeURIComponent(path);
80
+ }
81
+ catch {
82
+ // Malformed percent encoding — keep as-is rather than throw.
83
+ }
84
+ return path.replace(/\/+/g, '-');
85
+ }
86
+ let workspaceMapCache = null;
87
+ let workspaceMapCacheRoot = null;
88
+ let workspaceMapCacheStamp = null;
89
+ /// Visible for tests so a fixture can rebuild the map after writing fresh
90
+ /// workspace directories.
91
+ export function clearCursorWorkspaceMapCache() {
92
+ workspaceMapCache = null;
93
+ workspaceMapCacheRoot = null;
94
+ workspaceMapCacheStamp = null;
95
+ }
96
+ // The directory's mtime moves when a workspace is added or removed, but a chat
97
+ // started in a known workspace only rewrites that workspace's state.vscdb.
98
+ // The cost is one stat per workspace file per discovery. A same-size rewrite
99
+ // within the same millisecond is not detectable here.
100
+ function workspaceStorageStamp(workspaceStorageDir) {
101
+ const parts = [];
102
+ try {
103
+ parts.push(String(statSync(workspaceStorageDir).mtimeMs));
104
+ for (const hashDir of readdirSync(workspaceStorageDir)) {
105
+ for (const file of ['state.vscdb', 'state.vscdb-wal']) {
106
+ try {
107
+ const s = statSync(join(workspaceStorageDir, hashDir, file));
108
+ parts.push(`${hashDir}/${file}:${s.mtimeMs}:${s.size}`);
109
+ }
110
+ catch { }
111
+ }
112
+ }
113
+ }
114
+ catch { }
115
+ return parts.join('|');
116
+ }
117
+ /// Discovery passes `recheck` so a resident process picks up new workspaces
118
+ /// and chats; parsers reuse the map their discovery built.
119
+ function loadWorkspaceMap(workspaceStorageDir, recheck = false) {
120
+ const cached = workspaceMapCache && workspaceMapCacheRoot === workspaceStorageDir ? workspaceMapCache : null;
121
+ if (cached && !recheck)
122
+ return cached;
123
+ const stamp = workspaceStorageStamp(workspaceStorageDir);
124
+ if (cached && stamp === workspaceMapCacheStamp)
125
+ return cached;
126
+ workspaceMapCacheStamp = stamp;
127
+ const result = {
128
+ composerToWorkspace: new Map(),
129
+ workspaceProjectName: new Map(),
130
+ };
131
+ let entries;
132
+ try {
133
+ entries = readdirSync(workspaceStorageDir);
134
+ }
135
+ catch {
136
+ workspaceMapCache = result;
137
+ workspaceMapCacheRoot = workspaceStorageDir;
138
+ return result;
139
+ }
140
+ for (const hashDir of entries) {
141
+ const wsJsonPath = join(workspaceStorageDir, hashDir, 'workspace.json');
142
+ const wsDbPath = join(workspaceStorageDir, hashDir, 'state.vscdb');
143
+ let wsJsonRaw;
144
+ try {
145
+ wsJsonRaw = readFileSync(wsJsonPath, 'utf-8');
146
+ }
147
+ catch {
148
+ continue;
149
+ }
150
+ let folder;
151
+ try {
152
+ const parsed = JSON.parse(wsJsonRaw);
153
+ folder = parsed.folder;
154
+ }
155
+ catch {
156
+ continue;
157
+ }
158
+ if (!folder)
159
+ continue;
160
+ if (!existsSync(wsDbPath))
161
+ continue;
162
+ let db;
163
+ try {
164
+ db = openDatabase(wsDbPath);
165
+ }
166
+ catch (err) {
167
+ if (isSqliteReadonlyError(err))
168
+ warnSqliteReadonlyOnce(wsDbPath);
169
+ continue;
170
+ }
171
+ try {
172
+ // Cursor renamed the per-workspace composer list from
173
+ // 'composer.composerData' to 'composer.composerHeaders' in newer builds
174
+ // (identical { allComposers: [{ composerId }] } shape). Read both keys
175
+ // and merge so the composer -> workspace mapping keeps working across
176
+ // Cursor versions. Without this, on builds that only write
177
+ // 'composer.composerHeaders' every composer falls through to the
178
+ // 'cursor' orphan bucket and per-project attribution is lost.
179
+ const rows = db.query("SELECT value FROM ItemTable WHERE key IN ('composer.composerData', 'composer.composerHeaders')");
180
+ if (rows.length === 0)
181
+ continue;
182
+ const project = sanitizeWorkspaceUri(folder);
183
+ let added = 0;
184
+ for (const row of rows) {
185
+ let parsed;
186
+ try {
187
+ parsed = JSON.parse(row.value);
188
+ }
189
+ catch {
190
+ continue;
191
+ }
192
+ for (const c of parsed.allComposers ?? []) {
193
+ if (typeof c.composerId === 'string') {
194
+ result.composerToWorkspace.set(c.composerId, folder);
195
+ added += 1;
196
+ }
197
+ }
198
+ }
199
+ if (added > 0) {
200
+ result.workspaceProjectName.set(folder, project);
201
+ }
202
+ }
203
+ catch {
204
+ // best-effort
205
+ }
206
+ finally {
207
+ db.close();
208
+ }
209
+ }
210
+ workspaceMapCache = result;
211
+ workspaceMapCacheRoot = workspaceStorageDir;
212
+ return result;
213
+ }
214
+ /// Pulls the composer id out of a `bubbleId:<composerId>:<bubbleUuid>` key.
215
+ /// Returns null when the composer segment contains a CR/LF, which is the
216
+ /// signature Cursor uses for tool-call sub-composer rows in real data —
217
+ /// e.g. `bubbleId:task-call_xxxx\nfc_yyyy:<bubbleUuid>` is one key with a
218
+ /// literal newline between the `task-call_` and `fc_` halves. Those rows
219
+ /// are not standalone composers and would otherwise inflate the orphan
220
+ /// project's session count.
221
+ function parseComposerIdFromKey(key) {
222
+ if (!key)
223
+ return null;
224
+ const firstColon = key.indexOf(':');
225
+ if (firstColon < 0)
226
+ return null;
227
+ const secondColon = key.indexOf(':', firstColon + 1);
228
+ if (secondColon < 0)
229
+ return null;
230
+ const candidate = key.slice(firstColon + 1, secondColon);
231
+ if (!candidate)
232
+ return null;
233
+ // Reject any multi-line / control-char composer id. Real composer ids
234
+ // (UUIDs) and synthetic fixture ids are both single-line.
235
+ if (/[\r\n\x00]/.test(candidate))
236
+ return null;
237
+ return candidate;
238
+ }
239
+ // Encodes the active workspace into source.path so the parser knows which
240
+ // composers to filter for. `#cursor-ws=` is a private separator: `state.vscdb`
241
+ // does not contain `#` (we construct the path ourselves), and the literal
242
+ // token only appears in source paths emitted from this provider, so there
243
+ // is no realistic collision.
244
+ const WORKSPACE_SEP = '#cursor-ws=';
245
+ function encodeSourcePath(dbPath, workspaceTag) {
246
+ return `${dbPath}${WORKSPACE_SEP}${workspaceTag}`;
247
+ }
248
+ function decodeSourcePath(sourcePath) {
249
+ const idx = sourcePath.indexOf(WORKSPACE_SEP);
250
+ // Backwards-compat: a bare DB path with no workspace tag means "give me
251
+ // every call from this DB". Older cached SessionSource entries and any
252
+ // hand-constructed source from a test land here.
253
+ if (idx < 0)
254
+ return { dbPath: sourcePath, workspaceTag: '__all__' };
255
+ return {
256
+ dbPath: sourcePath.slice(0, idx),
257
+ workspaceTag: sourcePath.slice(idx + WORKSPACE_SEP.length),
258
+ };
259
+ }
260
+ function extractLanguages(codeBlocksJson) {
261
+ if (!codeBlocksJson)
262
+ return [];
263
+ try {
264
+ const blocks = JSON.parse(codeBlocksJson);
265
+ if (!Array.isArray(blocks))
266
+ return [];
267
+ const langs = new Set();
268
+ for (const block of blocks) {
269
+ if (block.languageId && block.languageId !== 'plaintext') {
270
+ langs.add(block.languageId);
271
+ }
272
+ }
273
+ return [...langs];
274
+ }
275
+ catch {
276
+ return [];
277
+ }
278
+ }
279
+ function resolveModel(raw) {
280
+ if (!raw || raw === 'default')
281
+ return CURSOR_COST_MODEL;
282
+ return raw;
283
+ }
284
+ function modelForDisplay(raw) {
285
+ if (!raw || raw === 'default')
286
+ return 'cursor-auto';
287
+ return raw;
288
+ }
289
+ const BUBBLE_QUERY_BASE = `
290
+ SELECT
291
+ key as bubble_key,
292
+ json_extract(value, '$.bubbleId') as bubble_id,
293
+ json_extract(value, '$.tokenCount.inputTokens') as input_tokens,
294
+ json_extract(value, '$.tokenCount.outputTokens') as output_tokens,
295
+ json_extract(value, '$.modelInfo.modelName') as model,
296
+ json_extract(value, '$.createdAt') as created_at,
297
+ json_extract(value, '$.requestId') as request_id,
298
+ CAST(substr(json_extract(value, '$.text'), 1, 500) AS BLOB) as user_text,
299
+ length(json_extract(value, '$.text')) as text_length,
300
+ json_extract(value, '$.type') as bubble_type,
301
+ CAST(json_extract(value, '$.codeBlocks') AS BLOB) as code_blocks
302
+ FROM cursorDiskKV
303
+ WHERE key LIKE 'bubbleId:%' AND json_valid(value, 10)
304
+ `;
305
+ // agentKv blobs are content-addressed and also hold JSONL logs and files that
306
+ // start with '{'; one of them makes json_extract throw for the whole query.
307
+ // json_valid flag 10 (JSON5 text or strictly valid JSONB) admits exactly what
308
+ // json_extract reads; flag 6 checks JSONB only superficially.
309
+ const AGENTKV_WHERE = `
310
+ FROM cursorDiskKV
311
+ WHERE key LIKE 'agentKv:blob:%'
312
+ AND hex(substr(value, 1, 1)) = '7B'`;
313
+ const AGENTKV_QUERY = `
314
+ SELECT
315
+ json_extract(value, '$.role') as role,
316
+ CAST(json_extract(value, '$.content') AS BLOB) as content,
317
+ json_extract(value, '$.providerOptions.cursor.requestId') as request_id,
318
+ json_extract(value, '$.providerOptions.cursor.modelName') as model
319
+ ${AGENTKV_WHERE}
320
+ AND json_valid(value, 10)
321
+ ORDER BY ROWID ASC
322
+ `;
323
+ const AGENTKV_MALFORMED_QUERY = `SELECT COUNT(*) as cnt ${AGENTKV_WHERE} AND NOT json_valid(value, 10)`;
324
+ const BUBBLE_REQUEST_IDS_QUERY = `
325
+ SELECT json_extract(value, '$.requestId') as request_id,
326
+ json_extract(value, '$.createdAt') as created_at
327
+ FROM cursorDiskKV
328
+ WHERE key LIKE 'bubbleId:%'
329
+ AND json_valid(value, 10)
330
+ AND json_extract(value, '$.requestId') IN`;
331
+ // Under the 999 bound-parameter limit of older SQLite builds. Each chunk is
332
+ // one table scan, so many unjoined streams on a huge DB cost several scans.
333
+ // About 0.9 s per chunk on a 3.75 GB, 60k-bubble database, so one parse looks
334
+ // up at most 9,000 ids (near 9 s). Ids past the cap are left for the next
335
+ // parse, which resumes in sorted order because resolved ids are remembered.
336
+ const REQUEST_ID_CHUNK = 900;
337
+ const MAX_REQUEST_ID_CHUNKS = 10;
338
+ // Sidecar key for a looked-up request's newest bubble time.
339
+ const BUBBLE_TIME_KEY = 'bubble:';
340
+ // Split into HEAD (predicates we always emit) and TAIL (ORDER BY) so the
341
+ // caller can splice in an optional `ROWID >= ?` cutoff without rewriting
342
+ // the whole template. The original combined string is preserved as
343
+ // BUBBLE_QUERY_SINCE for any caller that doesn't want the cap.
344
+ const BUBBLE_QUERY_SINCE_HEAD = BUBBLE_QUERY_BASE + `
345
+ AND json_extract(value, '$.createdAt') IS NOT NULL
346
+ AND json_extract(value, '$.createdAt') > ?`;
347
+ const BUBBLE_QUERY_SINCE_TAIL = `
348
+ ORDER BY ROWID ASC
349
+ `;
350
+ const BUBBLE_QUERY_SINCE = BUBBLE_QUERY_SINCE_HEAD + BUBBLE_QUERY_SINCE_TAIL;
351
+ // Paged variant for very large DBs: fetches one ROWID-descending page below a
352
+ // cursor. Returns ROWID and createdAt so the caller can stop once it has paged
353
+ // past the requested window floor. No date predicate here — the caller filters
354
+ // by createdAt in JS so it can see the window boundary.
355
+ const BUBBLE_QUERY_PAGE = `
356
+ SELECT
357
+ key as bubble_key,
358
+ json_extract(value, '$.bubbleId') as bubble_id,
359
+ ROWID as rid,
360
+ json_extract(value, '$.tokenCount.inputTokens') as input_tokens,
361
+ json_extract(value, '$.tokenCount.outputTokens') as output_tokens,
362
+ json_extract(value, '$.modelInfo.modelName') as model,
363
+ json_extract(value, '$.createdAt') as created_at,
364
+ json_extract(value, '$.requestId') as request_id,
365
+ CAST(substr(json_extract(value, '$.text'), 1, 500) AS BLOB) as user_text,
366
+ length(json_extract(value, '$.text')) as text_length,
367
+ json_extract(value, '$.type') as bubble_type,
368
+ CAST(json_extract(value, '$.codeBlocks') AS BLOB) as code_blocks
369
+ FROM cursorDiskKV
370
+ WHERE key LIKE 'bubbleId:%' AND ROWID < ? AND json_valid(value, 10)
371
+ ORDER BY ROWID DESC
372
+ LIMIT ?
373
+ `;
374
+ function validateSchema(db) {
375
+ try {
376
+ const rows = db.query("SELECT COUNT(*) as cnt FROM cursorDiskKV WHERE key LIKE 'bubbleId:%' LIMIT 1");
377
+ return rows.length > 0;
378
+ }
379
+ catch (err) {
380
+ rethrowBusy(err);
381
+ return false;
382
+ }
383
+ }
384
+ /// Scans bubbles for very large DBs by paging ROWID-descending (newest first),
385
+ /// keeping only rows within the requested window (createdAt > timeFloor), and
386
+ /// stopping once a full page lands below the floor. A `budget` caps the number
387
+ /// of in-range bubbles collected so a genuinely enormous in-range scan can't
388
+ /// stall; `truncated` is set only when that budget is actually hit, so the
389
+ /// caller warns only when older in-range sessions were really dropped.
390
+ function scanBubblesPaged(db, timeFloor, budget) {
391
+ const BATCH = 25_000;
392
+ const collected = [];
393
+ let beforeRowId = Number.MAX_SAFE_INTEGER;
394
+ let truncated = false;
395
+ paging: while (true) {
396
+ let batch;
397
+ try {
398
+ batch = db.query(BUBBLE_QUERY_PAGE, [beforeRowId, BATCH]);
399
+ }
400
+ catch (err) {
401
+ rethrowBusy(err);
402
+ break;
403
+ }
404
+ if (batch.length === 0)
405
+ break;
406
+ for (const row of batch) {
407
+ if (collected.length >= budget) {
408
+ truncated = true;
409
+ break paging;
410
+ }
411
+ if (row.created_at != null && row.created_at > timeFloor)
412
+ collected.push(row);
413
+ }
414
+ const oldest = batch[batch.length - 1];
415
+ beforeRowId = oldest.rid ?? 0;
416
+ if (beforeRowId <= 0)
417
+ break;
418
+ if (batch.length < BATCH)
419
+ break; // exhausted the table
420
+ // Pages are ROWID-descending (~chronological), so once the oldest row in a
421
+ // full page predates the window, every older page does too.
422
+ if (oldest.created_at != null && oldest.created_at <= timeFloor)
423
+ break;
424
+ }
425
+ // Restore ROWID-ascending order to match the un-paged query's row ordering.
426
+ collected.sort((a, b) => (a.rid ?? 0) - (b.rid ?? 0));
427
+ return { rows: collected, truncated };
428
+ }
429
+ // Cursor leaves the per-bubble tokenCount at {0,0} on current builds. The only
430
+ // real input figure on disk is the latest context-window snapshot, which Cursor
431
+ // records in composerData.promptTokenBreakdown.totalUsedTokens or
432
+ // contextTokensUsed (the in-app context meter). This is not cumulative per-turn,
433
+ // so local SQLite undercounts admin-console usage; parity requires the opt-in
434
+ // Cursor Admin API: POST api.cursor.com/teams/filtered-usage-events.
435
+ // The key-range predicate seeks the primary key instead of scanning the table.
436
+ const COMPOSER_META_QUERY = `
437
+ SELECT
438
+ substr(key, length('composerData:') + 1) as composer_id,
439
+ json_extract(value, '$.promptTokenBreakdown.totalUsedTokens') as used,
440
+ json_extract(value, '$.contextTokensUsed') as ctx,
441
+ json_extract(value, '$.createdAt') as created_at,
442
+ json_extract(value, '$.latestChatGenerationUUID') as latest_request_id,
443
+ json_extract(value, '$.subagentInfo.parentRequestId') as parent_request_id
444
+ FROM cursorDiskKV
445
+ WHERE key >= 'composerData:' AND key < 'composerData;' AND json_valid(value, 10)
446
+ `;
447
+ // Also maps each request a conversation names (its latest request, or the
448
+ // request that spawned it as a subagent) to the conversation's start, which
449
+ // dates agent-only requests whose prompt carried no timestamp.
450
+ function loadComposerMeta(db) {
451
+ const map = new Map();
452
+ const requestStart = new Map();
453
+ try {
454
+ const rows = db.query(COMPOSER_META_QUERY);
455
+ for (const r of rows) {
456
+ // `||` rather than `??`: a recorded-but-zero breakdown must fall through
457
+ // to the context meter instead of shadowing it.
458
+ const tokens = (r.used || r.ctx) ?? 0;
459
+ if (r.composer_id && tokens > 0)
460
+ map.set(r.composer_id, { tokens, createdAt: r.created_at ?? null });
461
+ if (typeof r.created_at !== 'number' || r.created_at <= 0)
462
+ continue;
463
+ for (const requestId of [r.latest_request_id, r.parent_request_id]) {
464
+ if (typeof requestId !== 'string' || !requestId)
465
+ continue;
466
+ const known = requestStart.get(requestId);
467
+ if (known === undefined || r.created_at < known)
468
+ requestStart.set(requestId, r.created_at);
469
+ }
470
+ }
471
+ }
472
+ catch (err) {
473
+ rethrowBusy(err);
474
+ /* best-effort: callers fall back to the per-bubble text estimate */
475
+ }
476
+ return { meta: map, requestStart };
477
+ }
478
+ function newAgentStream() {
479
+ return { tools: [], bash: [], userChars: 0, contextChars: 0, assistantChars: 0, model: null, promptAt: null };
480
+ }
481
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
482
+ // Cursor opens a text block of each user turn with the send time, e.g.
483
+ // <timestamp>Friday, Feb 13, 2026, 9:41 PM (UTC-8)</timestamp>.
484
+ const PROMPT_TIME = /^\s*<timestamp>\w+, (\w{3}) (\d{1,2}), (\d{4}), (\d{1,2}):(\d{2}) (AM|PM)( \(UTC(?:([+-]\d{1,2})(?::(\d{2}))?)?\))?<\/timestamp>/;
485
+ function promptTime(raw) {
486
+ let blocks;
487
+ try {
488
+ const parsed = JSON.parse(raw);
489
+ blocks = Array.isArray(parsed) ? parsed : [parsed];
490
+ }
491
+ catch {
492
+ blocks = [raw];
493
+ }
494
+ for (const block of blocks) {
495
+ const text = typeof block === 'string' ? block : block?.text;
496
+ if (typeof text !== 'string')
497
+ continue;
498
+ const m = PROMPT_TIME.exec(text);
499
+ const month = m ? MONTHS.indexOf(m[1]) : -1;
500
+ if (!m || month < 0)
501
+ continue;
502
+ const [year, day, hour12, minute] = [Number(m[3]), Number(m[2]), Number(m[4]), Number(m[5])];
503
+ const offsetHours = Number(m[8] ?? 0);
504
+ const offsetMins = Number(m[9] ?? 0);
505
+ if (hour12 < 1 || hour12 > 12 || minute > 59 || Math.abs(offsetHours) > 14 || offsetMins > 59)
506
+ continue;
507
+ const hour = hour12 % 12 + (m[6] === 'PM' ? 12 : 0);
508
+ // A day past the month's end would roll over into the next month.
509
+ const calendar = new Date(Date.UTC(year, month, day));
510
+ if (calendar.getUTCFullYear() !== year || calendar.getUTCMonth() !== month || calendar.getUTCDate() !== day)
511
+ continue;
512
+ // No zone in the tag: the prompt was written in this machine's zone.
513
+ if (!m[7])
514
+ return new Date(year, month, day, hour, minute).getTime();
515
+ const offsetMinutes = offsetHours * 60 + Math.sign(offsetHours || 1) * offsetMins;
516
+ return Date.UTC(year, month, day, hour, minute) - offsetMinutes * 60_000;
517
+ }
518
+ return null;
519
+ }
520
+ // agentKv rows store content as a plain string or a block array; count only
521
+ // the text inside blocks so the JSON envelope and non-text parts are not
522
+ // billed as prompt characters.
523
+ function contentTextLength(raw) {
524
+ const trimmed = raw.trimStart();
525
+ if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
526
+ try {
527
+ const parsed = JSON.parse(trimmed);
528
+ const blocks = Array.isArray(parsed) ? parsed : [parsed];
529
+ let len = 0;
530
+ for (const block of blocks) {
531
+ if (block == null || typeof block !== 'object')
532
+ continue;
533
+ const b = block;
534
+ if (typeof b.text === 'string')
535
+ len += b.text.length;
536
+ else if (typeof b.content === 'string')
537
+ len += b.content.length;
538
+ }
539
+ return len;
540
+ }
541
+ catch {
542
+ return raw.length;
543
+ }
544
+ }
545
+ return raw.length;
546
+ }
547
+ // Cursor logs the agent's stream (prompt, injected context, tool calls, reply
548
+ // deltas) in agentKv blobs keyed by requestId. Bubbles carry the same
549
+ // requestId, so the map built from the scanned bubbles joins each request to
550
+ // its conversation. Requests with no matching bubble are kept separately:
551
+ // they are real sessions (background runs, older builds) that would otherwise
552
+ // vanish from totals.
553
+ function loadAgentStreams(db, requestToComposer) {
554
+ const byComposer = new Map();
555
+ const unjoined = new Map();
556
+ let rows;
557
+ let malformed = 0;
558
+ try {
559
+ rows = db.query(AGENTKV_QUERY);
560
+ malformed = db.query(AGENTKV_MALFORMED_QUERY)[0]?.cnt ?? 0;
561
+ }
562
+ catch (err) {
563
+ rethrowBusy(err);
564
+ return { byComposer, unjoined, order: [], malformed };
565
+ }
566
+ const bucketFor = (requestId) => {
567
+ const composer = requestToComposer.get(requestId);
568
+ const map = composer ? byComposer : unjoined;
569
+ const key = composer ?? requestId;
570
+ const existing = map.get(key);
571
+ if (existing)
572
+ return existing;
573
+ const fresh = newAgentStream();
574
+ map.set(key, fresh);
575
+ return fresh;
576
+ };
577
+ // Only the turn-opening (user) agentKv row carries the requestId; rows that
578
+ // follow inherit it. Rows written BEFORE their request's id appears (the
579
+ // system prompt and opening user prompt at a conversation start) buffer
580
+ // until the next id, and a system row closes the previous request so
581
+ // interleaved sessions cannot inherit across a conversation boundary.
582
+ let currentRequestId = null;
583
+ let pendingUserChars = 0;
584
+ let pendingContextChars = 0;
585
+ let pendingPromptAt = null;
586
+ // Request ids in the order the stream first wrote them.
587
+ const order = [];
588
+ const ordered = new Set();
589
+ for (const row of rows) {
590
+ if (row.request_id) {
591
+ currentRequestId = row.request_id;
592
+ if (!ordered.has(currentRequestId)) {
593
+ ordered.add(currentRequestId);
594
+ order.push(currentRequestId);
595
+ }
596
+ if (pendingUserChars > 0 || pendingContextChars > 0 || pendingPromptAt !== null) {
597
+ const bucket = bucketFor(currentRequestId);
598
+ bucket.userChars += pendingUserChars;
599
+ bucket.contextChars += pendingContextChars;
600
+ bucket.promptAt ??= pendingPromptAt;
601
+ pendingUserChars = 0;
602
+ pendingContextChars = 0;
603
+ pendingPromptAt = null;
604
+ }
605
+ }
606
+ if (row.model && currentRequestId) {
607
+ const bucket = bucketFor(currentRequestId);
608
+ if (!bucket.model)
609
+ bucket.model = row.model;
610
+ }
611
+ if (!row.content)
612
+ continue;
613
+ if (row.role === 'system') {
614
+ pendingContextChars += contentTextLength(blobToText(row.content));
615
+ currentRequestId = null;
616
+ continue;
617
+ }
618
+ if (row.role === 'user') {
619
+ const text = blobToText(row.content);
620
+ const len = contentTextLength(text);
621
+ const at = promptTime(text);
622
+ if (currentRequestId) {
623
+ const bucket = bucketFor(currentRequestId);
624
+ bucket.userChars += len;
625
+ bucket.promptAt ??= at;
626
+ }
627
+ else {
628
+ pendingUserChars += len;
629
+ pendingPromptAt ??= at;
630
+ }
631
+ continue;
632
+ }
633
+ if (row.role === 'tool') {
634
+ if (currentRequestId)
635
+ bucketFor(currentRequestId).contextChars += contentTextLength(blobToText(row.content));
636
+ continue;
637
+ }
638
+ if (row.role !== 'assistant' || !currentRequestId)
639
+ continue;
640
+ let content;
641
+ try {
642
+ content = JSON.parse(blobToText(row.content));
643
+ }
644
+ catch {
645
+ continue;
646
+ }
647
+ if (!Array.isArray(content))
648
+ continue;
649
+ const bucket = bucketFor(currentRequestId);
650
+ for (const block of content) {
651
+ if (block == null || typeof block !== 'object')
652
+ continue;
653
+ if (typeof block.text === 'string')
654
+ bucket.assistantChars += block.text.length;
655
+ if (block.type !== 'tool-call' || typeof block.toolName !== 'string' || !block.toolName)
656
+ continue;
657
+ // Cursor's terminal tool is 'Shell'; emit the canonical 'Bash' so the
658
+ // cross-provider tool and command breakdowns merge.
659
+ bucket.tools.push(block.toolName === 'Shell' ? 'Bash' : block.toolName);
660
+ if (block.toolName === 'Shell' && typeof block.args?.command === 'string') {
661
+ bucket.bash.push(...extractBashCommands(block.args.command));
662
+ }
663
+ }
664
+ }
665
+ return { byComposer, unjoined, order, malformed };
666
+ }
667
+ function parseBubbles(db, seenKeys, timeFloor, agentKvTimestamp, firstSeen) {
668
+ const results = [];
669
+ let skipped = 0;
670
+ const { meta: composerMeta, requestStart } = loadComposerMeta(db);
671
+ // The bubble timestamp lives inside the JSON value (no index), so the date
672
+ // filter forces a full JSON decode per row. Multi-GB Cursor DBs (500k+
673
+ // bubbles) were producing 30s+ parse stalls, so the scan is bounded. The old
674
+ // approach kept only the most-recent MAX_BUBBLES by ROWID, which dropped
675
+ // in-range older sessions and warned even when the requested window fit
676
+ // comfortably. Instead, for large DBs we page the requested window
677
+ // (ROWID-descending, stopping past the window floor) and only fall back to a
678
+ // hard budget — warning — when the in-range scan genuinely exceeds it.
679
+ // Override the budget in tests via CODEBURN_CURSOR_MAX_BUBBLES.
680
+ const MAX_BUBBLES = Number(process.env['CODEBURN_CURSOR_MAX_BUBBLES']) || 250_000;
681
+ let total = 0;
682
+ try {
683
+ const countRows = db.query("SELECT COUNT(*) as cnt FROM cursorDiskKV WHERE key LIKE 'bubbleId:%'");
684
+ total = countRows[0]?.cnt ?? 0;
685
+ }
686
+ catch (err) {
687
+ rethrowBusy(err);
688
+ }
689
+ let rows;
690
+ try {
691
+ if (total > MAX_BUBBLES) {
692
+ const scan = scanBubblesPaged(db, timeFloor, MAX_BUBBLES);
693
+ rows = scan.rows;
694
+ if (scan.truncated) {
695
+ process.stderr.write(`codeburn: Cursor database has ${total.toLocaleString()} bubbles and the ` +
696
+ `requested range exceeds the ${MAX_BUBBLES.toLocaleString()}-bubble scan budget; ` +
697
+ `the oldest sessions in range may be missing from this report.\n`);
698
+ }
699
+ }
700
+ else {
701
+ rows = db.query(BUBBLE_QUERY_SINCE, [timeFloor]);
702
+ }
703
+ }
704
+ catch (err) {
705
+ rethrowBusy(err);
706
+ return { calls: results };
707
+ }
708
+ // Pre-pass: per-conversation facts the crediting decisions need, plus the
709
+ // requestId join for the agent stream — all from the rows already fetched,
710
+ // so no extra unbudgeted table scans.
711
+ const scans = new Map();
712
+ const requestToComposer = new Map();
713
+ for (const row of rows) {
714
+ const cid = parseComposerIdFromKey(row.bubble_key);
715
+ if (!cid)
716
+ continue;
717
+ if (row.request_id)
718
+ requestToComposer.set(row.request_id, cid);
719
+ let scan = scans.get(cid);
720
+ if (!scan) {
721
+ scan = { hasRealTokens: false, firstBubbleTs: null, assistantTextChars: 0, model: null };
722
+ scans.set(cid, scan);
723
+ }
724
+ if ((row.input_tokens ?? 0) > 0 || (row.output_tokens ?? 0) > 0)
725
+ scan.hasRealTokens = true;
726
+ if (!scan.firstBubbleTs && row.created_at)
727
+ scan.firstBubbleTs = row.created_at;
728
+ if (row.bubble_type !== 1)
729
+ scan.assistantTextChars += row.text_length ?? 0;
730
+ if (!scan.model && row.model)
731
+ scan.model = row.model;
732
+ }
733
+ const { byComposer: agentStreams, unjoined, order: streamOrder, malformed } = loadAgentStreams(db, requestToComposer);
734
+ skipped += malformed;
735
+ const lastUserMsg = new Map();
736
+ const inputSource = (cid) => {
737
+ if (scans.get(cid)?.hasRealTokens)
738
+ return 'bubbleTokens';
739
+ if (composerMeta.has(cid))
740
+ return 'meter';
741
+ const stream = agentStreams.get(cid);
742
+ if ((stream?.userChars ?? 0) + (stream?.contextChars ?? 0) > 0)
743
+ return 'stream';
744
+ return 'text';
745
+ };
746
+ const emit = (call) => {
747
+ results.push({
748
+ provider: 'cursor',
749
+ cacheCreationInputTokens: 0,
750
+ cacheReadInputTokens: 0,
751
+ cachedInputTokens: 0,
752
+ reasoningTokens: 0,
753
+ webSearchRequests: 0,
754
+ speed: 'standard',
755
+ // Output is a reply-text estimate and the input meter is the latest
756
+ // context snapshot, not a per-turn sum, so no cursor figure is exact.
757
+ costIsEstimated: true,
758
+ ...call,
759
+ });
760
+ };
761
+ const toolsAttached = new Set();
762
+ for (const row of rows) {
763
+ try {
764
+ // The real composerId lives in the row key `bubbleId:<composerId>:<uuid>`
765
+ // (the JSON conversationId field is empty in current builds).
766
+ // parseComposerIdFromKey returns null for non-UUID composer segments
767
+ // (tool-call output rows and similar shapes), which are NOT sessions.
768
+ const conversationId = parseComposerIdFromKey(row.bubble_key);
769
+ if (!conversationId) {
770
+ skipped++;
771
+ continue;
772
+ }
773
+ const createdAt = row.created_at;
774
+ if (!createdAt)
775
+ continue;
776
+ // Pair each user turn with its own prompt (even when the turn itself
777
+ // emits nothing) so the assistant reply that follows classifies against
778
+ // the right question.
779
+ if (row.bubble_type === 1) {
780
+ lastUserMsg.set(conversationId, blobToText(row.user_text));
781
+ }
782
+ let inputTokens = row.input_tokens ?? 0;
783
+ let outputTokens = row.output_tokens ?? 0;
784
+ if (inputTokens === 0 && outputTokens === 0) {
785
+ const textLen = row.text_length ?? 0;
786
+ if (row.bubble_type === 1) {
787
+ // Conversation-level input (meter or stream) is emitted once after
788
+ // this loop; per-bubble text only counts when it is the
789
+ // conversation's best available signal.
790
+ if (inputSource(conversationId) === 'text' && textLen > 0) {
791
+ inputTokens = estimateTokensFromChars(textLen);
792
+ }
793
+ }
794
+ else {
795
+ outputTokens = estimateTokensFromChars(textLen);
796
+ }
797
+ if (inputTokens === 0 && outputTokens === 0)
798
+ continue;
799
+ }
800
+ // Use the SQLite row key (bubbleId:<unique>) as the dedup key.
801
+ // Cursor mutates token counts on the row in place when streaming
802
+ // completes — including tokens in the dedup key (the previous
803
+ // implementation) caused the same bubble to be counted twice once
804
+ // its tokens stabilized.
805
+ const dedupKey = `cursor:bubble:${row.bubble_id ?? row.bubble_key}`;
806
+ if (seenKeys.has(dedupKey))
807
+ continue;
808
+ seenKeys.add(dedupKey);
809
+ // User bubbles (type=1) carry no modelInfo, so fall back to the
810
+ // conversation's model seen on its assistant bubbles or agent stream.
811
+ const effectiveModel = row.model ?? scans.get(conversationId)?.model ?? agentStreams.get(conversationId)?.model ?? null;
812
+ const pricingModel = resolveModel(effectiveModel);
813
+ const costUSD = calculateCost(pricingModel, inputTokens, outputTokens, 0, 0, 0);
814
+ const userQuestion = lastUserMsg.get(conversationId) ?? '';
815
+ const assistantText = blobToText(row.user_text);
816
+ const userText = (userQuestion + ' ' + assistantText).trim();
817
+ const languages = extractLanguages(blobToText(row.code_blocks));
818
+ const hasCode = languages.length > 0;
819
+ // Meter/stream conversations carry their agent tools on the synthetic
820
+ // conversation record below; the rest attach them to their first
821
+ // emitted call so they are counted exactly once.
822
+ let agentTurn;
823
+ const source = inputSource(conversationId);
824
+ if ((source === 'text' || source === 'bubbleTokens') && !toolsAttached.has(conversationId)) {
825
+ agentTurn = agentStreams.get(conversationId);
826
+ if (agentTurn)
827
+ toolsAttached.add(conversationId);
828
+ }
829
+ emit({
830
+ model: modelForDisplay(effectiveModel),
831
+ inputTokens,
832
+ outputTokens,
833
+ costUSD,
834
+ tools: [
835
+ ...(hasCode ? ['cursor:edit', ...languages.map(l => `lang:${l}`)] : []),
836
+ ...(agentTurn?.tools ?? []),
837
+ ],
838
+ bashCommands: agentTurn?.bash ?? [],
839
+ timestamp: createdAt,
840
+ deduplicationKey: dedupKey,
841
+ userMessage: userText,
842
+ sessionId: conversationId,
843
+ });
844
+ }
845
+ catch {
846
+ skipped++;
847
+ }
848
+ }
849
+ // One conversation-level input record per metered/stream conversation,
850
+ // anchored to the conversation's own start (composerData.createdAt) so the
851
+ // credited day never depends on the parse window or cache state, and keyed
852
+ // by composerId so re-parses and daily-cache gap fills dedupe instead of
853
+ // multiplying. The meter is the LATEST context size, not a per-turn sum;
854
+ // growth after the anchor day is finalized stays uncounted, which keeps the
855
+ // documented undercount-vs-admin-console tradeoff but never double counts.
856
+ for (const [cid, scan] of scans) {
857
+ const source = inputSource(cid);
858
+ if (source !== 'meter' && source !== 'stream')
859
+ continue;
860
+ const stream = agentStreams.get(cid);
861
+ const meta = composerMeta.get(cid);
862
+ const inputTokens = source === 'meter'
863
+ ? meta?.tokens ?? 0
864
+ : estimateTokensFromChars((stream?.userChars ?? 0) + (stream?.contextChars ?? 0));
865
+ // Reply text normally lives on assistant bubbles; count the stream's
866
+ // reply deltas only when the bubbles carried none.
867
+ const outputTokens = scan.assistantTextChars > 0 ? 0 : estimateTokensFromChars(stream?.assistantChars ?? 0);
868
+ if (inputTokens === 0 && outputTokens === 0)
869
+ continue;
870
+ const dedupKey = `cursor:composer-input:${cid}`;
871
+ if (seenKeys.has(dedupKey))
872
+ continue;
873
+ seenKeys.add(dedupKey);
874
+ const createdAtMs = meta?.createdAt;
875
+ const timestamp = typeof createdAtMs === 'number' && createdAtMs > 0 ? new Date(createdAtMs).toISOString() : scan.firstBubbleTs;
876
+ if (!timestamp)
877
+ continue;
878
+ const effectiveModel = scan.model ?? stream?.model ?? null;
879
+ emit({
880
+ model: modelForDisplay(effectiveModel),
881
+ inputTokens,
882
+ outputTokens,
883
+ costUSD: calculateCost(resolveModel(effectiveModel), inputTokens, outputTokens, 0, 0, 0),
884
+ tools: stream?.tools ?? [],
885
+ bashCommands: stream?.bash ?? [],
886
+ timestamp,
887
+ deduplicationKey: dedupKey,
888
+ userMessage: '',
889
+ sessionId: cid,
890
+ });
891
+ }
892
+ // Sessions recorded only in the agent stream (no scanned bubble carries
893
+ // their requestId). A request whose bubbles predate the window belongs to
894
+ // that older conversation, not here; one whose bubbles the scan budget cut
895
+ // takes its newest bubble's time. agentKv stores no timestamps, so a request
896
+ // with no dated bubble takes the DB file's mtime and keeps it on every later
897
+ // parse; re-stamping would move it to the latest write each time. Both
898
+ // outcomes are kept in `firstSeen`, so each id is looked up once.
899
+ const billable = [...unjoined].filter(([, stream]) => stream.userChars + stream.contextChars + stream.assistantChars > 0);
900
+ const bubbleTimes = new Map();
901
+ const unresolvedIds = billable
902
+ .map(([requestId]) => requestId)
903
+ .filter(requestId => !firstSeen.has(requestId) && !firstSeen.has(BUBBLE_TIME_KEY + requestId))
904
+ .sort();
905
+ const unjoinedIds = unresolvedIds.slice(0, REQUEST_ID_CHUNK * MAX_REQUEST_ID_CHUNKS);
906
+ const lookedUp = new Set(unjoinedIds);
907
+ try {
908
+ for (let i = 0; i < unjoinedIds.length; i += REQUEST_ID_CHUNK) {
909
+ const chunk = unjoinedIds.slice(i, i + REQUEST_ID_CHUNK);
910
+ const sql = `${BUBBLE_REQUEST_IDS_QUERY} (${chunk.map(() => '?').join(',')})`;
911
+ // The newest time per request is taken here: GROUP BY with MAX re-reads
912
+ // every bubble's JSON and ran 3.4x slower on a real database.
913
+ for (const row of db.query(sql, chunk)) {
914
+ if (!row.request_id)
915
+ continue;
916
+ // A numeric or unparseable createdAt counts as undated.
917
+ const ms = typeof row.created_at === 'string' ? Date.parse(row.created_at) : NaN;
918
+ const at = Number.isFinite(ms) ? new Date(ms).toISOString() : null;
919
+ const known = bubbleTimes.get(row.request_id);
920
+ if (!known || (at && at > known))
921
+ bubbleTimes.set(row.request_id, at);
922
+ }
923
+ }
924
+ }
925
+ catch (err) {
926
+ rethrowBusy(err);
927
+ }
928
+ for (const [requestId, at] of bubbleTimes) {
929
+ if (at)
930
+ firstSeen.set(BUBBLE_TIME_KEY + requestId, at);
931
+ }
932
+ // A request with no bubble is dated from its own prompt, else from the
933
+ // conversation that names it, else from the dated requests written just
934
+ // before and after it in the stream when both fall on the same day. Only
935
+ // undated requests fall back to the first-seen stamp.
936
+ const ownDate = (requestId) => {
937
+ const at = unjoined.get(requestId)?.promptAt ?? requestStart.get(requestId) ?? null;
938
+ return at !== null && Number.isFinite(at) ? at : null;
939
+ };
940
+ const bubbleAt = new Map();
941
+ for (const row of rows) {
942
+ const ms = row.request_id && row.created_at ? Date.parse(row.created_at) : NaN;
943
+ if (Number.isFinite(ms) && ms > (bubbleAt.get(row.request_id) ?? -Infinity))
944
+ bubbleAt.set(row.request_id, ms);
945
+ }
946
+ const anchors = streamOrder.map((requestId) => {
947
+ const scanned = bubbleAt.get(requestId);
948
+ if (scanned !== undefined)
949
+ return scanned;
950
+ const lookedUpAt = Date.parse(firstSeen.get(BUBBLE_TIME_KEY + requestId) ?? '');
951
+ return Number.isFinite(lookedUpAt) ? lookedUpAt : ownDate(requestId);
952
+ });
953
+ const nextAnchor = [];
954
+ for (let i = anchors.length - 1, after = null; i >= 0; i--) {
955
+ nextAnchor[i] = after;
956
+ after = anchors[i] ?? after;
957
+ }
958
+ const between = new Map();
959
+ for (let i = 0, before = null; i < anchors.length; i++) {
960
+ const after = nextAnchor[i] ?? null;
961
+ if (anchors[i] === null && before !== null && after !== null && new Date(before).toDateString() === new Date(after).toDateString()) {
962
+ between.set(streamOrder[i], before);
963
+ }
964
+ before = anchors[i] ?? before;
965
+ }
966
+ const streamDate = (requestId) => {
967
+ const at = ownDate(requestId) ?? between.get(requestId) ?? null;
968
+ return at === null ? null : new Date(at).toISOString();
969
+ };
970
+ for (const [requestId, stream] of billable) {
971
+ // Request ids are UUIDs, so a historic bubble sharing one with a billable
972
+ // agent-only stream is not expected.
973
+ const bubbleTime = firstSeen.get(BUBBLE_TIME_KEY + requestId);
974
+ if (bubbleTime && bubbleTime <= timeFloor)
975
+ continue;
976
+ if (!bubbleTime && !firstSeen.has(requestId) && !lookedUp.has(requestId))
977
+ continue;
978
+ const datedAt = bubbleTime ? null : streamDate(requestId);
979
+ if (datedAt && datedAt <= timeFloor)
980
+ continue;
981
+ const inputTokens = estimateTokensFromChars(stream.userChars + stream.contextChars);
982
+ const outputTokens = estimateTokensFromChars(stream.assistantChars);
983
+ if (inputTokens === 0 && outputTokens === 0)
984
+ continue;
985
+ const dedupKey = `cursor:agentKv:${requestId}`;
986
+ if (seenKeys.has(dedupKey))
987
+ continue;
988
+ seenKeys.add(dedupKey);
989
+ if (!bubbleTime && !datedAt && !firstSeen.has(requestId))
990
+ firstSeen.set(requestId, agentKvTimestamp);
991
+ emit({
992
+ model: modelForDisplay(stream.model),
993
+ inputTokens,
994
+ outputTokens,
995
+ costUSD: calculateCost(resolveModel(stream.model), inputTokens, outputTokens, 0, 0, 0),
996
+ tools: stream.tools,
997
+ bashCommands: stream.bash,
998
+ timestamp: bubbleTime ?? datedAt ?? firstSeen.get(requestId),
999
+ deduplicationKey: dedupKey,
1000
+ userMessage: '',
1001
+ sessionId: requestId,
1002
+ });
1003
+ }
1004
+ if (skipped > 0) {
1005
+ process.stderr.write(`codeburn: skipped ${skipped} unreadable Cursor entries\n`);
1006
+ }
1007
+ return { calls: results, lookupPending: unresolvedIds.length > unjoinedIds.length };
1008
+ }
1009
+ // Always the full lookback, never the requested range: the session cache keys
1010
+ // this parse on the DB fingerprint alone and serves it to every later range.
1011
+ function createParser(source, seenKeys) {
1012
+ const timeFloor = getCursorTimeFloor();
1013
+ let lookupPending = false;
1014
+ return {
1015
+ incomplete: () => lookupPending,
1016
+ async *parse() {
1017
+ if (!isSqliteAvailable()) {
1018
+ process.stderr.write(getSqliteLoadError() + '\n');
1019
+ return;
1020
+ }
1021
+ const { dbPath, workspaceTag } = decodeSourcePath(source.path);
1022
+ // Decide which composers belong to this source. The workspace map is
1023
+ // built once per process from `workspaceStorage/*` and reused across
1024
+ // every workspace-scoped source, so we pay the directory walk cost
1025
+ // only once per CLI run regardless of how many projects the user has.
1026
+ // `composerFilter` holds the set of composers EITHER allowed (workspace
1027
+ // source) or denied (orphan source); `filterMode` says which.
1028
+ let composerFilter = null;
1029
+ let filterMode = 'include';
1030
+ if (workspaceTag !== '__all__') {
1031
+ const wsMap = loadWorkspaceMap(getCursorWorkspaceStorageDir(dbPath));
1032
+ if (workspaceTag === ORPHAN_TAG) {
1033
+ // Orphan source: every composer that is mapped to SOME workspace
1034
+ // is excluded here, so unmapped composers (and any non-UUID
1035
+ // sub-composer ids that slip through) land in this bucket.
1036
+ composerFilter = new Set(wsMap.composerToWorkspace.keys());
1037
+ filterMode = 'exclude';
1038
+ }
1039
+ else {
1040
+ composerFilter = new Set();
1041
+ for (const [composerId, folder] of wsMap.composerToWorkspace) {
1042
+ if (folder === workspaceTag)
1043
+ composerFilter.add(composerId);
1044
+ }
1045
+ filterMode = 'include';
1046
+ }
1047
+ }
1048
+ // Cache is keyed on the bare DB path so multiple workspace-scoped
1049
+ // sources reuse one parsed bubble set per CLI run. Filtering happens
1050
+ // post-cache so each source emits only its own composers.
1051
+ let allCalls = null;
1052
+ const cached = await readCachedResults(dbPath, timeFloor);
1053
+ if (cached) {
1054
+ allCalls = cached;
1055
+ }
1056
+ else {
1057
+ let db;
1058
+ try {
1059
+ db = openDatabase(dbPath);
1060
+ }
1061
+ catch (err) {
1062
+ rethrowBusy(err);
1063
+ process.stderr.write(`codeburn: cannot open Cursor database: ${err instanceof Error ? err.message : err}\n`);
1064
+ return;
1065
+ }
1066
+ try {
1067
+ if (!validateSchema(db)) {
1068
+ process.stderr.write('codeburn: Cursor storage format not recognized. You may need to update CodeBurn.\n');
1069
+ return;
1070
+ }
1071
+ // Use a fresh local Set for intra-parse dedup so the global
1072
+ // seenKeys is not mutated by calls that the workspace filter is
1073
+ // about to drop. Cross-source dedup happens at yield time.
1074
+ const localSeen = new Set();
1075
+ // agentKv rows carry no timestamps; sessions found only there get
1076
+ // the DB's last-write time.
1077
+ let agentKvTimestamp;
1078
+ try {
1079
+ agentKvTimestamp = new Date(statSync(dbPath).mtimeMs).toISOString();
1080
+ }
1081
+ catch {
1082
+ agentKvTimestamp = new Date().toISOString();
1083
+ }
1084
+ const firstSeen = await readFirstSeen();
1085
+ const knownFirstSeen = firstSeen.size;
1086
+ const parsed = parseBubbles(db, localSeen, timeFloor, agentKvTimestamp, firstSeen);
1087
+ if (firstSeen.size > knownFirstSeen)
1088
+ await writeFirstSeen(firstSeen);
1089
+ allCalls = parsed.calls;
1090
+ lookupPending = parsed.lookupPending === true;
1091
+ // Keyed on the DB alone, a stored result would serve this partial
1092
+ // one to an unchanged DB for good; the next parse resumes the lookup.
1093
+ if (!lookupPending)
1094
+ await writeCachedResults(dbPath, allCalls, timeFloor);
1095
+ }
1096
+ finally {
1097
+ db.close();
1098
+ }
1099
+ }
1100
+ for (const call of allCalls) {
1101
+ if (composerFilter !== null) {
1102
+ const inSet = composerFilter.has(call.sessionId);
1103
+ if (filterMode === 'include' && !inSet)
1104
+ continue;
1105
+ if (filterMode === 'exclude' && inSet)
1106
+ continue;
1107
+ }
1108
+ if (seenKeys.has(call.deduplicationKey))
1109
+ continue;
1110
+ seenKeys.add(call.deduplicationKey);
1111
+ yield call;
1112
+ }
1113
+ },
1114
+ };
1115
+ }
1116
+ export function createCursorProvider(dbPathOverride) {
1117
+ return {
1118
+ name: 'cursor',
1119
+ displayName: 'Cursor',
1120
+ modelDisplayName(model) {
1121
+ return ownValue(modelDisplayNames, model) ?? model;
1122
+ },
1123
+ toolDisplayName(rawTool) {
1124
+ return rawTool;
1125
+ },
1126
+ async probeRoots() {
1127
+ return [{ path: dbPathOverride ?? getCursorDbPath(), label: 'db' }];
1128
+ },
1129
+ async discoverSessions() {
1130
+ const imported = importSource('cursor');
1131
+ if (!isSqliteAvailable())
1132
+ return imported;
1133
+ const dbPath = dbPathOverride ?? getCursorDbPath();
1134
+ if (!existsSync(dbPath))
1135
+ return imported;
1136
+ const wsMap = loadWorkspaceMap(getCursorWorkspaceStorageDir(dbPath), true);
1137
+ const sources = [];
1138
+ for (const [folder, project] of wsMap.workspaceProjectName) {
1139
+ sources.push({
1140
+ path: encodeSourcePath(dbPath, folder),
1141
+ project,
1142
+ provider: 'cursor',
1143
+ });
1144
+ }
1145
+ // Always emit a catch-all source for composers with no workspace
1146
+ // mapping. About a third of composers in real-world Cursor installs
1147
+ // are unmapped (multi-root workspaces, "no folder open" sessions,
1148
+ // deleted workspaces with surviving global rows). When the user has
1149
+ // no workspaces at all this source captures everything and the
1150
+ // dashboard looks identical to the pre-PR `cursor` project.
1151
+ sources.push({
1152
+ path: encodeSourcePath(dbPath, ORPHAN_TAG),
1153
+ project: ORPHAN_PROJECT,
1154
+ provider: 'cursor',
1155
+ });
1156
+ return [...sources, ...imported];
1157
+ },
1158
+ createSessionParser(source, seenKeys) {
1159
+ return importSourceParser(source, seenKeys, 'cursor') ?? createParser(source, seenKeys);
1160
+ },
1161
+ };
1162
+ }
1163
+ export const cursor = createCursorProvider();