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,551 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readdirSync, statSync } from 'fs';
3
+ import { readFile, readdir, stat } from 'fs/promises';
4
+ import { basename, delimiter as pathDelimiter, join, resolve } from 'path';
5
+ import { homedir } from 'os';
6
+ import { createHash } from 'crypto';
7
+ import { calculateCost, getShortModelName } from '../models.js';
8
+ import { readConfig } from '../config.js';
9
+ import { FS_SCAN_CONCURRENCY, mapWithConcurrency, readSessionLines } from '../fs-utils.js';
10
+ import { wslHomes } from '../wsl.js';
11
+ function expandHome(p) {
12
+ if (p === '~')
13
+ return homedir();
14
+ if (p.startsWith('~/') || p.startsWith('~\\'))
15
+ return join(homedir(), p.slice(2));
16
+ return p;
17
+ }
18
+ function dedupeResolved(paths) {
19
+ const seen = new Set();
20
+ const out = [];
21
+ for (const p of paths) {
22
+ if (!seen.has(p)) {
23
+ seen.add(p);
24
+ out.push(p);
25
+ }
26
+ }
27
+ return out;
28
+ }
29
+ /// Stable id for one config directory, shared by session sources, the menubar's
30
+ /// claudeConfigs selector, live sessions and the quota payload's claudeProfiles.
31
+ export function claudeConfigSourceId(path) {
32
+ return 'claude-config:' + createHash('sha256').update(path).digest('hex').slice(0, 16);
33
+ }
34
+ /// Stable id for a Claude Desktop sessions directory.
35
+ export function claudeDesktopSourceId(base) {
36
+ return 'claude-desktop:' + createHash('sha256').update(resolve(base)).digest('hex').slice(0, 16);
37
+ }
38
+ // `\\wsl$\<distro>\home\<user>\.claude` -> distro, and the home's own name
39
+ // (`<user>`, or `root`). Either separator after the prefix: the join that
40
+ // builds these follows the host platform, which is `/` under test.
41
+ const WSL_CONFIG_DIR = /^\\\\wsl(?:\$|\.localhost)\\([^\\/]+)[\\/](?:home[\\/])?([^\\/]+)[\\/]/i;
42
+ function baseClaudeConfigLabel(path, siblings) {
43
+ const normalized = resolve(path);
44
+ if (normalized === resolve(join(homedir(), '.claude')))
45
+ return 'Default Claude';
46
+ // Every WSL root basenames to ".claude", so name them by distro instead of
47
+ // letting makeUniqueLabels number them "claude 1", "claude 2" (#1059). Two
48
+ // homes in the same distro would collide on the distro alone, so those also
49
+ // carry the user name.
50
+ const wsl = WSL_CONFIG_DIR.exec(path);
51
+ if (wsl) {
52
+ const shared = siblings.filter(p => WSL_CONFIG_DIR.exec(p)?.[1]?.toLowerCase() === wsl[1].toLowerCase());
53
+ return shared.length > 1 ? `${wsl[1]} (WSL, ${wsl[2]})` : `${wsl[1]} (WSL)`;
54
+ }
55
+ const name = basename(normalized).replace(/^\./, '').trim();
56
+ return name || normalized;
57
+ }
58
+ function makeUniqueLabels(sources) {
59
+ const counts = new Map();
60
+ for (const source of sources)
61
+ counts.set(source.label, (counts.get(source.label) ?? 0) + 1);
62
+ if (![...counts.values()].some(count => count > 1))
63
+ return sources;
64
+ const seen = new Map();
65
+ return sources.map(source => {
66
+ if ((counts.get(source.label) ?? 0) <= 1)
67
+ return source;
68
+ const index = (seen.get(source.label) ?? 0) + 1;
69
+ seen.set(source.label, index);
70
+ return { ...source, label: `${source.label} ${index}` };
71
+ });
72
+ }
73
+ /// Returns every Claude config dir to scan, in priority order with duplicates
74
+ /// removed (resolved-path equality). Precedence: `CLAUDE_CONFIG_DIRS` (a
75
+ /// `path.delimiter`-separated list, ":" on POSIX, ";" on Windows), then
76
+ /// `CLAUDE_CONFIG_DIR` (single dir), then the `claudeConfigDirs` array in
77
+ /// `~/.config/codeburn/config.json` (how the macOS menubar configures
78
+ /// multi-account aggregation, since a GUI app can't inherit the shell env),
79
+ /// then `~/.claude`. Sessions from every returned dir are merged into one
80
+ /// ProjectSummary per project name in `src/parser.ts:scanProjectDirs`, so two
81
+ /// dirs holding the same sanitized project slug naturally aggregate (#208).
82
+ export async function getClaudeConfigDirs() {
83
+ // WSL homes are additive, not an override: a Windows user who points
84
+ // CLAUDE_CONFIG_DIRS at a second Windows account still wants the sessions
85
+ // Claude Code wrote inside their distro (#1059). Off-win32 this is empty.
86
+ const wsl = wslHomes().map(home => join(home, '.claude'));
87
+ return dedupeResolved([...await configuredClaudeConfigDirs(), ...wsl]);
88
+ }
89
+ async function configuredClaudeConfigDirs() {
90
+ const multi = process.env['CLAUDE_CONFIG_DIRS'];
91
+ if (multi !== undefined && multi !== '') {
92
+ const dirs = multi
93
+ .split(pathDelimiter)
94
+ .map(s => s.trim())
95
+ .filter(s => s.length > 0)
96
+ .map(s => resolve(expandHome(s)));
97
+ if (dirs.length > 0)
98
+ return dedupeResolved(dirs);
99
+ }
100
+ const single = process.env['CLAUDE_CONFIG_DIR'];
101
+ if (single !== undefined && single !== '')
102
+ return [resolve(expandHome(single))];
103
+ // Config-file fallback (menubar-driven). Env vars always win so a power user
104
+ // can still override per-shell. A non-array or empty value falls through to
105
+ // the ~/.claude default, matching the "unset" behavior.
106
+ const config = await readConfig();
107
+ if (Array.isArray(config.claudeConfigDirs)) {
108
+ const dirs = config.claudeConfigDirs
109
+ .filter((s) => typeof s === 'string' && s.trim().length > 0)
110
+ .map(s => resolve(expandHome(s.trim())));
111
+ if (dirs.length > 0)
112
+ return dedupeResolved(dirs);
113
+ }
114
+ return [join(homedir(), '.claude')];
115
+ }
116
+ export async function discoverClaudeConfigSources() {
117
+ const dirs = await getClaudeConfigDirs();
118
+ return makeUniqueLabels(dirs.map(path => ({
119
+ id: claudeConfigSourceId(path),
120
+ label: baseClaudeConfigLabel(path, dirs),
121
+ path,
122
+ })));
123
+ }
124
+ // Filesystem changes under an unchanged input key intentionally do not invalidate this cache.
125
+ const desktopSessionsDirsCache = new Map();
126
+ function cacheDesktopSessionsDirs(key, candidates) {
127
+ const dirs = dedupeResolved(candidates.map(candidate => resolve(candidate)));
128
+ desktopSessionsDirsCache.set(key, dirs);
129
+ return [...dirs];
130
+ }
131
+ export function getDesktopSessionsDirs() {
132
+ const override = process.env['CODEBURN_DESKTOP_SESSIONS_DIR'];
133
+ const appDataInput = process.env['APPDATA'];
134
+ const localAppDataInput = process.env['LOCALAPPDATA'];
135
+ const platform = process.platform;
136
+ // homedir() feeds every non-override branch below, so a key without it hands
137
+ // back the previous home's paths once the home directory moves.
138
+ const cacheKey = JSON.stringify([
139
+ platform,
140
+ override ?? null,
141
+ appDataInput ?? null,
142
+ localAppDataInput ?? null,
143
+ homedir(),
144
+ ]);
145
+ const cached = desktopSessionsDirsCache.get(cacheKey);
146
+ if (cached)
147
+ return [...cached];
148
+ if (override)
149
+ return cacheDesktopSessionsDirs(cacheKey, [override]);
150
+ if (platform === 'darwin') {
151
+ const appSupport = join(homedir(), 'Library', 'Application Support');
152
+ return cacheDesktopSessionsDirs(cacheKey, [
153
+ join(appSupport, 'Claude', 'local-agent-mode-sessions'),
154
+ // Current Claude Desktop 3p builds use a distinct Electron user-data
155
+ // directory for Cowork, while the Code surface continues to use the
156
+ // traditional ~/.claude project store.
157
+ join(appSupport, 'Claude-3p', 'local-agent-mode-sessions'),
158
+ ]);
159
+ }
160
+ if (platform === 'win32') {
161
+ const appData = appDataInput?.trim();
162
+ const candidates = [
163
+ join(appData || join(homedir(), 'AppData', 'Roaming'), 'Claude', 'local-agent-mode-sessions'),
164
+ ];
165
+ const localAppData = localAppDataInput?.trim();
166
+ const packagesDir = join(localAppData || join(homedir(), 'AppData', 'Local'), 'Packages');
167
+ try {
168
+ const entries = readdirSync(packagesDir, { withFileTypes: true })
169
+ .filter(entry => entry.isDirectory() &&
170
+ (entry.name.startsWith('Claude_') || entry.name.includes('.Claude_')))
171
+ .sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
172
+ for (const entry of entries) {
173
+ const sessionsDir = join(packagesDir, entry.name, 'LocalCache', 'Roaming', 'Claude', 'local-agent-mode-sessions');
174
+ try {
175
+ if (statSync(sessionsDir).isDirectory())
176
+ candidates.push(sessionsDir);
177
+ }
178
+ catch {
179
+ // A package may disappear or be unreadable while Packages is scanned.
180
+ }
181
+ }
182
+ }
183
+ catch {
184
+ // Missing or unreadable Packages is equivalent to no MSIX candidates.
185
+ }
186
+ return cacheDesktopSessionsDirs(cacheKey, candidates);
187
+ }
188
+ return cacheDesktopSessionsDirs(cacheKey, [join(homedir(), '.config', 'Claude', 'local-agent-mode-sessions')]);
189
+ }
190
+ async function findDesktopProjectDirs(base) {
191
+ const results = [];
192
+ async function walk(dir, depth) {
193
+ if (depth > 8)
194
+ return;
195
+ const entries = await readdir(dir).catch(() => []);
196
+ for (const entry of entries) {
197
+ if (entry === 'node_modules' || entry === '.git')
198
+ continue;
199
+ const full = join(dir, entry);
200
+ const s = await stat(full).catch(() => null);
201
+ if (!s?.isDirectory())
202
+ continue;
203
+ if (entry === 'projects') {
204
+ const projectDirs = await readdir(full).catch(() => []);
205
+ for (const pd of projectDirs) {
206
+ const pdFull = join(full, pd);
207
+ const pdStat = await stat(pdFull).catch(() => null);
208
+ if (pdStat?.isDirectory())
209
+ results.push(pdFull);
210
+ }
211
+ }
212
+ else {
213
+ await walk(full, depth + 1);
214
+ }
215
+ }
216
+ }
217
+ await walk(base, 0);
218
+ return results;
219
+ }
220
+ async function findDesktopUsageLedgerFiles(base) {
221
+ const results = [];
222
+ async function walk(dir, depth) {
223
+ if (depth > 8)
224
+ return;
225
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
226
+ for (const entry of entries) {
227
+ if (!entry.isDirectory())
228
+ continue;
229
+ if (entry.name === 'node_modules' || entry.name === '.git')
230
+ continue;
231
+ const full = join(dir, entry.name);
232
+ if (entry.name === 'usage-ledger') {
233
+ const ledgerEntries = await readdir(full, { withFileTypes: true }).catch(() => []);
234
+ for (const ledgerEntry of ledgerEntries) {
235
+ if (ledgerEntry.isFile() && ledgerEntry.name.endsWith('.ndjson')) {
236
+ results.push(join(full, ledgerEntry.name));
237
+ }
238
+ }
239
+ continue;
240
+ }
241
+ await walk(full, depth + 1);
242
+ }
243
+ }
244
+ await walk(base, 0);
245
+ return results;
246
+ }
247
+ function ledgerObject(value) {
248
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
249
+ ? value
250
+ : null;
251
+ }
252
+ function ledgerNumber(value) {
253
+ if (typeof value === 'number' && Number.isFinite(value))
254
+ return value;
255
+ if (typeof value === 'string' && value.trim() !== '') {
256
+ const parsed = Number(value);
257
+ if (Number.isFinite(parsed))
258
+ return parsed;
259
+ }
260
+ return undefined;
261
+ }
262
+ function ledgerTimestamp(value) {
263
+ const raw = ledgerNumber(value);
264
+ if (raw === undefined)
265
+ return undefined;
266
+ const milliseconds = raw >= 1_000_000_000_000 ? raw : raw * 1000;
267
+ const date = new Date(milliseconds);
268
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
269
+ }
270
+ function createCoworkLedgerParser(source, seenKeys) {
271
+ return {
272
+ async *parse() {
273
+ if (source.sourceKind !== 'claude-desktop-ledger')
274
+ return;
275
+ let lineNumber = 0;
276
+ for await (const rawLine of readSessionLines(source.path)) {
277
+ lineNumber++;
278
+ let parsed;
279
+ try {
280
+ parsed = JSON.parse(rawLine);
281
+ }
282
+ catch {
283
+ // Cowork appends records while a turn is in flight. Ignore a torn
284
+ // final line; valid records elsewhere in the ledger remain usable.
285
+ continue;
286
+ }
287
+ const record = ledgerObject(parsed);
288
+ const surface = record?.['surface'];
289
+ if (!record || (surface !== 'cowork' && surface !== 'code'))
290
+ continue;
291
+ const sessionId = typeof record['sessionId'] === 'string' ? record['sessionId'] : '';
292
+ const timestamp = ledgerTimestamp(record['ts']);
293
+ if (!sessionId || !timestamp)
294
+ continue;
295
+ const models = ledgerObject(record['models']);
296
+ if (!models)
297
+ continue;
298
+ for (const [model, rawUsage] of Object.entries(models)) {
299
+ const usage = ledgerObject(rawUsage);
300
+ if (!usage)
301
+ continue;
302
+ const inputTokens = Math.max(0, ledgerNumber(usage['inputTokens']) ?? 0);
303
+ const outputTokens = Math.max(0, ledgerNumber(usage['outputTokens']) ?? 0);
304
+ const cacheReadInputTokens = Math.max(0, ledgerNumber(usage['cacheReadTokens']) ?? 0);
305
+ const cacheCreationInputTokens = Math.max(0, ledgerNumber(usage['cacheWriteTokens']) ?? 0);
306
+ const webSearchRequests = Math.max(0, ledgerNumber(usage['webSearchRequests']) ?? 0);
307
+ const recordedCost = ledgerNumber(ledgerObject(usage['cost'])?.['usd']);
308
+ const estimatedCost = calculateCost(model, inputTokens, outputTokens, cacheCreationInputTokens, cacheReadInputTokens, webSearchRequests, 'standard', 0, 'claude');
309
+ if (inputTokens === 0 &&
310
+ outputTokens === 0 &&
311
+ cacheReadInputTokens === 0 &&
312
+ cacheCreationInputTokens === 0 &&
313
+ recordedCost === undefined) {
314
+ continue;
315
+ }
316
+ const deduplicationKey = `claude-cowork-ledger:${source.path}:${sessionId}:${timestamp}:${model}`;
317
+ if (seenKeys.has(deduplicationKey))
318
+ continue;
319
+ seenKeys.add(deduplicationKey);
320
+ yield {
321
+ provider: 'claude',
322
+ model,
323
+ inputTokens,
324
+ outputTokens,
325
+ cacheCreationInputTokens,
326
+ cacheReadInputTokens,
327
+ cachedInputTokens: cacheReadInputTokens,
328
+ reasoningTokens: 0,
329
+ webSearchRequests,
330
+ // Keep the ledger's dollar amount only as a fallback for a model
331
+ // CodeBurn cannot price. Known models must use CodeBurn's pricing
332
+ // and overrides so cached usage can be repriced later.
333
+ costUSD: estimatedCost,
334
+ ...(recordedCost !== undefined ? { fallbackCostUSD: recordedCost } : {}),
335
+ tools: [],
336
+ bashCommands: [],
337
+ skills: [],
338
+ subagentTypes: [],
339
+ timestamp,
340
+ speed: 'standard',
341
+ deduplicationKey,
342
+ userMessage: '',
343
+ sessionId,
344
+ project: surface === 'code' ? 'Claude Code' : 'Claude Cowork',
345
+ turnId: `${timestamp}:${lineNumber}`,
346
+ };
347
+ }
348
+ }
349
+ },
350
+ };
351
+ }
352
+ // Cache spaces.json per workspace directory to avoid redundant reads.
353
+ const spacesJsonCache = new Map();
354
+ async function loadSpacesJson(workspaceDir) {
355
+ if (spacesJsonCache.has(workspaceDir))
356
+ return spacesJsonCache.get(workspaceDir) ?? null;
357
+ try {
358
+ const raw = await readFile(join(workspaceDir, 'spaces.json'), 'utf-8');
359
+ const parsed = JSON.parse(raw);
360
+ if (parsed !== null &&
361
+ typeof parsed === 'object' &&
362
+ 'spaces' in parsed &&
363
+ Array.isArray(parsed.spaces)) {
364
+ const result = parsed;
365
+ spacesJsonCache.set(workspaceDir, result);
366
+ return result;
367
+ }
368
+ }
369
+ catch {
370
+ // unreadable or malformed — treat as no spaces
371
+ }
372
+ spacesJsonCache.set(workspaceDir, null);
373
+ return null;
374
+ }
375
+ async function resolveCoworkSpaceName(workspaceDir, sessionId) {
376
+ const [spacesFile, sessionMetaRaw] = await Promise.all([
377
+ loadSpacesJson(workspaceDir),
378
+ readFile(join(workspaceDir, `${sessionId}.json`), 'utf-8').catch(() => null),
379
+ ]);
380
+ if (!sessionMetaRaw)
381
+ return null;
382
+ let sessionMeta;
383
+ try {
384
+ sessionMeta = JSON.parse(sessionMetaRaw);
385
+ }
386
+ catch {
387
+ return null;
388
+ }
389
+ if (sessionMeta === null || typeof sessionMeta !== 'object')
390
+ return null;
391
+ const meta = sessionMeta;
392
+ const spaceId = meta['spaceId'];
393
+ if (typeof spaceId === 'string' && spacesFile) {
394
+ const spaceName = spacesFile.spaces.find(s => s.id === spaceId)?.name;
395
+ if (spaceName)
396
+ return spaceName;
397
+ }
398
+ // No spaceId (standalone session): fall back to selected folder then title.
399
+ const folders = meta['userSelectedFolders'];
400
+ if (Array.isArray(folders) && folders.length > 0 && typeof folders[0] === 'string') {
401
+ return basename(folders[0]);
402
+ }
403
+ const title = meta['title'];
404
+ if (typeof title === 'string' && title.trim().length > 0)
405
+ return title.trim();
406
+ return null;
407
+ }
408
+ export const claude = {
409
+ name: 'claude',
410
+ displayName: 'Claude',
411
+ modelDisplayName(model) {
412
+ return getShortModelName(model);
413
+ },
414
+ toolDisplayName(rawTool) {
415
+ return rawTool;
416
+ },
417
+ // Each config dir's `projects/` subdir is what discoverSessions readdir's,
418
+ // plus the Claude Desktop sessions base. Resolved via the same helpers so a
419
+ // CLAUDE_CONFIG_DIR(S) override is reflected exactly.
420
+ async probeRoots() {
421
+ const dirs = await getClaudeConfigDirs();
422
+ const roots = dirs.map(dir => ({ path: join(dir, 'projects'), label: 'projects' }));
423
+ roots.push(...getDesktopSessionsDirs().map(path => ({ path, label: 'desktop' })));
424
+ return roots;
425
+ },
426
+ async discoverSessions() {
427
+ const sources = [];
428
+ const seenProjectDirs = new Set();
429
+ const configSources = await discoverClaudeConfigSources();
430
+ let anyDirReadable = false;
431
+ for (const configSource of configSources) {
432
+ const claudeDir = configSource.path;
433
+ const projectsDir = join(claudeDir, 'projects');
434
+ let entries;
435
+ try {
436
+ entries = await readdir(projectsDir);
437
+ anyDirReadable = true;
438
+ }
439
+ catch {
440
+ // Missing or unreadable dir is not fatal: a user can configure both
441
+ // a real and a stale path in CLAUDE_CONFIG_DIRS without breaking.
442
+ continue;
443
+ }
444
+ // stat() (not the readdir Dirent) decides directory-ness so a symlinked
445
+ // project dir still counts; issue them concurrently, then apply the
446
+ // order-sensitive dedup serially.
447
+ const dirStats = await mapWithConcurrency(entries, FS_SCAN_CONCURRENCY, dirName => stat(join(projectsDir, dirName)).catch(() => null));
448
+ for (const [i, dirName] of entries.entries()) {
449
+ const dirPath = join(projectsDir, dirName);
450
+ // Resolve before deduping so two CLAUDE_CONFIG_DIRS entries that
451
+ // reach the same projects/<slug> directory (via symlinks or
452
+ // overlapping configs) emit only one SessionSource.
453
+ const resolved = resolve(dirPath);
454
+ if (seenProjectDirs.has(resolved))
455
+ continue;
456
+ const dirStat = dirStats[i];
457
+ if (!dirStat?.isDirectory())
458
+ continue;
459
+ seenProjectDirs.add(resolved);
460
+ // `project: dirName` is identical across config dirs for the same
461
+ // sanitized slug, which is exactly what makes the parser merge
462
+ // their sessions into a single ProjectSummary.
463
+ sources.push({
464
+ path: dirPath,
465
+ project: dirName,
466
+ provider: 'claude',
467
+ sourceId: configSource.id,
468
+ sourceLabel: configSource.label,
469
+ sourcePath: configSource.path,
470
+ sourceKind: 'claude-config',
471
+ });
472
+ }
473
+ }
474
+ // If the user explicitly set CLAUDE_CONFIG_DIRS and every entry was
475
+ // unreadable, emit a one-line stderr hint. Catches the most common
476
+ // misconfiguration: a Windows user typing `:` (POSIX delimiter) when
477
+ // the platform expects `;`, which produces a single bogus path that
478
+ // silently resolves to nothing on disk.
479
+ const explicitMulti = process.env['CLAUDE_CONFIG_DIRS'];
480
+ if (!anyDirReadable && explicitMulti !== undefined && explicitMulti !== '' && configSources.length > 0) {
481
+ process.stderr.write(`codeburn: CLAUDE_CONFIG_DIRS was set but no listed directory could be read. ` +
482
+ `Tried: ${configSources.map(s => s.path).join(', ')}. ` +
483
+ `Use "${pathDelimiter}" as the separator on this platform.\n`);
484
+ }
485
+ for (const desktopBase of getDesktopSessionsDirs()) {
486
+ const desktopDirs = await findDesktopProjectDirs(desktopBase);
487
+ const sep = desktopBase.includes('\\') ? '\\' : '/';
488
+ // Desktop / Cowork sessions belong to no CLAUDE_CONFIG_DIR. Tag them with a
489
+ // distinct source so a per-config view can account for them as their own
490
+ // "Claude Desktop" bucket instead of silently dropping them (which made
491
+ // sum-of-configs < All).
492
+ const desktopSourceId = claudeDesktopSourceId(desktopBase);
493
+ for (const dirPath of desktopDirs) {
494
+ const resolved = resolve(dirPath);
495
+ if (seenProjectDirs.has(resolved))
496
+ continue;
497
+ seenProjectDirs.add(resolved);
498
+ // For Claude Desktop local-agent-mode (Cowork) sessions, the project dir
499
+ // lives inside local_<sessionId>/.claude/projects/. We resolve the space
500
+ // name from the sibling .json and spaces.json so it groups correctly.
501
+ // Path structure: <desktopBase>/<appId>/<workspaceId>/local_<id>/.claude/projects/<slug>
502
+ let projectName = basename(dirPath);
503
+ const resolvedBase = resolve(desktopBase);
504
+ if (resolved.startsWith(resolvedBase + sep) || resolved.startsWith(resolvedBase + '/')) {
505
+ const rel = resolved.slice(resolvedBase.length + 1);
506
+ const parts = rel.split(/[/\\]/);
507
+ // parts = [appId, workspaceId, local_sessionId, .claude, projects, slug]
508
+ if (parts.length >= 6 &&
509
+ parts[2]?.startsWith('local_') &&
510
+ parts[3] === '.claude' &&
511
+ parts[4] === 'projects') {
512
+ const workspaceDir = join(resolvedBase, parts[0], parts[1]);
513
+ const sessionId = parts[2];
514
+ const spaceName = await resolveCoworkSpaceName(workspaceDir, sessionId);
515
+ if (spaceName)
516
+ projectName = spaceName;
517
+ }
518
+ }
519
+ sources.push({
520
+ path: dirPath,
521
+ project: projectName,
522
+ provider: 'claude',
523
+ sourceId: desktopSourceId,
524
+ sourceLabel: 'Claude Desktop',
525
+ sourcePath: desktopBase,
526
+ sourceKind: 'claude-desktop',
527
+ });
528
+ }
529
+ // Current Claude Desktop Cowork builds also keep metered usage in a
530
+ // workspace-level usage-ledger/*.ndjson file. These records are separate
531
+ // from the Claude Code JSONL transcripts above and must be exposed as
532
+ // leaf sources so the generic provider cache can fingerprint and parse
533
+ // them incrementally.
534
+ for (const ledgerPath of await findDesktopUsageLedgerFiles(desktopBase)) {
535
+ sources.push({
536
+ path: ledgerPath,
537
+ project: 'Claude Cowork',
538
+ provider: 'claude',
539
+ sourceId: desktopSourceId,
540
+ sourceLabel: 'Claude Desktop',
541
+ sourcePath: desktopBase,
542
+ sourceKind: 'claude-desktop-ledger',
543
+ });
544
+ }
545
+ }
546
+ return sources;
547
+ },
548
+ createSessionParser(source, seenKeys) {
549
+ return createCoworkLedgerParser(source, seenKeys);
550
+ },
551
+ };