chompyy 0.4.7 → 0.6.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 (161) hide show
  1. package/README.md +40 -6
  2. package/dist/advice.js +2 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/appstate.js +72 -5
  6. package/dist/away.js +44 -5
  7. package/dist/blueprint.js +3 -7
  8. package/dist/board.js +4 -0
  9. package/dist/cli.js +328 -15
  10. package/dist/codexquota.js +106 -0
  11. package/dist/codexusage.js +10 -0
  12. package/dist/config.js +2 -0
  13. package/dist/context.js +30 -0
  14. package/dist/costs.js +1 -0
  15. package/dist/daytime.js +68 -0
  16. package/dist/demon.js +20 -0
  17. package/dist/didwork.js +46 -0
  18. package/dist/label.js +33 -0
  19. package/dist/learning.js +35 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +60 -0
  22. package/dist/nudge.js +47 -18
  23. package/dist/pacing.js +16 -1
  24. package/dist/questions.js +71 -0
  25. package/dist/recap.js +74 -0
  26. package/dist/receipt.js +48 -0
  27. package/dist/recipe.js +79 -0
  28. package/dist/send.js +46 -20
  29. package/dist/stamps.js +14 -0
  30. package/dist/taste.js +67 -7
  31. package/dist/triggers.js +5 -0
  32. package/dist/unkeep.js +220 -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 +6953 -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/package.json +11 -3
