chompyy 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +14 -1
  2. package/dist/advice.js +98 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/approvals.js +129 -0
  6. package/dist/appstate.js +73 -3
  7. package/dist/away.js +48 -5
  8. package/dist/blueprint.js +3 -7
  9. package/dist/board.js +1 -0
  10. package/dist/cli.js +343 -18
  11. package/dist/codexquota.js +106 -0
  12. package/dist/codexusage.js +10 -0
  13. package/dist/config.js +2 -0
  14. package/dist/context.js +30 -0
  15. package/dist/costs.js +41 -2
  16. package/dist/demon.js +20 -0
  17. package/dist/detect.js +38 -6
  18. package/dist/didwork.js +26 -0
  19. package/dist/label.js +33 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +72 -0
  22. package/dist/nudge.js +70 -24
  23. package/dist/pacing.js +16 -1
  24. package/dist/punchcard.js +39 -0
  25. package/dist/questions.js +71 -0
  26. package/dist/recap.js +74 -0
  27. package/dist/receipt.js +48 -0
  28. package/dist/recipe.js +79 -0
  29. package/dist/savings.js +111 -0
  30. package/dist/stamps.js +14 -0
  31. package/dist/suggest.js +15 -5
  32. package/dist/triggers.js +5 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6955 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/dist/wastechecks.js +233 -0
  162. package/package.json +1 -1
