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,328 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import stripAnsi from '../shims/strip-ansi.js';
3
+ const FIFTEEN_MINUTES = 15;
4
+ const ONE_HOUR = 60;
5
+ const ONE_DAY = 24 * 60;
6
+ const MINUTE_MS = 60 * 1000;
7
+ const MAX_SERIES_PER_METRIC = 6;
8
+ // Keep metadata bounded for the legend and tooltip: 80 characters preserves a
9
+ // useful title without letting the parser's 200-char transcript cap dominate
10
+ // either UI surface.
11
+ const MAX_SESSION_TITLE_LENGTH = 80;
12
+ function nonNegative(value) {
13
+ return Number.isFinite(value) && value > 0 ? value : 0;
14
+ }
15
+ export function granularBucketMinutes(range) {
16
+ const durationMs = Math.max(0, range.end.getTime() - range.start.getTime());
17
+ if (durationMs <= 48 * ONE_HOUR * MINUTE_MS)
18
+ return FIFTEEN_MINUTES;
19
+ // Hourly beyond ~8 days means 200+ points of overlapping spikes; daily
20
+ // buckets keep month-scale charts readable.
21
+ if (durationMs <= 8 * ONE_DAY * MINUTE_MS)
22
+ return ONE_HOUR;
23
+ return ONE_DAY;
24
+ }
25
+ function bucketStart(date, bucketMinutes) {
26
+ if (bucketMinutes === ONE_DAY) {
27
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate());
28
+ }
29
+ // Floor against local wall-clock time so :00 means the user's hour even in
30
+ // half-hour timezones. Applying that timestamp's own offset also keeps the
31
+ // two repeated hours distinct across a daylight-saving fallback.
32
+ const intervalMs = bucketMinutes * MINUTE_MS;
33
+ const offsetMs = date.getTimezoneOffset() * MINUTE_MS;
34
+ const localEpoch = date.getTime() - offsetMs;
35
+ return new Date(Math.floor(localEpoch / intervalMs) * intervalMs + offsetMs);
36
+ }
37
+ function nextBucket(date, bucketMinutes) {
38
+ if (bucketMinutes === ONE_DAY) {
39
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
40
+ }
41
+ return new Date(date.getTime() + bucketMinutes * MINUTE_MS);
42
+ }
43
+ function add(map, key, cost, tokens) {
44
+ const total = map.get(key) ?? { cost: 0, tokens: 0 };
45
+ total.cost += cost;
46
+ total.tokens += tokens;
47
+ map.set(key, total);
48
+ }
49
+ function topSeriesKeys(totals) {
50
+ const selected = new Set();
51
+ const rows = [...totals.entries()];
52
+ for (const [key] of [...rows].sort((a, b) => b[1].cost - a[1].cost).slice(0, MAX_SERIES_PER_METRIC)) {
53
+ selected.add(key);
54
+ }
55
+ for (const [key] of [...rows].sort((a, b) => b[1].tokens - a[1].tokens).slice(0, MAX_SERIES_PER_METRIC)) {
56
+ selected.add(key);
57
+ }
58
+ return selected;
59
+ }
60
+ function shortSessionId(sessionId) {
61
+ const trimmed = sessionId.trim();
62
+ return trimmed.length > 12 ? `${trimmed.slice(0, 6)}…${trimmed.slice(-4)}` : trimmed || 'unknown';
63
+ }
64
+ function cleanSessionTitle(title) {
65
+ if (title === undefined)
66
+ return undefined;
67
+ // Match the control-character range used by the model-name sanitizer. ANSI
68
+ // sequences are removed first; remaining controls become spaces so transcript
69
+ // line breaks cannot join words before internal whitespace is collapsed.
70
+ const cleaned = stripAnsi(title)
71
+ .replace(/[\x00-\x1F\x7F-\x9F]/g, ' ')
72
+ .replace(/\s+/g, ' ')
73
+ .trim();
74
+ if (!cleaned)
75
+ return undefined;
76
+ return Array.from(cleaned).slice(0, MAX_SESSION_TITLE_LENGTH).join('').trimEnd() || undefined;
77
+ }
78
+ // SessionSummary.lastTimestamp is normally an ISO timestamp, but fixtures and
79
+ // older cache entries can be incomplete. Valid timestamps win over invalid
80
+ // ones; two invalid values are an exact tie and are resolved alphabetically by
81
+ // the caller.
82
+ function compareTimestamps(a, b) {
83
+ const aMs = Date.parse(a);
84
+ const bMs = Date.parse(b);
85
+ const aValid = Number.isFinite(aMs);
86
+ const bValid = Number.isFinite(bMs);
87
+ if (aValid && bValid)
88
+ return aMs - bMs;
89
+ if (aValid)
90
+ return 1;
91
+ if (bValid)
92
+ return -1;
93
+ return 0;
94
+ }
95
+ function preferredProjectName(projectNames) {
96
+ return [...projectNames].sort()[0] ?? 'Unknown project';
97
+ }
98
+ function preferredSessionTitle(titleCandidates) {
99
+ const cleaned = [...titleCandidates.values()]
100
+ .map(candidate => {
101
+ const title = cleanSessionTitle(candidate.title);
102
+ return title === undefined ? undefined : { title, lastTimestamp: candidate.lastTimestamp };
103
+ })
104
+ .filter((candidate) => candidate !== undefined);
105
+ cleaned.sort((a, b) => {
106
+ const timestampOrder = compareTimestamps(b.lastTimestamp, a.lastTimestamp);
107
+ if (timestampOrder !== 0)
108
+ return timestampOrder;
109
+ return a.title < b.title ? -1 : a.title > b.title ? 1 : 0;
110
+ });
111
+ return cleaned[0]?.title;
112
+ }
113
+ // Chart legend is `max-w-40` at 10px ≈ 24–32 glyphs. A title that is unique in
114
+ // that window can lead; otherwise the short id must stay in the prefix or
115
+ // truncated series look identical (the #997 class). Count code points, matching
116
+ // the title cap — a UTF-16 slice can split an emoji and collide two titles.
117
+ const VISIBLE_LEGEND_PREFIX = 24;
118
+ function visibleLegendPrefix(label) {
119
+ return Array.from(label).slice(0, VISIBLE_LEGEND_PREFIX).join('');
120
+ }
121
+ function buildSessionLabels(inputs) {
122
+ // Stable raw-key order makes the residual used-label guard independent of
123
+ // project/session discovery order when a title happens to match another
124
+ // label shape.
125
+ const draft = [...inputs.entries()].map(([key, info]) => {
126
+ const title = preferredSessionTitle(info.titleCandidates);
127
+ const project = shortProjectLabel(info.projectPath, preferredProjectName(info.projectNames));
128
+ const shortId = shortSessionId(info.sessionId);
129
+ const idFirst = title
130
+ ? `${shortId} (${info.provider}) · ${title}`
131
+ : `${shortId} (${info.provider}) · ${project}`;
132
+ const titleFirst = title ? `${title} (${info.provider})` : idFirst;
133
+ return { key, info, baseLabel: titleFirst, idFirst };
134
+ }).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
135
+ const titlePrefixCounts = new Map();
136
+ for (const entry of draft) {
137
+ const prefix = visibleLegendPrefix(entry.baseLabel);
138
+ titlePrefixCounts.set(prefix, (titlePrefixCounts.get(prefix) ?? 0) + 1);
139
+ }
140
+ const entries = draft.map(entry => {
141
+ const prefix = visibleLegendPrefix(entry.baseLabel);
142
+ const titleLeads = (titlePrefixCounts.get(prefix) ?? 0) === 1;
143
+ return { ...entry, baseLabel: titleLeads ? entry.baseLabel : entry.idFirst };
144
+ });
145
+ const byBaseLabel = new Map();
146
+ for (const entry of entries) {
147
+ const group = byBaseLabel.get(entry.baseLabel) ?? [];
148
+ group.push(entry);
149
+ byBaseLabel.set(entry.baseLabel, group);
150
+ }
151
+ const labels = new Map();
152
+ const usedLabels = new Set();
153
+ const setUniqueLabel = (entry, candidate) => {
154
+ let label = candidate;
155
+ if (usedLabels.has(label)) {
156
+ const identity = `${candidate} · ${entry.info.projectPath} · ${entry.info.sessionId}`;
157
+ label = identity;
158
+ let suffix = 2;
159
+ while (usedLabels.has(label))
160
+ label = `${identity} · ${suffix++}`;
161
+ }
162
+ labels.set(entry.key, label);
163
+ usedLabels.add(label);
164
+ };
165
+ for (const group of byBaseLabel.values()) {
166
+ if (group.length === 1) {
167
+ setUniqueLabel(group[0], group[0].baseLabel);
168
+ continue;
169
+ }
170
+ const projectLabels = group.map(entry => shortProjectLabel(entry.info.projectPath, preferredProjectName(entry.info.projectNames)));
171
+ if (new Set(projectLabels).size === group.length) {
172
+ for (let i = 0; i < group.length; i++) {
173
+ const entry = group[i];
174
+ setUniqueLabel(entry, `${entry.baseLabel} · ${projectLabels[i]}`);
175
+ }
176
+ continue;
177
+ }
178
+ // A short project label can still collide (for example two worktrees with
179
+ // the same final path segments). The full path + id is only used for this
180
+ // residual collision, and is unique because provider/path/id form the key.
181
+ for (const entry of group) {
182
+ setUniqueLabel(entry, `${entry.baseLabel} · ${entry.info.projectPath} · ${entry.info.sessionId}`);
183
+ }
184
+ }
185
+ return labels;
186
+ }
187
+ // Legend labels: the sanitized project dir ("-Users-name-Projects-app") is
188
+ // unreadable, so prefer the real projectPath's last two segments ("app/web").
189
+ // Fall back to the sanitized name when no usable path exists.
190
+ function shortProjectLabel(projectPath, fallback) {
191
+ const segments = projectPath.trim().replace(/\\/g, '/').replace(/\/+$/, '').split('/').filter(Boolean);
192
+ if (segments.length === 0)
193
+ return fallback;
194
+ return segments.slice(-2).join('/');
195
+ }
196
+ function projectSeries(rawBuckets, kind, totals, labels) {
197
+ const selected = topSeriesKeys(totals);
198
+ const prefix = kind === 'models' ? 'model' : 'session';
199
+ const publicIds = new Map();
200
+ const series = [];
201
+ let index = 0;
202
+ for (const rawKey of selected) {
203
+ const id = `${prefix}_${index++}`;
204
+ publicIds.set(rawKey, id);
205
+ series.push({ id, label: labels.get(rawKey) ?? rawKey });
206
+ }
207
+ let hasOther = false;
208
+ const otherId = `${prefix}_other`;
209
+ const values = rawBuckets.map(bucket => {
210
+ const rows = [];
211
+ let otherCost = 0;
212
+ let otherTokens = 0;
213
+ for (const [rawKey, value] of bucket[kind]) {
214
+ const id = publicIds.get(rawKey);
215
+ if (id) {
216
+ rows.push({ seriesId: id, cost: value.cost, tokens: value.tokens });
217
+ }
218
+ else {
219
+ otherCost += value.cost;
220
+ otherTokens += value.tokens;
221
+ }
222
+ }
223
+ if (otherCost > 0 || otherTokens > 0) {
224
+ hasOther = true;
225
+ rows.push({ seriesId: otherId, cost: otherCost, tokens: otherTokens });
226
+ }
227
+ return rows;
228
+ });
229
+ if (hasOther)
230
+ series.push({ id: otherId, label: 'Other' });
231
+ return { series, values };
232
+ }
233
+ /**
234
+ * Build a selected-period timeline from real call timestamps. The result is
235
+ * bounded to the top six cost series plus the top six token series for each
236
+ * breakdown; everything else is retained in an aggregate Other series.
237
+ */
238
+ export function buildGranularHistory(projects, range, now = new Date()) {
239
+ const bucketMinutes = granularBucketMinutes(range);
240
+ const effectiveEnd = range.end.getTime() < now.getTime() ? range.end : now;
241
+ if (range.start.getTime() > effectiveEnd.getTime()) {
242
+ return { bucketMinutes, modelSeries: [], sessionSeries: [], points: [] };
243
+ }
244
+ const rawBuckets = [];
245
+ const byTimestamp = new Map();
246
+ for (let cursor = bucketStart(range.start, bucketMinutes); cursor.getTime() <= effectiveEnd.getTime(); cursor = nextBucket(cursor, bucketMinutes)) {
247
+ const timestamp = cursor.toISOString();
248
+ const bucket = { timestamp, cost: 0, tokens: 0, models: new Map(), sessions: new Map() };
249
+ rawBuckets.push(bucket);
250
+ byTimestamp.set(timestamp, bucket);
251
+ }
252
+ const modelTotals = new Map();
253
+ const sessionTotals = new Map();
254
+ const modelLabels = new Map();
255
+ const sessionLabelInputs = new Map();
256
+ let callCount = 0;
257
+ for (const project of projects) {
258
+ for (const session of project.sessions) {
259
+ for (const turn of session.turns) {
260
+ for (const call of turn.assistantCalls) {
261
+ const timestamp = Date.parse(call.timestamp);
262
+ if (!Number.isFinite(timestamp) || timestamp < range.start.getTime() || timestamp > effectiveEnd.getTime())
263
+ continue;
264
+ const bucket = byTimestamp.get(bucketStart(new Date(timestamp), bucketMinutes).toISOString());
265
+ if (!bucket)
266
+ continue;
267
+ const cost = nonNegative(call.costUSD);
268
+ // Match the browser's existing Tokens view: fresh input + output.
269
+ // Cache and reasoning remain available in their dedicated metrics.
270
+ const tokens = nonNegative(call.usage.inputTokens) + nonNegative(call.usage.outputTokens);
271
+ const modelKey = call.model || 'unknown';
272
+ // Session ids are usually globally unique, but a few providers scope
273
+ // them to a workspace. Include the project path so two workspaces do
274
+ // not collapse into one line when they reuse the same local id.
275
+ const sessionKey = `${call.provider}\0${project.projectPath}\0${session.sessionId}`;
276
+ const projectName = session.project || project.project || 'Unknown project';
277
+ bucket.cost += cost;
278
+ bucket.tokens += tokens;
279
+ add(bucket.models, modelKey, cost, tokens);
280
+ add(bucket.sessions, sessionKey, cost, tokens);
281
+ add(modelTotals, modelKey, cost, tokens);
282
+ add(sessionTotals, sessionKey, cost, tokens);
283
+ modelLabels.set(modelKey, modelKey === '<synthetic>' ? 'Other model' : modelKey);
284
+ // Collect raw metadata first. Titles are cleaned once per distinct
285
+ // session-key candidate after all calls are aggregated, so a late
286
+ // cache title can win without putting sanitisation on the call path.
287
+ const labelInfo = sessionLabelInputs.get(sessionKey) ?? {
288
+ provider: call.provider,
289
+ projectPath: project.projectPath,
290
+ projectNames: new Set(),
291
+ sessionId: session.sessionId,
292
+ titleCandidates: new Map(),
293
+ };
294
+ labelInfo.projectNames.add(projectName);
295
+ if (session.title !== undefined) {
296
+ const existingTitle = labelInfo.titleCandidates.get(session.title);
297
+ if (!existingTitle || compareTimestamps(session.lastTimestamp, existingTitle.lastTimestamp) > 0) {
298
+ labelInfo.titleCandidates.set(session.title, {
299
+ title: session.title,
300
+ lastTimestamp: session.lastTimestamp,
301
+ });
302
+ }
303
+ }
304
+ sessionLabelInputs.set(sessionKey, labelInfo);
305
+ callCount++;
306
+ }
307
+ }
308
+ }
309
+ }
310
+ if (callCount === 0) {
311
+ return { bucketMinutes, modelSeries: [], sessionSeries: [], points: [] };
312
+ }
313
+ const sessionLabels = buildSessionLabels(sessionLabelInputs);
314
+ const modelProjection = projectSeries(rawBuckets, 'models', modelTotals, modelLabels);
315
+ const sessionProjection = projectSeries(rawBuckets, 'sessions', sessionTotals, sessionLabels);
316
+ return {
317
+ bucketMinutes,
318
+ modelSeries: modelProjection.series,
319
+ sessionSeries: sessionProjection.series,
320
+ points: rawBuckets.map((bucket, i) => ({
321
+ timestamp: bucket.timestamp,
322
+ cost: bucket.cost,
323
+ tokens: bucket.tokens,
324
+ models: modelProjection.values[i] ?? [],
325
+ sessions: sessionProjection.values[i] ?? [],
326
+ })),
327
+ };
328
+ }