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,771 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readdir, stat } from 'fs/promises';
3
+ import { statSync } from 'fs';
4
+ import { basename, dirname, join } from 'path';
5
+ import { homedir } from 'os';
6
+ import { readGitOriginUrl } from '../git-origin.js';
7
+ import { calculateCost, getShortModelName, ownValue, routeFromProviderField } from '../models.js';
8
+ import { isUserHomeRoot } from '../path-privacy.js';
9
+ import { isSqliteAvailable, getSqliteLoadError, openDatabase, isSqliteBusyError } from '../sqlite.js';
10
+ import { getHermesCursor, hermesBaselineKey, hermesLedgerNow, hermesObservationKey, listHermesCursorSessionIds, loadHermesSessionLedger, recordHermesSnapshot, zeroHermesTokens, isHermesLedgerPublicationError, } from '../hermes-session-ledger.js';
11
+ const toolNameMap = {
12
+ terminal: 'Bash',
13
+ execute_code: 'CodeExecution',
14
+ read_file: 'Read',
15
+ search_files: 'Grep',
16
+ write_file: 'Write',
17
+ patch: 'Edit',
18
+ browser_navigate: 'Browser',
19
+ browser_click: 'Browser',
20
+ browser_type: 'Browser',
21
+ browser_press: 'Browser',
22
+ browser_scroll: 'Browser',
23
+ browser_snapshot: 'Browser',
24
+ browser_vision: 'Vision',
25
+ browser_console: 'Browser',
26
+ browser_get_images: 'Browser',
27
+ web_search: 'WebSearch',
28
+ web_extract: 'WebFetch',
29
+ delegate_task: 'Agent',
30
+ vision_analyze: 'Vision',
31
+ process: 'Bash',
32
+ todo: 'TodoWrite',
33
+ skill_view: 'Skill',
34
+ skill_manage: 'Skill',
35
+ skills_list: 'Skill',
36
+ memory: 'Memory',
37
+ session_search: 'SessionSearch',
38
+ };
39
+ function getHermesHome(override) {
40
+ if (override !== undefined)
41
+ return override;
42
+ const configuredHome = process.env['HERMES_HOME']?.trim();
43
+ if (configuredHome)
44
+ return configuredHome;
45
+ if (process.platform === 'win32') {
46
+ const localAppData = process.env['LOCALAPPDATA']?.trim();
47
+ return join(localAppData || join(homedir(), 'AppData', 'Local'), 'hermes');
48
+ }
49
+ return join(homedir(), '.hermes');
50
+ }
51
+ function displayProjectForProfile(profile) {
52
+ return profile === 'default' ? 'hermes' : sanitizeProject(profile);
53
+ }
54
+ function stripCodeRegions(text) {
55
+ const out = [];
56
+ let fence = null;
57
+ for (const line of text.split('\n')) {
58
+ const trimmed = line.replace(/\s+$/, '');
59
+ const open = trimmed.match(/^(\s*)([`~]{3,})(.*)$/);
60
+ if (!fence) {
61
+ if (open && !open[3].includes(open[2][0])) {
62
+ fence = { marker: open[2][0], length: open[2].length };
63
+ out.push(' ');
64
+ continue;
65
+ }
66
+ if (/^[ \t]{4,}\S/.test(line)) {
67
+ out.push(' ');
68
+ continue;
69
+ }
70
+ out.push(line.replace(/`[^`]*`/g, ' '));
71
+ continue;
72
+ }
73
+ const close = trimmed.match(/^(\s*)([`~]{3,})\s*$/);
74
+ if (close && close[2][0] === fence.marker && close[2].length >= fence.length) {
75
+ fence = null;
76
+ }
77
+ out.push(' ');
78
+ }
79
+ return out.join('\n');
80
+ }
81
+ function githubOwnerRepoFromUrl(url) {
82
+ const gh = url.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/i);
83
+ if (!gh)
84
+ return null;
85
+ return { owner: gh[1].toLowerCase(), repo: gh[2].replace(/\.git$/i, '').toLowerCase() };
86
+ }
87
+ // Memoized per repo root: every session in the same repo would otherwise
88
+ // re-read .git/config. Process-lifetime only, so a remote URL change needs a
89
+ // restart (a resident `serve` child included).
90
+ const originIdentityByRoot = new Map();
91
+ function githubOwnerRepoFromRoot(repoRoot) {
92
+ const memo = originIdentityByRoot.get(repoRoot);
93
+ if (memo !== undefined)
94
+ return memo;
95
+ const identity = readGithubOwnerRepoFromRoot(repoRoot);
96
+ originIdentityByRoot.set(repoRoot, identity);
97
+ return identity;
98
+ }
99
+ function readGithubOwnerRepoFromRoot(repoRoot) {
100
+ const url = readGitOriginUrl(repoRoot);
101
+ return url ? githubOwnerRepoFromUrl(url) : null;
102
+ }
103
+ function extractGithubPullUrls(texts, identity) {
104
+ if (!identity)
105
+ return [];
106
+ const found = new Set();
107
+ const re = /https:\/\/github\.com\/[^/\s"'<>]+\/[^/\s"'<>]+\/pull\/\d+/gi;
108
+ for (const text of texts) {
109
+ if (!text)
110
+ continue;
111
+ const searchable = stripCodeRegions(text);
112
+ for (const match of searchable.matchAll(re)) {
113
+ try {
114
+ const url = new URL(match[0]);
115
+ if (url.protocol !== 'https:')
116
+ continue;
117
+ const pathMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/\d+$/);
118
+ if (!pathMatch)
119
+ continue;
120
+ if (pathMatch[1].toLowerCase() !== identity.owner)
121
+ continue;
122
+ if (pathMatch[2].toLowerCase() !== identity.repo)
123
+ continue;
124
+ found.add(`${url.origin}${url.pathname}`);
125
+ }
126
+ catch {
127
+ // skip malformed
128
+ }
129
+ }
130
+ }
131
+ return [...found].sort();
132
+ }
133
+ function statSyncSafe(path) {
134
+ try {
135
+ const st = statSync(path);
136
+ if (st.isFile())
137
+ return 'file';
138
+ if (st.isDirectory())
139
+ return 'dir';
140
+ return null;
141
+ }
142
+ catch {
143
+ return null;
144
+ }
145
+ }
146
+ function sanitizeProject(raw) {
147
+ const trimmed = raw.trim();
148
+ if (!trimmed)
149
+ return 'hermes';
150
+ return trimmed.replace(/^[/\\]+/, '').replace(/[:/\\]/g, '-');
151
+ }
152
+ function parseProfileName(dbPath, hermesHome) {
153
+ const profilesDir = join(hermesHome, 'profiles');
154
+ const dir = dirname(dbPath);
155
+ if (dirname(dir) === profilesDir)
156
+ return basename(dir);
157
+ return 'default';
158
+ }
159
+ async function findStateDbs(hermesHome) {
160
+ const dbs = [];
161
+ const rootDb = join(hermesHome, 'state.db');
162
+ const rootStat = await stat(rootDb).catch(() => null);
163
+ if (rootStat?.isFile())
164
+ dbs.push({ dbPath: rootDb, profile: 'default' });
165
+ const profilesDir = join(hermesHome, 'profiles');
166
+ const profiles = await readdir(profilesDir, { withFileTypes: true }).catch(() => []);
167
+ for (const entry of profiles) {
168
+ if (!entry.isDirectory())
169
+ continue;
170
+ const dbPath = join(profilesDir, entry.name, 'state.db');
171
+ const s = await stat(dbPath).catch(() => null);
172
+ if (s?.isFile())
173
+ dbs.push({ dbPath, profile: entry.name });
174
+ }
175
+ return dbs;
176
+ }
177
+ function encodeSourcePath(dbPath, sessionId) {
178
+ return `${dbPath}#hermes-session=${encodeURIComponent(sessionId)}`;
179
+ }
180
+ function decodeSourcePath(path) {
181
+ const marker = '#hermes-session=';
182
+ const idx = path.lastIndexOf(marker);
183
+ if (idx === -1)
184
+ return null;
185
+ return {
186
+ dbPath: path.slice(0, idx),
187
+ sessionId: decodeURIComponent(path.slice(idx + marker.length)),
188
+ };
189
+ }
190
+ function validateSchema(db) {
191
+ try {
192
+ db.query('SELECT session_id, role, content, tool_calls FROM messages LIMIT 1');
193
+ const columns = getSessionColumns(db);
194
+ return columns.has('id') && columns.has('input_tokens') && columns.has('output_tokens');
195
+ }
196
+ catch (err) {
197
+ if (isSqliteBusyError(err))
198
+ throw err;
199
+ return false;
200
+ }
201
+ }
202
+ function getSessionColumns(db) {
203
+ return new Set(db.query('PRAGMA table_info(sessions)').map(row => row.name));
204
+ }
205
+ function numberColumn(columns, name) {
206
+ return columns.has(name) ? `coalesce(${name}, 0) AS ${name}` : `0 AS ${name}`;
207
+ }
208
+ function nullableColumn(columns, name) {
209
+ return columns.has(name) ? name : `NULL AS ${name}`;
210
+ }
211
+ function getMessageColumns(db) {
212
+ return new Set(db.query('PRAGMA table_info(messages)').map(row => row.name));
213
+ }
214
+ function readHelperUsage(db, sessionId) {
215
+ const columns = new Set(db.query('PRAGMA table_info(session_model_usage)').map(row => row.name));
216
+ if (!columns.has('task'))
217
+ return [];
218
+ // Auxiliary calls (compression, titles, ...) land only here, never in the sessions totals;
219
+ // voice_chat is the one task Hermes also adds to the sessions totals.
220
+ return db.query(`SELECT task, model, billing_provider, billing_base_url, billing_mode,
221
+ input_tokens AS inputTokens, output_tokens AS outputTokens,
222
+ cache_read_tokens AS cacheReadTokens, cache_write_tokens AS cacheWriteTokens,
223
+ reasoning_tokens AS reasoningTokens, estimated_cost_usd,
224
+ CASE WHEN cost_status = 'actual' THEN actual_cost_usd ELSE NULLIF(actual_cost_usd, 0) END AS actual_cost_usd, cost_status, cost_source, first_seen
225
+ FROM session_model_usage
226
+ WHERE session_id = ? AND task NOT IN ('', 'voice_chat')`, [sessionId]);
227
+ }
228
+ function usageExpression(columns) {
229
+ const usageColumns = [
230
+ 'input_tokens',
231
+ 'output_tokens',
232
+ 'cache_read_tokens',
233
+ 'cache_write_tokens',
234
+ 'reasoning_tokens',
235
+ ];
236
+ const parts = usageColumns
237
+ .filter(name => columns.has(name))
238
+ .map(name => `coalesce(${name}, 0)`);
239
+ return parts.length > 0 ? parts.join(' + ') : '0';
240
+ }
241
+ function parseTimestamp(raw) {
242
+ if (raw == null)
243
+ return '';
244
+ const ms = raw < 1e12 ? raw * 1000 : raw;
245
+ return new Date(ms).toISOString();
246
+ }
247
+ function firstUserMessage(messages) {
248
+ const msg = messages.find(m => m.role === 'user' && typeof m.content === 'string' && m.content.trim().length > 0);
249
+ return Array.from(msg?.content ?? '').slice(0, 500).join('');
250
+ }
251
+ function mapToolName(raw) {
252
+ // Composio MCP tools are matched first — the generic mcp_ prefix on line
253
+ // below would also match composio names, so order matters here.
254
+ if (raw.startsWith('mcp_composio_'))
255
+ return 'MCP';
256
+ if (raw.startsWith('mcp_') || raw.startsWith('mcp__'))
257
+ return raw;
258
+ if (raw.startsWith('browser_'))
259
+ return 'Browser';
260
+ return ownValue(toolNameMap, raw) ?? raw;
261
+ }
262
+ function parseToolCalls(raw) {
263
+ if (!raw)
264
+ return [];
265
+ try {
266
+ const parsed = JSON.parse(raw);
267
+ return Array.isArray(parsed) ? parsed : [];
268
+ }
269
+ catch {
270
+ return [];
271
+ }
272
+ }
273
+ function collectTools(messages) {
274
+ const tools = [];
275
+ const toolSequence = [];
276
+ const bashCommands = [];
277
+ for (const msg of messages) {
278
+ if (msg.role === 'assistant') {
279
+ const currentTurnTools = [];
280
+ for (const call of parseToolCalls(msg.tool_calls)) {
281
+ const rawName = call.function?.name ?? '';
282
+ if (!rawName)
283
+ continue;
284
+ const mapped = mapToolName(rawName);
285
+ tools.push(mapped);
286
+ const toolCall = { tool: mapped };
287
+ const rawArgs = call.function?.arguments;
288
+ if (rawArgs) {
289
+ try {
290
+ const args = JSON.parse(rawArgs);
291
+ const file = args['path'] ?? args['file_path'];
292
+ if (typeof file === 'string')
293
+ toolCall.file = file;
294
+ const command = args['command'];
295
+ if (typeof command === 'string') {
296
+ toolCall.command = command;
297
+ bashCommands.push(command);
298
+ }
299
+ }
300
+ catch {
301
+ // Ignore malformed arguments from historical sessions.
302
+ }
303
+ }
304
+ currentTurnTools.push(toolCall);
305
+ }
306
+ if (currentTurnTools.length > 0) {
307
+ toolSequence.push(currentTurnTools);
308
+ }
309
+ }
310
+ else if (msg.role === 'tool' && msg.tool_name) {
311
+ tools.push(mapToolName(msg.tool_name));
312
+ }
313
+ }
314
+ return {
315
+ tools: [...new Set(tools)],
316
+ toolSequence: toolSequence.length > 0 ? toolSequence : [],
317
+ bashCommands,
318
+ };
319
+ }
320
+ function isRealWorkspace(cwd) {
321
+ if (!cwd?.trim())
322
+ return false;
323
+ const trimmed = cwd.trim();
324
+ // A state.db is only ever read from this machine's own Hermes home
325
+ // (`HERMES_HOME` or `~/.hermes`), so the shapes it can hold are the host's.
326
+ // A Windows host also takes a POSIX-rooted path, which its own tooling
327
+ // produces (WSL, MSYS); a POSIX host takes only a POSIX-rooted path, so a
328
+ // literal `C:\...` string stays the non-workspace it has always been there.
329
+ // Slash-UNC (//server/share) stays out: it is not a local workspace.
330
+ const isAbsolute = process.platform === 'win32'
331
+ ? /^[a-zA-Z]:[\\/]/.test(trimmed) || /^\\\\[^\\/]+\\/.test(trimmed)
332
+ || (trimmed.startsWith('/') && !trimmed.startsWith('//'))
333
+ : trimmed.startsWith('/') && !trimmed.startsWith('//');
334
+ if (!isAbsolute)
335
+ return false;
336
+ const normalized = trimmed.replace(/\\/g, '/').replace(/\/+$/, '');
337
+ if (normalized === '/' || normalized === homedir() || normalized === homedir().replace(/\\/g, '/') || isUserHomeRoot(normalized))
338
+ return false;
339
+ if (/\.app\/Contents\//.test(normalized))
340
+ return false;
341
+ return true;
342
+ }
343
+ function resolveHermesWorkspace(row, messages) {
344
+ const provider = 'hermes';
345
+ const repo = row.git_repo_root?.trim();
346
+ if (isRealWorkspace(repo)) {
347
+ return { project: sanitizeProject(basename(repo)), projectPath: repo, workingDirectory: repo, provider };
348
+ }
349
+ const cwd = row.cwd?.trim();
350
+ if (isRealWorkspace(cwd)) {
351
+ return { project: sanitizeProject(cwd), projectPath: cwd, workingDirectory: cwd, provider };
352
+ }
353
+ const inferred = inferProject(messages, '');
354
+ if (isRealWorkspace(inferred.projectPath)) {
355
+ // Prompt-derived paths remain local display/grouping labels only.
356
+ return { project: inferred.project, provider };
357
+ }
358
+ return { project: provider, provider };
359
+ }
360
+ function tokenSum(tokens) {
361
+ return tokens.inputTokens + tokens.outputTokens + tokens.cacheReadTokens + tokens.cacheWriteTokens + tokens.reasoningTokens;
362
+ }
363
+ function resolveHermesCost(row, model, tokens) {
364
+ const calculatedCost = calculateCost(model, tokens.inputTokens, tokens.outputTokens, tokens.cacheWriteTokens, tokens.cacheReadTokens, 0);
365
+ // actual is a recorded invoice amount; explicit $0 still counts as recorded.
366
+ if (row && row.actual_cost_usd != null) {
367
+ return { costUSD: row.actual_cost_usd, costIsEstimated: false, costBasis: 'actual' };
368
+ }
369
+ const costStatus = row?.cost_status?.trim().toLowerCase();
370
+ const costSource = row?.cost_source?.trim().toLowerCase();
371
+ // Included subscription usage is real activity but not metered API spend.
372
+ // Its recorded zero must win over API-equivalent token pricing.
373
+ if (costStatus === 'included') {
374
+ return { costUSD: 0, costIsEstimated: false, costBasis: 'included' };
375
+ }
376
+ // An explicit Hermes estimate is authoritative even when it is zero (for
377
+ // example, a provider's free tier). Preserve that provenance in the UI.
378
+ if (costStatus === 'estimated' && row?.estimated_cost_usd != null) {
379
+ return { costUSD: row.estimated_cost_usd, costIsEstimated: true, costBasis: 'estimated' };
380
+ }
381
+ // Only rows predating BOTH provenance fields use the legacy positive-estimate
382
+ // fallback. A provenance-aware `unknown` row can retain a partial estimate
383
+ // from earlier priced calls; treating that as the session total undercounts.
384
+ if (!costStatus && !costSource && row && row.estimated_cost_usd != null && row.estimated_cost_usd > 0) {
385
+ return { costUSD: row.estimated_cost_usd, costIsEstimated: true, costBasis: 'estimated' };
386
+ }
387
+ return { costUSD: calculatedCost, costIsEstimated: true, costBasis: 'calculated' };
388
+ }
389
+ /// Who billed a call, read off the basis Hermes resolved its cost to.
390
+ /// `included` is usage a subscription already paid for; an `actual` amount is
391
+ /// a recorded invoice line, so it is metered — an explicit $0 (a free-tier
392
+ /// OpenRouter model) is still recorded. An estimate names no account, so it
393
+ /// yields no mode rather than a guess.
394
+ function billingFromCostBasis(basis) {
395
+ if (basis === 'included')
396
+ return 'subscription';
397
+ if (basis === 'actual')
398
+ return 'metered';
399
+ return undefined;
400
+ }
401
+ function observationToCall(observation, args) {
402
+ const later = observation.index > 0;
403
+ const billing = billingFromCostBasis(observation.costBasis);
404
+ return {
405
+ provider: 'hermes',
406
+ model: args.model,
407
+ inputTokens: observation.inputTokens,
408
+ outputTokens: observation.outputTokens,
409
+ cacheCreationInputTokens: observation.cacheWriteTokens,
410
+ cacheReadInputTokens: observation.cacheReadTokens,
411
+ cachedInputTokens: observation.cacheReadTokens,
412
+ reasoningTokens: observation.reasoningTokens,
413
+ webSearchRequests: 0,
414
+ costUSD: observation.costUSD,
415
+ // Later observations keep the stored basis. Included and actual are
416
+ // recorded facts; estimated and calculated remain estimates.
417
+ costIsEstimated: later
418
+ ? observation.costBasis === 'calculated' || observation.costBasis === 'estimated'
419
+ : args.costIsEstimated,
420
+ tools: later ? [] : args.tools,
421
+ bashCommands: later ? [] : args.bashCommands,
422
+ timestamp: observation.timestamp,
423
+ speed: 'standard',
424
+ deduplicationKey: later
425
+ ? hermesObservationKey(args.profile, args.sessionId, observation.index)
426
+ : hermesBaselineKey(args.profile, args.sessionId),
427
+ turnId: later ? `${args.sessionId}:obs:${observation.index}` : `${args.sessionId}:session`,
428
+ toolSequence: later || args.toolSequence.length === 0 ? undefined : args.toolSequence,
429
+ userMessage: later ? '' : args.userMessage,
430
+ sessionId: args.sessionId,
431
+ project: args.project,
432
+ projectPath: args.projectPath,
433
+ workingDirectory: args.workingDirectory,
434
+ ...(later || !args.prLinks?.length ? {} : { prLinks: args.prLinks }),
435
+ ...(later ? { supplementaryAccounting: true } : {}),
436
+ ...(args.route ? { route: args.route } : {}),
437
+ ...(billing ? { billing } : {}),
438
+ };
439
+ }
440
+ function inferProject(messages, fallback) {
441
+ const cwdPattern = /^Current working directory:\s*([a-zA-Z]:\\[^\r\n`"]+|\/[^\r\n`"\\]+)/m;
442
+ for (const msg of messages) {
443
+ if (msg.role !== 'user' && msg.role !== 'system')
444
+ continue;
445
+ const match = cwdPattern.exec(msg.content ?? '');
446
+ if (match?.[1]) {
447
+ const projectPath = match[1].trim();
448
+ return { project: sanitizeProject(projectPath), projectPath };
449
+ }
450
+ }
451
+ return { project: fallback };
452
+ }
453
+ async function discoverFromDb(dbPath, profile) {
454
+ let db;
455
+ try {
456
+ db = openDatabase(dbPath);
457
+ }
458
+ catch (err) {
459
+ // A busy/locked open is not an empty DB: escalate so discovery is marked
460
+ // failed rather than sealing an empty period (mirrors the query catch below).
461
+ if (isSqliteBusyError(err))
462
+ throw err;
463
+ return [];
464
+ }
465
+ try {
466
+ if (!validateSchema(db))
467
+ return [];
468
+ const columns = getSessionColumns(db);
469
+ const usage = usageExpression(columns);
470
+ const orderBy = columns.has('started_at') ? 'started_at DESC' : 'id DESC';
471
+ const rows = db.query(`SELECT id,
472
+ ${nullableColumn(columns, 'title')},
473
+ ${numberColumn(columns, 'input_tokens')},
474
+ ${numberColumn(columns, 'output_tokens')},
475
+ ${numberColumn(columns, 'cache_read_tokens')},
476
+ ${numberColumn(columns, 'cache_write_tokens')},
477
+ ${numberColumn(columns, 'reasoning_tokens')}
478
+ FROM sessions
479
+ WHERE ${usage} > 0
480
+ ORDER BY ${orderBy}
481
+ LIMIT 10000`);
482
+ const sources = rows.map(row => ({
483
+ path: encodeSourcePath(dbPath, row.id),
484
+ project: displayProjectForProfile(profile),
485
+ provider: 'hermes',
486
+ }));
487
+ // After the >0 filter, reconcile every already-ledgered identity against
488
+ // this state.db so an all-zero (or missing) row still reaches the cursor.
489
+ // Without this, 150→0 is invisible and the later 40 is treated as a shrink.
490
+ const discoveredIds = new Set(rows.map(row => row.id));
491
+ const ledger = loadHermesSessionLedger();
492
+ for (const sessionId of listHermesCursorSessionIds(ledger, profile)) {
493
+ if (discoveredIds.has(sessionId) || sessionId.includes('#helper:'))
494
+ continue;
495
+ sources.push({
496
+ path: encodeSourcePath(dbPath, sessionId),
497
+ project: displayProjectForProfile(profile),
498
+ provider: 'hermes',
499
+ });
500
+ }
501
+ return sources;
502
+ }
503
+ catch (err) {
504
+ if (isSqliteBusyError(err))
505
+ throw err;
506
+ process.stderr.write(`codeburn: error querying Hermes database: ${err instanceof Error ? err.message : err}\n`);
507
+ return [];
508
+ }
509
+ finally {
510
+ db.close();
511
+ }
512
+ }
513
+ function createParser(source, seenKeys, hermesHome) {
514
+ return {
515
+ async *parse() {
516
+ if (!isSqliteAvailable()) {
517
+ process.stderr.write(getSqliteLoadError() + '\n');
518
+ return;
519
+ }
520
+ const decoded = decodeSourcePath(source.path);
521
+ if (!decoded)
522
+ return;
523
+ const profile = parseProfileName(decoded.dbPath, hermesHome);
524
+ let db;
525
+ try {
526
+ db = openDatabase(decoded.dbPath);
527
+ }
528
+ catch (err) {
529
+ // A busy/locked open must reach the caller, not read as an empty session.
530
+ if (isSqliteBusyError(err))
531
+ throw err;
532
+ process.stderr.write(`codeburn: cannot open Hermes database: ${err instanceof Error ? err.message : err}\n`);
533
+ return;
534
+ }
535
+ let result;
536
+ try {
537
+ if (!validateSchema(db))
538
+ return;
539
+ const columns = getSessionColumns(db);
540
+ const rows = db.query(`SELECT id,
541
+ ${nullableColumn(columns, 'source')},
542
+ ${nullableColumn(columns, 'model')},
543
+ ${nullableColumn(columns, 'cwd')},
544
+ ${nullableColumn(columns, 'git_repo_root')},
545
+ ${nullableColumn(columns, 'billing_provider')},
546
+ ${numberColumn(columns, 'input_tokens')},
547
+ ${numberColumn(columns, 'output_tokens')},
548
+ ${numberColumn(columns, 'cache_read_tokens')},
549
+ ${numberColumn(columns, 'cache_write_tokens')},
550
+ ${numberColumn(columns, 'reasoning_tokens')},
551
+ ${nullableColumn(columns, 'estimated_cost_usd')},
552
+ ${nullableColumn(columns, 'actual_cost_usd')},
553
+ ${nullableColumn(columns, 'cost_status')},
554
+ ${nullableColumn(columns, 'cost_source')},
555
+ ${numberColumn(columns, 'api_call_count')},
556
+ ${numberColumn(columns, 'tool_call_count')},
557
+ ${nullableColumn(columns, 'started_at')},
558
+ ${nullableColumn(columns, 'ended_at')},
559
+ ${nullableColumn(columns, 'title')}
560
+ FROM sessions
561
+ WHERE id = ?`, [decoded.sessionId]);
562
+ const row = rows[0];
563
+ const ledger = loadHermesSessionLedger();
564
+ const existingCursor = getHermesCursor(ledger, profile, decoded.sessionId);
565
+ if (!row) {
566
+ if (!existingCursor)
567
+ return;
568
+ const baselineKey = hermesBaselineKey(profile, decoded.sessionId);
569
+ if (seenKeys.has(baselineKey))
570
+ return;
571
+ seenKeys.add(baselineKey);
572
+ const cursor = await recordHermesSnapshot({
573
+ profile,
574
+ sessionId: decoded.sessionId,
575
+ startedAt: existingCursor.observations[0]?.timestamp || hermesLedgerNow().toISOString(),
576
+ observedAt: hermesLedgerNow().toISOString(),
577
+ tokens: zeroHermesTokens(),
578
+ costUSD: 0,
579
+ costBasis: 'calculated',
580
+ });
581
+ for (const observation of cursor.observations) {
582
+ if (observation.index > 0)
583
+ seenKeys.add(hermesObservationKey(profile, decoded.sessionId, observation.index));
584
+ }
585
+ result = {
586
+ calls: cursor.observations.map(observation => observationToCall(observation, {
587
+ profile,
588
+ sessionId: decoded.sessionId,
589
+ model: 'unknown',
590
+ tools: [],
591
+ bashCommands: [],
592
+ toolSequence: [],
593
+ userMessage: '',
594
+ project: displayProjectForProfile(profile),
595
+ costIsEstimated: false,
596
+ })),
597
+ };
598
+ }
599
+ else {
600
+ const messageColumns = getMessageColumns(db);
601
+ const orderColumns = ['timestamp', 'id'].filter(name => messageColumns.has(name));
602
+ const orderBy = orderColumns.length > 0 ? `ORDER BY ${orderColumns.join(' ASC, ')} ASC` : '';
603
+ const messages = db.query(`SELECT ${numberColumn(messageColumns, 'id')},
604
+ role,
605
+ content,
606
+ tool_calls,
607
+ ${nullableColumn(messageColumns, 'tool_name')},
608
+ ${nullableColumn(messageColumns, 'timestamp')}
609
+ FROM messages
610
+ WHERE session_id = ?
611
+ ${orderBy}`, [decoded.sessionId]);
612
+ const inputTokens = row.input_tokens ?? 0;
613
+ const outputTokens = row.output_tokens ?? 0;
614
+ const cacheReadTokens = row.cache_read_tokens ?? 0;
615
+ const cacheWriteTokens = row.cache_write_tokens ?? 0;
616
+ const reasoningTokens = row.reasoning_tokens ?? 0;
617
+ const tokens = {
618
+ inputTokens,
619
+ outputTokens,
620
+ cacheReadTokens,
621
+ cacheWriteTokens,
622
+ reasoningTokens,
623
+ };
624
+ if (tokenSum(tokens) === 0 && !existingCursor)
625
+ return;
626
+ const model = row.model ?? 'unknown';
627
+ const { tools, toolSequence, bashCommands } = collectTools(messages);
628
+ const workspace = resolveHermesWorkspace(row, messages);
629
+ const timestamp = parseTimestamp(row.started_at);
630
+ const baselineKey = hermesBaselineKey(profile, row.id);
631
+ if (seenKeys.has(baselineKey))
632
+ return;
633
+ seenKeys.add(baselineKey);
634
+ const identity = workspace.projectPath
635
+ ? githubOwnerRepoFromRoot(workspace.projectPath)
636
+ : null;
637
+ const prLinks = extractGithubPullUrls(messages
638
+ .filter(msg => msg.role === 'assistant' || msg.role === 'user')
639
+ .map(msg => msg.content), identity);
640
+ const cost = resolveHermesCost(row, model, tokens);
641
+ // Decided rule: a session's cost delta lands on the day it is OBSERVED
642
+ // (`observedAt`), not the day the session started. A mid-session price
643
+ // change therefore shows up on the observation day, and a sealed day is
644
+ // never rewritten to reprice it.
645
+ const cursor = await recordHermesSnapshot({
646
+ profile,
647
+ sessionId: row.id,
648
+ startedAt: timestamp || hermesLedgerNow().toISOString(),
649
+ observedAt: hermesLedgerNow().toISOString(),
650
+ tokens,
651
+ costUSD: cost.costUSD,
652
+ costBasis: cost.costBasis,
653
+ });
654
+ for (const observation of cursor.observations) {
655
+ if (observation.index > 0)
656
+ seenKeys.add(hermesObservationKey(profile, row.id, observation.index));
657
+ }
658
+ result = {
659
+ calls: cursor.observations.map(observation => observationToCall(observation, {
660
+ profile,
661
+ sessionId: row.id,
662
+ model,
663
+ tools,
664
+ bashCommands,
665
+ toolSequence,
666
+ userMessage: firstUserMessage(messages),
667
+ project: workspace.project,
668
+ projectPath: workspace.projectPath,
669
+ workingDirectory: workspace.workingDirectory,
670
+ prLinks,
671
+ costIsEstimated: cost.costIsEstimated,
672
+ route: routeFromProviderField(row.billing_provider)?.id,
673
+ })),
674
+ };
675
+ for (const helper of readHelperUsage(db, row.id)) {
676
+ const helperId = `${row.id}#helper:${[helper.task, helper.model, helper.billing_provider, helper.billing_base_url, helper.billing_mode].join('|')}`;
677
+ const helperKey = hermesBaselineKey(profile, helperId);
678
+ if (seenKeys.has(helperKey))
679
+ continue;
680
+ seenKeys.add(helperKey);
681
+ const helperCost = resolveHermesCost(helper, helper.model, helper);
682
+ const helperCursor = await recordHermesSnapshot({
683
+ profile,
684
+ sessionId: helperId,
685
+ startedAt: parseTimestamp(helper.first_seen) || timestamp || hermesLedgerNow().toISOString(),
686
+ observedAt: hermesLedgerNow().toISOString(),
687
+ tokens: {
688
+ inputTokens: helper.inputTokens,
689
+ outputTokens: helper.outputTokens,
690
+ cacheReadTokens: helper.cacheReadTokens,
691
+ cacheWriteTokens: helper.cacheWriteTokens,
692
+ reasoningTokens: helper.reasoningTokens,
693
+ },
694
+ costUSD: helperCost.costUSD,
695
+ costBasis: helperCost.costBasis,
696
+ });
697
+ for (const observation of helperCursor.observations) {
698
+ if (observation.index > 0)
699
+ seenKeys.add(hermesObservationKey(profile, helperId, observation.index));
700
+ result.calls.push({
701
+ ...observationToCall(observation, {
702
+ profile,
703
+ sessionId: helperId,
704
+ model: helper.model,
705
+ tools: [],
706
+ bashCommands: [],
707
+ toolSequence: [],
708
+ userMessage: '',
709
+ project: workspace.project,
710
+ projectPath: workspace.projectPath,
711
+ workingDirectory: workspace.workingDirectory,
712
+ costIsEstimated: helperCost.costIsEstimated,
713
+ route: routeFromProviderField(helper.billing_provider)?.id,
714
+ }),
715
+ sessionId: row.id,
716
+ supplementaryAccounting: true,
717
+ });
718
+ }
719
+ }
720
+ }
721
+ }
722
+ catch (err) {
723
+ // A transient lock on the live state.db, or a ledger publication
724
+ // failure, must propagate so the caller retries — not get swallowed
725
+ // into an empty (negatively cached) result.
726
+ if (isSqliteBusyError(err) || isHermesLedgerPublicationError(err))
727
+ throw err;
728
+ const detail = err instanceof Error ? err.message : err;
729
+ process.stderr.write(`codeburn: error querying Hermes database: ${detail}\n`);
730
+ return;
731
+ }
732
+ finally {
733
+ db.close();
734
+ }
735
+ if (result) {
736
+ for (const call of result.calls)
737
+ yield call;
738
+ }
739
+ },
740
+ };
741
+ }
742
+ export function createHermesProvider(hermesHomeOverride) {
743
+ const hermesHome = getHermesHome(hermesHomeOverride);
744
+ return {
745
+ name: 'hermes',
746
+ displayName: 'Hermes Agent',
747
+ modelDisplayName(model) {
748
+ return getShortModelName(model);
749
+ },
750
+ toolDisplayName(rawTool) {
751
+ return mapToolName(rawTool);
752
+ },
753
+ async probeRoots() {
754
+ return [{ path: hermesHome, label: 'home' }];
755
+ },
756
+ async discoverSessions() {
757
+ if (!isSqliteAvailable())
758
+ return [];
759
+ const dbs = await findStateDbs(hermesHome);
760
+ const sessions = [];
761
+ for (const { dbPath, profile } of dbs) {
762
+ sessions.push(...await discoverFromDb(dbPath, profile));
763
+ }
764
+ return sessions;
765
+ },
766
+ createSessionParser(source, seenKeys) {
767
+ return createParser(source, seenKeys, hermesHome);
768
+ },
769
+ };
770
+ }
771
+ export const hermes = createHermesProvider();