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,118 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { billableOutputTokens, calculateCost, ownValue, recordedCostFallback, routeFromProviderField } from '../models.js';
3
+ import { extractBashCommands } from '../bash-utils.js';
4
+ const toolNameMap = {
5
+ bash: 'Bash',
6
+ read: 'Read',
7
+ edit: 'Edit',
8
+ write: 'Write',
9
+ glob: 'Glob',
10
+ grep: 'Grep',
11
+ task: 'Agent',
12
+ fetch: 'WebFetch',
13
+ search: 'WebSearch',
14
+ todo: 'TodoWrite',
15
+ skill: 'Skill',
16
+ patch: 'Patch',
17
+ };
18
+ export function normalizeToolName(rawTool) {
19
+ if (!rawTool)
20
+ return '';
21
+ if (rawTool.startsWith('mcp__'))
22
+ return rawTool;
23
+ const builtIn = ownValue(toolNameMap, rawTool);
24
+ if (builtIn)
25
+ return builtIn;
26
+ const serverSeparator = rawTool.indexOf('_');
27
+ if (serverSeparator > 0 && serverSeparator < rawTool.length - 1) {
28
+ const server = rawTool.slice(0, serverSeparator);
29
+ const tool = rawTool.slice(serverSeparator + 1);
30
+ return `mcp__${server}__${tool}`;
31
+ }
32
+ return rawTool;
33
+ }
34
+ export function sanitize(dir) {
35
+ return dir.replace(/^\//, '').replace(/\//g, '-');
36
+ }
37
+ export function parseTimestamp(raw) {
38
+ const ms = raw < 1e12 ? raw * 1000 : raw;
39
+ return new Date(ms).toISOString();
40
+ }
41
+ // Build a ParsedProviderCall from one assistant message and its parts. Returns
42
+ // null when the message has no tokens, no cost, and no substantive parts (an
43
+ // empty or errored turn worth skipping). Shared by the SQLite and file-based
44
+ // OpenCode parsers so both attribute tokens, tools, and cost identically.
45
+ export function buildAssistantCall(opts) {
46
+ const { data, parts } = opts;
47
+ const tokens = {
48
+ input: data.tokens?.input ?? data.usage?.input_tokens ?? 0,
49
+ output: data.tokens?.output ?? data.usage?.output_tokens ?? 0,
50
+ reasoning: data.tokens?.reasoning ?? 0,
51
+ cacheRead: data.tokens?.cache?.read ?? data.usage?.cache_read_input_tokens ?? 0,
52
+ cacheWrite: data.tokens?.cache?.write ?? data.usage?.cache_creation_input_tokens ?? 0,
53
+ };
54
+ const toolParts = parts.filter((p) => (p.type === 'tool' || p.type === 'tool-call' || p.type === 'tool_call') && normalizeToolName(p.tool));
55
+ const hasTextOutput = parts.some((p) => p.type === 'text' && typeof p.text === 'string' && p.text.trim().length > 0);
56
+ const hasToolOrTextParts = hasTextOutput || toolParts.length > 0;
57
+ const hasAnySubstantiveParts = parts.some((p) => p.type === 'text' || p.type === 'tool' || p.type === 'tool-call' || p.type === 'tool_call' ||
58
+ p.type === 'tool-result' || p.type === 'tool_result' || p.type === 'reasoning' || p.type === 'file');
59
+ const hasActivity = hasToolOrTextParts || hasAnySubstantiveParts;
60
+ const allZero = tokens.input === 0 &&
61
+ tokens.output === 0 &&
62
+ tokens.reasoning === 0 &&
63
+ tokens.cacheRead === 0 &&
64
+ tokens.cacheWrite === 0;
65
+ if (allZero && (data.cost ?? 0) === 0 && !hasActivity)
66
+ return null;
67
+ const tools = toolParts
68
+ .map((p) => normalizeToolName(p.tool))
69
+ .filter(Boolean);
70
+ const bashCommands = toolParts
71
+ .filter((p) => p.tool === 'bash' && typeof p.state?.input?.command === 'string')
72
+ .flatMap((p) => extractBashCommands(p.state.input.command));
73
+ // The skill/subagent name lives in the tool-call input, not the tool name, so
74
+ // the Skills & Agents breakdown needs these extracted alongside the tool list.
75
+ const skills = toolParts
76
+ .filter((p) => p.tool === 'skill' && typeof p.state?.input?.name === 'string')
77
+ .map((p) => p.state.input.name)
78
+ .filter(Boolean);
79
+ const subagentTypes = toolParts
80
+ .filter((p) => p.tool === 'task' && typeof p.state?.input?.subagent_type === 'string')
81
+ .map((p) => p.state.input.subagent_type)
82
+ .filter(Boolean);
83
+ const model = data.modelID ?? data.model ?? 'unknown';
84
+ const route = routeFromProviderField(data.providerID)?.id;
85
+ let costUSD = calculateCost(model, tokens.input,
86
+ // Same single source of truth the cache-rehydration path uses, so a fresh
87
+ // parse and a cached read can never disagree about whether this provider's
88
+ // reasoning tokens already sit inside its output count. (#1075, #1334)
89
+ billableOutputTokens(opts.providerName, tokens.output, tokens.reasoning), tokens.cacheWrite, tokens.cacheRead, 0);
90
+ const fallbackCostUSD = recordedCostFallback(model, costUSD, data.cost);
91
+ if (fallbackCostUSD)
92
+ costUSD = fallbackCostUSD;
93
+ return {
94
+ provider: opts.providerName,
95
+ model,
96
+ ...(route ? { route } : {}),
97
+ inputTokens: tokens.input,
98
+ outputTokens: tokens.output,
99
+ cacheCreationInputTokens: tokens.cacheWrite,
100
+ cacheReadInputTokens: tokens.cacheRead,
101
+ cachedInputTokens: tokens.cacheRead,
102
+ reasoningTokens: tokens.reasoning,
103
+ webSearchRequests: 0,
104
+ costUSD,
105
+ ...(fallbackCostUSD ? { fallbackCostUSD } : {}),
106
+ // A call with output but no usage recorded has unknown tokens, not zero.
107
+ ...(allZero && costUSD === 0 ? { costIsEstimated: true } : {}),
108
+ tools,
109
+ bashCommands,
110
+ skills,
111
+ subagentTypes,
112
+ timestamp: parseTimestamp(opts.timeCreatedMs),
113
+ speed: 'standard',
114
+ deduplicationKey: opts.dedupKey,
115
+ userMessage: opts.userMessage,
116
+ sessionId: opts.sessionId,
117
+ };
118
+ }
@@ -0,0 +1,457 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readdir } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { billableOutputTokens, calculateCost, recordedCostFallback, routeFromProviderField } from '../models.js';
5
+ import { isSqliteAvailable, getSqliteLoadError, openDatabase, blobToText, isSqliteBusyError, isSqliteReadonlyError, warnSqliteReadonlyOnce, } from '../sqlite.js';
6
+ import { buildAssistantCall, parseTimestamp, sanitize } from './session-message.js';
7
+ /**
8
+ * OpenCode 2.x generations (issue #1293): v2 writes `session_v2` + `session_message`
9
+ * (its FK points at `session_v2(id)`), while the legacy `session`/`message`/`part`
10
+ * tables freeze at upgrade and stay frozen — a session created on 2.x has rows in
11
+ * `session_message` and zero new rows in `message`. This returns the DB's
12
+ * primary generation (v2 when present), but on an upgraded DB the frozen legacy
13
+ * rows are NOT dead: any legacy session whose id never made it into `session_v2`
14
+ * is real history and is unioned in (see `discoverSqliteSessions` and the
15
+ * per-session resolution in `parse`). For an id present in both, `parse` reads
16
+ * legacy first and adds only the v2 turns legacy does not hold.
17
+ */
18
+ function detectGeneration(db) {
19
+ try {
20
+ const v2 = db.query("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type = 'table' AND name IN ('session_v2', 'session_message')");
21
+ if ((v2[0]?.cnt ?? 0) === 2)
22
+ return 'v2';
23
+ }
24
+ catch (err) {
25
+ if (isSqliteBusyError(err))
26
+ throw err;
27
+ }
28
+ return validateSchemaDetailed(db).ok ? 'legacy' : null;
29
+ }
30
+ /** True when `id` exists in `session_v2` (used to prefer v2 over a legacy row of
31
+ * the same id, and to route a legacy-only session to the legacy reader). */
32
+ function sessionInV2(db, id) {
33
+ try {
34
+ const rows = db.query('SELECT COUNT(*) as cnt FROM session_v2 WHERE id = ?', [id]);
35
+ return (rows[0]?.cnt ?? 0) > 0;
36
+ }
37
+ catch (err) {
38
+ if (isSqliteBusyError(err))
39
+ throw err;
40
+ return false;
41
+ }
42
+ }
43
+ /**
44
+ * Normalizes v2 `session_message` rows into the legacy message/part shape the
45
+ * shared parse loop already consumes. v2 payloads are tagged by the `type`
46
+ * column (no `role` field); assistant messages carry `content` inline (no part
47
+ * table), `model` as a `{id, providerID}` ref, and `tokens` in the same
48
+ * normalized shape legacy stored.
49
+ */
50
+ function v2RowsToLegacyShape(rows) {
51
+ const messages = [];
52
+ const partsByMsg = new Map();
53
+ for (const row of rows) {
54
+ let payload;
55
+ try {
56
+ payload = JSON.parse(blobToText(row.data));
57
+ }
58
+ catch {
59
+ continue;
60
+ }
61
+ if (row.type === 'user') {
62
+ messages.push({ session_id: row.session_id, id: row.id, time_created: row.time_created, data: JSON.stringify({ role: 'user' }) });
63
+ const text = typeof payload['text'] === 'string' ? payload['text'] : '';
64
+ if (text)
65
+ partsByMsg.set(row.id, [{ type: 'text', text }]);
66
+ continue;
67
+ }
68
+ // Compaction rows carry their own CompactionUsage (cost + tokens for the
69
+ // compaction request itself) and counted as assistant messages on 1.x, so
70
+ // they must keep landing here or every compacted 2.x session undercounts.
71
+ // A `running` compaction has neither and is dropped by buildAssistantCall.
72
+ if (row.type !== 'assistant' && row.type !== 'compaction')
73
+ continue;
74
+ const model = payload['model'];
75
+ const data = { role: 'assistant' };
76
+ if (model !== null && typeof model === 'object' && !Array.isArray(model)) {
77
+ const ref = model;
78
+ const id = typeof ref['id'] === 'string' ? ref['id'] : '';
79
+ const providerID = typeof ref['providerID'] === 'string' ? ref['providerID'] : '';
80
+ if (providerID)
81
+ data.providerID = providerID;
82
+ // Bare id, as 1.x stored `modelID`: the provider prefix breaks pricing for
83
+ // ids like `opencode/claude-haiku-4-5` or `github-copilot/gpt-5`, and a
84
+ // migrated turn must price the same whichever table it is read from.
85
+ if (id)
86
+ data.modelID = id;
87
+ }
88
+ if (typeof payload['cost'] === 'number')
89
+ data.cost = payload['cost'];
90
+ const tokens = payload['tokens'];
91
+ if (tokens !== null && typeof tokens === 'object' && !Array.isArray(tokens))
92
+ data.tokens = tokens;
93
+ const parts = [];
94
+ const content = payload['content'];
95
+ if (Array.isArray(content)) {
96
+ for (const item of content) {
97
+ if (item === null || typeof item !== 'object')
98
+ continue;
99
+ const c = item;
100
+ if ((c['type'] === 'text' || c['type'] === 'reasoning') && typeof c['text'] === 'string' && c['text']) {
101
+ parts.push({ type: c['type'], text: c['text'] });
102
+ }
103
+ else if (c['type'] === 'tool') {
104
+ const state = c['state'];
105
+ const input = state !== null && typeof state === 'object' && state['input'] !== null
106
+ && typeof state['input'] === 'object'
107
+ ? state['input']
108
+ : {};
109
+ parts.push({ type: 'tool', tool: typeof c['name'] === 'string' ? c['name'] : '', state: { input } });
110
+ }
111
+ }
112
+ }
113
+ messages.push({ session_id: row.session_id, id: row.id, time_created: row.time_created, data: JSON.stringify(data) });
114
+ partsByMsg.set(row.id, parts);
115
+ }
116
+ return { messages, partsByMsg };
117
+ }
118
+ function parseSessionModel(value) {
119
+ try {
120
+ const parsed = JSON.parse(blobToText(value));
121
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
122
+ return undefined;
123
+ const model = parsed;
124
+ const id = typeof model['id'] === 'string' ? model['id'].trim() : '';
125
+ const providerID = typeof model['providerID'] === 'string' ? model['providerID'] : '';
126
+ const normalizedProviderID = providerID.trim();
127
+ // Bare id, the same one the per-message path prices.
128
+ return id && normalizedProviderID ? { model: id, providerID } : undefined;
129
+ }
130
+ catch {
131
+ return undefined;
132
+ }
133
+ }
134
+ function tryQuerySessionTokens(db, sessionId, generation) {
135
+ try {
136
+ // Both generations expose the same token columns; only the table name moves.
137
+ const table = generation === 'v2' ? 'session_v2' : 'session';
138
+ const rows = db.query(`SELECT cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write,
139
+ CAST(model AS BLOB) AS model
140
+ FROM ${table} WHERE id = ?`, [sessionId]);
141
+ if (rows.length === 0)
142
+ return null;
143
+ const r = rows[0];
144
+ const parsedModel = parseSessionModel(r.model);
145
+ return {
146
+ cost: r.cost ?? 0,
147
+ input: r.tokens_input ?? 0,
148
+ output: r.tokens_output ?? 0,
149
+ reasoning: r.tokens_reasoning ?? 0,
150
+ cacheRead: r.tokens_cache_read ?? 0,
151
+ cacheWrite: r.tokens_cache_write ?? 0,
152
+ model: parsedModel?.model,
153
+ providerID: parsedModel?.providerID,
154
+ };
155
+ }
156
+ catch (err) {
157
+ if (isSqliteBusyError(err))
158
+ throw err;
159
+ return null;
160
+ }
161
+ }
162
+ function validateSchemaDetailed(db) {
163
+ const required = ['session', 'message', 'part'];
164
+ const missing = [];
165
+ for (const table of required) {
166
+ try {
167
+ db.query(`SELECT COUNT(*) as cnt FROM ${table} LIMIT 1`);
168
+ }
169
+ catch (err) {
170
+ if (isSqliteBusyError(err))
171
+ throw err;
172
+ missing.push(table);
173
+ }
174
+ }
175
+ return missing.length === 0 ? { ok: true } : { ok: false, missing };
176
+ }
177
+ const warnedSchemas = new Map();
178
+ function warnUnrecognizedSchemaOnce(providerLabel, missing) {
179
+ const providerSet = warnedSchemas.get(providerLabel) ?? new Set();
180
+ const key = missing.slice().sort().join(',');
181
+ if (providerSet.has(key))
182
+ return;
183
+ providerSet.add(key);
184
+ warnedSchemas.set(providerLabel, providerSet);
185
+ process.stderr.write(`codeburn: ${providerLabel} database is missing expected tables (${missing.join(', ')}). ` +
186
+ `Run ${providerLabel} once to apply migrations, or report at https://github.com/getagentseal/codeburn/issues if this persists.\n`);
187
+ }
188
+ export function createSqliteSessionParser(source, seenKeys, config) {
189
+ return {
190
+ async *parse() {
191
+ if (!isSqliteAvailable()) {
192
+ process.stderr.write(getSqliteLoadError() + '\n');
193
+ return;
194
+ }
195
+ const segments = source.path.split(':');
196
+ const sessionId = segments[segments.length - 1];
197
+ const dbPath = segments.slice(0, -1).join(':');
198
+ let db;
199
+ try {
200
+ db = openDatabase(dbPath);
201
+ }
202
+ catch (err) {
203
+ process.stderr.write(`codeburn: cannot open ${config.displayName} database: ${err instanceof Error ? err.message : err}\n`);
204
+ return;
205
+ }
206
+ try {
207
+ const generation = detectGeneration(db);
208
+ if (generation === null) {
209
+ const schema = validateSchemaDetailed(db);
210
+ if (!schema.ok)
211
+ warnUnrecognizedSchemaOnce(config.displayName, schema.missing);
212
+ return;
213
+ }
214
+ // On an upgraded (v2 + legacy) DB, a session id that never migrated into
215
+ // session_v2 lives only in the frozen legacy tables and must be read as
216
+ // legacy — reading it from session_message would find nothing and drop
217
+ // its history. v2-only and legacy-only DBs resolve to `generation` as
218
+ // before.
219
+ const legacyOk = generation === 'legacy' || validateSchemaDetailed(db).ok;
220
+ const gen = generation === 'v2' && !sessionInV2(db, sessionId) && legacyOk
221
+ ? 'legacy'
222
+ : generation;
223
+ let messages = [];
224
+ const partsByMsg = new Map();
225
+ // A migrated session keeps its full pre-upgrade history in the frozen
226
+ // legacy tables, while session_message holds only what OpenCode's
227
+ // migration carried over (it drops compaction summaries, task-tool
228
+ // turns and any message it fails to decode, and can stop partway) plus
229
+ // turns added after the upgrade. Legacy is read first so pre-upgrade
230
+ // turns count exactly as on 1.x; migrated rows keep their legacy
231
+ // message ids, so the seenKeys dedup below skips the v2 copies.
232
+ if (legacyOk) {
233
+ messages = db.query(`WITH RECURSIVE session_tree(id) AS (
234
+ SELECT id FROM session WHERE id = ?
235
+ UNION
236
+ SELECT child.id
237
+ FROM session child
238
+ JOIN session_tree parent ON child.parent_id = parent.id
239
+ )
240
+ SELECT session_id, id, time_created, CAST(data AS BLOB) AS data
241
+ FROM message
242
+ WHERE session_id IN (SELECT id FROM session_tree)
243
+ ORDER BY time_created ASC, id ASC`, [sessionId]);
244
+ const parts = db.query(`WITH RECURSIVE session_tree(id) AS (
245
+ SELECT id FROM session WHERE id = ?
246
+ UNION
247
+ SELECT child.id
248
+ FROM session child
249
+ JOIN session_tree parent ON child.parent_id = parent.id
250
+ )
251
+ SELECT message_id, CAST(data AS BLOB) AS data
252
+ FROM part
253
+ WHERE session_id IN (SELECT id FROM session_tree)
254
+ ORDER BY message_id, id`, [sessionId]);
255
+ for (const part of parts) {
256
+ try {
257
+ const parsed = JSON.parse(blobToText(part.data));
258
+ const list = partsByMsg.get(part.message_id) ?? [];
259
+ list.push(parsed);
260
+ partsByMsg.set(part.message_id, list);
261
+ }
262
+ catch {
263
+ // skip corrupt part data
264
+ }
265
+ }
266
+ }
267
+ if (gen === 'v2') {
268
+ const rows = db.query(`WITH RECURSIVE session_tree(id) AS (
269
+ SELECT id FROM session_v2 WHERE id = ?
270
+ UNION
271
+ SELECT child.id
272
+ FROM session_v2 child
273
+ JOIN session_tree parent ON child.parent_id = parent.id
274
+ )
275
+ SELECT session_id, id, type, seq, time_created, CAST(data AS BLOB) AS data
276
+ FROM session_message
277
+ WHERE session_id IN (SELECT id FROM session_tree)
278
+ ORDER BY time_created ASC, session_id ASC, seq ASC`, [sessionId]);
279
+ const normalized = v2RowsToLegacyShape(rows);
280
+ messages.push(...normalized.messages);
281
+ for (const [id, parts] of normalized.partsByMsg) {
282
+ if (!partsByMsg.has(id))
283
+ partsByMsg.set(id, parts);
284
+ }
285
+ }
286
+ const currentUserMessageBySession = new Map();
287
+ let yieldCount = 0;
288
+ let parseFailCount = 0;
289
+ let roleSkipCount = 0;
290
+ for (const msg of messages) {
291
+ let data;
292
+ try {
293
+ data = JSON.parse(blobToText(msg.data));
294
+ }
295
+ catch {
296
+ parseFailCount++;
297
+ continue;
298
+ }
299
+ if (data.role === 'user') {
300
+ const textParts = (partsByMsg.get(msg.id) ?? [])
301
+ .filter((p) => p.type === 'text')
302
+ .map((p) => p.text ?? '')
303
+ .filter(Boolean);
304
+ if (textParts.length > 0) {
305
+ currentUserMessageBySession.set(msg.session_id, textParts.join(' '));
306
+ }
307
+ continue;
308
+ }
309
+ if (data.role !== 'assistant' && data.role !== 'model') {
310
+ if (data.role !== 'user')
311
+ roleSkipCount++;
312
+ continue;
313
+ }
314
+ const dedupKey = `${config.providerName}:${msg.session_id}:${msg.id}`;
315
+ if (seenKeys.has(dedupKey))
316
+ continue;
317
+ const call = buildAssistantCall({
318
+ providerName: config.providerName,
319
+ dedupKey,
320
+ sessionId,
321
+ data,
322
+ parts: partsByMsg.get(msg.id) ?? [],
323
+ timeCreatedMs: msg.time_created,
324
+ userMessage: currentUserMessageBySession.get(msg.session_id) ?? '',
325
+ });
326
+ if (!call)
327
+ continue;
328
+ seenKeys.add(dedupKey);
329
+ yieldCount++;
330
+ yield call;
331
+ }
332
+ if (yieldCount === 0 && messages.length > 0) {
333
+ const sessionTokens = tryQuerySessionTokens(db, sessionId, gen);
334
+ if (sessionTokens && (sessionTokens.cost > 0 || sessionTokens.input > 0 || sessionTokens.output > 0)) {
335
+ const dedupKey = `${config.providerName}:${sessionId}:session-level`;
336
+ if (!seenKeys.has(dedupKey)) {
337
+ seenKeys.add(dedupKey);
338
+ const model = sessionTokens.model ?? 'unknown';
339
+ const route = routeFromProviderField(sessionTokens.providerID)?.id;
340
+ // OpenCode stores reasoning in its own session column and bills it
341
+ // at the output rate, so it has to join the output bucket here the
342
+ // same way the per-message path does. Routed through
343
+ // billableOutputTokens so this fallback can never drift from the
344
+ // per-message pricing in buildAssistantCall. (#1334)
345
+ const outputForCost = billableOutputTokens(config.providerName, sessionTokens.output, sessionTokens.reasoning);
346
+ let costUSD = calculateCost(model, sessionTokens.input, outputForCost, sessionTokens.cacheWrite, sessionTokens.cacheRead, 0);
347
+ const fallbackCostUSD = recordedCostFallback(model, costUSD, sessionTokens.cost);
348
+ if (fallbackCostUSD)
349
+ costUSD = fallbackCostUSD;
350
+ yield {
351
+ provider: config.providerName,
352
+ model,
353
+ ...(route ? { route } : {}),
354
+ inputTokens: sessionTokens.input,
355
+ outputTokens: sessionTokens.output,
356
+ cacheCreationInputTokens: sessionTokens.cacheWrite,
357
+ cacheReadInputTokens: sessionTokens.cacheRead,
358
+ cachedInputTokens: sessionTokens.cacheRead,
359
+ reasoningTokens: sessionTokens.reasoning,
360
+ webSearchRequests: 0,
361
+ costUSD,
362
+ ...(fallbackCostUSD ? { fallbackCostUSD } : {}),
363
+ tools: [],
364
+ bashCommands: [],
365
+ timestamp: parseTimestamp(messages[0].time_created),
366
+ speed: 'standard',
367
+ deduplicationKey: dedupKey,
368
+ userMessage: '',
369
+ sessionId,
370
+ };
371
+ yieldCount++;
372
+ }
373
+ }
374
+ if (yieldCount === 0 && process.env['CODEBURN_VERBOSE'] === '1') {
375
+ process.stderr.write(`codeburn: ${config.displayName} session ${sessionId} has ${messages.length} messages ` +
376
+ `(${parseFailCount} unparseable, ${roleSkipCount} non-user/assistant roles) ` +
377
+ `but yielded 0 calls.\n`);
378
+ }
379
+ }
380
+ }
381
+ finally {
382
+ db.close();
383
+ }
384
+ },
385
+ };
386
+ }
387
+ export async function discoverSqliteSessions(config) {
388
+ if (!isSqliteAvailable())
389
+ return [];
390
+ let dbPaths;
391
+ try {
392
+ const entries = await readdir(config.dbDir);
393
+ dbPaths = entries
394
+ .filter((f) => f.startsWith(config.dbFilePrefix) && f.endsWith('.db'))
395
+ .map((f) => join(config.dbDir, f));
396
+ }
397
+ catch {
398
+ return [];
399
+ }
400
+ if (dbPaths.length === 0)
401
+ return [];
402
+ const sessions = [];
403
+ for (const dbPath of dbPaths) {
404
+ let db;
405
+ try {
406
+ db = openDatabase(dbPath);
407
+ }
408
+ catch (err) {
409
+ if (isSqliteReadonlyError(err))
410
+ warnSqliteReadonlyOnce(dbPath);
411
+ continue;
412
+ }
413
+ try {
414
+ const generation = detectGeneration(db);
415
+ if (generation === null) {
416
+ const schema = validateSchemaDetailed(db);
417
+ if (!schema.ok)
418
+ warnUnrecognizedSchemaOnce(config.displayName, schema.missing);
419
+ continue;
420
+ }
421
+ // Same projection on both generations; only the table name moves.
422
+ const table = generation === 'v2' ? 'session_v2' : 'session';
423
+ const rows = db.query(`SELECT id, CAST(directory AS BLOB) AS directory, CAST(title AS BLOB) AS title, time_created
424
+ FROM ${table} WHERE parent_id IS NULL ORDER BY time_created DESC`);
425
+ // On an upgraded DB, also surface legacy top-level sessions that never
426
+ // migrated into session_v2 — their frozen history is otherwise dropped
427
+ // (#1293). Sessions present in both are excluded here so each is listed once.
428
+ if (generation === 'v2' && validateSchemaDetailed(db).ok) {
429
+ rows.push(...db.query(`SELECT id, CAST(directory AS BLOB) AS directory, CAST(title AS BLOB) AS title, time_created
430
+ FROM session
431
+ WHERE parent_id IS NULL AND id NOT IN (SELECT id FROM session_v2)
432
+ ORDER BY time_created DESC`));
433
+ }
434
+ for (const row of rows) {
435
+ const dir = blobToText(row.directory);
436
+ const title = blobToText(row.title);
437
+ sessions.push({
438
+ path: `${dbPath}:${row.id}`,
439
+ project: dir ? sanitize(dir) : sanitize(title),
440
+ provider: config.providerName,
441
+ });
442
+ }
443
+ }
444
+ catch (err) {
445
+ // A busy/locked DB (OpenCode or KiloCode open during the scan) is not an
446
+ // empty DB: let it reach the caller so discovery is marked failed rather
447
+ // than sealing an empty period as fully scanned.
448
+ if (isSqliteBusyError(err))
449
+ throw err;
450
+ // skip this DB
451
+ }
452
+ finally {
453
+ db.close();
454
+ }
455
+ }
456
+ return sessions;
457
+ }
@@ -0,0 +1,5 @@
1
+ // Thrown by a parser whose source is temporarily unreadable (a network fetch
2
+ // that failed transiently). The parse loop treats it like a busy SQLite
3
+ // store: the source's cached rows keep serving and the next refresh retries.
4
+ export class RetryableSourceError extends Error {
5
+ }