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,664 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { open, readdir, stat } from 'fs/promises';
3
+ import { existsSync } from 'fs';
4
+ import { delimiter, join } from 'path';
5
+ import { homedir } from 'os';
6
+ import chalk from '../shims/chalk.js';
7
+ import { readSessionLines } from './fs-utils.js';
8
+ import { formatTokens } from './format.js';
9
+ import { estimateTokensFromChars } from './token-estimate.js';
10
+ // Block token counts are chars/4 estimates; the "context (exact)" line comes
11
+ // from the last assistant message's API usage. Transcripts store thinking
12
+ // blocks with their text stripped, so reasoning is derived per message as
13
+ // output_tokens minus the estimated visible output.
14
+ export const IMAGE_TOKEN_FALLBACK = 1600;
15
+ // A single line above this decodes to a string near V8's limit; skip it
16
+ // instead of letting toString abort the whole walk.
17
+ const MAX_LINE_BYTES = 256 * 1024 * 1024;
18
+ export function lineToText(line) {
19
+ if (typeof line === 'string')
20
+ return line;
21
+ if (line.length > MAX_LINE_BYTES)
22
+ return null;
23
+ try {
24
+ return line.toString('utf-8');
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ }
30
+ function newBlockStat() {
31
+ return { count: 0, tokens: 0 };
32
+ }
33
+ export function newAcc() {
34
+ return {
35
+ messages: 0,
36
+ assistantCount: 0,
37
+ assistantText: newBlockStat(),
38
+ assistantReasoning: newBlockStat(),
39
+ toolCall: newBlockStat(),
40
+ byTool: new Map(),
41
+ userCount: 0,
42
+ userText: newBlockStat(),
43
+ userImage: newBlockStat(),
44
+ userCompactSummary: newBlockStat(),
45
+ userMeta: newBlockStat(),
46
+ toolResult: newBlockStat(),
47
+ system: newBlockStat(),
48
+ };
49
+ }
50
+ export function estimateTokens(text) {
51
+ return estimateTokensFromChars(text.length);
52
+ }
53
+ export function add(stat, tokens) {
54
+ stat.count += 1;
55
+ stat.tokens += tokens;
56
+ }
57
+ // Injected harness content (slash-command wrappers, system reminders, hook
58
+ // output) rather than something the user typed.
59
+ const META_TEXT_RE = /^\s*<(command-name|command-message|command-args|command-contents|local-command-stdout|local-command-stderr|system-reminder|task-notification)/;
60
+ function pngDims(buf) {
61
+ if (buf.length < 24 || buf.readUInt32BE(0) !== 0x89504e47)
62
+ return null;
63
+ return [buf.readUInt32BE(16), buf.readUInt32BE(20)];
64
+ }
65
+ function jpegDims(buf) {
66
+ if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8)
67
+ return null;
68
+ let i = 2;
69
+ while (i + 9 < buf.length) {
70
+ if (buf[i] !== 0xff) {
71
+ i++;
72
+ continue;
73
+ }
74
+ const marker = buf[i + 1];
75
+ const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
76
+ if (isSof)
77
+ return [buf.readUInt16BE(i + 7), buf.readUInt16BE(i + 5)];
78
+ const len = buf.readUInt16BE(i + 2);
79
+ if (len < 2)
80
+ return null;
81
+ i += 2 + len;
82
+ }
83
+ return null;
84
+ }
85
+ // Anthropic vision pricing: ~(w*h)/750 tokens after the API downscales to fit
86
+ // 1568px on the long edge / ~1.15MP total.
87
+ function imageTokens(source) {
88
+ const data = source?.data;
89
+ if (typeof data !== 'string' || data.length === 0)
90
+ return IMAGE_TOKEN_FALLBACK;
91
+ let buf;
92
+ try {
93
+ buf = Buffer.from(data.slice(0, 262144), 'base64');
94
+ }
95
+ catch {
96
+ return IMAGE_TOKEN_FALLBACK;
97
+ }
98
+ const dims = pngDims(buf) ?? jpegDims(buf);
99
+ if (!dims)
100
+ return IMAGE_TOKEN_FALLBACK;
101
+ const [w, h] = dims;
102
+ if (!(w > 0) || !(h > 0))
103
+ return IMAGE_TOKEN_FALLBACK;
104
+ const scale = Math.min(1, 1568 / Math.max(w, h), Math.sqrt(1_150_000 / (w * h)));
105
+ return Math.max(1, Math.min(IMAGE_TOKEN_FALLBACK, Math.round((w * scale * h * scale) / 750)));
106
+ }
107
+ function toolResultTokens(content) {
108
+ if (typeof content === 'string')
109
+ return estimateTokens(content);
110
+ if (!Array.isArray(content))
111
+ return 0;
112
+ let tokens = 0;
113
+ for (const block of content) {
114
+ if (block == null || typeof block !== 'object')
115
+ continue;
116
+ const b = block;
117
+ if (b.type === 'text' && typeof b.text === 'string')
118
+ tokens += estimateTokens(b.text);
119
+ else if (b.type === 'image')
120
+ tokens += imageTokens(b.source);
121
+ }
122
+ return tokens;
123
+ }
124
+ class TreeBuilder {
125
+ full = newAcc();
126
+ effective = newAcc();
127
+ pending = new Map();
128
+ model = 'unknown';
129
+ lastUsage = null;
130
+ maxSeenTokens = 0;
131
+ accs(effective) {
132
+ return effective ? [this.full, this.effective] : [this.full];
133
+ }
134
+ addEntry(entry, effective) {
135
+ const role = entry.message?.role;
136
+ if (entry.type === 'assistant' && role === 'assistant') {
137
+ this.addAssistant(entry, effective);
138
+ }
139
+ else if (entry.type === 'user' && role === 'user') {
140
+ this.addUser(entry, effective);
141
+ }
142
+ else if (entry.type === 'system') {
143
+ const tokens = typeof entry.content === 'string' ? estimateTokens(entry.content) : 0;
144
+ for (const acc of this.accs(effective))
145
+ add(acc.system, tokens);
146
+ }
147
+ else if (entry.type === 'attachment') {
148
+ let tokens = 0;
149
+ try {
150
+ tokens = entry.attachment == null ? 0 : estimateTokens(JSON.stringify(entry.attachment));
151
+ }
152
+ catch {
153
+ tokens = 0;
154
+ }
155
+ for (const acc of this.accs(effective))
156
+ add(acc.userMeta, tokens);
157
+ }
158
+ }
159
+ addAssistant(entry, effective) {
160
+ const msg = entry.message;
161
+ if (!msg)
162
+ return;
163
+ if (typeof msg.model === 'string' && msg.model && msg.model !== '<synthetic>')
164
+ this.model = msg.model;
165
+ const usage = msg.usage;
166
+ if (usage && ((usage.input_tokens ?? 0) > 0 || (usage.cache_read_input_tokens ?? 0) > 0)) {
167
+ this.lastUsage = usage;
168
+ }
169
+ const id = msg.id ?? entry.uuid ?? '';
170
+ let pending = this.pending.get(id);
171
+ if (!pending) {
172
+ pending = { effective, visibleEstTokens: 0, thinkingCount: 0, outputTokens: 0 };
173
+ this.pending.set(id, pending);
174
+ for (const acc of this.accs(effective)) {
175
+ acc.assistantCount += 1;
176
+ acc.messages += 1;
177
+ }
178
+ }
179
+ if (usage?.output_tokens !== undefined)
180
+ pending.outputTokens = usage.output_tokens;
181
+ const content = msg.content;
182
+ if (!Array.isArray(content))
183
+ return;
184
+ for (const block of content) {
185
+ if (block == null || typeof block !== 'object')
186
+ continue;
187
+ const b = block;
188
+ if (b.type === 'text' && typeof b.text === 'string') {
189
+ const tokens = estimateTokens(b.text);
190
+ pending.visibleEstTokens += tokens;
191
+ for (const acc of this.accs(pending.effective))
192
+ add(acc.assistantText, tokens);
193
+ }
194
+ else if (b.type === 'thinking' || b.type === 'redacted_thinking') {
195
+ pending.thinkingCount += 1;
196
+ }
197
+ else if (b.type === 'tool_use' || b.type === 'server_tool_use') {
198
+ let tokens = 0;
199
+ try {
200
+ tokens = estimateTokens(JSON.stringify(b.input ?? {}));
201
+ }
202
+ catch {
203
+ tokens = 0;
204
+ }
205
+ pending.visibleEstTokens += tokens;
206
+ const tool = typeof b.name === 'string' && b.name ? b.name : 'unknown';
207
+ for (const acc of this.accs(pending.effective)) {
208
+ add(acc.toolCall, tokens);
209
+ const stat = acc.byTool.get(tool) ?? newBlockStat();
210
+ add(stat, tokens);
211
+ acc.byTool.set(tool, stat);
212
+ }
213
+ }
214
+ else if (b.type === 'web_search_tool_result' || b.type === 'web_fetch_tool_result') {
215
+ for (const acc of this.accs(pending.effective))
216
+ add(acc.toolResult, toolResultTokens(b.content));
217
+ }
218
+ }
219
+ }
220
+ addUser(entry, effective) {
221
+ for (const acc of this.accs(effective)) {
222
+ acc.userCount += 1;
223
+ acc.messages += 1;
224
+ }
225
+ const content = entry.message?.content;
226
+ const bucketFor = (acc, text) => {
227
+ if (entry.isCompactSummary)
228
+ return acc.userCompactSummary;
229
+ if (entry.isMeta || META_TEXT_RE.test(text))
230
+ return acc.userMeta;
231
+ return acc.userText;
232
+ };
233
+ if (typeof content === 'string') {
234
+ for (const acc of this.accs(effective))
235
+ add(bucketFor(acc, content), estimateTokens(content));
236
+ return;
237
+ }
238
+ if (!Array.isArray(content))
239
+ return;
240
+ for (const block of content) {
241
+ if (block == null || typeof block !== 'object')
242
+ continue;
243
+ const b = block;
244
+ if (b.type === 'text' && typeof b.text === 'string') {
245
+ for (const acc of this.accs(effective))
246
+ add(bucketFor(acc, b.text), estimateTokens(b.text));
247
+ }
248
+ else if (b.type === 'image') {
249
+ const tokens = imageTokens(b.source);
250
+ for (const acc of this.accs(effective))
251
+ add(acc.userImage, tokens);
252
+ }
253
+ else if (b.type === 'tool_result') {
254
+ const tokens = toolResultTokens(b.content);
255
+ for (const acc of this.accs(effective))
256
+ add(acc.toolResult, tokens);
257
+ }
258
+ }
259
+ }
260
+ // Transcripts strip thinking text, so estimate reasoning as the message's
261
+ // output_tokens minus its estimated visible output. Only messages that
262
+ // actually contained thinking blocks get a reasoning row; the remainder for
263
+ // other messages is chars/4 drift, not reasoning.
264
+ flushReasoning() {
265
+ for (const pending of this.pending.values()) {
266
+ if (pending.thinkingCount === 0)
267
+ continue;
268
+ const tokens = Math.max(0, pending.outputTokens - pending.visibleEstTokens);
269
+ for (const acc of this.accs(pending.effective)) {
270
+ acc.assistantReasoning.count += pending.thinkingCount;
271
+ acc.assistantReasoning.tokens += tokens;
272
+ }
273
+ }
274
+ }
275
+ }
276
+ export function snapshot(acc) {
277
+ const assistantTokens = acc.assistantText.tokens + acc.assistantReasoning.tokens + acc.toolCall.tokens;
278
+ const userTokens = acc.userText.tokens + acc.userImage.tokens + acc.userCompactSummary.tokens + acc.userMeta.tokens;
279
+ const byTool = [...acc.byTool.entries()]
280
+ .map(([tool, stat]) => ({ tool, count: stat.count, tokens: stat.tokens }))
281
+ .sort((a, b) => b.tokens - a.tokens);
282
+ return {
283
+ messages: acc.messages,
284
+ tokens: assistantTokens + userTokens + acc.toolResult.tokens + acc.system.tokens,
285
+ assistant: {
286
+ count: acc.assistantCount,
287
+ tokens: assistantTokens,
288
+ text: acc.assistantText,
289
+ reasoning: acc.assistantReasoning,
290
+ toolCall: acc.toolCall,
291
+ byTool,
292
+ },
293
+ user: {
294
+ count: acc.userCount,
295
+ tokens: userTokens,
296
+ text: acc.userText,
297
+ image: acc.userImage,
298
+ compactSummary: acc.userCompactSummary,
299
+ meta: acc.userMeta,
300
+ },
301
+ toolResult: acc.toolResult,
302
+ system: acc.system,
303
+ };
304
+ }
305
+ const skipFileSnapshots = (head) => head.includes('"type":"file-history-snapshot"');
306
+ // Pass 1: locate the last compaction. The live window starts at the preserved
307
+ // segment's head (messages Claude Code carried across the compaction), not at
308
+ // the boundary itself.
309
+ async function findLastBoundary(filePath) {
310
+ let headUuid = null;
311
+ let compactions = 0;
312
+ let maxPreTokens = 0;
313
+ for await (const line of readSessionLines(filePath, skipFileSnapshots, { largeLineAsBuffer: true })) {
314
+ if (typeof line !== 'string')
315
+ continue;
316
+ if (!line.includes('"subtype":"compact_boundary"'))
317
+ continue;
318
+ let entry;
319
+ try {
320
+ entry = JSON.parse(line);
321
+ }
322
+ catch {
323
+ continue;
324
+ }
325
+ if (entry.type !== 'system' || entry.subtype !== 'compact_boundary')
326
+ continue;
327
+ compactions += 1;
328
+ headUuid = entry.compactMetadata?.preservedSegment?.headUuid ?? null;
329
+ maxPreTokens = Math.max(maxPreTokens, entry.compactMetadata?.preTokens ?? 0);
330
+ }
331
+ return { headUuid, compactions, maxPreTokens };
332
+ }
333
+ // Claude models with a 1M window: opus-4-8 (auto-compactions on disk show
334
+ // ~1.0M preTokens), the Claude 5 Fable / Mythos ids (claude-fable-5-1 and
335
+ // claude-mythos-5-1 run a 1M window from the first turn), and the "[1m]"
336
+ // long-context variants. Others default to 200K unless the session itself
337
+ // proves bigger.
338
+ const MILLION_WINDOW_RE = /opus-4-8|fable-5|mythos-5|\[1m\]/;
339
+ export function reportedContextWindow(model, maxSeenTokens) {
340
+ return MILLION_WINDOW_RE.test(model) || maxSeenTokens > 220_000 ? 1_000_000 : 200_000;
341
+ }
342
+ export async function buildContextTree(session) {
343
+ const boundary = await findLastBoundary(session.filePath);
344
+ const builder = new TreeBuilder();
345
+ builder.maxSeenTokens = boundary.maxPreTokens;
346
+ let boundariesSeen = 0;
347
+ let inPreservedSegment = false;
348
+ for await (const line of readSessionLines(session.filePath, skipFileSnapshots, { largeLineAsBuffer: true })) {
349
+ const text = lineToText(line);
350
+ if (!text || text.charCodeAt(0) !== 123)
351
+ continue;
352
+ let entry;
353
+ try {
354
+ entry = JSON.parse(text);
355
+ }
356
+ catch {
357
+ continue;
358
+ }
359
+ if (entry.isSidechain === true)
360
+ continue;
361
+ if (entry.type === 'system' && entry.subtype === 'compact_boundary') {
362
+ boundariesSeen += 1;
363
+ continue;
364
+ }
365
+ if (boundary.headUuid && entry.uuid === boundary.headUuid)
366
+ inPreservedSegment = true;
367
+ const effective = boundariesSeen >= boundary.compactions || inPreservedSegment;
368
+ builder.addEntry(entry, effective);
369
+ }
370
+ builder.flushReasoning();
371
+ let reported = null;
372
+ if (builder.lastUsage) {
373
+ const context = (builder.lastUsage.input_tokens ?? 0) +
374
+ (builder.lastUsage.cache_read_input_tokens ?? 0) +
375
+ (builder.lastUsage.cache_creation_input_tokens ?? 0) +
376
+ (builder.lastUsage.output_tokens ?? 0);
377
+ builder.maxSeenTokens = Math.max(builder.maxSeenTokens, context);
378
+ reported = { context, window: reportedContextWindow(builder.model, builder.maxSeenTokens) };
379
+ }
380
+ return {
381
+ session,
382
+ model: builder.model,
383
+ compactions: boundary.compactions,
384
+ reported,
385
+ effective: snapshot(builder.effective),
386
+ full: snapshot(builder.full),
387
+ };
388
+ }
389
+ // Mirrors the env handling of providers/claude.ts so the context views cover
390
+ // the same session roots as usage tracking.
391
+ function claudeProjectRoots() {
392
+ const dirsEnv = process.env['CLAUDE_CONFIG_DIRS'];
393
+ const dirs = dirsEnv ? dirsEnv.split(delimiter).filter(Boolean) : [process.env['CLAUDE_CONFIG_DIR'] ?? join(homedir(), '.claude')];
394
+ return dirs.map((d) => join(d, 'projects'));
395
+ }
396
+ async function listSessionFiles() {
397
+ const files = [];
398
+ for (const root of claudeProjectRoots()) {
399
+ if (!existsSync(root))
400
+ continue;
401
+ let projectDirs;
402
+ try {
403
+ projectDirs = await readdir(root);
404
+ }
405
+ catch {
406
+ continue;
407
+ }
408
+ for (const dir of projectDirs) {
409
+ let names;
410
+ try {
411
+ names = await readdir(join(root, dir));
412
+ }
413
+ catch {
414
+ continue;
415
+ }
416
+ for (const name of names) {
417
+ if (!name.endsWith('.jsonl'))
418
+ continue;
419
+ files.push({
420
+ filePath: join(root, dir, name),
421
+ sessionId: name.slice(0, -'.jsonl'.length),
422
+ project: dir.split('-').filter(Boolean).pop() ?? dir,
423
+ });
424
+ }
425
+ }
426
+ }
427
+ return files;
428
+ }
429
+ async function statRef(file) {
430
+ try {
431
+ const info = await stat(file.filePath);
432
+ if (!info.isFile() || info.size === 0)
433
+ return null;
434
+ return { ...file, mtimeMs: info.mtimeMs, sizeBytes: info.size };
435
+ }
436
+ catch {
437
+ return null;
438
+ }
439
+ }
440
+ function newestFirst(refs) {
441
+ return refs.filter((r) => r !== null).sort((a, b) => b.mtimeMs - a.mtimeMs);
442
+ }
443
+ export async function listRecentSessions(limit = 15) {
444
+ const files = await listSessionFiles();
445
+ return newestFirst(await Promise.all(files.map(statRef))).slice(0, limit);
446
+ }
447
+ // Id lookups match filenames directly so only the matching files get stated.
448
+ export async function findClaudeSession(idPrefix) {
449
+ const matches = (await listSessionFiles()).filter((f) => f.sessionId.startsWith(idPrefix));
450
+ return newestFirst(await Promise.all(matches.map(statRef)))[0] ?? null;
451
+ }
452
+ // Claude Code stores an AI-generated session name as "ai-title" entries (the
453
+ // last one is current; sessions get re-titled) and, in older sessions, as
454
+ // "summary" entries near the top. Scanning one tail and one head chunk finds
455
+ // it without reading a potentially 100MB transcript.
456
+ const TITLE_CHUNK_BYTES = 262_144;
457
+ function titleFromChunk(chunk) {
458
+ let title = '';
459
+ let summary = '';
460
+ for (const line of chunk.split('\n')) {
461
+ if (line.includes('"type":"ai-title"')) {
462
+ try {
463
+ const t = JSON.parse(line).aiTitle;
464
+ if (typeof t === 'string' && t)
465
+ title = t;
466
+ }
467
+ catch {
468
+ continue;
469
+ }
470
+ }
471
+ else if (!summary && line.includes('"type":"summary"')) {
472
+ try {
473
+ const t = JSON.parse(line).summary;
474
+ if (typeof t === 'string' && t)
475
+ summary = t;
476
+ }
477
+ catch {
478
+ continue;
479
+ }
480
+ }
481
+ }
482
+ return title || summary;
483
+ }
484
+ export async function readChunk(filePath, start, length) {
485
+ const fd = await open(filePath, 'r');
486
+ try {
487
+ const buf = Buffer.alloc(length);
488
+ const { bytesRead } = await fd.read(buf, 0, length, start);
489
+ return buf.subarray(0, bytesRead).toString('utf-8');
490
+ }
491
+ finally {
492
+ await fd.close();
493
+ }
494
+ }
495
+ export async function readSessionTitle(ref) {
496
+ try {
497
+ const tailStart = Math.max(0, ref.sizeBytes - TITLE_CHUNK_BYTES);
498
+ let title = titleFromChunk(await readChunk(ref.filePath, tailStart, TITLE_CHUNK_BYTES));
499
+ if (!title && tailStart > 0)
500
+ title = titleFromChunk(await readChunk(ref.filePath, 0, TITLE_CHUNK_BYTES));
501
+ return title.replace(/\s+/g, ' ').trim();
502
+ }
503
+ catch {
504
+ return '';
505
+ }
506
+ }
507
+ async function resolveSession(arg, provider) {
508
+ if (arg && (arg.endsWith('.jsonl') || arg.includes('/'))) {
509
+ if (!existsSync(arg))
510
+ return null;
511
+ const info = await stat(arg);
512
+ const base = arg.split('/').pop() ?? arg;
513
+ return {
514
+ filePath: arg,
515
+ sessionId: base.replace(/\.jsonl$/, ''),
516
+ project: '',
517
+ mtimeMs: info.mtimeMs,
518
+ sizeBytes: info.size,
519
+ };
520
+ }
521
+ if (provider === 'codex') {
522
+ const codex = await import('./context-tree-codex.js');
523
+ if (!arg)
524
+ return (await codex.listRecentCodexSessions(1))[0] ?? null;
525
+ return codex.findCodexSession(arg);
526
+ }
527
+ if (!arg)
528
+ return (await listRecentSessions(1))[0] ?? null;
529
+ return findClaudeSession(arg);
530
+ }
531
+ function num(n) {
532
+ return n.toLocaleString('en-US');
533
+ }
534
+ export function relativeAge(mtimeMs) {
535
+ const mins = Math.max(0, Math.round((Date.now() - mtimeMs) / 60_000));
536
+ if (mins < 60)
537
+ return `${mins}m ago`;
538
+ if (mins < 60 * 24)
539
+ return `${Math.round(mins / 60)}h ago`;
540
+ return `${Math.round(mins / (60 * 24))}d ago`;
541
+ }
542
+ export function snapshotRows(view) {
543
+ const rows = [];
544
+ rows.push({ depth: 0, label: 'assistant', count: view.assistant.count, tokens: view.assistant.tokens, bold: true });
545
+ rows.push({ depth: 1, label: 'text', count: view.assistant.text.count, tokens: view.assistant.text.tokens });
546
+ if (view.assistant.reasoning.count > 0)
547
+ rows.push({ depth: 1, label: 'reasoning', count: view.assistant.reasoning.count, tokens: view.assistant.reasoning.tokens });
548
+ rows.push({ depth: 1, label: 'tool-call', count: view.assistant.toolCall.count, tokens: view.assistant.toolCall.tokens });
549
+ for (const t of view.assistant.byTool)
550
+ rows.push({ depth: 2, label: t.tool, count: t.count, tokens: t.tokens });
551
+ rows.push({ depth: 0, label: 'user', count: view.user.count, tokens: view.user.tokens, bold: true });
552
+ rows.push({ depth: 1, label: 'text', count: view.user.text.count, tokens: view.user.text.tokens });
553
+ if (view.user.image.count > 0)
554
+ rows.push({ depth: 1, label: 'image', count: view.user.image.count, tokens: view.user.image.tokens });
555
+ if (view.user.compactSummary.count > 0)
556
+ rows.push({ depth: 1, label: 'compact-summary', count: view.user.compactSummary.count, tokens: view.user.compactSummary.tokens });
557
+ if (view.user.meta.count > 0)
558
+ rows.push({ depth: 1, label: 'meta', count: view.user.meta.count, tokens: view.user.meta.tokens });
559
+ rows.push({ depth: 0, label: 'tool', count: view.toolResult.count, tokens: view.toolResult.tokens, bold: true });
560
+ rows.push({ depth: 1, label: 'tool-result', count: view.toolResult.count, tokens: view.toolResult.tokens });
561
+ if (view.system.count > 0)
562
+ rows.push({ depth: 0, label: 'system', count: view.system.count, tokens: view.system.tokens, bold: true });
563
+ return rows;
564
+ }
565
+ function renderRows(rows) {
566
+ const leftLen = (r) => r.depth * 2 + (r.depth > 0 ? 2 : 0) + r.label.length;
567
+ const labelWidth = Math.max(...rows.map(leftLen)) + 2;
568
+ const countWidth = Math.max(...rows.map((r) => num(r.count).length)) + 1;
569
+ const tokenWidth = Math.max(...rows.map((r) => num(r.tokens).length));
570
+ return rows.map((r) => {
571
+ const indent = ' '.repeat(r.depth);
572
+ const bullet = r.depth > 0 ? chalk.dim('◦ ') : '';
573
+ const label = r.depth === 0 ? chalk.bold(r.label) : r.label;
574
+ const pad = ' '.repeat(labelWidth - leftLen(r));
575
+ const count = chalk.dim(`${num(r.count)}x`.padStart(countWidth + 1));
576
+ const tokens = (r.bold ? chalk.cyan.bold : chalk.cyan)(num(r.tokens).padStart(tokenWidth + 2));
577
+ return ` ${indent}${bullet}${label}${pad}${count}${tokens} ${chalk.dim('tokens')}`;
578
+ });
579
+ }
580
+ export function renderContextTree(result, opts = {}) {
581
+ const view = opts.full ? result.full : result.effective;
582
+ const lines = [];
583
+ const scopeLabel = opts.full ? 'full session' : 'effective';
584
+ lines.push('');
585
+ lines.push(` ${chalk.bold('Context Token Usage')} ${chalk.dim(`(${scopeLabel})`)}`);
586
+ const sizeMb = (result.session.sizeBytes / 1024 / 1024).toFixed(1);
587
+ const project = result.session.project ? `${result.session.project} · ` : '';
588
+ lines.push(chalk.dim(` session ${result.session.sessionId.slice(0, 8)} · ${project}${result.model} · ${relativeAge(result.session.mtimeMs)} · ${sizeMb}MB on disk`));
589
+ lines.push('');
590
+ const masked = Math.max(0, result.full.tokens - result.effective.tokens);
591
+ lines.push(` messages: ${chalk.bold(num(view.messages))}`);
592
+ lines.push(` tokens: ${chalk.bold(formatTokens(result.full.tokens))} ${chalk.dim('estimated across the session')}`);
593
+ if (result.compactions > 0) {
594
+ const pct = result.full.tokens > 0 ? Math.round((result.effective.tokens / result.full.tokens) * 100) : 0;
595
+ lines.push(` ${chalk.dim('◦')} ${formatTokens(masked)} ${chalk.dim(`compacted away (${num(result.compactions)} compaction${result.compactions === 1 ? '' : 's'})`)}`);
596
+ lines.push(` ${chalk.dim('◦')} ${formatTokens(result.effective.tokens)} ${chalk.dim(`effective (${pct}%)`)}`);
597
+ }
598
+ if (result.reported) {
599
+ const { context, window } = result.reported;
600
+ const windowPart = window ? ` ${chalk.dim(`of ${formatTokens(window)} window (${Math.round((context / window) * 100)}%)`)}` : '';
601
+ lines.push(` context (exact, last turn): ${chalk.bold(formatTokens(context))}${windowPart}`);
602
+ const overhead = result.reported.context - result.effective.tokens;
603
+ if (overhead >= 0) {
604
+ lines.push(` ${chalk.dim('◦')} ${formatTokens(overhead)} ${chalk.dim('system prompt, tools & memory (derived)')}`);
605
+ }
606
+ }
607
+ lines.push('');
608
+ lines.push(...renderRows(snapshotRows(view)));
609
+ lines.push('');
610
+ lines.push(chalk.dim(' block tokens are estimated (chars/4, images by pixel count, reasoning from per-message usage);'));
611
+ lines.push(chalk.dim(' "context (exact)" comes from API usage.'));
612
+ if (!opts.full && result.compactions > 0)
613
+ lines.push(chalk.dim(' showing the live window since the last compaction; use --full for the whole session.'));
614
+ lines.push('');
615
+ return lines.join('\n');
616
+ }
617
+ function renderSessionList(refs, provider) {
618
+ const heading = provider === 'codex' ? 'Recent Codex sessions' : 'Recent Claude Code sessions';
619
+ const hint = provider === 'codex' ? 'codeburn context <id> --provider codex to inspect one' : 'codeburn context <id> to inspect one';
620
+ const lines = ['', ` ${chalk.bold(heading)}`, ''];
621
+ const projectWidth = Math.max(...refs.map((r) => r.project.length));
622
+ for (const ref of refs) {
623
+ const sizeMb = (ref.sizeBytes / 1024 / 1024).toFixed(1).padStart(6);
624
+ const shortTitle = ref.title.length > 48 ? `${ref.title.slice(0, 47)}…` : ref.title;
625
+ lines.push(` ${chalk.cyan(ref.sessionId.slice(0, 8))} ${chalk.dim(`${sizeMb}MB`)} ${relativeAge(ref.mtimeMs).padStart(7)} ${chalk.dim(ref.project.padEnd(projectWidth))} ${shortTitle}`);
626
+ }
627
+ lines.push('');
628
+ lines.push(chalk.dim(` ${hint}`));
629
+ lines.push('');
630
+ return lines.join('\n');
631
+ }
632
+ export async function listRecentTitledSessions(limit = 15) {
633
+ const refs = await listRecentSessions(limit);
634
+ const titles = await Promise.all(refs.map(readSessionTitle));
635
+ return refs.map((r, i) => ({ ...r, title: titles[i] ?? '' }));
636
+ }
637
+ export async function runContextCommand(sessionArg, opts) {
638
+ const provider = opts.provider === 'codex' ? 'codex' : 'claude';
639
+ if (opts.list) {
640
+ const refs = provider === 'codex' ? await (await import('./context-tree-codex.js')).listRecentCodexSessions(15) : await listRecentTitledSessions(15);
641
+ if (refs.length === 0) {
642
+ console.log(provider === 'codex' ? 'No Codex sessions found.' : 'No Claude Code sessions found.');
643
+ return;
644
+ }
645
+ if (opts.json) {
646
+ console.log(JSON.stringify({ sessions: refs }, null, 2));
647
+ return;
648
+ }
649
+ console.log(renderSessionList(refs, provider));
650
+ return;
651
+ }
652
+ const session = await resolveSession(sessionArg, provider);
653
+ if (!session) {
654
+ console.error(sessionArg ? `No ${provider} session matching "${sessionArg}".` : `No ${provider} sessions found.`);
655
+ process.exitCode = 1;
656
+ return;
657
+ }
658
+ const result = provider === 'codex' ? await (await import('./context-tree-codex.js')).buildCodexContextTree(session) : await buildContextTree(session);
659
+ if (opts.json) {
660
+ console.log(JSON.stringify(result, null, 2));
661
+ return;
662
+ }
663
+ console.log(renderContextTree(result, { full: opts.full }));
664
+ }
@@ -0,0 +1,16 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ // Copilot AI credits. Official rate from GitHub Docs, *Usage-based billing
3
+ // for individuals*, fetched 2026-08-23:
4
+ // https://docs.github.com/copilot/concepts/billing/usage-based-billing-for-individuals
5
+ // 1e9 nano-AIU = 1 credit = $0.01. No per-model rate table in this slice.
6
+ export const NANO_AIU_PER_CREDIT = 1e9;
7
+ export const AI_CREDIT_USD = 0.01;
8
+ export function isFiniteNanoAiu(value) {
9
+ return typeof value === 'number' && Number.isFinite(value);
10
+ }
11
+ export function nanoAiuToCredits(nanoAiu) {
12
+ return nanoAiu / NANO_AIU_PER_CREDIT;
13
+ }
14
+ export function creditsToUsd(credits) {
15
+ return credits * AI_CREDIT_USD;
16
+ }