@@ -0,0 +1,544 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { open, stat } from 'node:fs/promises';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { createTextReadStream } from './fs-utils.js';
5
+ import { billableOutputTokens } from './models.js';
6
+ import { isCodexForkReplay, startCodexForkReplay } from './codex-fork-replay.js';
7
+ const CHUNK_BYTES = 64 * 1024;
8
+ const MAX_PENDING_LINE_CHARS = 4 * 1024 * 1024;
9
+ const TRUNCATION_MARKER = '__CODEBURN_TRUNCATED_LINE__';
10
+ function rawString(source, field) {
11
+ const match = new RegExp(`"${field}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`).exec(source);
12
+ if (!match)
13
+ return undefined;
14
+ try {
15
+ return JSON.parse(`"${match[1]}"`);
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ function rawNumber(source, field) {
22
+ const match = new RegExp(`"${field}"\\s*:\\s*(-?\\d+(?:\\.\\d+)?)`).exec(source);
23
+ if (!match)
24
+ return undefined;
25
+ const value = Number(match[1]);
26
+ return Number.isFinite(value) ? value : undefined;
27
+ }
28
+ function compactUsage(source, field) {
29
+ const index = source.indexOf(`"${field}"`);
30
+ if (index < 0)
31
+ return undefined;
32
+ const body = source.slice(index, index + 4096);
33
+ return {
34
+ output_tokens: rawNumber(body, 'output_tokens'),
35
+ reasoning_output_tokens: rawNumber(body, 'reasoning_output_tokens'),
36
+ total_tokens: rawNumber(body, 'total_tokens'),
37
+ };
38
+ }
39
+ function parseRawDurationValue(value) {
40
+ const objectMatch = /^\s*\{\s*"secs"\s*:\s*(-?\d+(?:\.\d+)?)\s*,\s*"nanos"\s*:\s*(-?\d+(?:\.\d+)?)\s*\}/.exec(value);
41
+ if (objectMatch) {
42
+ const seconds = Number(objectMatch[1]);
43
+ const nanos = Number(objectMatch[2]);
44
+ if (Number.isFinite(seconds) && Number.isFinite(nanos))
45
+ return seconds * 1000 + nanos / 1e6;
46
+ }
47
+ const stringMatch = /^\s*"(\d+(?:\.\d+)?)(ms|s)?"/.exec(value);
48
+ if (stringMatch) {
49
+ const parsed = Number(stringMatch[1]);
50
+ if (Number.isFinite(parsed))
51
+ return parsed * (stringMatch[2] === 's' ? 1000 : 1);
52
+ }
53
+ const numberMatch = /^\s*(-?\d+(?:\.\d+)?)/.exec(value);
54
+ if (numberMatch) {
55
+ const parsed = Number(numberMatch[1]);
56
+ if (Number.isFinite(parsed))
57
+ return parsed;
58
+ }
59
+ return undefined;
60
+ }
61
+ function durationMs(payload) {
62
+ if (!payload)
63
+ return undefined;
64
+ if (typeof payload.duration_ms === 'number' && Number.isFinite(payload.duration_ms))
65
+ return payload.duration_ms;
66
+ if (typeof payload.duration === 'object' && payload.duration) {
67
+ const seconds = payload.duration.secs;
68
+ const nanos = payload.duration.nanos;
69
+ if (typeof seconds === 'number' && typeof nanos === 'number' && Number.isFinite(seconds) && Number.isFinite(nanos)) {
70
+ return seconds * 1000 + nanos / 1e6;
71
+ }
72
+ }
73
+ if (typeof payload.duration === 'string') {
74
+ const match = /^(\d+(?:\.\d+)?)(ms|s)?$/.exec(payload.duration.trim());
75
+ if (match)
76
+ return Number(match[1]) * (match[2] === 's' ? 1000 : 1);
77
+ }
78
+ return undefined;
79
+ }
80
+ // Shared with src/providers/codex.ts (#1088 BUG-8): both clip a task's tool
81
+ // intervals to its [taskStartedAt, taskStartedAt + durationMs] window, merge
82
+ // overlaps, and cap the sum at durationMs. Was copy-pasted inline in
83
+ // providers/codex.ts and had already drifted (duration parsing there accepted
84
+ // only a plain `duration_ms` number); one copy now, called from both.
85
+ export function mergeToolIntervals(intervals, durationMs, taskStartedAt, taskCompletedAt) {
86
+ const windowStart = taskStartedAt ?? (taskCompletedAt !== undefined ? taskCompletedAt - durationMs : undefined);
87
+ const windowEnd = windowStart !== undefined ? windowStart + durationMs : undefined;
88
+ const clipped = intervals.map(([start, end]) => [
89
+ windowStart !== undefined ? Math.max(start, windowStart) : start,
90
+ windowEnd !== undefined ? Math.min(end, windowEnd) : end,
91
+ ]).filter(([start, end]) => end > start);
92
+ const merged = clipped.sort((a, b) => a[0] - b[0]).reduce((result, interval) => {
93
+ const previous = result.at(-1);
94
+ if (previous && interval[0] <= previous[1])
95
+ previous[1] = Math.max(previous[1], interval[1]);
96
+ else
97
+ result.push([...interval]);
98
+ return result;
99
+ }, []);
100
+ return Math.min(durationMs, merged.reduce((total, [start, end]) => total + end - start, 0));
101
+ }
102
+ function parseLine(line) {
103
+ const payloadStart = line.indexOf('"payload"');
104
+ const payloadHead = payloadStart >= 0 ? line.slice(payloadStart) : line;
105
+ if (line.length > 256 * 1024 || line.startsWith(TRUNCATION_MARKER)) {
106
+ const payloadType = rawString(payloadHead, 'type');
107
+ const infoStart = payloadHead.indexOf('"info"');
108
+ const info = infoStart >= 0 ? payloadHead.slice(infoStart) : '';
109
+ return {
110
+ type: rawString(line, 'type'),
111
+ timestamp: rawString(line, 'timestamp'),
112
+ payload: {
113
+ type: payloadType,
114
+ turn_id: rawString(payloadHead, 'turn_id'),
115
+ call_id: rawString(payloadHead, 'call_id'),
116
+ started_at: rawNumber(payloadHead, 'started_at'),
117
+ duration_ms: rawNumber(payloadHead, 'duration_ms'),
118
+ duration: rawString(payloadHead, 'duration') ?? (rawNumber(payloadHead, 'secs') !== undefined
119
+ ? { secs: rawNumber(payloadHead, 'secs'), nanos: rawNumber(payloadHead, 'nanos') }
120
+ : undefined),
121
+ model: rawString(payloadHead, 'model'),
122
+ forked_from_id: rawString(payloadHead, 'forked_from_id'),
123
+ info: {
124
+ last_token_usage: compactUsage(info, 'last_token_usage'),
125
+ total_token_usage: compactUsage(info, 'total_token_usage'),
126
+ },
127
+ },
128
+ };
129
+ }
130
+ try {
131
+ return JSON.parse(line);
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ }
137
+ function newThroughputState() {
138
+ return {
139
+ previousOutput: 0,
140
+ previousReasoning: 0,
141
+ currentTaskGenerated: 0,
142
+ currentTaskToolIntervals: [],
143
+ toolStarts: new Map(),
144
+ points: [],
145
+ };
146
+ }
147
+ /**
148
+ * Incrementally parses a rollout. Watch mode feeds only newly appended bytes
149
+ * to this reader, so a growing JSONL file is not reparsed from byte zero.
150
+ */
151
+ export class CodexThroughputReader {
152
+ offset = 0;
153
+ pending = '';
154
+ decoder = new StringDecoder('utf8');
155
+ pendingDurationMs;
156
+ scanDepth = 0;
157
+ scanPayloadDepth;
158
+ scanInString = false;
159
+ scanEscape = false;
160
+ scanString = '';
161
+ scanLastString = '';
162
+ scanAwaitingColon = false;
163
+ scanCurrentKey;
164
+ scanCapture;
165
+ state = newThroughputState();
166
+ reset() {
167
+ this.offset = 0;
168
+ this.pending = '';
169
+ this.decoder = new StringDecoder('utf8');
170
+ this.pendingDurationMs = undefined;
171
+ this.scanDepth = 0;
172
+ this.scanPayloadDepth = undefined;
173
+ this.scanInString = false;
174
+ this.scanEscape = false;
175
+ this.scanString = '';
176
+ this.scanLastString = '';
177
+ this.scanAwaitingColon = false;
178
+ this.scanCurrentKey = undefined;
179
+ this.scanCapture = undefined;
180
+ this.state = newThroughputState();
181
+ }
182
+ finishDurationCapture() {
183
+ if (!this.scanCapture)
184
+ return;
185
+ const value = this.scanCapture.mode === 'string' ? `"${this.scanCapture.text}"` : this.scanCapture.text;
186
+ const parsed = parseRawDurationValue(value);
187
+ if (parsed !== undefined && this.pendingDurationMs === undefined)
188
+ this.pendingDurationMs = parsed;
189
+ this.scanCapture = undefined;
190
+ }
191
+ scanDurationSegment(source) {
192
+ for (let i = 0; i < source.length; i++) {
193
+ const char = source[i];
194
+ if (this.scanInString) {
195
+ if (this.scanEscape) {
196
+ this.scanEscape = false;
197
+ if (this.scanCapture?.mode === 'object')
198
+ this.scanCapture.text += char;
199
+ else if (this.scanCapture?.mode === 'string')
200
+ this.scanCapture.text += char;
201
+ else
202
+ this.scanString += char;
203
+ continue;
204
+ }
205
+ if (char === '\\') {
206
+ this.scanEscape = true;
207
+ if (this.scanCapture?.mode === 'object' || this.scanCapture?.mode === 'string')
208
+ this.scanCapture.text += char;
209
+ continue;
210
+ }
211
+ if (char === '"') {
212
+ if (this.scanCapture?.mode === 'object')
213
+ this.scanCapture.text += char;
214
+ this.scanInString = false;
215
+ if (this.scanCapture?.mode === 'string')
216
+ this.finishDurationCapture();
217
+ else if (this.scanCapture?.mode === 'object') {
218
+ this.scanAwaitingColon = false;
219
+ this.scanCurrentKey = undefined;
220
+ }
221
+ else {
222
+ this.scanLastString = this.scanString;
223
+ this.scanAwaitingColon = true;
224
+ }
225
+ continue;
226
+ }
227
+ if (this.scanCapture?.mode === 'object' || this.scanCapture?.mode === 'string')
228
+ this.scanCapture.text += char;
229
+ else
230
+ this.scanString += char;
231
+ continue;
232
+ }
233
+ if (this.scanCapture?.mode === 'primitive') {
234
+ if (char === ',' || char === '}' || char === ']')
235
+ this.finishDurationCapture();
236
+ else {
237
+ this.scanCapture.text += char;
238
+ continue;
239
+ }
240
+ }
241
+ if (this.scanAwaitingColon) {
242
+ if (/\s/.test(char))
243
+ continue;
244
+ if (char === ':') {
245
+ this.scanCurrentKey = this.scanLastString;
246
+ this.scanAwaitingColon = false;
247
+ continue;
248
+ }
249
+ this.scanAwaitingColon = false;
250
+ }
251
+ if (char === '"') {
252
+ this.scanString = '';
253
+ if (this.scanCapture?.mode === 'object')
254
+ this.scanCapture.text += char;
255
+ if (this.scanCurrentKey === 'duration' && this.scanPayloadDepth === this.scanDepth) {
256
+ this.scanCapture = { mode: 'string', text: '', depth: this.scanDepth };
257
+ this.scanCurrentKey = undefined;
258
+ }
259
+ this.scanInString = true;
260
+ continue;
261
+ }
262
+ if (char === '{' || char === '[') {
263
+ if (this.scanCurrentKey === 'payload' && char === '{' && this.scanPayloadDepth === undefined) {
264
+ this.scanPayloadDepth = this.scanDepth + 1;
265
+ }
266
+ if (this.scanCurrentKey === 'duration' && this.scanPayloadDepth === this.scanDepth) {
267
+ this.scanCapture = { mode: 'object', text: char, depth: this.scanDepth + 1 };
268
+ this.scanCurrentKey = undefined;
269
+ }
270
+ else if (this.scanCapture?.mode === 'object') {
271
+ this.scanCapture.text += char;
272
+ }
273
+ this.scanDepth++;
274
+ continue;
275
+ }
276
+ if (char === '}' || char === ']') {
277
+ if (this.scanCapture?.mode === 'object')
278
+ this.scanCapture.text += char;
279
+ this.scanDepth = Math.max(0, this.scanDepth - 1);
280
+ if (this.scanCapture?.mode === 'object' && this.scanDepth < this.scanCapture.depth)
281
+ this.finishDurationCapture();
282
+ continue;
283
+ }
284
+ if (this.scanCurrentKey === 'duration' && this.scanPayloadDepth === this.scanDepth && !/\s/.test(char)) {
285
+ this.scanCapture = { mode: 'primitive', text: char, depth: this.scanDepth };
286
+ this.scanCurrentKey = undefined;
287
+ continue;
288
+ }
289
+ if (this.scanCapture?.mode === 'object')
290
+ this.scanCapture.text += char;
291
+ }
292
+ }
293
+ processLine(line, durationOverride) {
294
+ const entry = parseLine(line);
295
+ if (!entry)
296
+ return;
297
+ if (durationOverride !== undefined && (line.startsWith(TRUNCATION_MARKER) || line.length > 256 * 1024) && entry.type === 'event_msg' && (entry.payload?.type === 'mcp_tool_call_end' || entry.payload?.type === 'task_complete')) {
298
+ entry.payload = { ...entry.payload, duration_ms: durationOverride };
299
+ }
300
+ const state = this.state;
301
+ if (entry.type === 'session_meta') {
302
+ if (entry.payload?.model)
303
+ state.model = entry.payload.model;
304
+ if (entry.payload?.forked_from_id && entry.timestamp) {
305
+ state.forkReplayState = startCodexForkReplay(entry.timestamp);
306
+ }
307
+ return;
308
+ }
309
+ if (entry.type === 'turn_context' && entry.payload?.model)
310
+ state.model = entry.payload.model;
311
+ const isForkReplay = isCodexForkReplay(state.forkReplayState, entry.timestamp);
312
+ if (isForkReplay && (entry.payload?.type === 'task_started' ||
313
+ entry.payload?.type === 'task_complete' ||
314
+ entry.payload?.type === 'function_call' ||
315
+ entry.payload?.type === 'function_call_output' ||
316
+ entry.payload?.type === 'custom_tool_call' ||
317
+ entry.payload?.type === 'custom_tool_call_output' ||
318
+ entry.payload?.type === 'mcp_tool_call_end' ||
319
+ entry.payload?.type === 'patch_apply_end' ||
320
+ entry.payload?.type === 'token_count')) {
321
+ if (entry.payload?.type === 'token_count') {
322
+ const info = entry.payload.info;
323
+ const total = info?.total_token_usage;
324
+ if (total?.total_tokens !== undefined && Number.isFinite(total.total_tokens)) {
325
+ state.previousTotal = total.total_tokens;
326
+ state.previousOutput = total.output_tokens ?? state.previousOutput;
327
+ state.previousReasoning = total.reasoning_output_tokens ?? state.previousReasoning;
328
+ }
329
+ const outputTokens = info?.last_token_usage?.output_tokens ?? total?.output_tokens ?? 0;
330
+ const reasoningTokens = info?.last_token_usage?.reasoning_output_tokens ?? total?.reasoning_output_tokens ?? 0;
331
+ const replayTimestamp = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
332
+ if ((outputTokens > 0 || reasoningTokens > 0) && Number.isFinite(replayTimestamp)) {
333
+ state.previousTimestamp = Math.max(replayTimestamp, state.forkReplayState?.startedAtMs ?? replayTimestamp);
334
+ }
335
+ }
336
+ return;
337
+ }
338
+ if (entry.type === 'event_msg' && entry.payload?.type === 'task_started') {
339
+ state.currentTaskGenerated = 0;
340
+ state.currentTaskToolIntervals = [];
341
+ const startedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
342
+ state.currentTaskStartedAt = Number.isFinite(startedAt) ? startedAt : undefined;
343
+ state.toolStarts.clear();
344
+ }
345
+ if (entry.type === 'response_item' && (entry.payload?.type === 'function_call' || entry.payload?.type === 'custom_tool_call') && entry.payload.call_id && entry.timestamp) {
346
+ const started = Date.parse(entry.timestamp);
347
+ if (Number.isFinite(started))
348
+ state.toolStarts.set(entry.payload.call_id, started);
349
+ }
350
+ if (entry.type === 'response_item' && (entry.payload?.type === 'function_call_output' || entry.payload?.type === 'custom_tool_call_output') && entry.payload.call_id && entry.timestamp) {
351
+ const ended = Date.parse(entry.timestamp);
352
+ const started = state.toolStarts.get(entry.payload.call_id);
353
+ if (started !== undefined && Number.isFinite(ended) && ended > started)
354
+ state.currentTaskToolIntervals.push([started, ended]);
355
+ state.toolStarts.delete(entry.payload.call_id);
356
+ }
357
+ if (entry.type === 'event_msg' && entry.payload?.type === 'mcp_tool_call_end' && entry.timestamp) {
358
+ const ended = Date.parse(entry.timestamp);
359
+ const elapsed = durationMs(entry.payload);
360
+ if (Number.isFinite(ended) && elapsed !== undefined && elapsed > 0)
361
+ state.currentTaskToolIntervals.push([ended - elapsed, ended]);
362
+ }
363
+ if (entry.type === 'event_msg' && entry.payload?.type === 'task_complete') {
364
+ const taskDurationMs = durationMs(entry.payload);
365
+ if (state.latestPoint && typeof taskDurationMs === 'number' && taskDurationMs > 0 && state.currentTaskGenerated > 0) {
366
+ state.latestPoint.taskGeneratedTokens = state.currentTaskGenerated;
367
+ const completedAt = entry.timestamp ? Date.parse(entry.timestamp) : undefined;
368
+ const toolWaitMs = mergeToolIntervals(state.currentTaskToolIntervals, taskDurationMs, state.currentTaskStartedAt, Number.isFinite(completedAt) ? completedAt : undefined);
369
+ const activeMs = taskDurationMs - toolWaitMs;
370
+ if (activeMs > 0) {
371
+ state.latestPoint.activeDurationSeconds = activeMs / 1000;
372
+ state.latestPoint.toolWaitSeconds = toolWaitMs / 1000;
373
+ state.latestPoint.activeGeneratedTokensPerSecond = state.currentTaskGenerated / (activeMs / 1000);
374
+ }
375
+ }
376
+ }
377
+ if (entry.type !== 'event_msg' || entry.payload?.type !== 'token_count')
378
+ return;
379
+ const info = entry.payload.info;
380
+ if (!info || !entry.timestamp)
381
+ return;
382
+ const last = info.last_token_usage;
383
+ const total = info.total_token_usage;
384
+ const cumulative = total?.total_tokens;
385
+ if (cumulative !== undefined && cumulative === state.previousTotal)
386
+ return;
387
+ let outputTokens = last?.output_tokens ?? 0;
388
+ let reasoningTokens = last?.reasoning_output_tokens ?? 0;
389
+ if (!last && total && cumulative !== undefined && state.previousTotal !== undefined) {
390
+ outputTokens = Math.max(0, (total.output_tokens ?? 0) - state.previousOutput);
391
+ reasoningTokens = Math.max(0, (total.reasoning_output_tokens ?? 0) - state.previousReasoning);
392
+ }
393
+ if (cumulative !== undefined) {
394
+ state.previousTotal = cumulative;
395
+ state.previousOutput = total?.output_tokens ?? state.previousOutput;
396
+ state.previousReasoning = total?.reasoning_output_tokens ?? state.previousReasoning;
397
+ }
398
+ // Reasoning is already inside output_tokens (#1075/#1078); same numerator
399
+ // as the cost path so live Tok/s can't drift from billed tokens (#1079).
400
+ const generatedTokens = billableOutputTokens('codex', outputTokens, reasoningTokens);
401
+ if (generatedTokens <= 0)
402
+ return;
403
+ const timestampMs = Date.parse(entry.timestamp);
404
+ if (!Number.isFinite(timestampMs))
405
+ return;
406
+ const point = {
407
+ timestamp: entry.timestamp,
408
+ model: state.model,
409
+ outputTokens,
410
+ reasoningTokens,
411
+ generatedTokens,
412
+ };
413
+ state.currentTaskGenerated += generatedTokens;
414
+ state.latestPoint = point;
415
+ if (state.previousTimestamp !== undefined && timestampMs > state.previousTimestamp) {
416
+ const elapsedSeconds = (timestampMs - state.previousTimestamp) / 1000;
417
+ point.elapsedSeconds = elapsedSeconds;
418
+ point.generatedTokensPerSecond = generatedTokens / elapsedSeconds;
419
+ }
420
+ state.previousTimestamp = timestampMs;
421
+ state.points.push(point);
422
+ if (state.points.length > 10000)
423
+ state.points.splice(0, state.points.length - 10000);
424
+ }
425
+ consume(buffer) {
426
+ let chunk = this.decoder.write(buffer);
427
+ while (chunk.length > 0) {
428
+ const newlineIndex = chunk.search(/\r?\n/);
429
+ const segment = newlineIndex >= 0 ? chunk.slice(0, newlineIndex) : chunk;
430
+ this.pending += segment;
431
+ this.scanDurationSegment(segment);
432
+ if (newlineIndex < 0)
433
+ break;
434
+ const newlineLength = chunk[newlineIndex] === '\r' ? 2 : 1;
435
+ const line = this.pending;
436
+ const durationOverride = this.pendingDurationMs;
437
+ this.pending = '';
438
+ this.pendingDurationMs = undefined;
439
+ this.scanDepth = 0;
440
+ this.scanPayloadDepth = undefined;
441
+ this.scanInString = false;
442
+ this.scanEscape = false;
443
+ this.scanString = '';
444
+ this.scanLastString = '';
445
+ this.scanAwaitingColon = false;
446
+ this.scanCurrentKey = undefined;
447
+ this.scanCapture = undefined;
448
+ this.processLine(line, durationOverride);
449
+ chunk = chunk.slice(newlineIndex + newlineLength);
450
+ }
451
+ if (this.pending.length > MAX_PENDING_LINE_CHARS) {
452
+ const body = this.pending.startsWith(TRUNCATION_MARKER)
453
+ ? this.pending.slice(TRUNCATION_MARKER.length)
454
+ : this.pending;
455
+ this.pending = TRUNCATION_MARKER + body.slice(0, 256 * 1024) + body.slice(-256 * 1024);
456
+ }
457
+ }
458
+ async update(filePath, limit = 10, finalize = false) {
459
+ const info = await stat(filePath);
460
+ if (info.size < this.offset)
461
+ this.reset();
462
+ // A compressed rollout is immutable and its byte offsets are not text
463
+ // offsets, so it is decoded whole, once.
464
+ const compressed = filePath.endsWith('.zst');
465
+ if (compressed && this.offset === 0) {
466
+ try {
467
+ for await (const buffer of createTextReadStream(filePath))
468
+ this.consume(buffer);
469
+ }
470
+ catch (err) {
471
+ this.reset();
472
+ throw err;
473
+ }
474
+ this.offset = info.size;
475
+ }
476
+ const bytesToRead = compressed ? 0 : info.size - this.offset;
477
+ if (bytesToRead > 0) {
478
+ const file = await open(filePath, 'r');
479
+ try {
480
+ let position = this.offset;
481
+ while (position < info.size) {
482
+ const buffer = Buffer.allocUnsafe(Math.min(CHUNK_BYTES, info.size - position));
483
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
484
+ if (bytesRead === 0)
485
+ break;
486
+ position += bytesRead;
487
+ this.offset = position;
488
+ this.consume(buffer.subarray(0, bytesRead));
489
+ }
490
+ }
491
+ finally {
492
+ await file.close();
493
+ }
494
+ }
495
+ if (finalize && this.pending) {
496
+ this.processLine(this.pending, this.pendingDurationMs);
497
+ this.pending = '';
498
+ this.pendingDurationMs = undefined;
499
+ }
500
+ return limit > 0 ? this.state.points.slice(-limit) : this.state.points.slice();
501
+ }
502
+ }
503
+ export async function readCodexThroughput(filePath, limit = 10) {
504
+ return new CodexThroughputReader().update(filePath, limit, true);
505
+ }
506
+ export async function newestCodexSession(sessions) {
507
+ let newest;
508
+ for (const session of sessions) {
509
+ try {
510
+ const info = await stat(session.path);
511
+ if (!newest || info.mtimeMs > newest.mtimeMs)
512
+ newest = { path: session.path, mtimeMs: info.mtimeMs };
513
+ }
514
+ catch {
515
+ // A session can disappear while Codex rotates or archives it.
516
+ }
517
+ }
518
+ return newest?.path;
519
+ }
520
+ export function renderCodexThroughput(points, filePath) {
521
+ const latest = points.at(-1);
522
+ if (!latest)
523
+ return `No token_count checkpoints found in ${filePath}.`;
524
+ const lines = [
525
+ 'CodeBurn Codex throughput estimate',
526
+ `Session: ${filePath}`,
527
+ `Latest checkpoint: ${latest.timestamp}`,
528
+ `Latest checkpoint tokens: ${latest.generatedTokens.toLocaleString()} (${latest.outputTokens.toLocaleString()} output + ${latest.reasoningTokens.toLocaleString()} reasoning)`,
529
+ ];
530
+ if (latest.taskGeneratedTokens !== undefined)
531
+ lines.push(`Completed task total: ${latest.taskGeneratedTokens.toLocaleString()} generated tokens`);
532
+ if (latest.activeGeneratedTokensPerSecond !== undefined) {
533
+ lines.push(`Active throughput: ${latest.activeGeneratedTokensPerSecond.toFixed(1)} generated tokens/sec over ${latest.activeDurationSeconds.toFixed(1)}s`);
534
+ lines.push(`Excluded tool wait: ${latest.toolWaitSeconds.toFixed(1)}s`);
535
+ }
536
+ else if (latest.generatedTokensPerSecond !== undefined) {
537
+ lines.push(`Checkpoint estimate: ${latest.generatedTokensPerSecond.toFixed(1)} generated tokens/sec over ${latest.elapsedSeconds.toFixed(1)}s`);
538
+ }
539
+ else {
540
+ lines.push('Throughput: unavailable (waiting for a completed turn)');
541
+ }
542
+ lines.push('Note: offline JSONL estimate; tool intervals are removed, but server/prompt latency may remain.');
543
+ return lines.join('\n');
544
+ }