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,377 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readFile, mkdir, stat, open, rename, unlink } from 'fs/promises';
3
+ import { existsSync } from 'fs';
4
+ import { randomBytes } from 'crypto';
5
+ import { join, resolve } from 'path';
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
7
+ import { getCodeburnCacheDir, readExistingTextFile } from './cache-dir.js';
8
+ import { isWslUncPath } from './wsl.js';
9
+ // v4: attribute MCP calls emitted as event_msg/mcp_tool_call_end (issue #478).
10
+ // Recent Codex sessions cached under v3 dropped these, so force a re-parse.
11
+ // v5: also attribute CLI-wrapped MCP calls (`mcp-cli call server tool`) that
12
+ // Codex logs as a plain exec_command (issue #478 follow-up). Force a re-parse
13
+ // so sessions cached under v4 pick up the CLI-MCP attribution.
14
+ // v6/v7: rich-session-capture — per-call locAdded/locRemoved/editFailed from
15
+ // patch_apply_end. Sessions cached under v5 lack these fields; re-parse to add.
16
+ // v8: persist native MCP timing and compact invocation attribution.
17
+ // Deliberately NOT bumped for the resume fields (dev/ino + resumeOffset/
18
+ // resumeState): they are additive and absence-safe in both directions, so a
19
+ // bump would only throw away a warm multi-hundred-MB cache to gain nothing. An
20
+ // entry without them simply re-parses in full once and gains them.
21
+ // v9: parse large session_meta records structurally so nested provenance.model
22
+ // cannot overwrite the model selected by turn_context.
23
+ // v10: same depth-1 window for the rest of session_meta's raw string fields
24
+ // (cwd/name/originator/session_id/forked_from_id/model_provider).
25
+ // v11: codex pricing fix (#1075) - reasoning is no longer added on top of
26
+ // output, and cache_write_input_tokens is carved out of the input bucket. This
27
+ // file stores each call's costUSD and token buckets verbatim, so entries
28
+ // written by v10 carry the old (overstated) cost and must be re-derived.
29
+ // v13: codex throughput fix (#1079) - activeGeneratedTokens was summing
30
+ // output + reasoning, the same double-count Fix A removed from cost. This
31
+ // file stores activeGeneratedTokens/activeDurationMs/toolWaitMs verbatim (not
32
+ // re-derived on read), so v11 entries carry the overstated numerator and must
33
+ // re-parse. Not 12: v12 is claimed by feat/core-extraction's own port of this
34
+ // throughput feature (PR #1086), so reusing it would let two incompatible
35
+ // schemas share a filename.
36
+ // v14: MCP + Skill attribution for the shapes the classic `function_call` path
37
+ // never reached (#478) - the `exec` custom tool's `input` program and the item
38
+ // model's `item_completed`/`CommandExecution` item - plus SKILL.md reads landing
39
+ // in `skills`. This file stores each call's `tools`/`toolSequence`/`skills`
40
+ // verbatim (they are passed through on read, never re-derived), so v13 entries
41
+ // keep the old, MCP- and skill-less attribution until they re-parse.
42
+ // v15: builtin alias prices `codex-auto-review` (#1047). Exact-hit cache
43
+ // entries still hold the pre-alias $0; bump so unchanged rollouts reprice.
44
+ // Must be max(main v14 #1092, this)+1 — #1092 spent v14 on MCP/skills.
45
+ // No bump for #1264: the missing-cumulative branch is a no-op on real data
46
+ // (0 occurrences of info-without-total across 137k+ events; null-info pings
47
+ // already take the estimate path), so cached numbers are identical and a
48
+ // bump would only force a cold reparse.
49
+ // v17: fork replay suppression now ends at the first timestamp gap over one
50
+ // second, or five seconds past the fork regardless of gaps, so first real
51
+ // work is retained. Exact entries can hold the old undercount, and resume
52
+ // state used the old fixed cutoff; reparse both. Not 16: v16 was briefly
53
+ // shipped by a reverted PR, so reusing it would let stale entries pass the
54
+ // version check unreparsed.
55
+ // v18: read response-level token_usage_record and ignore later token_count
56
+ // twins. v17 entries miss interrupted/compaction usage and can include counts
57
+ // now suppressed after the source handover, so they must reparse.
58
+ // v19: codex priority-tier pricing (#1616) - turns run under Codex's Fast
59
+ // speed setting (thread_settings_applied service_tier "priority") now bill at
60
+ // the priority rates. This file stores each call's costUSD and speed verbatim,
61
+ // so v18 entries carry the standard-rate cost and must be re-derived.
62
+ // v20: `codex-auto-review` prices by date (gpt-5.4 before 30 Jul 2026, GPT-5.6
63
+ // Luna from then on) instead of gpt-5.5. Stored costUSD is the old price.
64
+ // v21: service_tier "flex" bills at the published Flex rates (it billed at
65
+ // standard), and `gpt-reserve` / `gpt-5.3-spark` price as GPT-5.6 Luna /
66
+ // GPT-5.3 Codex Spark instead of $0. Stored costUSD and speed are the old ones.
67
+ // v22: a fork's replay burst drops only records found in the parent rollout
68
+ // and counts the rest. v21 entries dropped the whole burst.
69
+ // v23: attribute the Responses built-in tools and item-model WebSearch records;
70
+ // v22 exact entries have no such tool activity, so they must reparse.
71
+ // v24: mcp-cli counts as an MCP call only in command position; v23 entries can
72
+ // hold fake mcp__ tools from commit messages, echoes and comments.
73
+ // v25: rollouts that name the thread only as payload.id key their calls on
74
+ // that UUID, so fork replays collide with them; v24 entries hold stem-keyed
75
+ // calls and double-counted fork replays. Same version: a turn-start
76
+ // rate-limit ping (null info, no output yet) is no longer an estimated call,
77
+ // a cumulative-only total that drops reads as a restart, not negative usage,
78
+ // a cumulative field the record omits counts as unchanged, not as zero, a
79
+ // restart zeroes every counter and starts a new key epoch, and measured usage
80
+ // replaces a ping estimate of the same turn.
81
+ export const CODEX_CACHE_VERSION = 25;
82
+ export const CODEX_LEGACY_CACHE_FILE = 'codex-results.json';
83
+ export function codexCacheFileName(version = CODEX_CACHE_VERSION) {
84
+ return `codex-results.v${version}.json`;
85
+ }
86
+ // Discovery only needs each rollout's project, so it reads this small index
87
+ // instead of the whole results file. Keyed by the same fingerprint, so an
88
+ // index that lags the results file only misses, never answers wrong.
89
+ export function codexProjectsFileName(version = CODEX_CACHE_VERSION) {
90
+ return `codex-projects.v${version}.json`;
91
+ }
92
+ const cacheDirContext = new AsyncLocalStorage();
93
+ function currentCacheDir() {
94
+ return cacheDirContext.getStore() ?? resolve(getCodeburnCacheDir());
95
+ }
96
+ // A parse can cross many async boundaries before the Codex provider publishes
97
+ // its incremental cache. Embedded hosts are allowed to change the process env
98
+ // between calls, so pin the call-time directory for the whole transaction
99
+ // instead of re-reading CODEBURN_CACHE_DIR at each cache operation.
100
+ export function withCodexCacheDirectory(cacheDir, operation) {
101
+ return cacheDirContext.run(resolve(cacheDir), operation);
102
+ }
103
+ function getCachePath(cacheDir) {
104
+ return join(cacheDir, codexCacheFileName());
105
+ }
106
+ function getLegacyCachePath(cacheDir) {
107
+ return join(cacheDir, CODEX_LEGACY_CACHE_FILE);
108
+ }
109
+ function isCurrentCache(cache) {
110
+ return cache.version === CODEX_CACHE_VERSION && !!cache.files && typeof cache.files === 'object';
111
+ }
112
+ // Embedded consumers can change CODEBURN_CACHE_DIR without reloading this
113
+ // module. Keep each directory's in-memory state separate so a warm cache (or an
114
+ // unflushed update) from A can never be read from or written into B.
115
+ const memCaches = new Map();
116
+ // Dropped by the resident RSS guard. Every write is published by
117
+ // flushCodexCache() in the parse's finally, so the next load re-reads disk.
118
+ export function clearCodexMemCaches() {
119
+ memCaches.clear();
120
+ inFlightLoads.clear();
121
+ projectIndexes.clear();
122
+ }
123
+ const projectIndexes = new Map();
124
+ function loadProjectIndex(cacheDir) {
125
+ let index = projectIndexes.get(cacheDir);
126
+ if (!index) {
127
+ index = readProjectIndex(cacheDir);
128
+ projectIndexes.set(cacheDir, index);
129
+ }
130
+ return index;
131
+ }
132
+ // Missing (a cache written before the index existed): built once from the
133
+ // results file, which is what discovery read before.
134
+ async function readProjectIndex(cacheDir) {
135
+ try {
136
+ const parsed = JSON.parse(await readFile(join(cacheDir, codexProjectsFileName()), 'utf-8'));
137
+ if (parsed.version === CODEX_CACHE_VERSION && parsed.files && typeof parsed.files === 'object')
138
+ return parsed.files;
139
+ }
140
+ catch { }
141
+ const cache = await loadCache(cacheDir);
142
+ if (Object.keys(cache.files).length > 0)
143
+ await writeProjectIndex(cacheDir, cache);
144
+ return cache.files;
145
+ }
146
+ async function writeProjectIndex(cacheDir, cache) {
147
+ const files = {};
148
+ for (const [path, e] of Object.entries(cache.files)) {
149
+ files[path] = { dev: e.dev, ino: e.ino, mtimeMs: e.mtimeMs, sizeBytes: e.sizeBytes, project: e.project };
150
+ }
151
+ try {
152
+ await writeFileAtomic(join(cacheDir, codexProjectsFileName()), JSON.stringify({ version: CODEX_CACHE_VERSION, files }));
153
+ }
154
+ catch { }
155
+ }
156
+ async function writeFileAtomic(finalPath, payload) {
157
+ const tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp`;
158
+ const handle = await open(tempPath, 'w', 0o600);
159
+ try {
160
+ await handle.writeFile(payload, { encoding: 'utf-8' });
161
+ await handle.sync();
162
+ }
163
+ finally {
164
+ await handle.close();
165
+ }
166
+ try {
167
+ await rename(tempPath, finalPath);
168
+ }
169
+ catch (err) {
170
+ try {
171
+ await unlink(tempPath);
172
+ }
173
+ catch { }
174
+ throw err;
175
+ }
176
+ }
177
+ // Concurrent callers must share one load. The memo below is only populated
178
+ // after the read + JSON.parse resolves, so without this every in-flight caller
179
+ // would re-read and re-parse the same (hundreds-of-MB) cache file.
180
+ const inFlightLoads = new Map();
181
+ function loadCache(cacheDir) {
182
+ const inMemory = memCaches.get(cacheDir);
183
+ if (inMemory)
184
+ return Promise.resolve(inMemory);
185
+ const pending = inFlightLoads.get(cacheDir);
186
+ if (pending)
187
+ return pending;
188
+ const load = loadCacheFromDisk(cacheDir).finally(() => inFlightLoads.delete(cacheDir));
189
+ inFlightLoads.set(cacheDir, load);
190
+ return load;
191
+ }
192
+ async function loadCacheFromDisk(cacheDir) {
193
+ const empty = { version: CODEX_CACHE_VERSION, files: {} };
194
+ const versioned = await readExistingTextFile(getCachePath(cacheDir));
195
+ if (versioned.status === 'ok') {
196
+ try {
197
+ const cache = JSON.parse(versioned.text);
198
+ if (isCurrentCache(cache)) {
199
+ memCaches.set(cacheDir, cache);
200
+ return cache;
201
+ }
202
+ }
203
+ catch { }
204
+ memCaches.set(cacheDir, empty);
205
+ return empty;
206
+ }
207
+ if (versioned.status === 'unreadable') {
208
+ memCaches.set(cacheDir, empty);
209
+ return empty;
210
+ }
211
+ // Versioned file is absent (ENOENT). Adopt the unsuffixed file only when its
212
+ // version matches — old binaries still own that path; we never write or delete it.
213
+ try {
214
+ const raw = await readFile(getLegacyCachePath(cacheDir), 'utf-8');
215
+ const cache = JSON.parse(raw);
216
+ if (isCurrentCache(cache)) {
217
+ memCaches.set(cacheDir, cache);
218
+ return cache;
219
+ }
220
+ }
221
+ catch { }
222
+ memCaches.set(cacheDir, empty);
223
+ return empty;
224
+ }
225
+ function getEntry(files, filePath, fp) {
226
+ if (!Object.hasOwn(files, filePath))
227
+ return null;
228
+ const entry = files[filePath];
229
+ if (entry
230
+ && entry.dev === fp.dev
231
+ && entry.ino === fp.ino
232
+ && entry.mtimeMs === fp.mtimeMs
233
+ && entry.sizeBytes === fp.sizeBytes) {
234
+ return entry;
235
+ }
236
+ return null;
237
+ }
238
+ // A grown file is only assumed to be an APPEND if the recorded boundary still
239
+ // falls right after a newline. A same-inode rewrite (truncate + refill, or an
240
+ // in-place edit) that happens to end up larger would otherwise resume into the
241
+ // middle of an unrelated line. Reading one byte is cheaper than being wrong.
242
+ async function endsLineAt(filePath, offset) {
243
+ if (offset === 0)
244
+ return true;
245
+ try {
246
+ const handle = await open(filePath, 'r');
247
+ try {
248
+ const buf = Buffer.alloc(1);
249
+ const { bytesRead } = await handle.read(buf, 0, 1, offset - 1);
250
+ return bytesRead === 1 && buf[0] === 0x0a;
251
+ }
252
+ finally {
253
+ await handle.close();
254
+ }
255
+ }
256
+ catch {
257
+ return false;
258
+ }
259
+ }
260
+ /// WSL's 9P share synthesizes dev/ino per mount, so they can differ run to run
261
+ /// for an unchanged file. Zero them for `\\wsl$\...` paths so the resume check
262
+ /// below still matches instead of re-reading every WSL rollout whole (#1059).
263
+ function fingerprintFromStat(filePath, s) {
264
+ if (isWslUncPath(filePath))
265
+ return { dev: 0, ino: 0, mtimeMs: s.mtimeMs, sizeBytes: s.size };
266
+ return { dev: s.dev, ino: s.ino, mtimeMs: s.mtimeMs, sizeBytes: s.size };
267
+ }
268
+ export async function readCachedCodexResults(filePath) {
269
+ try {
270
+ const s = await stat(filePath);
271
+ const cache = await loadCache(currentCacheDir());
272
+ const fp = fingerprintFromStat(filePath, s);
273
+ const entry = getEntry(cache.files, filePath, fp);
274
+ if (entry)
275
+ return { kind: 'exact', calls: entry.calls };
276
+ // Rollouts are append-only: the same inode, grown past a boundary we
277
+ // recorded, can be picked up from that boundary instead of re-read whole.
278
+ const stale = cache.files[filePath];
279
+ if (stale
280
+ && stale.dev === fp.dev
281
+ && stale.ino === fp.ino
282
+ && stale.resumeOffset !== undefined
283
+ && stale.resumeState !== undefined
284
+ && stale.resumeCallCount !== undefined
285
+ && fp.sizeBytes > stale.sizeBytes
286
+ && stale.resumeOffset <= fp.sizeBytes
287
+ && await endsLineAt(filePath, stale.resumeOffset)) {
288
+ return { kind: 'resume', calls: stale.calls, offset: stale.resumeOffset, state: stale.resumeState, callCount: stale.resumeCallCount };
289
+ }
290
+ }
291
+ catch { }
292
+ return null;
293
+ }
294
+ export async function getCachedCodexProject(filePath) {
295
+ try {
296
+ const s = await stat(filePath);
297
+ const cacheDir = currentCacheDir();
298
+ const files = memCaches.get(cacheDir)?.files ?? await loadProjectIndex(cacheDir);
299
+ const entry = getEntry(files, filePath, fingerprintFromStat(filePath, s));
300
+ return entry?.project ?? null;
301
+ }
302
+ catch { }
303
+ return null;
304
+ }
305
+ export async function fingerprintFile(filePath) {
306
+ try {
307
+ return fingerprintFromStat(filePath, await stat(filePath));
308
+ }
309
+ catch {
310
+ return null;
311
+ }
312
+ }
313
+ export async function writeCachedCodexResults(filePath, project, calls, fingerprint, resume) {
314
+ try {
315
+ const cache = await loadCache(currentCacheDir());
316
+ cache.files[filePath] = {
317
+ dev: fingerprint.dev,
318
+ ino: fingerprint.ino,
319
+ mtimeMs: fingerprint.mtimeMs,
320
+ sizeBytes: fingerprint.sizeBytes,
321
+ project,
322
+ calls,
323
+ ...(resume ? { resumeOffset: resume.offset, resumeState: resume.state, resumeCallCount: resume.callCount } : {}),
324
+ };
325
+ }
326
+ catch { }
327
+ }
328
+ /// Remove exact source paths after the session-cache reconciliation has proved
329
+ /// they were deleted under an active WSL home. The generic flush cannot make
330
+ /// that decision itself: statting an offline UNC share can hang, while treating
331
+ /// the resulting failure as deletion would lose a stopped distro's warm cache.
332
+ export async function evictCachedCodexResults(filePaths) {
333
+ try {
334
+ const cache = await loadCache(currentCacheDir());
335
+ let changed = false;
336
+ for (const filePath of filePaths) {
337
+ if (!Object.hasOwn(cache.files, filePath))
338
+ continue;
339
+ delete cache.files[filePath];
340
+ changed = true;
341
+ }
342
+ return changed;
343
+ }
344
+ catch {
345
+ return false;
346
+ }
347
+ }
348
+ export async function flushCodexCache() {
349
+ const cacheDir = currentCacheDir();
350
+ const memCache = memCaches.get(cacheDir);
351
+ if (!memCache)
352
+ return;
353
+ try {
354
+ // Evict entries for files that no longer exist on disk
355
+ const paths = Object.keys(memCache.files);
356
+ for (const p of paths) {
357
+ // A stopped WSL distro makes its UNC share unavailable. Probing it here
358
+ // can block for the OS/network timeout, and would evict the entry even
359
+ // though the source is still durable. WSL discovery owns availability;
360
+ // retain the entry until a later parse can observe the file again.
361
+ if (isWslUncPath(p))
362
+ continue;
363
+ try {
364
+ await stat(p);
365
+ }
366
+ catch {
367
+ delete memCache.files[p];
368
+ }
369
+ }
370
+ if (!existsSync(cacheDir))
371
+ await mkdir(cacheDir, { recursive: true });
372
+ await writeFileAtomic(getCachePath(cacheDir), JSON.stringify(memCache));
373
+ await writeProjectIndex(cacheDir, memCache);
374
+ projectIndexes.delete(cacheDir);
375
+ }
376
+ catch { }
377
+ }
@@ -0,0 +1,232 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { stat } from 'fs/promises';
3
+ import { basename, dirname } from 'path';
4
+ import { readSessionLines } from './fs-utils.js';
5
+ import { findRawObjectField, getRawJsonStringFieldAtObject } from './codex-jsonl-fields.js';
6
+ import { rolloutStem, walkRolloutFiles } from './launcher-homes.js';
7
+ /** Maximum timestamp gap between copied records in Codex's fork replay burst. */
8
+ export const CODEX_FORK_REPLAY_MAX_GAP_MS = 1000;
9
+ export function startCodexForkReplay(timestamp) {
10
+ if (!timestamp)
11
+ return undefined;
12
+ const startedAtMs = Date.parse(timestamp);
13
+ if (!Number.isFinite(startedAtMs))
14
+ return undefined;
15
+ return { startedAtMs, lastReplayAtMs: startedAtMs, active: true };
16
+ }
17
+ /**
18
+ * Codex rewrites fork history into a timestamp cluster near `session_meta`.
19
+ * A gap over one second ends that cluster, even when the first real turn lands
20
+ * within five seconds of the fork. Entries carrying original parent timestamps
21
+ * stay replay records as long as they precede the fork's metadata timestamp.
22
+ */
23
+ export function isCodexForkReplay(state, timestamp) {
24
+ if (!state?.active || !timestamp)
25
+ return false;
26
+ const timestampMs = Date.parse(timestamp);
27
+ if (!Number.isFinite(timestampMs))
28
+ return false;
29
+ // Some spawned sub-agent rollouts retain the parent's original timestamps.
30
+ if (timestampMs < state.startedAtMs)
31
+ return true;
32
+ // A burst that never sees a >1s gap (e.g. rapid tool-call chatter) must
33
+ // still end; five seconds past the fork is well outside any real replay.
34
+ if (timestampMs - state.startedAtMs > 5000) {
35
+ state.active = false;
36
+ return false;
37
+ }
38
+ // Keep a slightly out-of-order record in the burst without moving the
39
+ // boundary backwards; rollout records are usually ordered, but not required
40
+ // to be strictly monotonic.
41
+ if (timestampMs < state.lastReplayAtMs)
42
+ return true;
43
+ if (timestampMs - state.lastReplayAtMs > CODEX_FORK_REPLAY_MAX_GAP_MS) {
44
+ state.active = false;
45
+ return false;
46
+ }
47
+ state.lastReplayAtMs = timestampMs;
48
+ return true;
49
+ }
50
+ export function isCodexForkReplayState(value) {
51
+ if (!value || typeof value !== 'object')
52
+ return false;
53
+ const state = value;
54
+ return typeof state['startedAtMs'] === 'number'
55
+ && Number.isFinite(state['startedAtMs'])
56
+ && typeof state['lastReplayAtMs'] === 'number'
57
+ && Number.isFinite(state['lastReplayAtMs'])
58
+ && typeof state['active'] === 'boolean';
59
+ }
60
+ const usageCounters = (u) => u
61
+ ? [u.input_tokens ?? 0, u.cached_input_tokens ?? 0, u.cache_write_input_tokens ?? 0, u.output_tokens ?? 0, u.reasoning_output_tokens ?? 0, u.total_tokens ?? 0]
62
+ : null;
63
+ /** Identity of one token_count record, shared by a parent and the fork that copied it. */
64
+ export function codexReplayUsageIdentity(info) {
65
+ return JSON.stringify([usageCounters(info.total_token_usage), usageCounters(info.last_token_usage)]);
66
+ }
67
+ export const codexReplayResponseIdentity = (responseId) => `response:${responseId}`;
68
+ export const codexReplayNativeToolIdentity = (tool, itemId) => `native:${tool}:${itemId}`;
69
+ // Rollout names are `rollout-YYYY-MM-DDTHH-MM-SS-<id>.jsonl` (or `.jsonl.zst`).
70
+ const ROLLOUT_ID_OFFSET = 'rollout-YYYY-MM-DDTHH-MM-SS-'.length;
71
+ const rolloutIndexes = new Map();
72
+ function findRollout(home, id) {
73
+ let index = rolloutIndexes.get(home);
74
+ if (!index?.has(id)) {
75
+ index = new Map();
76
+ walkRolloutFiles(home, path => {
77
+ const id = rolloutStem(basename(path)).slice(ROLLOUT_ID_OFFSET);
78
+ // Plain wins over its .zst twin, as in discovery.
79
+ if (path.endsWith('.zst') && index.get(id)?.endsWith('.jsonl'))
80
+ return;
81
+ index.set(id, path);
82
+ });
83
+ if (!index.has(id))
84
+ index.set(id, null);
85
+ rolloutIndexes.set(home, index);
86
+ }
87
+ return index.get(id) ?? undefined;
88
+ }
89
+ function codexHomeOf(path) {
90
+ for (let dir = dirname(path); dir !== dirname(dir); dir = dirname(dir)) {
91
+ const name = basename(dir);
92
+ if (name === 'sessions' || name === 'archived_sessions')
93
+ return dirname(dir);
94
+ }
95
+ return undefined;
96
+ }
97
+ const parentReplayRecords = new Map();
98
+ function nativeToolForResponseType(type) {
99
+ if (type === 'web_search_call')
100
+ return 'WebSearch';
101
+ if (type === 'tool_search_call')
102
+ return 'ToolSearch';
103
+ if (type === 'image_generation_call')
104
+ return 'ImageGeneration';
105
+ return undefined;
106
+ }
107
+ function addBufferParentReplayRecord(records, source) {
108
+ const entryType = getRawJsonStringFieldAtObject(source, 0, 'type');
109
+ if (!entryType)
110
+ return;
111
+ const timestamp = getRawJsonStringFieldAtObject(source, 0, 'timestamp');
112
+ const at = timestamp ? Date.parse(timestamp) : NaN;
113
+ const payload = findRawObjectField(source, 0, 'payload');
114
+ if (!payload || source[payload.valueStart] !== 0x7b)
115
+ return;
116
+ const payloadStart = payload.valueStart;
117
+ const payloadType = getRawJsonStringFieldAtObject(source, payloadStart, 'type');
118
+ // Keep the original usage identity semantics exactly: historical counters
119
+ // still pass through JSON.parse, including when a large line is a Buffer.
120
+ if (entryType === 'token_usage_record' || (entryType === 'event_msg' && payloadType === 'token_count')) {
121
+ addParsedParentReplayRecord(records, source.toString('utf-8'));
122
+ return;
123
+ }
124
+ if (entryType === 'response_item') {
125
+ const tool = nativeToolForResponseType(payloadType);
126
+ if (!tool)
127
+ return;
128
+ const itemId = getRawJsonStringFieldAtObject(source, payloadStart, 'id')
129
+ ?? getRawJsonStringFieldAtObject(source, payloadStart, 'call_id');
130
+ if (itemId)
131
+ records.push([at, codexReplayNativeToolIdentity(tool, itemId)]);
132
+ return;
133
+ }
134
+ if (entryType !== 'event_msg' || payloadType !== 'item_completed')
135
+ return;
136
+ const item = findRawObjectField(source, payloadStart, 'item');
137
+ if (!item || source[item.valueStart] !== 0x7b)
138
+ return;
139
+ const itemType = getRawJsonStringFieldAtObject(source, item.valueStart, 'type');
140
+ const itemKind = getRawJsonStringFieldAtObject(source, item.valueStart, 'kind');
141
+ if (itemType !== 'WebSearch' && !(itemType === 'Extension' && itemKind === 'web.search'))
142
+ return;
143
+ const itemId = getRawJsonStringFieldAtObject(source, item.valueStart, 'id');
144
+ if (itemId)
145
+ records.push([at, codexReplayNativeToolIdentity('WebSearch', itemId)]);
146
+ }
147
+ function addParsedParentReplayRecord(records, line) {
148
+ let entry;
149
+ try {
150
+ entry = JSON.parse(line);
151
+ }
152
+ catch {
153
+ return;
154
+ }
155
+ const at = entry.timestamp ? Date.parse(entry.timestamp) : NaN;
156
+ if (entry.type === 'token_usage_record' && typeof entry.payload?.response_id === 'string') {
157
+ records.push([at, codexReplayResponseIdentity(entry.payload.response_id)]);
158
+ }
159
+ else if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload.info) {
160
+ records.push([at, codexReplayUsageIdentity(entry.payload.info)]);
161
+ }
162
+ else if (entry.type === 'response_item') {
163
+ const tool = nativeToolForResponseType(entry.payload?.type);
164
+ const itemId = typeof entry.payload?.id === 'string' && entry.payload.id
165
+ ? entry.payload.id
166
+ : typeof entry.payload?.call_id === 'string' && entry.payload.call_id
167
+ ? entry.payload.call_id
168
+ : undefined;
169
+ if (tool && itemId)
170
+ records.push([at, codexReplayNativeToolIdentity(tool, itemId)]);
171
+ }
172
+ else if (entry.type === 'event_msg' && entry.payload?.type === 'item_completed'
173
+ && (entry.payload.item?.type === 'WebSearch'
174
+ || (entry.payload.item?.type === 'Extension' && entry.payload.item.kind === 'web.search'))
175
+ && typeof entry.payload.item.id === 'string' && entry.payload.item.id) {
176
+ records.push([at, codexReplayNativeToolIdentity('WebSearch', entry.payload.item.id)]);
177
+ }
178
+ }
179
+ async function readParentReplayRecords(path) {
180
+ const records = [];
181
+ const skip = (head) => !head.includes('"token_count"')
182
+ && !head.includes('"token_usage_record"')
183
+ && !head.includes('"web_search_call"')
184
+ && !head.includes('"tool_search_call"')
185
+ && !head.includes('"image_generation_call"')
186
+ && !head.includes('"item_completed"');
187
+ for await (const line of readSessionLines(path, skip, { largeLineAsBuffer: true })) {
188
+ if (Buffer.isBuffer(line))
189
+ addBufferParentReplayRecord(records, line);
190
+ else
191
+ addParsedParentReplayRecord(records, line);
192
+ }
193
+ return records;
194
+ }
195
+ let parentReplayRequest = null;
196
+ /** A parse worker hands the lookup to the parent thread, so each parent is indexed and read once, not once per worker. */
197
+ export function routeCodexParentReplay(request) {
198
+ parentReplayRequest = request;
199
+ }
200
+ /**
201
+ * Usage and native item identities the parent rollout recorded up to the fork,
202
+ * read from the parent's raw file (its own copied history included, so a chain
203
+ * resolves one level at a time). A null result means the parent is not readable
204
+ * next to the fork; an empty native set means it was read and contains no items.
205
+ */
206
+ export async function loadCodexParentReplayIndex(forkPath, parentId, forkedAtMs) {
207
+ if (parentReplayRequest)
208
+ return parentReplayRequest(forkPath, parentId, forkedAtMs);
209
+ const home = codexHomeOf(forkPath);
210
+ const path = home ? findRollout(home, parentId) : undefined;
211
+ if (!path || path === forkPath)
212
+ return null;
213
+ let sig;
214
+ try {
215
+ const st = await stat(path);
216
+ sig = `${st.size}:${st.mtimeMs}`;
217
+ }
218
+ catch {
219
+ return null;
220
+ }
221
+ let cached = parentReplayRecords.get(path);
222
+ if (cached?.sig !== sig) {
223
+ cached = { sig, records: readParentReplayRecords(path) };
224
+ parentReplayRecords.set(path, cached);
225
+ }
226
+ // Records the parent wrote after the fork were never copied into it.
227
+ const records = (await cached.records).filter(([at]) => !(at > forkedAtMs));
228
+ return {
229
+ usageIdentities: new Set(records.map(([, id]) => id).filter(id => !id.startsWith('native:'))),
230
+ nativeIdentities: new Set(records.map(([, id]) => id).filter(id => id.startsWith('native:'))),
231
+ };
232
+ }