chompyy 0.5.0 → 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 (154) hide show
  1. package/README.md +11 -0
  2. package/dist/agentlimits.js +77 -0
  3. package/dist/agentusage.js +96 -0
  4. package/dist/appstate.js +63 -3
  5. package/dist/away.js +44 -5
  6. package/dist/blueprint.js +3 -7
  7. package/dist/board.js +1 -0
  8. package/dist/cli.js +263 -5
  9. package/dist/codexquota.js +106 -0
  10. package/dist/codexusage.js +10 -0
  11. package/dist/config.js +2 -0
  12. package/dist/context.js +30 -0
  13. package/dist/costs.js +1 -0
  14. package/dist/demon.js +20 -0
  15. package/dist/label.js +33 -0
  16. package/dist/menu.js +17 -0
  17. package/dist/nightcap.js +60 -0
  18. package/dist/nudge.js +47 -18
  19. package/dist/pacing.js +16 -1
  20. package/dist/questions.js +71 -0
  21. package/dist/recap.js +74 -0
  22. package/dist/receipt.js +48 -0
  23. package/dist/recipe.js +79 -0
  24. package/dist/stamps.js +14 -0
  25. package/dist/triggers.js +5 -0
  26. package/dist/usage.js +21 -1
  27. package/dist/vendor/codeburn/antigravity.js +309 -0
  28. package/dist/vendor/codeburn/codex.js +429 -0
  29. package/dist/vendor/codeburn/copilot.js +292 -0
  30. package/dist/vendor/codeburn/gemini.js +195 -0
  31. package/dist/vendor/codeburn/grokbot.js +182 -0
  32. package/dist/vendor/codeburn/kimi.js +178 -0
  33. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  34. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  35. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  36. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  37. package/dist/vendor/codeburn/src/act/types.js +37 -0
  38. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  39. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  40. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  41. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  42. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  43. package/dist/vendor/codeburn/src/classifier.js +209 -0
  44. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  45. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  46. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  47. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  48. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  49. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  50. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  51. package/dist/vendor/codeburn/src/config.js +145 -0
  52. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  53. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  54. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  55. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  56. package/dist/vendor/codeburn/src/currency.js +189 -0
  57. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  58. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  59. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  60. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  61. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  62. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  63. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  64. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  65. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  66. package/dist/vendor/codeburn/src/format.js +118 -0
  67. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  68. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  69. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  70. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  71. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  72. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  73. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  74. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  75. package/dist/vendor/codeburn/src/models.js +1879 -0
  76. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  77. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  78. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  79. package/dist/vendor/codeburn/src/parser.js +6953 -0
  80. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  81. package/dist/vendor/codeburn/src/plans.js +135 -0
  82. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  83. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  84. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  85. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  86. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  87. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  88. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  89. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  90. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  91. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  92. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  93. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  94. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  95. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  96. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  97. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  98. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  99. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  100. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  101. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  102. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  103. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  104. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  105. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  106. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  107. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  108. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  109. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  110. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  111. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  112. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  113. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  114. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  115. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  116. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  117. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  118. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  119. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  120. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  121. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  122. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  123. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  124. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  125. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  126. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  127. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  128. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  129. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  130. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  131. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  132. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  133. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  134. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  135. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  136. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  137. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  138. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  139. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  140. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  141. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  142. package/dist/vendor/codeburn/src/session-output.js +139 -0
  143. package/dist/vendor/codeburn/src/session-population.js +30 -0
  144. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  145. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  146. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  147. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  148. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  149. package/dist/vendor/codeburn/src/types.js +16 -0
  150. package/dist/vendor/codeburn/src/work-units.js +126 -0
  151. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  152. package/dist/vendor/codeburn/src/wsl.js +198 -0
  153. package/dist/vendor/codeburn/src/yield.js +666 -0
  154. package/package.json +1 -1