@@ -0,0 +1,358 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ /// "What is using the quota right now": sessions whose transcript was appended
3
+ /// inside a short liveness window, with the context each one is holding. Feeds
4
+ /// the optional `liveSessions` block of the menubar payload; the app renders
5
+ /// only what it finds here.
6
+ import { open, readdir, stat } from 'node:fs/promises';
7
+ import { basename, dirname, join } from 'node:path';
8
+ import { getClaudeConfigDirs, getDesktopSessionsDirs, claudeConfigSourceId, claudeDesktopSourceId } from './providers/claude.js';
9
+ import { kimicodeHomes, projectFromWorkDir, readState as readKimicodeState } from './providers/kimicode.js';
10
+ import { reportedContextWindow } from './context-tree.js';
11
+ import { modelRowKey } from './models.js';
12
+ export const LIVE_WINDOW_SECONDS = 600;
13
+ /// Only the tail of a live transcript is read, and it is scanned backwards only
14
+ /// as far as the last assistant turn. A long-running session's file reaches tens
15
+ /// of MB and this runs on every payload build; the fields we want (last model,
16
+ /// last usage, current branch) all sit at the end.
17
+ export const TAIL_BYTES = 256 * 1024;
18
+ /// Pure core: liveness and parent/sub-agent folding, newest first.
19
+ export function buildLiveSessions(inputs, nowMs, windowSeconds = LIVE_WINDOW_SECONDS) {
20
+ const windowMs = windowSeconds * 1000;
21
+ const isLive = (ms) => ms > 0 && nowMs - ms <= windowMs;
22
+ // A session working through a sub-agent leaves its own transcript untouched
23
+ // for as long as that agent runs, so its sub-agents count as its activity.
24
+ const activityOf = (input) => Math.max(input.lastActivityMs, ...input.subagentActivityMs);
25
+ const sessions = inputs
26
+ .filter(input => isLive(activityOf(input)))
27
+ .map(input => ({
28
+ id: input.id,
29
+ provider: input.provider,
30
+ ...(input.claudeConfigSourceId ? { claudeConfigSourceId: input.claudeConfigSourceId } : {}),
31
+ project: input.project,
32
+ branch: input.branch,
33
+ model: input.model,
34
+ contextTokens: input.contextTokens,
35
+ contextWindow: input.contextWindow,
36
+ startedAt: new Date(input.startedMs).toISOString(),
37
+ lastActivityAt: new Date(activityOf(input)).toISOString(),
38
+ idleSeconds: Math.max(0, Math.round((nowMs - activityOf(input)) / 1000)),
39
+ }))
40
+ .sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt));
41
+ return { windowSeconds, sessions };
42
+ }
43
+ async function readTail(filePath, maxBytes) {
44
+ const handle = await open(filePath, 'r');
45
+ try {
46
+ const { size } = await handle.stat();
47
+ const start = size > maxBytes ? size - maxBytes : 0;
48
+ const buffer = Buffer.alloc(size - start);
49
+ if (buffer.length === 0)
50
+ return '';
51
+ await handle.read(buffer, 0, buffer.length, start);
52
+ const text = buffer.toString('utf8');
53
+ // A mid-file start almost certainly lands inside a line; drop that fragment.
54
+ return start > 0 ? text.slice(text.indexOf('\n') + 1) : text;
55
+ }
56
+ finally {
57
+ await handle.close();
58
+ }
59
+ }
60
+ /// Tokens the next request would carry: everything the model reads back plus
61
+ /// what it just wrote. Mirrors the reported-context sum in context-tree.ts.
62
+ function contextOf(usage) {
63
+ return (usage.input_tokens ?? 0)
64
+ + (usage.cache_read_input_tokens ?? 0)
65
+ + (usage.cache_creation_input_tokens ?? 0)
66
+ + (usage.output_tokens ?? 0);
67
+ }
68
+ function assistantMessage(entry) {
69
+ const message = entry.message;
70
+ if (!message || typeof message !== 'object')
71
+ return null;
72
+ const candidate = message;
73
+ if (candidate.role !== 'assistant' || !candidate.usage)
74
+ return null;
75
+ return candidate;
76
+ }
77
+ /// Reads one live transcript tail and walks it backwards, stopping at the last
78
+ /// assistant turn. Never throws: an unreadable or unexpected file yields a bare
79
+ /// record rather than taking the payload down.
80
+ export async function scanTranscript(filePath) {
81
+ const result = {
82
+ sessionId: basename(filePath).replace(/\.jsonl$/, ''),
83
+ cwd: '',
84
+ isSidechain: false,
85
+ branch: null,
86
+ model: null,
87
+ contextTokens: null,
88
+ contextWindow: null,
89
+ };
90
+ let text = '';
91
+ try {
92
+ text = await readTail(filePath, TAIL_BYTES);
93
+ }
94
+ catch {
95
+ return result;
96
+ }
97
+ const lines = text.split('\n');
98
+ let needsIdentity = true;
99
+ let needsUsage = true;
100
+ // Backwards: the newest turn wins for every field, so the first hit going up
101
+ // is the answer and there is no reason to parse the rest of the tail.
102
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
103
+ if (!needsIdentity && !needsUsage)
104
+ break;
105
+ const line = lines[index];
106
+ if (!line || !line.trim())
107
+ continue;
108
+ let entry;
109
+ try {
110
+ entry = JSON.parse(line);
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ if (needsIdentity) {
116
+ if (typeof entry.sessionId === 'string' && entry.sessionId)
117
+ result.sessionId = entry.sessionId;
118
+ if (typeof entry.cwd === 'string' && entry.cwd)
119
+ result.cwd = entry.cwd;
120
+ if (entry.isSidechain === true)
121
+ result.isSidechain = true;
122
+ if (typeof entry.gitBranch === 'string' && entry.gitBranch)
123
+ result.branch = entry.gitBranch;
124
+ // cwd and branch travel together on every user/assistant entry, so one
125
+ // entry carrying them settles identity.
126
+ if (result.cwd && result.branch)
127
+ needsIdentity = false;
128
+ }
129
+ if (!needsUsage)
130
+ continue;
131
+ const assistant = assistantMessage(entry);
132
+ if (!assistant)
133
+ continue;
134
+ const context = contextOf(assistant.usage);
135
+ if (context <= 0)
136
+ continue;
137
+ result.contextTokens = context;
138
+ const rawModel = typeof assistant.model === 'string' ? assistant.model : '';
139
+ if (rawModel)
140
+ result.model = modelRowKey(rawModel);
141
+ // ponytail: the window comes from this one turn, so a session that compacted
142
+ // below 220k on a 1M model reads as 200k until its next big turn. Track a
143
+ // running max again if that misreport ever matters.
144
+ result.contextWindow = reportedContextWindow(rawModel, context);
145
+ needsUsage = false;
146
+ }
147
+ return result;
148
+ }
149
+ /// Claude nests sub-agent transcripts under their parent's own directory
150
+ /// (`<parent-session-id>/subagents/...`), so the parent file is that directory
151
+ /// plus `.jsonl`. Returns null for any other shape.
152
+ function parentTranscriptPath(sidechainPath) {
153
+ const marker = sidechainPath.lastIndexOf('/subagents/');
154
+ if (marker <= 0)
155
+ return null;
156
+ return `${sidechainPath.slice(0, marker)}.jsonl`;
157
+ }
158
+ /// Transcript roots, straight from the Claude config rather than through the
159
+ /// provider registry. `discoverAllSessions` walks every provider's tree and
160
+ /// costs about half a second on a large history; this block only ever reads
161
+ /// Claude transcripts, and it runs on every payload build. Each root carries
162
+ /// the config source id its transcripts belong to.
163
+ async function transcriptRoots() {
164
+ const configured = await getClaudeConfigDirs().catch(() => []);
165
+ return [
166
+ ...configured.map(dir => ({ root: join(dir, 'projects'), sourceId: claudeConfigSourceId(dir) })),
167
+ ...getDesktopSessionsDirs().map(dir => ({ root: dir, sourceId: claudeDesktopSourceId(dir) })),
168
+ ];
169
+ }
170
+ /// Every transcript touched inside the window. One recursive listing per root,
171
+ /// then a stat per file: nothing is opened until it is known to be live.
172
+ async function liveTranscripts(nowMs, windowMs) {
173
+ const paths = [];
174
+ for (const { root, sourceId } of await transcriptRoots()) {
175
+ const entries = await readdir(root, { recursive: true, withFileTypes: true }).catch(() => []);
176
+ for (const entry of entries) {
177
+ if (!entry.isFile() || !entry.name.endsWith('.jsonl'))
178
+ continue;
179
+ paths.push({ path: join(entry.parentPath, entry.name), sourceId });
180
+ }
181
+ }
182
+ const stats = await Promise.all(paths.map(async ({ path, sourceId }) => {
183
+ const info = await stat(path).catch(() => null);
184
+ if (!info?.isFile())
185
+ return null;
186
+ if (nowMs - info.mtimeMs > windowMs)
187
+ return null;
188
+ return { path, mtimeMs: info.mtimeMs, birthtimeMs: info.birthtimeMs || info.mtimeMs, sourceId };
189
+ }));
190
+ return stats.filter((entry) => entry !== null);
191
+ }
192
+ /// Walks the live transcripts and builds the pure-core inputs. Sidechain
193
+ /// (sub-agent) transcripts fold into their parent session: they keep it alive
194
+ /// while it waits on them.
195
+ export async function collectLiveSessionInputs(nowMs, windowSeconds) {
196
+ const windowMs = windowSeconds * 1000;
197
+ const inputs = new Map();
198
+ const pendingSidechains = [];
199
+ const toInput = (scan, times, fallbackProject) => ({
200
+ id: scan.sessionId,
201
+ provider: 'claude',
202
+ claudeConfigSourceId: times.sourceId,
203
+ project: scan.cwd ? basename(scan.cwd) : fallbackProject,
204
+ branch: scan.branch,
205
+ model: scan.model,
206
+ contextTokens: scan.contextTokens,
207
+ contextWindow: scan.contextWindow,
208
+ startedMs: times.birthtimeMs,
209
+ lastActivityMs: times.mtimeMs,
210
+ subagentActivityMs: [],
211
+ });
212
+ /// A parent whose own transcript is idle because its sub-agent is doing the
213
+ /// work. Its file is not live, so read it here to recover its details. The
214
+ /// parent lives in the same transcript tree as the sidechain, so it carries
215
+ /// the sidechain's config source id.
216
+ const loadIdleParent = async (sidechain) => {
217
+ const parentPath = parentTranscriptPath(sidechain.path);
218
+ if (!parentPath)
219
+ return null;
220
+ const info = await stat(parentPath).catch(() => null);
221
+ if (!info?.isFile())
222
+ return null;
223
+ const scan = await scanTranscript(parentPath);
224
+ return toInput(scan, { path: parentPath, mtimeMs: info.mtimeMs, birthtimeMs: info.birthtimeMs || info.mtimeMs, sourceId: sidechain.sourceId }, basename(parentPath).replace(/\.jsonl$/, ''));
225
+ };
226
+ for (const file of await liveTranscripts(nowMs, windowMs)) {
227
+ const scan = await scanTranscript(file.path);
228
+ if (scan.isSidechain) {
229
+ pendingSidechains.push({ sessionId: scan.sessionId, mtimeMs: file.mtimeMs, path: file.path, sourceId: file.sourceId });
230
+ continue;
231
+ }
232
+ inputs.set(scan.sessionId, toInput(scan, file, basename(file.path).replace(/\.jsonl$/, '')));
233
+ }
234
+ // Claude writes the PARENT session id into every sidechain line, so the scan's
235
+ // session id is the parent to attach to.
236
+ for (const sidechain of pendingSidechains) {
237
+ let parent = inputs.get(sidechain.sessionId);
238
+ if (!parent) {
239
+ const recovered = await loadIdleParent(sidechain);
240
+ if (!recovered)
241
+ continue;
242
+ parent = recovered;
243
+ inputs.set(parent.id, parent);
244
+ }
245
+ parent.subagentActivityMs.push(sidechain.mtimeMs);
246
+ }
247
+ return [...inputs.values(), ...await collectKimicodeInputs(nowMs, windowMs)];
248
+ }
249
+ /// What the tail of the main wire file says about the session: the model it
250
+ /// last asked for, the context Kimi itself measured after the last turn, and
251
+ /// the window it asked for. Tail-only, like the Claude scanner: a running wire
252
+ /// file reaches tens of MB and only the end matters.
253
+ async function kimicodeTail(wirePath) {
254
+ const out = { model: null, contextTokens: null, contextWindow: null };
255
+ let text = '';
256
+ try {
257
+ text = await readTail(wirePath, TAIL_BYTES);
258
+ }
259
+ catch {
260
+ return out;
261
+ }
262
+ const lines = text.split('\n');
263
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
264
+ const line = lines[index];
265
+ if (!line || !line.trim())
266
+ continue;
267
+ let record;
268
+ try {
269
+ record = JSON.parse(line);
270
+ }
271
+ catch {
272
+ continue;
273
+ }
274
+ if (record.type === 'llm.request' && out.model === null) {
275
+ if (typeof record.model === 'string' && record.model)
276
+ out.model = record.model;
277
+ if (typeof record.maxTokens === 'number' && record.maxTokens > 0)
278
+ out.contextWindow = record.maxTokens;
279
+ }
280
+ else if (record.type === 'token_counting.measured' && out.contextTokens === null) {
281
+ if (typeof record.tokens === 'number' && record.tokens >= 0)
282
+ out.contextTokens = record.tokens;
283
+ }
284
+ if (out.model !== null && out.contextTokens !== null)
285
+ break;
286
+ }
287
+ // A measurement without a window (or the reverse) draws nothing; the app
288
+ // needs both to size the ring.
289
+ if (out.contextTokens === null || out.contextWindow === null) {
290
+ out.contextTokens = null;
291
+ out.contextWindow = null;
292
+ }
293
+ return out;
294
+ }
295
+ /// Kimi Code keeps a directory per session, the session's own turns in
296
+ /// `agents/main/wire.jsonl` and every sub-agent in a sibling agent directory.
297
+ /// A missing or unreadable store is silent: no Kimi install means no rows.
298
+ export async function collectKimicodeInputs(nowMs, windowMs, roots = kimicodeHomes()) {
299
+ // Walked level by level rather than recursively: an agent directory also
300
+ // holds `blobs` and `file-history` trees, and descending into those turns a
301
+ // two-thousand-file scan into an eighteen-thousand-entry one.
302
+ const subdirectories = async (path) => (await readdir(path, { withFileTypes: true }).catch(() => []))
303
+ .filter(entry => entry.isDirectory())
304
+ .map(entry => join(path, entry.name));
305
+ const paths = [];
306
+ await Promise.all(roots.map(async (root) => {
307
+ await Promise.all((await subdirectories(join(root, 'sessions'))).map(async (workDir) => {
308
+ await Promise.all((await subdirectories(workDir)).map(async (sessionDir) => {
309
+ for (const agent of await subdirectories(join(sessionDir, 'agents'))) {
310
+ paths.push(join(agent, 'wire.jsonl'));
311
+ }
312
+ }));
313
+ }));
314
+ }));
315
+ const bySession = new Map();
316
+ await Promise.all(paths.map(async (path) => {
317
+ const info = await stat(path).catch(() => null);
318
+ if (!info?.isFile())
319
+ return;
320
+ const sessionDir = dirname(dirname(dirname(path)));
321
+ const agents = bySession.get(sessionDir) ?? { mainMs: 0, subagentMs: [] };
322
+ if (basename(dirname(path)) === 'main')
323
+ agents.mainMs = info.mtimeMs;
324
+ else if (nowMs - info.mtimeMs <= windowMs)
325
+ agents.subagentMs.push(info.mtimeMs);
326
+ bySession.set(sessionDir, agents);
327
+ }));
328
+ const inputs = [];
329
+ for (const [sessionDir, agents] of bySession) {
330
+ const mainIsLive = agents.mainMs > 0 && nowMs - agents.mainMs <= windowMs;
331
+ if (!mainIsLive && agents.subagentMs.length === 0)
332
+ continue;
333
+ const state = await readKimicodeState(sessionDir);
334
+ // `createdAt` is absent on stores that never wrote it; the state file itself
335
+ // is created with the session, so its birthtime is the same moment.
336
+ const birthtimeMs = state.createdAtMs
337
+ ? 0
338
+ : (await stat(join(sessionDir, 'state.json')).catch(() => null))?.birthtimeMs ?? 0;
339
+ const tail = await kimicodeTail(join(sessionDir, 'agents', 'main', 'wire.jsonl'));
340
+ inputs.push({
341
+ id: basename(sessionDir).replace(/^session_/, ''),
342
+ provider: 'kimicode',
343
+ project: projectFromWorkDir(state.cwd || state.workDir || '', basename(dirname(sessionDir))),
344
+ branch: null,
345
+ model: tail.model,
346
+ contextTokens: tail.contextTokens,
347
+ contextWindow: tail.contextWindow,
348
+ startedMs: state.createdAtMs || birthtimeMs,
349
+ lastActivityMs: agents.mainMs,
350
+ subagentActivityMs: agents.subagentMs,
351
+ });
352
+ }
353
+ return inputs;
354
+ }
355
+ export async function collectLiveSessions(nowMs = Date.now(), windowSeconds = LIVE_WINDOW_SECONDS) {
356
+ const inputs = await collectLiveSessionInputs(nowMs, windowSeconds);
357
+ return buildLiveSessions(inputs, nowMs, windowSeconds);
358
+ }
@@ -0,0 +1,8 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ export function maxOf(values, initial) {
3
+ let max = initial;
4
+ for (const value of values)
5
+ if (value > max)
6
+ max = value;
7
+ return max;
8
+ }
@@ -0,0 +1,294 @@
1
+ import { findingUSD } from './optimize.js';
2
+ import { getCurrency } from './currency.js';
3
+ import { modelRowKey } from './models.js';
4
+ import { sessionCacheHitPercent } from './sessions-report.js';
5
+ import { buildTelemetrySnapshot } from './telemetry-snapshot.js';
6
+ const TOP_ACTIVITIES_LIMIT = 20;
7
+ const TOP_FINDINGS_LIMIT = 10;
8
+ const HISTORY_DAYS_LIMIT = 365;
9
+ const SYNTHETIC_MODEL_NAME = '<synthetic>';
10
+ const TOP_PROJECTS_LIMIT = 5;
11
+ const TOP_SESSIONS_LIMIT = 3;
12
+ const MODEL_EFFICIENCY_LIMIT = 5;
13
+ const TOP_REWORKED_FILES_LIMIT = 8;
14
+ function oneShotRateFor(editTurns, oneShotTurns) {
15
+ if (editTurns === 0)
16
+ return null;
17
+ return oneShotTurns / editTurns;
18
+ }
19
+ function aggregateOneShotRate(categories) {
20
+ let edits = 0;
21
+ let oneShots = 0;
22
+ for (const cat of categories) {
23
+ edits += cat.editTurns;
24
+ oneShots += cat.oneShotTurns;
25
+ }
26
+ if (edits === 0)
27
+ return null;
28
+ return oneShots / edits;
29
+ }
30
+ function buildTopActivities(categories) {
31
+ return categories.slice(0, TOP_ACTIVITIES_LIMIT).map(cat => ({
32
+ name: cat.name,
33
+ cost: cat.cost,
34
+ savingsUSD: cat.savingsUSD,
35
+ turns: cat.turns,
36
+ oneShotRate: oneShotRateFor(cat.editTurns, cat.oneShotTurns),
37
+ ...(cat.rawCategory ? { rawCategory: cat.rawCategory } : {}),
38
+ }));
39
+ }
40
+ /// Per-model token counts merged alongside cost. A `undefined` accumulator is
41
+ /// "unknown", not zero: a legacy row that predates the counts must not turn the
42
+ /// merged row into a plausible-looking 0, so one unknown contributor marks the
43
+ /// merged count unknown and the field is omitted from the payload.
44
+ ///
45
+ /// KNOWN GAP: on the durable (daily-cache) path this guard cannot fire today.
46
+ /// `ModelDayStats` types the four counts as required numbers and daily-cache's
47
+ /// `sanitizeModels` runs every field through `num()`, which turns a missing
48
+ /// value into a known `0`. A day carried forward from a generation that
49
+ /// predates the counts therefore contributes an exact zero and the period row
50
+ /// under-reports as if it were complete, instead of going unknown here. Making
51
+ /// it reachable means widening `ModelDayStats` to optional counts and teaching
52
+ /// every daily-cache arithmetic site (fold, subtract, reduce) plus
53
+ /// `buildPeriodDataFromDays` to propagate absence — a durable-cache contract
54
+ /// change, tracked separately. The guard stays because the PeriodData contract
55
+ /// already types these counts optional: fresh-session and plugin-sourced rows
56
+ /// may legitimately omit them.
57
+ const MODEL_COUNT_KEYS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens'];
58
+ function mergeCount(target, key, value) {
59
+ // Once a contributor without this count has been seen, the merged count is
60
+ // unknown for good — later contributors must not resurrect a partial sum.
61
+ if (value === undefined) {
62
+ target.unknown.add(key);
63
+ delete target.counts[key];
64
+ return;
65
+ }
66
+ if (target.unknown.has(key))
67
+ return;
68
+ target.counts[key] = (target.counts[key] ?? 0) + value;
69
+ }
70
+ function buildTopModels(models) {
71
+ // Day entries key models by the raw provider id (day-aggregator), so resolve
72
+ // display names here — the menubar shows "Kimi K3" rather than "k3". Ids that
73
+ // collapse to one display name (e.g. k3 and kimi-k3) merge into a single row,
74
+ // and their token counts merge under the same grouping as cost.
75
+ //
76
+ // The list is uncapped (#1318): the desktop Overview renders it as the
77
+ // period's model table, where cutting at N would drop exactly the local and
78
+ // free models the table exists to expose. Every consumer that wants fewer
79
+ // rows already slices its own (the desktop hero takes 8, MCP tables take 5
80
+ // or the caller's limit) — rows are still cost-ranked, so "top" ordering
81
+ // survives without a count limit.
82
+ const merged = new Map();
83
+ for (const m of models) {
84
+ if (m.name === SYNTHETIC_MODEL_NAME)
85
+ continue;
86
+ const name = modelRowKey(m.name);
87
+ const acc = merged.get(name) ?? { cost: 0, calls: 0, savingsUSD: 0, estimatedCostUSD: 0, counts: {}, unknown: new Set() };
88
+ acc.cost += m.cost;
89
+ acc.calls += m.calls;
90
+ acc.savingsUSD += m.savingsUSD ?? 0;
91
+ acc.estimatedCostUSD += m.estimatedCostUSD ?? 0;
92
+ for (const key of MODEL_COUNT_KEYS)
93
+ mergeCount(acc, key, m[key]);
94
+ merged.set(name, acc);
95
+ }
96
+ return [...merged.entries()]
97
+ .sort(([, a], [, b]) => b.cost - a.cost)
98
+ .map(([name, d]) => ({
99
+ name,
100
+ cost: d.cost,
101
+ calls: d.calls,
102
+ savingsUSD: d.savingsUSD,
103
+ savingsBaselineModel: '',
104
+ estimatedCostUSD: d.estimatedCostUSD,
105
+ ...(d.counts.inputTokens === undefined ? {} : { inputTokens: d.counts.inputTokens }),
106
+ ...(d.counts.outputTokens === undefined ? {} : { outputTokens: d.counts.outputTokens }),
107
+ ...(d.counts.cacheReadTokens === undefined ? {} : { cacheReadTokens: d.counts.cacheReadTokens }),
108
+ ...(d.counts.cacheWriteTokens === undefined ? {} : { cacheWriteTokens: d.counts.cacheWriteTokens }),
109
+ }));
110
+ }
111
+ function buildOptimize(optimize) {
112
+ if (!optimize || optimize.findings.length === 0) {
113
+ return { findingCount: 0, savingsUSD: 0, topFindings: [] };
114
+ }
115
+ const { findings, costRate } = optimize;
116
+ const totalSavingsUSD = findings.reduce((s, f) => s + findingUSD(f, costRate), 0);
117
+ const topFindings = findings.slice(0, TOP_FINDINGS_LIMIT).map(f => ({
118
+ title: f.title,
119
+ impact: f.impact,
120
+ savingsUSD: findingUSD(f, costRate),
121
+ }));
122
+ return {
123
+ findingCount: findings.length,
124
+ savingsUSD: totalSavingsUSD,
125
+ topFindings,
126
+ };
127
+ }
128
+ function buildProviders(providers) {
129
+ const map = {};
130
+ for (const p of providers) {
131
+ if (p.cost < 0)
132
+ continue;
133
+ map[p.displayName.toLowerCase()] = p.cost;
134
+ }
135
+ return map;
136
+ }
137
+ function buildProviderDetails(providers) {
138
+ return providers
139
+ .filter(p => p.cost >= 0)
140
+ .map(p => ({
141
+ id: p.name,
142
+ label: p.displayName,
143
+ cost: p.cost,
144
+ calls: p.calls ?? 0,
145
+ hasUsage: p.hasUsage ?? (p.cost > 0 || (p.calls ?? 0) > 0),
146
+ ...(p.excludedFromTotal ? { excludedFromTotal: true } : {}),
147
+ ...(p.inputTokens === undefined ? {} : { inputTokens: p.inputTokens }),
148
+ ...(p.outputTokens === undefined ? {} : { outputTokens: p.outputTokens }),
149
+ ...(p.sessions === undefined ? {} : { sessions: p.sessions }),
150
+ ...(p.sessionCountBasis ? { sessionCountBasis: p.sessionCountBasis } : {}),
151
+ ...(p.cacheReadTokens === undefined || p.cacheReadIncomplete ? {} : { cacheReadTokens: p.cacheReadTokens }),
152
+ ...(p.estimatedCostUSD ? { estimatedCostUSD: p.estimatedCostUSD } : {}),
153
+ }));
154
+ }
155
+ function buildHistory(daily, timeline) {
156
+ if (!daily || daily.length === 0)
157
+ return { daily: [], ...(timeline ? { timeline } : {}) };
158
+ const sorted = [...daily].sort((a, b) => a.date.localeCompare(b.date));
159
+ const trimmed = sorted.slice(-HISTORY_DAYS_LIMIT);
160
+ return { daily: trimmed, ...(timeline ? { timeline } : {}) };
161
+ }
162
+ function buildTopProjects(projects) {
163
+ return (projects ?? [])
164
+ .filter(p => p.cost > 0 || p.savingsUSD > 0)
165
+ .sort((a, b) => (b.cost + b.savingsUSD) - (a.cost + a.savingsUSD))
166
+ .slice(0, TOP_PROJECTS_LIMIT)
167
+ .map(p => ({
168
+ ...(p.id ? { id: p.id } : {}),
169
+ name: p.name,
170
+ cost: p.cost,
171
+ savingsUSD: p.savingsUSD,
172
+ sessions: p.sessions,
173
+ avgCostPerSession: p.sessions > 0 ? p.cost / p.sessions : 0,
174
+ ...(p.sessionCountBasis ? { sessionCountBasis: p.sessionCountBasis } : {}),
175
+ ...(p.checkouts ? { checkouts: p.checkouts, checkoutCount: p.checkoutCount } : {}),
176
+ ...(p.temporary ? { temporary: true } : {}),
177
+ sessionDetails: (p.sessionDetails ?? []).map(s => ({
178
+ cost: s.cost,
179
+ savingsUSD: s.savingsUSD,
180
+ calls: s.calls,
181
+ inputTokens: s.inputTokens,
182
+ outputTokens: s.outputTokens,
183
+ date: s.date,
184
+ models: s.models,
185
+ // Drill-through identity (additive, optional): lets the desktop open the
186
+ // exact session (provider + id), not just a lookalike row.
187
+ ...(s.sessionId ? { sessionId: s.sessionId } : {}),
188
+ ...(s.provider ? { provider: s.provider } : {}),
189
+ })),
190
+ }));
191
+ }
192
+ function buildModelEfficiency(models) {
193
+ return (models ?? [])
194
+ .filter(m => m.costPerEdit !== null)
195
+ .sort((a, b) => (a.costPerEdit ?? Infinity) - (b.costPerEdit ?? Infinity))
196
+ .slice(0, MODEL_EFFICIENCY_LIMIT)
197
+ .map(m => ({ name: m.name, costPerEdit: m.costPerEdit, oneShotRate: m.oneShotRate }));
198
+ }
199
+ function buildWorkflow(workflow) {
200
+ return {
201
+ corrections: workflow?.corrections ?? 0,
202
+ correctionRate: workflow?.correctionRate ?? null,
203
+ medianTimeToFirstEditMs: workflow?.medianTimeToFirstEditMs ?? null,
204
+ };
205
+ }
206
+ function buildTopReworkedFiles(files) {
207
+ return (files ?? [])
208
+ .slice(0, TOP_REWORKED_FILES_LIMIT)
209
+ // Basename only: the menubar/web payload can leave the machine, so drop the
210
+ // directory path and keep just the file name.
211
+ .map(f => ({ path: f.path.split('/').pop() || f.path, sessions: f.sessions, edits: f.edits }));
212
+ }
213
+ function buildTopSessions(sessions) {
214
+ return (sessions ?? [])
215
+ .sort((a, b) => (b.cost + b.savingsUSD) - (a.cost + a.savingsUSD))
216
+ .slice(0, TOP_SESSIONS_LIMIT)
217
+ .map(s => ({
218
+ project: s.project,
219
+ cost: s.cost,
220
+ savingsUSD: s.savingsUSD,
221
+ calls: s.calls,
222
+ date: s.date,
223
+ // Drill-through identity (additive, optional): provider + session id make
224
+ // the row openable even when another provider reuses the same id or title.
225
+ ...(s.sessionId ? { sessionId: s.sessionId } : {}),
226
+ ...(s.provider ? { provider: s.provider } : {}),
227
+ ...(s.projectKey ? { projectKey: s.projectKey } : {}),
228
+ }));
229
+ }
230
+ export function buildMenubarPayload(current, providers, optimize, dailyHistory, retryTax, routingWaste, breakdowns, claudeConfigs, granularHistory, stale, hydration) {
231
+ const payload = {
232
+ generated: new Date().toISOString(),
233
+ current: {
234
+ label: current.label,
235
+ cost: current.cost,
236
+ calls: current.calls,
237
+ sessions: current.sessions,
238
+ ...(current.sessionCountBasis ? { sessionCountBasis: current.sessionCountBasis } : {}),
239
+ oneShotRate: aggregateOneShotRate(current.categories),
240
+ inputTokens: current.inputTokens,
241
+ outputTokens: current.outputTokens,
242
+ cacheReadTokens: current.cacheReadTokens,
243
+ cacheWriteTokens: current.cacheWriteTokens,
244
+ cacheHitPercent: sessionCacheHitPercent(current.inputTokens, current.cacheReadTokens, current.cacheWriteTokens) ?? 0,
245
+ codexCredits: current.codexCredits ?? 0,
246
+ estimatedCostUSD: current.estimatedCostUSD ?? 0,
247
+ ...(current.costBasis ? { costBasis: current.costBasis } : {}),
248
+ topActivities: buildTopActivities(current.categories),
249
+ topModels: buildTopModels(current.models),
250
+ unpricedModels: current.unpricedModels ?? [],
251
+ localModelSavings: breakdowns?.localModelSavings ?? { totalUSD: 0, calls: 0, byModel: [], byProvider: [] },
252
+ providers: buildProviders(providers),
253
+ providerDetails: buildProviderDetails(providers),
254
+ topProjects: buildTopProjects(current.projects ?? []),
255
+ modelEfficiency: buildModelEfficiency(current.modelEfficiency ?? []),
256
+ topSessions: buildTopSessions(current.topSessions ?? []),
257
+ workflow: buildWorkflow(current.workflow),
258
+ topReworkedFiles: buildTopReworkedFiles(current.topReworkedFiles),
259
+ pricingCoverage: current.pricingCoverage ?? null,
260
+ retryTax: retryTax ?? { totalUSD: 0, retries: 0, editTurns: 0, byModel: [] },
261
+ routingWaste: routingWaste ?? { totalSavingsUSD: 0, baselineModel: '', baselineCostPerEdit: 0, byModel: [] },
262
+ tools: breakdowns?.tools ?? [],
263
+ skills: breakdowns?.skills ?? [],
264
+ subagents: breakdowns?.subagents ?? [],
265
+ mcpServers: breakdowns?.mcpServers ?? [],
266
+ // Add-only: emitted only when the producer computed them (all-provider
267
+ // path), omitted otherwise so the schema stays stable for consumers that
268
+ // predate the fields.
269
+ ...(current.pullRequests ? { pullRequests: current.pullRequests } : {}),
270
+ ...(current.byBranch ? { byBranch: current.byBranch } : {}),
271
+ ...(current.identities ? { identities: current.identities } : {}),
272
+ },
273
+ optimize: buildOptimize(optimize),
274
+ history: buildHistory(dailyHistory, granularHistory),
275
+ currency: (() => {
276
+ const c = getCurrency();
277
+ return { code: c.code, symbol: c.symbol, rate: c.rate };
278
+ })(),
279
+ telemetrySnapshot: null,
280
+ };
281
+ // Derived from the payload that was just assembled, so the snapshot can never
282
+ // report something the payload does not already say.
283
+ payload.telemetrySnapshot = buildTelemetrySnapshot(payload, breakdowns?.telemetry);
284
+ if (claudeConfigs && claudeConfigs.options.length > 1) {
285
+ payload.claudeConfigs = claudeConfigs;
286
+ }
287
+ if (stale) {
288
+ payload.stale = true;
289
+ }
290
+ if (hydration) {
291
+ payload.hydration = hydration;
292
+ }
293
+ return payload;
294
+ }