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,575 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { join } from 'path';
3
+ import { homedir } from 'os';
4
+ import { extractBashCommands } from '../bash-utils.js';
5
+ import { calculateCost, getShortModelName, ownValue } from '../models.js';
6
+ import { blobToText, getSqliteLoadError, isBlockedDatabaseError, isSqliteAvailable, isSqliteBusyError, openDatabase } from '../sqlite.js';
7
+ import { estimateTokensFromChars } from '../token-estimate.js';
8
+ import { isPermissionError, safeNumber } from '../parser.js';
9
+ const WARP_GROUP_CONTAINER = '2BBY89MBSN.dev.warp';
10
+ const WARP_STABLE_BUNDLE_ID = 'dev.warp.Warp-Stable';
11
+ const WARP_PREVIEW_BUNDLE_ID = 'dev.warp.Warp-Preview';
12
+ const PRIMARY_AGENT_CATEGORY = 'primary_agent';
13
+ // Warp bills agent usage in credits, not tokens. Warp's published pricing sets
14
+ // the base rate at 1,500 credits for $20 (the Build/Business monthly allotment,
15
+ // described on warp.dev/pricing as "$20 of included agent usage at API rates"),
16
+ // i.e. $0.013333 per credit. Warp's authoritative per-account rate lives
17
+ // server-side in `payg_cost_per_thousand_credits_cents` / `AddonCreditsOption`
18
+ // (github.com/warpdotdev/warp, crates/graphql/src/api/billing.rs) and is NOT
19
+ // shipped as a client constant, so the published allotment rate is the best
20
+ // public evidence available.
21
+ // ponytail: fixed public rate; the real per-account PAYG rate varies with
22
+ // volume discounts. CONFIRM against Warp's current published pricing.
23
+ const CREDIT_USD_RATE = 20 / 1500; // $0.013333 per credit ($13.33 / 1000 credits)
24
+ const modelAliases = {
25
+ 'Claude Sonnet 4.6': 'claude-sonnet-4-6',
26
+ 'Claude Sonnet 4.5': 'claude-sonnet-4-5',
27
+ 'Claude Haiku 4.5': 'claude-haiku-4-5',
28
+ 'Claude Opus 4.6': 'claude-opus-4-6',
29
+ 'GPT-5.3 Codex (low reasoning)': 'gpt-5.3-codex',
30
+ 'GPT-5.3 Codex (medium reasoning)': 'gpt-5.3-codex',
31
+ 'GPT-5.3 Codex (high reasoning)': 'gpt-5.3-codex',
32
+ 'GPT-5.3 Codex (extra high reasoning)': 'gpt-5.3-codex',
33
+ 'auto-efficient': 'warp-auto-efficient',
34
+ 'auto-powerful': 'warp-auto-powerful',
35
+ };
36
+ const RUNNING_EXCHANGE_TIMEOUT_MS = 24 * 60 * 60 * 1000;
37
+ function sanitizeProject(path) {
38
+ return path.replace(/^\/+/, '').replace(/\//g, '-');
39
+ }
40
+ function warpDbPath(bundleId) {
41
+ return join(homedir(), 'Library', 'Group Containers', WARP_GROUP_CONTAINER, 'Library', 'Application Support', bundleId, 'warp.sqlite');
42
+ }
43
+ // Linux and Windows locations from Warp's file-locations docs; Linux Preview
44
+ // appends -preview to the warp-terminal directory.
45
+ export function getDbCandidates(dbPathOverride, platform = process.platform) {
46
+ if (dbPathOverride)
47
+ return [dbPathOverride];
48
+ if (process.env['WARP_DB_PATH'])
49
+ return [process.env['WARP_DB_PATH']];
50
+ if (platform === 'win32') {
51
+ const localAppData = process.env['LOCALAPPDATA'] || join(homedir(), 'AppData', 'Local');
52
+ return [join(localAppData, 'warp', 'Warp', 'data', 'warp.sqlite')];
53
+ }
54
+ if (platform === 'linux') {
55
+ const stateHome = process.env['XDG_STATE_HOME'] || join(homedir(), '.local', 'state');
56
+ return [join(stateHome, 'warp-terminal', 'warp.sqlite'), join(stateHome, 'warp-terminal-preview', 'warp.sqlite')];
57
+ }
58
+ if (platform === 'darwin')
59
+ return [warpDbPath(WARP_STABLE_BUNDLE_ID), warpDbPath(WARP_PREVIEW_BUNDLE_ID)];
60
+ return [];
61
+ }
62
+ function normalizeModel(rawModel) {
63
+ const model = rawModel.trim();
64
+ if (!model)
65
+ return model;
66
+ return ownValue(modelAliases, model) ?? model;
67
+ }
68
+ function modelDisplayName(model) {
69
+ if (model === 'warp-auto-efficient')
70
+ return 'Warp Auto (efficient)';
71
+ if (model === 'warp-auto-powerful')
72
+ return 'Warp Auto (powerful)';
73
+ return getShortModelName(model);
74
+ }
75
+ function parseTimestamp(raw) {
76
+ if (!raw)
77
+ return null;
78
+ const trimmed = raw.trim();
79
+ if (!trimmed)
80
+ return null;
81
+ const withT = trimmed.includes('T') ? trimmed : trimmed.replace(' ', 'T');
82
+ const lastPlus = withT.lastIndexOf('+');
83
+ const lastMinus = withT.lastIndexOf('-');
84
+ const hasOffset = lastPlus > 9 || lastMinus > 9;
85
+ const hasTimezone = withT.endsWith('Z') || hasOffset;
86
+ const normalized = hasTimezone ? withT : `${withT}Z`;
87
+ const ms = Date.parse(normalized);
88
+ return Number.isNaN(ms) ? null : ms;
89
+ }
90
+ function parseJsonString(raw) {
91
+ try {
92
+ const parsed = JSON.parse(raw);
93
+ return typeof parsed === 'string' ? parsed : raw;
94
+ }
95
+ catch {
96
+ return raw;
97
+ }
98
+ }
99
+ function isFinalStatus(rawStatus) {
100
+ const status = parseJsonString(rawStatus);
101
+ return status === 'Completed' || status === 'Cancelled' || status === 'Failed';
102
+ }
103
+ function extractCategoryTokens(categories, key) {
104
+ if (!categories)
105
+ return 0;
106
+ return safeNumber(categories[key]);
107
+ }
108
+ function extractTokenBudget(rawConversationData) {
109
+ let conversationData;
110
+ try {
111
+ conversationData = JSON.parse(rawConversationData);
112
+ }
113
+ catch {
114
+ return { tokenBudget: 0, dominantModel: '' };
115
+ }
116
+ const entries = conversationData.conversation_usage_metadata?.token_usage ?? [];
117
+ let primaryTotal = 0;
118
+ let fallbackTotal = 0;
119
+ let dominantPrimaryTokens = 0;
120
+ let dominantFallbackTokens = 0;
121
+ let dominantModel = '';
122
+ for (const entry of entries) {
123
+ const primaryTokens = extractCategoryTokens(entry.warp_token_usage_by_category, PRIMARY_AGENT_CATEGORY) +
124
+ extractCategoryTokens(entry.byok_token_usage_by_category, PRIMARY_AGENT_CATEGORY);
125
+ const entryTotal = safeNumber(entry.warp_tokens) + safeNumber(entry.byok_tokens);
126
+ primaryTotal += primaryTokens;
127
+ fallbackTotal += entryTotal;
128
+ if (primaryTokens > dominantPrimaryTokens) {
129
+ dominantPrimaryTokens = primaryTokens;
130
+ dominantModel = typeof entry.model_id === 'string' ? entry.model_id : dominantModel;
131
+ }
132
+ if (dominantPrimaryTokens === 0 && entryTotal > dominantFallbackTokens) {
133
+ dominantFallbackTokens = entryTotal;
134
+ dominantModel = typeof entry.model_id === 'string' ? entry.model_id : dominantModel;
135
+ }
136
+ }
137
+ const tokenBudget = primaryTotal > 0 ? primaryTotal : fallbackTotal;
138
+ return { tokenBudget: Math.max(0, Math.round(tokenBudget)), dominantModel: normalizeModel(dominantModel) };
139
+ }
140
+ // Warp records what it actually charged in the same blob as the token counts.
141
+ // Prefer those real dollars over the token-floor estimate. Ladder, most to
142
+ // least authoritative:
143
+ // (a) total_provider_cost_in_cents — server-authoritative USD (exact)
144
+ // (b) sum of total_charged_usage — server per-category USD (exact)
145
+ // (c) total_billed_cost_in_cents — server billed snapshot USD (exact)
146
+ // (d) credits_spent × CREDIT_USD_RATE — credits at published rate (heuristic)
147
+ // (e) null → caller falls back to the token × LiteLLM estimate (floor)
148
+ // A value of 0/absent at a rung is treated as "not recorded here" and defers to
149
+ // the next rung, so a zero never masks a real cost recorded elsewhere.
150
+ function conversationCostUsd(rawConversationData) {
151
+ let meta;
152
+ try {
153
+ meta = JSON.parse(rawConversationData).conversation_usage_metadata;
154
+ }
155
+ catch {
156
+ return null;
157
+ }
158
+ if (!meta)
159
+ return null;
160
+ const providerCents = safeNumber(meta.total_provider_cost_in_cents);
161
+ if (providerCents > 0)
162
+ return { usd: providerCents / 100, estimated: false, rung: 'a' };
163
+ const charged = meta.total_charged_usage;
164
+ if (charged) {
165
+ const cents = safeNumber(charged.input_cost_in_cents) +
166
+ safeNumber(charged.output_cost_in_cents) +
167
+ safeNumber(charged.input_cache_read_cost_in_cents) +
168
+ safeNumber(charged.input_cache_write_cost_in_cents) +
169
+ safeNumber(charged.platform_cost_in_cents) +
170
+ safeNumber(charged.web_search_cost_in_cents);
171
+ if (cents > 0)
172
+ return { usd: cents / 100, estimated: false, rung: 'b' };
173
+ }
174
+ const billedCents = safeNumber(meta.total_billed_cost_in_cents);
175
+ if (billedCents > 0)
176
+ return { usd: billedCents / 100, estimated: false, rung: 'c' };
177
+ const credits = safeNumber(meta.credits_spent);
178
+ if (credits > 0)
179
+ return { usd: credits * CREDIT_USD_RATE, estimated: true, rung: 'd' };
180
+ return null;
181
+ }
182
+ // Split a conversation-level USD total across exchanges by the same char-based
183
+ // weights used to split tokens, so per-exchange cost tracks per-exchange size.
184
+ function allocateCost(weights, totalUsd) {
185
+ if (weights.length === 0)
186
+ return [];
187
+ if (!(totalUsd > 0))
188
+ return weights.map(() => 0);
189
+ const normalized = weights.map(w => Math.max(0, w));
190
+ const totalWeight = normalized.reduce((sum, w) => sum + w, 0);
191
+ if (totalWeight === 0)
192
+ return normalized.map(() => totalUsd / normalized.length);
193
+ return normalized.map(w => (totalUsd * w) / totalWeight);
194
+ }
195
+ // Warp records usage per conversation, not per exchange, so every parse
196
+ // re-splits the running total over all finished exchanges, and a later
197
+ // exchange's spend would move onto earlier days. Exchanges the previous parse
198
+ // cached keep their share; only the growth since then is split, over the new
199
+ // exchanges (or added to the latest one when there is none). A total that
200
+ // shrank, a removed exchange, or a cost that changed rung falls back to the
201
+ // fresh split. The total also grows while an exchange runs, so a running
202
+ // exchange takes its share of the growth and that share is held back until it
203
+ // finishes, instead of landing on the finished exchange before it. A running
204
+ // exchange whose row is pruned was never cached, so its time is gone with it;
205
+ // its held share stays in the conversation total and lands on the latest
206
+ // remaining exchange, like any growth with no new exchange.
207
+ export function keepCachedWarpShares(prior, parsed) {
208
+ const calls = parsed.filter(c => !c.inProgress);
209
+ const running = parsed.filter(c => c.inProgress);
210
+ if (!prior)
211
+ return calls;
212
+ const cached = new Map(prior.turns.flatMap(t => t.calls).map(c => [c.deduplicationKey, c]));
213
+ const current = new Set(calls.map(c => c.deduplicationKey));
214
+ // An exchange the cache held is gone: the old shares no longer add up to
215
+ // anything Warp reports, so split the current total fresh.
216
+ if ([...cached.keys()].some(key => !current.has(key)))
217
+ return calls;
218
+ const kept = calls.filter(c => cached.has(c.deduplicationKey));
219
+ if (kept.length === 0)
220
+ return calls;
221
+ const billed = calls[0].costFromBilling === true;
222
+ if (billed && kept.some(c => {
223
+ const prev = cached.get(c.deduplicationKey);
224
+ // A cache written before the rung was stored has none: it re-splits once.
225
+ return prev.costUSD === undefined || prev.costRung !== c.costRung;
226
+ }))
227
+ return calls;
228
+ const sum = (values) => values.reduce((a, b) => a + b, 0);
229
+ const keptTokens = sum(kept.map(c => cached.get(c.deduplicationKey).usage.inputTokens));
230
+ const keptCost = billed ? sum(kept.map(c => cached.get(c.deduplicationKey).costUSD)) : 0;
231
+ const deltaTokens = sum(calls.map(c => c.inputTokens)) - keptTokens;
232
+ const deltaCost = billed ? sum(calls.map(c => c.costUSD)) - keptCost : 0;
233
+ if (deltaTokens < 0 || deltaCost < -1e-9)
234
+ return calls;
235
+ const fresh = calls.filter(c => !cached.has(c.deduplicationKey));
236
+ const targets = fresh.length + running.length > 0 ? [...fresh, ...running] : [calls[calls.length - 1]];
237
+ const tokenShares = allocateTokens(targets.map(c => c.inputTokens), deltaTokens);
238
+ const costShares = allocateCost(targets.map(c => c.costUSD), Math.max(0, deltaCost));
239
+ return calls.map(call => {
240
+ const prev = cached.get(call.deduplicationKey);
241
+ const t = targets.indexOf(call);
242
+ const inputTokens = (prev?.usage.inputTokens ?? 0) + (t >= 0 ? tokenShares[t] : 0);
243
+ const costUSD = billed
244
+ ? (prev?.costUSD ?? 0) + (t >= 0 ? costShares[t] : 0)
245
+ : calculateCost(call.model, inputTokens, 0, 0, 0, 0);
246
+ return { ...call, inputTokens, costUSD };
247
+ });
248
+ }
249
+ function extractUserMessage(rawInput) {
250
+ try {
251
+ const parsed = JSON.parse(rawInput);
252
+ if (!Array.isArray(parsed))
253
+ return '';
254
+ for (const item of parsed) {
255
+ if (!item || typeof item !== 'object')
256
+ continue;
257
+ const query = item.Query;
258
+ if (!query || typeof query !== 'object')
259
+ continue;
260
+ if (typeof query.text === 'string' && query.text.trim())
261
+ return query.text;
262
+ }
263
+ return '';
264
+ }
265
+ catch {
266
+ return '';
267
+ }
268
+ }
269
+ function estimateWeight(rawInput) {
270
+ const userMessage = extractUserMessage(rawInput);
271
+ const source = userMessage || rawInput;
272
+ const tokens = estimateTokensFromChars(source.length);
273
+ return Math.max(1, tokens);
274
+ }
275
+ function allocateTokens(weights, tokenBudget) {
276
+ if (weights.length === 0)
277
+ return [];
278
+ const normalizedWeights = weights.map(w => Math.max(0, Math.round(w)));
279
+ const totalWeight = normalizedWeights.reduce((sum, weight) => sum + weight, 0);
280
+ const budget = Math.max(0, Math.round(tokenBudget));
281
+ if (budget === 0)
282
+ return normalizedWeights.map(() => 0);
283
+ if (totalWeight === 0) {
284
+ const even = Math.floor(budget / normalizedWeights.length);
285
+ const allocated = normalizedWeights.map(() => even);
286
+ let remainder = budget - even * normalizedWeights.length;
287
+ let index = 0;
288
+ while (remainder > 0) {
289
+ allocated[index] = (allocated[index] ?? 0) + 1;
290
+ remainder--;
291
+ index = (index + 1) % normalizedWeights.length;
292
+ }
293
+ return allocated;
294
+ }
295
+ const rawAllocation = normalizedWeights.map(weight => (budget * weight) / totalWeight);
296
+ const allocated = rawAllocation.map(value => Math.floor(value));
297
+ let remainder = budget - allocated.reduce((sum, value) => sum + value, 0);
298
+ const byLargestFraction = rawAllocation
299
+ .map((value, index) => ({ index, fraction: value - Math.floor(value) }))
300
+ .sort((a, b) => b.fraction - a.fraction);
301
+ let pointer = 0;
302
+ while (remainder > 0 && byLargestFraction.length > 0) {
303
+ const index = byLargestFraction[pointer].index;
304
+ allocated[index] = (allocated[index] ?? 0) + 1;
305
+ remainder--;
306
+ pointer = (pointer + 1) % byLargestFraction.length;
307
+ }
308
+ return allocated;
309
+ }
310
+ function resolveModelForExchange(exchange, dominantModel) {
311
+ const candidate = exchange.model_id.trim() ||
312
+ exchange.coding_model_id.trim() ||
313
+ exchange.planning_model_id.trim() ||
314
+ dominantModel ||
315
+ 'warp-auto-efficient';
316
+ const normalized = normalizeModel(candidate);
317
+ if ((normalized === 'warp-auto-efficient' || normalized === 'warp-auto-powerful') && dominantModel) {
318
+ return dominantModel;
319
+ }
320
+ return normalized;
321
+ }
322
+ function assignCommandBlocksToExchanges(blocks, exchanges) {
323
+ const toolsByExchange = new Map();
324
+ function getOrCreate(exchangeId) {
325
+ const existing = toolsByExchange.get(exchangeId);
326
+ if (existing)
327
+ return existing;
328
+ const created = { tools: [], bashCommands: [] };
329
+ toolsByExchange.set(exchangeId, created);
330
+ return created;
331
+ }
332
+ for (const block of blocks) {
333
+ const blockStartMs = parseTimestamp(block.start_ts);
334
+ if (blockStartMs === null)
335
+ continue;
336
+ let targetExchange = null;
337
+ for (const exchange of exchanges) {
338
+ if (exchange.startMs > blockStartMs)
339
+ break;
340
+ targetExchange = exchange;
341
+ }
342
+ if (!targetExchange)
343
+ continue;
344
+ const info = getOrCreate(targetExchange.exchange_id);
345
+ if (!info.tools.includes('Bash'))
346
+ info.tools.push('Bash');
347
+ const commandText = blobToText(block.stylized_command);
348
+ for (const command of extractBashCommands(commandText)) {
349
+ if (!info.bashCommands.includes(command))
350
+ info.bashCommands.push(command);
351
+ }
352
+ }
353
+ return toolsByExchange;
354
+ }
355
+ function decodeSourcePath(path) {
356
+ const splitIndex = path.lastIndexOf(':');
357
+ if (splitIndex <= 0)
358
+ return { dbPath: path, conversationId: '' };
359
+ return {
360
+ dbPath: path.slice(0, splitIndex),
361
+ conversationId: path.slice(splitIndex + 1),
362
+ };
363
+ }
364
+ function validateSchema(db) {
365
+ try {
366
+ db.query('SELECT COUNT(*) as cnt FROM agent_conversations LIMIT 1');
367
+ db.query('SELECT COUNT(*) as cnt FROM ai_queries LIMIT 1');
368
+ db.query('SELECT COUNT(*) as cnt FROM blocks LIMIT 1');
369
+ return true;
370
+ }
371
+ catch {
372
+ return false;
373
+ }
374
+ }
375
+ function createParser(source, seenKeys) {
376
+ return {
377
+ async *parse() {
378
+ if (!isSqliteAvailable()) {
379
+ process.stderr.write(getSqliteLoadError() + '\n');
380
+ return;
381
+ }
382
+ const { dbPath, conversationId } = decodeSourcePath(source.path);
383
+ if (!conversationId)
384
+ return;
385
+ let db;
386
+ try {
387
+ db = openDatabase(dbPath);
388
+ }
389
+ catch (err) {
390
+ // A busy/locked hit on Warp's continuously-written DB must reach the
391
+ // caller, not read as an empty session that seals the period.
392
+ if (isSqliteBusyError(err))
393
+ throw err;
394
+ process.stderr.write(`codeburn: cannot open Warp database: ${err instanceof Error ? err.message : err}\n`);
395
+ return;
396
+ }
397
+ try {
398
+ if (!validateSchema(db))
399
+ return;
400
+ const conversations = db.query(`SELECT conversation_id, conversation_data, last_modified_at
401
+ FROM agent_conversations
402
+ WHERE conversation_id = ?
403
+ LIMIT 1`, [conversationId]);
404
+ if (conversations.length === 0)
405
+ return;
406
+ const exchanges = db.query(`SELECT exchange_id, conversation_id, start_ts, input, working_directory, output_status, model_id, planning_model_id, coding_model_id
407
+ FROM ai_queries
408
+ WHERE conversation_id = ?
409
+ ORDER BY start_ts ASC`, [conversationId]);
410
+ // Warp writes the conversation as a running exchange streams. A day
411
+ // with no write means the app quit or crashed mid-exchange and left its
412
+ // status unfinished for good, so the exchange is released as finished
413
+ // instead of holding its share back forever.
414
+ const modifiedMs = parseTimestamp(conversations[0].last_modified_at);
415
+ const abandoned = modifiedMs !== null && Date.now() - modifiedMs > RUNNING_EXCHANGE_TIMEOUT_MS;
416
+ const parsedExchanges = [];
417
+ for (const [index, exchange] of exchanges.entries()) {
418
+ const unfinished = !isFinalStatus(exchange.output_status);
419
+ // Only the newest exchange can still be running; an older unfinished
420
+ // one was abandoned and stays out, as before.
421
+ if (unfinished && index !== exchanges.length - 1)
422
+ continue;
423
+ const running = unfinished && !abandoned;
424
+ const startMs = parseTimestamp(exchange.start_ts);
425
+ if (startMs === null)
426
+ continue;
427
+ parsedExchanges.push({ ...exchange, startMs, running });
428
+ }
429
+ if (!parsedExchanges.some(exchange => !exchange.running))
430
+ return;
431
+ const blocks = db.query(`SELECT block_id, start_ts, CAST(stylized_command AS BLOB) AS stylized_command
432
+ FROM blocks
433
+ WHERE ai_metadata IS NOT NULL
434
+ AND ai_metadata <> ''
435
+ AND json_extract(ai_metadata, '$.conversation_id') = ?
436
+ ORDER BY start_ts ASC`, [conversationId]);
437
+ const { tokenBudget, dominantModel } = extractTokenBudget(conversations[0].conversation_data);
438
+ const weights = parsedExchanges.map(exchange => estimateWeight(exchange.input));
439
+ const fallbackBudget = weights.reduce((sum, weight) => sum + weight, 0);
440
+ const allocatedTokens = allocateTokens(weights, tokenBudget > 0 ? tokenBudget : fallbackBudget);
441
+ const conversationCost = conversationCostUsd(conversations[0].conversation_data);
442
+ const allocatedCosts = conversationCost ? allocateCost(weights, conversationCost.usd) : null;
443
+ const toolsByExchange = assignCommandBlocksToExchanges(blocks, parsedExchanges);
444
+ for (let index = 0; index < parsedExchanges.length; index++) {
445
+ const exchange = parsedExchanges[index];
446
+ const deduplicationKey = `warp:${conversationId}:${exchange.exchange_id}`;
447
+ if (seenKeys.has(deduplicationKey))
448
+ continue;
449
+ const timestamp = new Date(exchange.startMs).toISOString();
450
+ const model = resolveModelForExchange(exchange, dominantModel);
451
+ const inputTokens = allocatedTokens[index] ?? 0;
452
+ const exchangeTools = toolsByExchange.get(exchange.exchange_id) ?? { tools: [], bashCommands: [] };
453
+ const userMessage = extractUserMessage(exchange.input).slice(0, 500);
454
+ const projectPath = exchange.working_directory?.trim() || undefined;
455
+ const project = projectPath ? sanitizeProject(projectPath) : source.project;
456
+ if (!exchange.running)
457
+ seenKeys.add(deduplicationKey);
458
+ yield {
459
+ provider: 'warp',
460
+ model,
461
+ inputTokens,
462
+ // Warp exposes only conversation-level usage totals in these tables,
463
+ // so we cannot reliably split per-exchange input vs output tokens.
464
+ outputTokens: 0,
465
+ cacheCreationInputTokens: 0,
466
+ cacheReadInputTokens: 0,
467
+ cachedInputTokens: 0,
468
+ reasoningTokens: 0,
469
+ webSearchRequests: 0,
470
+ costUSD: allocatedCosts ? (allocatedCosts[index] ?? 0) : calculateCost(model, inputTokens, 0, 0, 0, 0),
471
+ costIsEstimated: conversationCost ? conversationCost.estimated : true,
472
+ // Rungs (a)-(d) are Warp's own billing record; keep them through
473
+ // the cache. Rung (e) is the token floor, which stays re-priceable.
474
+ ...(conversationCost ? { costFromBilling: true, costRung: conversationCost.rung } : {}),
475
+ ...(exchange.running ? { inProgress: true } : {}),
476
+ tools: exchangeTools.tools,
477
+ bashCommands: exchangeTools.bashCommands,
478
+ timestamp,
479
+ speed: 'standard',
480
+ deduplicationKey,
481
+ userMessage,
482
+ sessionId: conversationId,
483
+ project,
484
+ projectPath,
485
+ };
486
+ }
487
+ }
488
+ finally {
489
+ db.close();
490
+ }
491
+ },
492
+ };
493
+ }
494
+ async function discoverFromDb(dbPath) {
495
+ let db;
496
+ try {
497
+ db = openDatabase(dbPath);
498
+ }
499
+ catch (err) {
500
+ // A blocked, busy, or permission-denied database means "unknown", not "no
501
+ // sessions": let it reach the registry so the run is marked degraded
502
+ // instead of silently empty. A plain EACCES/EPERM (e.g. a WARP_DB_PATH
503
+ // override the OS won't let us read) is recoverable once access is granted.
504
+ if (isBlockedDatabaseError(err) || isSqliteBusyError(err) || isPermissionError(err))
505
+ throw err;
506
+ return [];
507
+ }
508
+ try {
509
+ if (!validateSchema(db))
510
+ return [];
511
+ const rows = db.query(`SELECT c.conversation_id AS conversation_id,
512
+ (
513
+ SELECT q.working_directory
514
+ FROM ai_queries q
515
+ WHERE q.conversation_id = c.conversation_id
516
+ AND q.working_directory IS NOT NULL
517
+ AND q.working_directory <> ''
518
+ ORDER BY q.start_ts DESC
519
+ LIMIT 1
520
+ ) AS working_directory
521
+ FROM agent_conversations c
522
+ WHERE EXISTS (
523
+ SELECT 1 FROM ai_queries q
524
+ WHERE q.conversation_id = c.conversation_id
525
+ )
526
+ ORDER BY c.last_modified_at DESC`);
527
+ return rows.map(row => {
528
+ const projectPath = row.working_directory?.trim() ?? '';
529
+ return {
530
+ path: `${dbPath}:${row.conversation_id}`,
531
+ project: projectPath ? sanitizeProject(projectPath) : 'warp',
532
+ provider: 'warp',
533
+ };
534
+ });
535
+ }
536
+ catch (err) {
537
+ // Warp writes this DB constantly, so a SQLITE_BUSY/LOCKED here is the likely
538
+ // spot: escalate rather than seal an empty discovery.
539
+ if (isSqliteBusyError(err))
540
+ throw err;
541
+ return [];
542
+ }
543
+ finally {
544
+ db.close();
545
+ }
546
+ }
547
+ export function createWarpProvider(dbPathOverride) {
548
+ return {
549
+ name: 'warp',
550
+ displayName: 'Warp',
551
+ modelDisplayName(model) {
552
+ return modelDisplayName(model);
553
+ },
554
+ toolDisplayName(rawTool) {
555
+ return rawTool === 'run_command' ? 'Bash' : rawTool;
556
+ },
557
+ async probeRoots() {
558
+ return getDbCandidates(dbPathOverride).map(path => ({ path, label: 'db' }));
559
+ },
560
+ async discoverSessions() {
561
+ if (!isSqliteAvailable())
562
+ return [];
563
+ const sessions = [];
564
+ for (const candidate of getDbCandidates(dbPathOverride)) {
565
+ const found = await discoverFromDb(candidate);
566
+ sessions.push(...found);
567
+ }
568
+ return sessions;
569
+ },
570
+ createSessionParser(source, seenKeys) {
571
+ return createParser(source, seenKeys);
572
+ },
573
+ };
574
+ }
575
+ export const warp = createWarpProvider();