@@ -0,0 +1,690 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { open, readdir, readFile, stat } from 'fs/promises';
3
+ import { basename, join } from 'path';
4
+ import { homedir } from 'os';
5
+ import zlib from 'zlib';
6
+ import { MAX_SESSION_FILE_BYTES, readSessionFile, readSessionLines } from '../fs-utils.js';
7
+ import { billableOutputTokens, calculateCost, getShortModelName, ownValue } from '../models.js';
8
+ import { extractBashCommands } from '../bash-utils.js';
9
+ // DeepSeek Harness (dsh) stores one session per directory:
10
+ // <DSH_HOME|~/.dsh>/sessions/<encoded-cwd>/session-<uuid>/session.jsonl.zstd
11
+ // (or an uncompressed session.jsonl when compression=none). The .zstd file is
12
+ // a concatenation of INDEPENDENT zstd frames — one per appended event batch —
13
+ // so node:zlib's one-shot zstdDecompressSync (which decodes a single frame)
14
+ // must be driven frame-by-frame behind a structural frame-boundary scan. The
15
+ // scan below is a port of scanZstdFrames from the official
16
+ // @deepseek-ai/dsh-session-persistence-jsonl package, which is third-party code
17
+ // under its own license - see THIRD_PARTY_NOTICES.md.
18
+ const ZSTD_MAGIC = 0xfd2fb528;
19
+ // SESSION_FORMAT_VERSION in @deepseek-ai/dsh-session. DSH refuses to load a log
20
+ // stamped with any other version, and a bump means an event's meaning changed,
21
+ // so a foreign version is skipped rather than read with today's assumptions.
22
+ // A zstd frame's declared content size is attacker-controlled, so a few KB of
23
+ // crafted input can expand to gigabytes. Every decode is capped: no single
24
+ // frame may exceed this, and no file may decode to more than it would have been
25
+ // allowed to occupy uncompressed (MAX_SESSION_FILE_BYTES). Overflow throws, and
26
+ // the caller skips the WHOLE file rather than counting the frames it got to.
27
+ const MAX_FRAME_DECODED_BYTES = 64 * 1024 * 1024;
28
+ // v4 (dsh 0.2.0-rc.2) only lifts tool-result roles and adds metadata this parser ignores.
29
+ const SUPPORTED_SESSION_FORMAT_VERSIONS = new Set([0, 1, 2, 3, 4]);
30
+ const SESSION_LOG_NAME = /^session(?:\.v(\d+))?\.jsonl(?:\.zstd)?$/u;
31
+ const MIN_REASONABLE_TIMESTAMP_MS = 1_000_000_000_000;
32
+ // Discovery walks every session, so a per-file notice would repeat once per
33
+ // log; each distinct message is worth saying exactly once.
34
+ const noticed = new Set();
35
+ function notice(message) {
36
+ if (noticed.has(message))
37
+ return;
38
+ noticed.add(message);
39
+ process.stderr.write(message);
40
+ }
41
+ // A notice naming a file cannot dedup on its text: a systematic problem prints
42
+ // one line per session and grows `noticed` without bound. Dedup on the kind
43
+ // instead and show a few example paths.
44
+ const PATH_NOTICE_EXAMPLES = 3;
45
+ const noticedPaths = new Map();
46
+ function noticePath(kind, detail) {
47
+ const seen = (noticedPaths.get(kind) ?? 0) + 1;
48
+ noticedPaths.set(kind, seen);
49
+ if (seen <= PATH_NOTICE_EXAMPLES)
50
+ process.stderr.write(`codeburn: ${kind}: ${detail}\n`);
51
+ else if (seen === PATH_NOTICE_EXAMPLES + 1)
52
+ process.stderr.write(`codeburn: ${kind}: further paths suppressed\n`);
53
+ }
54
+ // Locate complete frames without decompressing their blocks. An EOF inside the
55
+ // final frame (a torn append from a crashed writer) returns its start so the
56
+ // caller can ignore the tail; invalid complete structure rejects.
57
+ function scanZstdFrames(buffer, maxFrames = Number.POSITIVE_INFINITY) {
58
+ const frames = [];
59
+ let offset = 0;
60
+ while (offset < buffer.length) {
61
+ const start = offset;
62
+ if (buffer.length - offset < 4)
63
+ return { frames, tornStart: start };
64
+ if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) {
65
+ throw new Error(`invalid zstd frame magic at byte ${offset}`);
66
+ }
67
+ offset += 4;
68
+ if (offset === buffer.length)
69
+ return { frames, tornStart: start };
70
+ const descriptor = buffer.readUInt8(offset);
71
+ offset += 1;
72
+ if ((descriptor & 24) !== 0)
73
+ throw new Error(`reserved frame-header bit at byte ${offset - 1}`);
74
+ const contentSizeFlag = descriptor >>> 6;
75
+ const singleSegment = (descriptor & 32) !== 0;
76
+ const checksum = (descriptor & 4) !== 0;
77
+ const dictionaryFlag = descriptor & 3;
78
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
79
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
80
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
81
+ if (buffer.length - offset < remainingHeaderBytes)
82
+ return { frames, tornStart: start };
83
+ offset += remainingHeaderBytes;
84
+ for (;;) {
85
+ if (buffer.length - offset < 3)
86
+ return { frames, tornStart: start };
87
+ const blockHeader = buffer.readUIntLE(offset, 3);
88
+ offset += 3;
89
+ const lastBlock = (blockHeader & 1) !== 0;
90
+ const blockType = (blockHeader >>> 1) & 3;
91
+ const blockSize = blockHeader >>> 3;
92
+ if (blockType === 3)
93
+ throw new Error(`reserved block type at byte ${offset - 3}`);
94
+ const payloadBytes = blockType === 1 ? 1 : blockSize;
95
+ if (buffer.length - offset < payloadBytes)
96
+ return { frames, tornStart: start };
97
+ offset += payloadBytes;
98
+ if (lastBlock)
99
+ break;
100
+ }
101
+ if (checksum) {
102
+ if (buffer.length - offset < 4)
103
+ return { frames, tornStart: start };
104
+ offset += 4;
105
+ }
106
+ frames.push({ start, end: offset });
107
+ if (frames.length === maxFrames)
108
+ return { frames };
109
+ }
110
+ return { frames };
111
+ }
112
+ const toolNameMap = {
113
+ bash: 'Bash',
114
+ pwsh: 'Bash',
115
+ read: 'Read',
116
+ write: 'Write',
117
+ edit: 'Edit',
118
+ str_replace_editor: 'Edit',
119
+ glob: 'Glob',
120
+ grep: 'Grep',
121
+ todo_write: 'TodoWrite',
122
+ todo: 'TodoWrite',
123
+ web_search: 'WebSearch',
124
+ skill: 'Skill',
125
+ agent: 'Agent',
126
+ ask_user_question: 'AskUserQuestion',
127
+ };
128
+ function mapToolName(raw) {
129
+ return ownValue(toolNameMap, raw) ?? raw;
130
+ }
131
+ // Usage fields are whatever the JSON held. A string or array would flow
132
+ // straight into the global token totals and the persisted cache, where
133
+ // `0 + [1, 2]` silently becomes "01,2". Same semantics as copilot.ts.
134
+ function numberOrZero(raw) {
135
+ return typeof raw === 'number' && Number.isSafeInteger(raw) && raw > 0 ? raw : 0;
136
+ }
137
+ function usageIsComplete(usage) {
138
+ const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
139
+ return count(usage.inputTokens) && count(usage.outputTokens)
140
+ && [usage.cacheReadTokens, usage.cacheWriteTokens, usage.reasoningTokens].every(value => value === undefined || count(value))
141
+ && (usage.reasoningTokens === undefined || usage.reasoningTokens <= usage.outputTokens);
142
+ }
143
+ // A log stamped with a version this parser was not written against is skipped
144
+ // whole: a bump means an event's meaning changed, so reading it with today's
145
+ // assumptions would report confident wrong numbers.
146
+ function isReadableVersion(header) {
147
+ if (typeof header.version === 'number' && SUPPORTED_SESSION_FORMAT_VERSIONS.has(header.version))
148
+ return true;
149
+ // Keyed on the version, not the path: a DSH upgrade makes EVERY session
150
+ // unreadable at once, and one line per session log is noise, not a report.
151
+ notice(`codeburn: skipping DSH sessions written in session format version ${String(header.version)}; upgrade codeburn.\n`);
152
+ return false;
153
+ }
154
+ function generationFromPath(filePath) {
155
+ const match = SESSION_LOG_NAME.exec(basename(filePath));
156
+ if (!match)
157
+ return undefined;
158
+ return match[1] === undefined ? 0 : Number(match[1]);
159
+ }
160
+ function headerMatchesPath(header, filePath) {
161
+ const generation = generationFromPath(filePath);
162
+ if (generation === undefined || header.version !== generation) {
163
+ noticePath('skipping DSH session log whose filename and header versions disagree', filePath);
164
+ return false;
165
+ }
166
+ return isReadableVersion(header);
167
+ }
168
+ // DSH writes epoch milliseconds; promote a seconds-resolution value and reject
169
+ // what stays implausible, matching the guard cline-cli.ts uses on the hazard.
170
+ function isoTimestamp(value, fallback) {
171
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
172
+ return fallback;
173
+ const ms = value < MIN_REASONABLE_TIMESTAMP_MS ? value * 1000 : value;
174
+ const date = new Date(ms);
175
+ if (Number.isNaN(date.getTime()) || date.getTime() < MIN_REASONABLE_TIMESTAMP_MS)
176
+ return fallback;
177
+ return date.toISOString();
178
+ }
179
+ function getDshHome(override) {
180
+ // An empty-string DSH_HOME is treated as unset.
181
+ return override ?? (process.env['DSH_HOME'] || undefined) ?? join(homedir(), '.dsh');
182
+ }
183
+ // DSH writes native-platform paths into the header (backslashes on Windows);
184
+ // split on both separators so discovery is correct on any host.
185
+ function projectFromCwd(cwd, fallback) {
186
+ const segments = cwd.split(/[\\/]/).filter(Boolean);
187
+ return segments[segments.length - 1] ?? fallback;
188
+ }
189
+ // Decode every complete frame and yield its JSONL lines. A torn final frame is
190
+ // ignored; a structurally corrupt file, or one that decodes past `budget`,
191
+ // throws for the caller to report. Exported for the decode-budget test.
192
+ export function* readZstdLines(buffer, maxFrames = Number.POSITIVE_INFINITY, budget = MAX_SESSION_FILE_BYTES) {
193
+ const { frames } = scanZstdFrames(buffer, maxFrames);
194
+ let remaining = budget;
195
+ for (const frame of frames) {
196
+ if (remaining <= 0)
197
+ throw new Error(`decodes past the ${budget}-byte cap`);
198
+ // node throws ERR_BUFFER_TOO_LARGE without allocating past the cap, so the
199
+ // per-frame limit doubles as the running budget for the frames after it.
200
+ const decoded = zlib.zstdDecompressSync(buffer.subarray(frame.start, frame.end), {
201
+ maxOutputLength: Math.min(remaining, MAX_FRAME_DECODED_BYTES),
202
+ });
203
+ remaining -= decoded.length;
204
+ for (const line of decoded.toString('utf-8').split('\n')) {
205
+ if (line.trim())
206
+ yield line;
207
+ }
208
+ }
209
+ }
210
+ async function readEventLines(filePath) {
211
+ if (filePath.endsWith('.zstd')) {
212
+ let buffer;
213
+ try {
214
+ // The whole log is buffered to scan its frames, so it needs the same
215
+ // oversize guard readSessionFile applies to the uncompressed variant.
216
+ const size = (await stat(filePath)).size;
217
+ if (size > MAX_SESSION_FILE_BYTES) {
218
+ noticePath('skipped oversize DSH session log', `${filePath} (${size} bytes)`);
219
+ return null;
220
+ }
221
+ buffer = await readFile(filePath);
222
+ }
223
+ catch {
224
+ return null;
225
+ }
226
+ try {
227
+ return [...readZstdLines(buffer)];
228
+ }
229
+ catch (err) {
230
+ noticePath('skipped corrupt DSH session log', `${filePath}: ${err instanceof Error ? err.message : err}`);
231
+ return null;
232
+ }
233
+ }
234
+ const content = await readSessionFile(filePath);
235
+ if (content === null)
236
+ return null;
237
+ return content.split('\n').filter(l => l.trim());
238
+ }
239
+ // Cheap discovery probe: decompress ONLY the first frame (the session header
240
+ // batch) instead of the whole log. The header frame is tiny, so a bounded head
241
+ // read almost always contains it; fall back to a full read when it does not.
242
+ async function readSessionHeader(filePath) {
243
+ const firstLine = async () => {
244
+ if (filePath.endsWith('.zstd')) {
245
+ let head;
246
+ try {
247
+ const handle = await open(filePath, 'r');
248
+ try {
249
+ const size = (await handle.stat()).size;
250
+ const length = Math.min(size, 256 * 1024);
251
+ head = Buffer.alloc(length);
252
+ await handle.read(head, 0, length, 0);
253
+ }
254
+ finally {
255
+ await handle.close();
256
+ }
257
+ }
258
+ catch {
259
+ return null;
260
+ }
261
+ let { frames } = scanZstdFrames(head, 1);
262
+ if (frames.length === 0) {
263
+ // Head read did not cover one full frame; take the whole file. A fork's
264
+ // first batch carries the whole inherited seed, so this is reachable on
265
+ // a real log and needs the same oversize guard as the parse read.
266
+ try {
267
+ if ((await stat(filePath)).size > MAX_SESSION_FILE_BYTES)
268
+ return null;
269
+ const full = await readFile(filePath);
270
+ frames = scanZstdFrames(full, 1).frames;
271
+ if (frames.length === 0)
272
+ return null;
273
+ head = full;
274
+ }
275
+ catch {
276
+ return null;
277
+ }
278
+ }
279
+ const text = zlib.zstdDecompressSync(head.subarray(frames[0].start, frames[0].end), {
280
+ maxOutputLength: MAX_FRAME_DECODED_BYTES,
281
+ }).toString('utf-8');
282
+ return text.split('\n').find(l => l.trim()) ?? null;
283
+ }
284
+ for await (const line of readSessionLines(filePath)) {
285
+ if (line.trim())
286
+ return line;
287
+ }
288
+ return null;
289
+ };
290
+ try {
291
+ const line = await firstLine();
292
+ if (!line)
293
+ return null;
294
+ const event = JSON.parse(line);
295
+ if (event.type !== 'session')
296
+ return null;
297
+ return event;
298
+ }
299
+ catch {
300
+ return null;
301
+ }
302
+ }
303
+ async function discoverSessionsInDir(sessionsDir, onSkippedVersion) {
304
+ const sources = [];
305
+ let projectDirs;
306
+ try {
307
+ projectDirs = await readdir(sessionsDir);
308
+ }
309
+ catch {
310
+ return sources;
311
+ }
312
+ for (const dirName of projectDirs) {
313
+ const dirPath = join(sessionsDir, dirName);
314
+ const dirStat = await stat(dirPath).catch(() => null);
315
+ if (!dirStat?.isDirectory())
316
+ continue;
317
+ let sessionDirs;
318
+ try {
319
+ sessionDirs = await readdir(dirPath);
320
+ }
321
+ catch {
322
+ continue;
323
+ }
324
+ for (const sessionDir of sessionDirs) {
325
+ const sessionPath = join(dirPath, sessionDir);
326
+ const sessionStat = await stat(sessionPath).catch(() => null);
327
+ if (!sessionStat?.isDirectory())
328
+ continue;
329
+ // DSH keeps migrated generations beside their immutable predecessors.
330
+ // Resolve the numerically highest canonical generation once per Session;
331
+ // never fall back to an older snapshot when that authoritative file is
332
+ // unknown or corrupt, since that would silently report stale usage.
333
+ const generationFiles = [];
334
+ const slots = new Set();
335
+ let ambiguous;
336
+ const names = await readdir(sessionPath).catch(() => []);
337
+ for (const name of names) {
338
+ const match = SESSION_LOG_NAME.exec(name);
339
+ if (!match)
340
+ continue;
341
+ const version = match[1] === undefined ? 0 : Number(match[1]);
342
+ const candidate = join(sessionPath, name);
343
+ const fileStat = await stat(candidate).catch(() => null);
344
+ if (!fileStat?.isFile())
345
+ continue;
346
+ const compressed = name.endsWith('.zstd');
347
+ // `session.v0.jsonl` names the unversioned generation and
348
+ // `session.v03.jsonl` names generation 3, so two files can claim one
349
+ // generation; past 2^53 a generation cannot be ordered at all. Either
350
+ // way no canonical log can be resolved, and dropping the session
351
+ // silently is the omission #1281 was about.
352
+ const slot = `${version}:${String(compressed)}`;
353
+ if (!Number.isSafeInteger(version) || slots.has(slot)) {
354
+ ambiguous ??= version;
355
+ continue;
356
+ }
357
+ slots.add(slot);
358
+ generationFiles.push({ path: candidate, version, compressed });
359
+ }
360
+ if (ambiguous !== undefined) {
361
+ onSkippedVersion?.(ambiguous);
362
+ noticePath('skipping DSH session whose generation filenames are ambiguous', sessionPath);
363
+ continue;
364
+ }
365
+ generationFiles.sort((a, b) => b.version - a.version || Number(b.compressed) - Number(a.compressed));
366
+ const selected = generationFiles[0];
367
+ if (!selected)
368
+ continue;
369
+ const filePath = selected.path;
370
+ if (!SUPPORTED_SESSION_FORMAT_VERSIONS.has(selected.version)) {
371
+ onSkippedVersion?.(selected.version);
372
+ notice(`codeburn: skipping DSH sessions written in session format version ${selected.version}; upgrade codeburn.\n`);
373
+ continue;
374
+ }
375
+ const header = await readSessionHeader(filePath);
376
+ if (!header) {
377
+ onSkippedVersion?.(selected.version);
378
+ noticePath('skipping unreadable DSH session header', filePath);
379
+ continue;
380
+ }
381
+ if (!headerMatchesPath(header, filePath)) {
382
+ onSkippedVersion?.(selected.version);
383
+ continue;
384
+ }
385
+ const cwd = typeof header.cwd === 'string' && header.cwd.trim() ? header.cwd : dirName;
386
+ sources.push({ path: filePath, project: projectFromCwd(cwd, dirName), provider: 'dsh' });
387
+ }
388
+ }
389
+ return sources;
390
+ }
391
+ function parseToolArguments(raw) {
392
+ if (!raw)
393
+ return null;
394
+ try {
395
+ const parsed = JSON.parse(raw);
396
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
397
+ }
398
+ catch {
399
+ return null;
400
+ }
401
+ }
402
+ function usageFromStream(stream) {
403
+ if (!Array.isArray(stream))
404
+ return undefined;
405
+ for (let index = stream.length - 1; index >= 0; index -= 1) {
406
+ const record = stream[index];
407
+ if (record?.type === 'chunk' && record.chunk?.type === 'usage')
408
+ return record.chunk.usage;
409
+ }
410
+ return undefined;
411
+ }
412
+ function emptyStepBucket() {
413
+ return { observations: [], tools: [], skills: [], bashCommands: [] };
414
+ }
415
+ function createParser(source, seenKeys) {
416
+ return {
417
+ async *parse() {
418
+ const lines = await readEventLines(source.path);
419
+ if (!lines)
420
+ return;
421
+ const events = [];
422
+ let corruptInterior = false;
423
+ for (const [index, line] of lines.entries()) {
424
+ try {
425
+ const value = JSON.parse(line);
426
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
427
+ if (index === 0)
428
+ return;
429
+ corruptInterior = true;
430
+ continue;
431
+ }
432
+ events.push(value);
433
+ }
434
+ catch {
435
+ if (index === 0)
436
+ return;
437
+ // A torn final append may be discarded. Malformed rows in the middle
438
+ // of a versioned log cannot justify a complete historical total.
439
+ if (index < lines.length - 1)
440
+ corruptInterior = true;
441
+ }
442
+ }
443
+ const header = events[0];
444
+ if (header?.type !== 'session' || !headerMatchesPath(header, source.path))
445
+ return;
446
+ const formatVersion = header.version;
447
+ if (formatVersion >= 2 && corruptInterior) {
448
+ noticePath('skipping corrupt DSH session with malformed interior rows', source.path);
449
+ return;
450
+ }
451
+ const sessionId = typeof header.id === 'string' ? header.id : '';
452
+ const cwd = typeof header.cwd === 'string' ? header.cwd : '';
453
+ let headerModel = 'unknown';
454
+ let contextModel = '';
455
+ let currentTurn = 0;
456
+ const sessionStart = isoTimestamp(header.createdAt, '');
457
+ // Events a forked session inherited from its parent. They are a verbatim
458
+ // copy of the parent's log, which codeburn parses as its own session, so
459
+ // counting them here would bill the same calls twice.
460
+ let inheritedCut = formatVersion <= 1 && typeof header.parentSession === 'string' && header.parentSession
461
+ && typeof header.seedLength === 'number'
462
+ ? header.seedLength - 1
463
+ : -1;
464
+ if (formatVersion >= 2) {
465
+ const taggedCuts = events
466
+ .filter(event => event.type === 'session/end-seed' && event.data?.inherited === true && typeof event.seq === 'number')
467
+ .map(event => event.seq);
468
+ if (header.isSeeded === true && taggedCuts.length === 0) {
469
+ noticePath('skipping corrupt seeded DSH session without an inherited end-seed marker', source.path);
470
+ return;
471
+ }
472
+ if (header.isSeeded !== true && taggedCuts.length > 0) {
473
+ noticePath('skipping corrupt unseeded DSH session with an inherited end-seed marker', source.path);
474
+ return;
475
+ }
476
+ inheritedCut = taggedCuts.at(-1) ?? -1;
477
+ }
478
+ const userMessageByTurn = new Map();
479
+ const buckets = new Map();
480
+ const activeAttempts = new Map();
481
+ for (const event of events) {
482
+ if (event.type === 'session') {
483
+ continue;
484
+ }
485
+ // Inherited request state can remain authoritative for the child's
486
+ // first local attempt even though inherited usage is not billable.
487
+ if (event.type === 'request/header') {
488
+ // Emitted at most once per request; steps after the last header
489
+ // inherit its config as their model.
490
+ const nextModel = event.data?.header?.config?.model;
491
+ if (typeof nextModel === 'string' && nextModel) {
492
+ if (nextModel !== headerModel)
493
+ contextModel = '';
494
+ headerModel = nextModel;
495
+ }
496
+ continue;
497
+ }
498
+ if (event.type === 'request/context') {
499
+ const nextModel = event.data?.model;
500
+ if (typeof nextModel === 'string' && nextModel)
501
+ contextModel = nextModel;
502
+ continue;
503
+ }
504
+ if (typeof event.seq === 'number' && event.seq <= inheritedCut)
505
+ continue;
506
+ if (event.type === 'turn/start') {
507
+ currentTurn = event.data?.turn ?? currentTurn;
508
+ continue;
509
+ }
510
+ if (event.type === 'llm/retry-started') {
511
+ const turn = event.data?.turn ?? currentTurn;
512
+ const step = event.data?.step ?? 0;
513
+ activeAttempts.delete(`${turn}:${step}`);
514
+ continue;
515
+ }
516
+ if (event.type === 'user/message') {
517
+ // Plugin-injected context (runtime snapshots, skill bodies, file-change
518
+ // notices) rides the same event type as a typed prompt; only the latter
519
+ // is a useful preview.
520
+ if (event.data?.source?.kind !== 'user')
521
+ continue;
522
+ if (userMessageByTurn.has(currentTurn))
523
+ continue;
524
+ const content = event.data?.content;
525
+ const texts = (Array.isArray(content) ? content : [])
526
+ .filter(c => c?.type === 'text' && typeof c.text === 'string' && c.text)
527
+ .map(c => c.text);
528
+ if (texts.length > 0)
529
+ userMessageByTurn.set(currentTurn, texts.join(' ').slice(0, 500));
530
+ continue;
531
+ }
532
+ if (event.type === 'tool/call') {
533
+ const turn = event.data?.turn ?? currentTurn;
534
+ const step = event.data?.step ?? 0;
535
+ const rawName = event.data?.name;
536
+ if (typeof rawName !== 'string' || !rawName)
537
+ continue;
538
+ const key = `${turn}:${step}`;
539
+ let bucket = buckets.get(key);
540
+ if (!bucket) {
541
+ bucket = emptyStepBucket();
542
+ buckets.set(key, bucket);
543
+ }
544
+ bucket.tools.push(mapToolName(rawName));
545
+ const args = parseToolArguments(event.data?.arguments);
546
+ if ((rawName === 'bash' || rawName === 'pwsh') && typeof args?.['command'] === 'string') {
547
+ bucket.bashCommands.push(...extractBashCommands(args['command']));
548
+ }
549
+ if (rawName === 'skill' && typeof args?.['name'] === 'string') {
550
+ bucket.skills.push(args['name']);
551
+ }
552
+ continue;
553
+ }
554
+ let usage;
555
+ let isFinal = false;
556
+ // The model that actually served the call, when the message records it.
557
+ // request/header only describes the request codeburn is about to see.
558
+ let reportedModel = contextModel || headerModel;
559
+ if (formatVersion <= 1 && event.type === 'assistant/chunk' && event.data?.chunk?.type === 'usage') {
560
+ usage = event.data.chunk.usage;
561
+ }
562
+ else if (event.type === 'assistant/message') {
563
+ usage = event.data?.usage ?? (formatVersion >= 2 ? usageFromStream(event.data?.stream) : undefined);
564
+ isFinal = true;
565
+ const messageModel = event.data?.message?.source?.model;
566
+ if (typeof messageModel === 'string' && messageModel)
567
+ reportedModel = messageModel;
568
+ }
569
+ else if (formatVersion >= 2 && event.type === 'assistant/attempt') {
570
+ usage = usageFromStream(event.data?.stream);
571
+ isFinal = true;
572
+ }
573
+ else {
574
+ continue;
575
+ }
576
+ const turn = event.data?.turn ?? currentTurn;
577
+ const step = event.data?.step ?? 0;
578
+ if (![turn, step].every(value => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)) {
579
+ noticePath('skipping DSH usage with invalid attempt coordinates', source.path);
580
+ continue;
581
+ }
582
+ const key = `${turn}:${step}`;
583
+ if (!usage) {
584
+ if (!activeAttempts.has(key)) {
585
+ noticePath('DSH session contains an attempt without usage; totals may be incomplete', source.path);
586
+ }
587
+ continue;
588
+ }
589
+ let bucket = buckets.get(key);
590
+ if (!bucket) {
591
+ bucket = emptyStepBucket();
592
+ buckets.set(key, bucket);
593
+ }
594
+ const observation = { usage, time: event.time, model: reportedModel, final: isFinal };
595
+ // A different step cannot close this step's replacement slot. Only
596
+ // its own retry-started event makes the next observation additive.
597
+ const activeIndex = activeAttempts.get(key);
598
+ if (activeIndex !== undefined) {
599
+ if (!bucket.observations[activeIndex]?.final || isFinal) {
600
+ bucket.observations[activeIndex] = observation;
601
+ }
602
+ }
603
+ else {
604
+ bucket.observations.push(observation);
605
+ activeAttempts.set(key, bucket.observations.length - 1);
606
+ }
607
+ }
608
+ const sortedKeys = [...buckets.keys()].sort((a, b) => {
609
+ const [ta, sa] = a.split(':').map(Number);
610
+ const [tb, sb] = b.split(':').map(Number);
611
+ return ta - tb || sa - sb;
612
+ });
613
+ for (const key of sortedKeys) {
614
+ const bucket = buckets.get(key);
615
+ for (let attempt = 0; attempt < bucket.observations.length; attempt += 1) {
616
+ const observation = bucket.observations[attempt];
617
+ const input = numberOrZero(observation.usage.inputTokens);
618
+ const output = numberOrZero(observation.usage.outputTokens);
619
+ const cacheRead = numberOrZero(observation.usage.cacheReadTokens);
620
+ const cacheWrite = numberOrZero(observation.usage.cacheWriteTokens);
621
+ const reasoning = Math.min(numberOrZero(observation.usage.reasoningTokens), output);
622
+ const completeUsage = usageIsComplete(observation.usage);
623
+ if (!completeUsage) {
624
+ noticePath('DSH session contains incomplete or invalid usage; retained counts are estimated', source.path);
625
+ }
626
+ if (input + output + cacheRead + cacheWrite === 0)
627
+ continue;
628
+ const attemptKey = attempt === 0 ? key : `${key}:attempt:${attempt + 1}`;
629
+ const dedupKey = `dsh:${sessionId || source.path}:${attemptKey}`;
630
+ if (seenKeys.has(dedupKey))
631
+ continue;
632
+ seenKeys.add(dedupKey);
633
+ // DSH TokenUsage defines reasoning as informational detail already
634
+ // included in outputTokens. Preserve raw output and use the same
635
+ // shared rule as cache rehydration and display (#1075).
636
+ const costUSD = calculateCost(observation.model, input, billableOutputTokens('dsh', output, reasoning), cacheWrite, cacheRead, 0);
637
+ const [turn] = key.split(':').map(Number);
638
+ yield {
639
+ provider: 'dsh',
640
+ model: observation.model,
641
+ inputTokens: input,
642
+ outputTokens: output,
643
+ cacheCreationInputTokens: cacheWrite,
644
+ cacheReadInputTokens: cacheRead,
645
+ cachedInputTokens: cacheRead,
646
+ reasoningTokens: reasoning,
647
+ webSearchRequests: 0,
648
+ costUSD,
649
+ costIsEstimated: !completeUsage,
650
+ tools: attempt === bucket.observations.length - 1 ? [...new Set(bucket.tools)] : [],
651
+ bashCommands: attempt === bucket.observations.length - 1 ? bucket.bashCommands : [],
652
+ skills: attempt === bucket.observations.length - 1 && bucket.skills.length > 0 ? [...new Set(bucket.skills)] : undefined,
653
+ timestamp: isoTimestamp(observation.time, sessionStart),
654
+ speed: 'standard',
655
+ deduplicationKey: dedupKey,
656
+ userMessage: userMessageByTurn.get(turn) ?? '',
657
+ sessionId: sessionId || source.path,
658
+ project: cwd ? projectFromCwd(cwd, source.project) : source.project,
659
+ projectPath: cwd || undefined,
660
+ workingDirectory: cwd || undefined,
661
+ };
662
+ }
663
+ }
664
+ },
665
+ };
666
+ }
667
+ export function createDshProvider(dshHomeOverride) {
668
+ const dshHome = getDshHome(dshHomeOverride);
669
+ const sessionsDir = join(dshHome, 'sessions');
670
+ return {
671
+ name: 'dsh',
672
+ displayName: 'DeepSeek Harness',
673
+ modelDisplayName(model) {
674
+ return getShortModelName(model);
675
+ },
676
+ toolDisplayName(rawTool) {
677
+ return mapToolName(rawTool);
678
+ },
679
+ async probeRoots() {
680
+ return [{ path: sessionsDir, label: 'sessions' }];
681
+ },
682
+ async discoverSessions(onSkippedVersion) {
683
+ return discoverSessionsInDir(sessionsDir, onSkippedVersion);
684
+ },
685
+ createSessionParser(source, seenKeys) {
686
+ return createParser(source, seenKeys);
687
+ },
688
+ };
689
+ }
690
+ export const dsh = createDshProvider();