llmtop 0.0.0-stage → 0.1.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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +259 -2
  3. package/bin/llmtop.mjs +101 -0
  4. package/dashboard/dist/apple-touch-icon.png +0 -0
  5. package/dashboard/dist/assets/index-BVbAwMVB.js +9 -0
  6. package/dashboard/dist/assets/index-Cp7Swcz5.css +1 -0
  7. package/dashboard/dist/assets/llmtop-lockup-DtFPJmhv.svg +1 -0
  8. package/dashboard/dist/assets/llmtop-lockup-reversed-D9OmQIVU.svg +1 -0
  9. package/dashboard/dist/favicon.ico +0 -0
  10. package/dashboard/dist/favicon.svg +1 -0
  11. package/dashboard/dist/index.html +19 -0
  12. package/dashboard/dist/llmtop-mark-192.png +0 -0
  13. package/dashboard/dist/llmtop-mark-512.png +0 -0
  14. package/dashboard/dist/site.webmanifest +11 -0
  15. package/dashboard/src/App.tsx +213 -0
  16. package/dashboard/src/controls/DateRange.tsx +108 -0
  17. package/dashboard/src/controls/Disclosure.tsx +15 -0
  18. package/dashboard/src/controls/Search.tsx +18 -0
  19. package/dashboard/src/controls/Select.tsx +48 -0
  20. package/dashboard/src/controls/popover.tsx +31 -0
  21. package/dashboard/src/dash.ts +23 -0
  22. package/dashboard/src/extra.test.ts +9 -0
  23. package/dashboard/src/extra.ts +16 -0
  24. package/dashboard/src/format.ts +29 -0
  25. package/dashboard/src/i18n.tsx +52 -0
  26. package/dashboard/src/index.ts +7 -0
  27. package/dashboard/src/main.tsx +7 -0
  28. package/dashboard/src/model.test.ts +110 -0
  29. package/dashboard/src/model.ts +255 -0
  30. package/dashboard/src/state.test.ts +48 -0
  31. package/dashboard/src/state.ts +61 -0
  32. package/dashboard/src/styles.css +401 -0
  33. package/dashboard/src/tip.ts +51 -0
  34. package/dashboard/src/treemap.test.ts +23 -0
  35. package/dashboard/src/treemap.ts +30 -0
  36. package/dashboard/src/ui.tsx +327 -0
  37. package/dashboard/src/views/Activity.tsx +177 -0
  38. package/dashboard/src/views/Context.tsx +183 -0
  39. package/dashboard/src/views/Models.tsx +155 -0
  40. package/dashboard/src/views/Overview.tsx +83 -0
  41. package/dashboard/src/views/Projects.tsx +116 -0
  42. package/dashboard/src/views/Sessions.tsx +54 -0
  43. package/dashboard/src/views/Subagents.tsx +102 -0
  44. package/docs/brand/README.md +91 -0
  45. package/docs/brand/brand.json +67 -0
  46. package/docs/brand/favicon.ico +0 -0
  47. package/docs/brand/png/apple-touch-icon.png +0 -0
  48. package/docs/brand/png/favicon-16.png +0 -0
  49. package/docs/brand/png/favicon-32.png +0 -0
  50. package/docs/brand/png/favicon-48.png +0 -0
  51. package/docs/brand/png/llmtop-lockup-reversed@2x.png +0 -0
  52. package/docs/brand/png/llmtop-lockup@2x.png +0 -0
  53. package/docs/brand/png/llmtop-mark-1024.png +0 -0
  54. package/docs/brand/png/llmtop-mark-192.png +0 -0
  55. package/docs/brand/png/llmtop-mark-512.png +0 -0
  56. package/docs/brand/png/llmtop-wordmark@2x.png +0 -0
  57. package/docs/brand/source/build_brand.py +173 -0
  58. package/docs/brand/svg/favicon.svg +1 -0
  59. package/docs/brand/svg/llmtop-glyph.svg +1 -0
  60. package/docs/brand/svg/llmtop-lockup-reversed.svg +1 -0
  61. package/docs/brand/svg/llmtop-lockup.svg +1 -0
  62. package/docs/brand/svg/llmtop-mark-light.svg +1 -0
  63. package/docs/brand/svg/llmtop-mark.svg +1 -0
  64. package/docs/brand/svg/llmtop-wordmark-reversed.svg +1 -0
  65. package/docs/brand/svg/llmtop-wordmark.svg +1 -0
  66. package/llmtop.config.example.json +10 -0
  67. package/package.json +71 -4
  68. package/prices.md +27 -0
  69. package/src/api.mjs +53 -0
  70. package/src/archive.mjs +142 -0
  71. package/src/config.mjs +55 -0
  72. package/src/context.mjs +151 -0
  73. package/src/dashboard.mjs +61 -0
  74. package/src/db.mjs +102 -0
  75. package/src/derive.mjs +346 -0
  76. package/src/effort.mjs +18 -0
  77. package/src/format.mjs +19 -0
  78. package/src/paths.mjs +82 -0
  79. package/src/prices-command.mjs +25 -0
  80. package/src/prices.mjs +146 -0
  81. package/src/providers/agy.mjs +438 -0
  82. package/src/providers/claude.mjs +274 -0
  83. package/src/providers/codex.mjs +589 -0
  84. package/src/providers/index.mjs +25 -0
  85. package/src/rebuilds.mjs +85 -0
  86. package/src/scan.mjs +214 -0
  87. package/src/serve.mjs +44 -0
  88. package/src/show.mjs +20 -0
  89. package/src/usage-command.mjs +110 -0
  90. package/src/usage.mjs +388 -0
  91. package/src/zone.mjs +15 -0
package/src/derive.mjs ADDED
@@ -0,0 +1,346 @@
1
+ // Per-session values computed after every scan from the ingested rows. Cheap: one pass over sessions.
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { basename, dirname, join, resolve, sep } from "node:path";
5
+ import { repoFromUrl } from "./paths.mjs";
6
+ import { markRebuilds } from "./rebuilds.mjs";
7
+ import { zoner } from "./zone.mjs";
8
+ import { missOf, priceAt, readPrices, requestCost, usageCost } from "./prices.mjs";
9
+
10
+ const IGNORE_GIT_ROOTS = new Set(["/", homedir(), tmpdir(), "/tmp", "/var/tmp"]);
11
+ const GENERIC_DIR_RE = /^(?:repo|src|worktree|checkout|tmp|temp|home|code|docs|tests|test|scripts|tools)$/i;
12
+ const validRepoName = (n) => Boolean(n && n.length >= 3 && !n.startsWith(".") && !GENERIC_DIR_RE.test(n));
13
+ const inTmpDir = (p) => p.startsWith(tmpdir() + sep) || p.startsWith("/tmp/") || p.startsWith("/var/tmp/");
14
+
15
+ function manifestNameOf(dir) {
16
+ try {
17
+ const pkg = join(dir, "package.json");
18
+ if (existsSync(pkg)) {
19
+ const n = JSON.parse(readFileSync(pkg, "utf8"))?.name;
20
+ if (typeof n === "string" && n.trim()) return n.trim().replace(/^@[^/]+\//, "");
21
+ }
22
+ const py = join(dir, "pyproject.toml");
23
+ if (existsSync(py)) {
24
+ const text = readFileSync(py, "utf8");
25
+ const sec = text.match(/\[(?:project|tool\.poetry)\]([\s\S]*?)(?:\n\[|$)/);
26
+ const m = (sec ? sec[1] : text).match(/^\s*name\s*=\s*["']([^"']+)["']/m);
27
+ if (m) return m[1].trim();
28
+ }
29
+ const cargo = join(dir, "Cargo.toml");
30
+ if (existsSync(cargo)) {
31
+ const text = readFileSync(cargo, "utf8");
32
+ const sec = text.match(/\[package\]([\s\S]*?)(?:\n\[|$)/);
33
+ const m = sec?.[1].match(/^\s*name\s*=\s*["']([^"']+)["']/m);
34
+ if (m) return m[1].trim();
35
+ }
36
+ const gomod = join(dir, "go.mod");
37
+ if (existsSync(gomod)) {
38
+ const m = readFileSync(gomod, "utf8").match(/^\s*module\s+(\S+)/m);
39
+ if (m) return basename(m[1].replace(/\/v\d+$/, ""));
40
+ }
41
+ } catch { /* ignore unreadable manifest */ }
42
+ return null;
43
+ }
44
+
45
+ function originNameOf(gitDir, depth = 0) {
46
+ if (depth >= 3) return null;
47
+ const cfg = join(gitDir, "config");
48
+ if (!existsSync(cfg)) return null;
49
+ try {
50
+ const text = readFileSync(cfg, "utf8");
51
+ const m = text.match(/\[remote "origin"\][\s\S]*?^\s*url\s*=\s*(.+)$/m) ?? text.match(/\[remote "[^"]+"\][\s\S]*?^\s*url\s*=\s*(.+)$/m);
52
+ if (!m) return null;
53
+ const url = m[1].trim();
54
+ if (url.startsWith("/") && existsSync(url)) {
55
+ const clean = url.replace(/\/+$/, "").replace(/\.git$/i, "");
56
+ if (inTmpDir(clean) || GENERIC_DIR_RE.test(basename(clean))) {
57
+ return resolveGitDirName(clean, join(clean, ".git"), depth + 1);
58
+ }
59
+ return basename(clean);
60
+ }
61
+ return repoFromUrl(url);
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ function resolveGitDirName(dir, gitDir, depth = 0) {
68
+ const base = basename(dir);
69
+ if (inTmpDir(dir) || GENERIC_DIR_RE.test(base)) {
70
+ const orig = originNameOf(gitDir, depth);
71
+ if (orig && !GENERIC_DIR_RE.test(orig)) return orig;
72
+ const man = manifestNameOf(dir);
73
+ if (man && !GENERIC_DIR_RE.test(man)) return man;
74
+ }
75
+ return base;
76
+ }
77
+
78
+ function gitRepoOf(p) {
79
+ if (!p || !existsSync(p)) return null;
80
+ let dir = p;
81
+ try {
82
+ if (!statSync(dir).isDirectory()) dir = dirname(dir);
83
+ } catch {
84
+ return null;
85
+ }
86
+ for (; ; dir = dirname(dir)) {
87
+ if (!IGNORE_GIT_ROOTS.has(dir)) {
88
+ const g = join(dir, ".git");
89
+ if (existsSync(g)) {
90
+ try {
91
+ const st = statSync(g);
92
+ if (st.isFile()) {
93
+ const m = readFileSync(g, "utf8").match(/^gitdir:\s*(.+)$/m);
94
+ if (m) {
95
+ const gd = resolve(dir, m[1].trim());
96
+ const wt = gd.match(/^(.*)[/\\]\.git[/\\]worktrees[/\\]/);
97
+ if (wt) {
98
+ const mainRoot = wt[1];
99
+ let name = resolveGitDirName(mainRoot, join(mainRoot, ".git"));
100
+ if (GENERIC_DIR_RE.test(name)) name = manifestNameOf(dir) || name;
101
+ return { root: mainRoot, name };
102
+ }
103
+ }
104
+ } else if (st.isDirectory()) {
105
+ return { root: dir, name: resolveGitDirName(dir, g) };
106
+ }
107
+ } catch { /* unreadable .git metadata; fall back to dir name */ }
108
+ return { root: dir, name: basename(dir) };
109
+ }
110
+ }
111
+ if (dirname(dir) === dir) break;
112
+ }
113
+ return null;
114
+ }
115
+
116
+ // The nearest directory at or above cwd that holds .git (skipping root/home/tmp, resolving worktrees/temp clones), else cwd's own name.
117
+ // onDisk tells whether cwd still exists, so a session whose folder is gone keeps the project it had without climbing parent repos.
118
+ export function projectOf(cwd) {
119
+ if (!cwd) return null;
120
+ const onDisk = existsSync(cwd);
121
+ if (onDisk) {
122
+ const g = gitRepoOf(cwd);
123
+ if (g) return { name: g.name, onDisk: true };
124
+ }
125
+ return { name: basename(cwd) || "(no project)", onDisk };
126
+ }
127
+
128
+ function matchSeg(seg, skip, knownRepos, sortedKnown) {
129
+ if (!seg || skip.has(seg)) return null;
130
+ if (knownRepos.has(seg)) return seg;
131
+ for (const k of sortedKnown) {
132
+ if (skip.has(k)) continue;
133
+ if (seg.startsWith(`${k}.`) || seg.startsWith(`${k}-`) || seg.startsWith(`${k}_`)) return k;
134
+ }
135
+ return null;
136
+ }
137
+
138
+ function matchFallbackPath(dir, cwdRepo, knownRepos, sortedKnown) {
139
+ if (!dir) return null;
140
+ const skip = new Set();
141
+ let scanPath = dir;
142
+ if (cwdRepo) {
143
+ for (const seg of cwdRepo.root.split(/[/\\]+/).filter(Boolean)) skip.add(seg);
144
+ skip.add(cwdRepo.name);
145
+ if (dir.startsWith(cwdRepo.root + sep)) scanPath = dir.slice(cwdRepo.root.length + 1);
146
+ }
147
+ const parts = scanPath.split(/[/\\]+/).filter(Boolean);
148
+ for (let i = parts.length - 1; i >= 0; i--) {
149
+ const hit = matchSeg(parts[i], skip, knownRepos, sortedKnown);
150
+ if (hit) return hit;
151
+ }
152
+ return null;
153
+ }
154
+
155
+ function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, knownRepos, sortedKnown) {
156
+ const cwdRepo = cwd ? gitRepoOf(cwd) : null;
157
+ const urlRepo = repoFromUrl(repoUrl);
158
+ const byRepo = new Map();
159
+ for (const [dir, [w, r]] of Object.entries(pathWeights ?? {})) {
160
+ let name = gitRepoOf(dir)?.name ?? null;
161
+ if (!name && (!existsSync(dir) || inTmpDir(dir))) name = matchFallbackPath(dir, cwdRepo, knownRepos, sortedKnown);
162
+ if (!name) continue;
163
+ const cur = byRepo.get(name) ?? { name, w: 0, r: 0 };
164
+ cur.w += w;
165
+ cur.r += r;
166
+ byRepo.set(name, cur);
167
+ }
168
+ const repos = [...byRepo.values()].sort((a, b) => (b.w - a.w) || ((b.w + b.r) - (a.w + a.r)));
169
+ const totalW = repos.reduce((n, x) => n + x.w, 0);
170
+ const totalR = repos.reduce((n, x) => n + x.r, 0);
171
+ const totalScore = totalW + totalR;
172
+ const cwdEntry = cwdRepo ? byRepo.get(cwdRepo.name) : null;
173
+ const cwdScore = (cwdEntry?.w ?? 0) + (cwdEntry?.r ?? 0);
174
+ const bestOther = repos.find((x) => !GENERIC_DIR_RE.test(x.name) && (!cwdRepo || x.name !== cwdRepo.name)) ?? null;
175
+
176
+ if (cwdRepo && bestOther) {
177
+ const otherScore = bestOther.w + bestOther.r;
178
+ if (bestOther.w > 0 && bestOther.w > (cwdEntry?.w ?? 0) && bestOther.w >= 0.5 * totalW) return bestOther.name;
179
+ if (totalW === 0 && bestOther.r >= 3 && bestOther.r > (cwdEntry?.r ?? 0) && bestOther.r >= 0.5 * totalR) return bestOther.name;
180
+ if (bestOther.r >= 5 && otherScore >= 2 * cwdScore && otherScore >= 0.5 * totalScore) return bestOther.name;
181
+ }
182
+ if (!cwdRepo && urlRepo) return urlRepo;
183
+ if (!cwdRepo && bestOther && (bestOther.w > 0 || bestOther.r >= 2)) return bestOther.name;
184
+ if (cwdRepo) {
185
+ if (GENERIC_DIR_RE.test(cwdRepo.name)) {
186
+ if (urlRepo && !GENERIC_DIR_RE.test(urlRepo)) return urlRepo;
187
+ if (bestOther) return bestOther.name;
188
+ }
189
+ return cwdRepo.name;
190
+ }
191
+ if (urlRepo) return urlRepo;
192
+ const p = projectOf(cwd);
193
+ if (p && !p.onDisk) {
194
+ const segHit = matchSeg(basename(cwd), new Set(), knownRepos, sortedKnown);
195
+ if (segHit) return segHit;
196
+ }
197
+ return p && !p.onDisk && existingProject ? existingProject : (p?.name ?? null);
198
+ }
199
+
200
+ const firstLine = (text) => text.split("\n").find((l) => l.trim())?.trim().slice(0, 80) ?? null;
201
+
202
+ export function derive(db, config) {
203
+ const files = db.prepare("SELECT id, provider, session_id, path, cwd, own_first first_ts, own_last last_ts FROM files WHERE kind = 'main'").all();
204
+ const existing = new Map(db.prepare("SELECT id, project FROM sessions").all().map((s) => [s.id, s.project]));
205
+ const titles = db.prepare("SELECT kind, title FROM titles WHERE file_id = ? ORDER BY line DESC");
206
+ const firstOwner = db.prepare("SELECT text FROM owner_messages WHERE session_id = ? AND kind = 'typed' ORDER BY ts, line LIMIT 1");
207
+ const lastCost = db.prepare("SELECT * FROM cost_states WHERE file_id = ? ORDER BY line DESC LIMIT 1");
208
+ const knownRepos = new Set();
209
+ for (const f of files) {
210
+ const g = f.cwd ? gitRepoOf(f.cwd) : null;
211
+ if (g && validRepoName(g.name)) knownRepos.add(g.name);
212
+ }
213
+ const sessionMeta = new Map();
214
+ for (const r of db.prepare(`SELECT f.session_id, f.kind, m.api_ms, m.tool_ms, m.lines_added, m.lines_removed, m.repo_url, m.target_paths
215
+ FROM file_meta m JOIN files f ON f.id = m.file_id`).all()) {
216
+ let cur = sessionMeta.get(r.session_id);
217
+ if (!cur) {
218
+ cur = { api_ms: null, tool_ms: null, lines_added: null, lines_removed: null, repo_url: null, pathWeights: {} };
219
+ sessionMeta.set(r.session_id, cur);
220
+ }
221
+ if (r.api_ms !== null) cur.api_ms = (cur.api_ms ?? 0) + r.api_ms;
222
+ if (r.tool_ms !== null) cur.tool_ms = (cur.tool_ms ?? 0) + r.tool_ms;
223
+ if (r.lines_added !== null) cur.lines_added = (cur.lines_added ?? 0) + r.lines_added;
224
+ if (r.lines_removed !== null) cur.lines_removed = (cur.lines_removed ?? 0) + r.lines_removed;
225
+ if (r.repo_url) {
226
+ if (r.kind === "main" || !cur.repo_url) cur.repo_url = r.repo_url;
227
+ const u = repoFromUrl(r.repo_url);
228
+ if (validRepoName(u)) knownRepos.add(u);
229
+ }
230
+ if (r.target_paths) {
231
+ try {
232
+ for (const [dir, pair] of Object.entries(JSON.parse(r.target_paths))) {
233
+ if (!Array.isArray(pair)) continue;
234
+ const prev = cur.pathWeights[dir] ?? (cur.pathWeights[dir] = [0, 0]);
235
+ prev[0] += Number(pair[0]) || 0;
236
+ prev[1] += Number(pair[1]) || 0;
237
+ const g = gitRepoOf(dir);
238
+ if (g && validRepoName(g.name)) knownRepos.add(g.name);
239
+ }
240
+ } catch { /* ignore malformed json */ }
241
+ }
242
+ }
243
+ const sortedKnown = [...knownRepos].sort((a, b) => b.length - a.length);
244
+ // The session this file continues or forks: of the sessions owning the requests it repeats, the latest to start.
245
+ // CROSS JOIN keeps the order from the file's few repeats; left to the planner it scanned every file and request per file.
246
+ const predecessor = db.prepare(`SELECT f.session_id id FROM repeats p CROSS JOIN requests q ON q.message_id = p.message_id
247
+ CROSS JOIN files f ON f.kind = 'main' AND f.session_id = q.session_id
248
+ WHERE p.file_id = ? AND q.session_id <> ? GROUP BY f.id ORDER BY f.own_first DESC LIMIT 1`);
249
+ const requestsOf = db.prepare("SELECT model, day, input, output, cache_read, cache_write, cache_write_1h FROM requests WHERE session_id = ?");
250
+ const prices = readPrices(config).rows;
251
+ const zone = zoner(config.timeZone);
252
+ const upsert = db.prepare(`INSERT INTO sessions(id, provider, slug, cwd, project, title, first_ts, last_ts, cost, cost_incomplete, cost_estimated, price_check,
253
+ api_ms, tool_ms, lines_added, lines_removed, carried_from, model_cost, model_tokens)
254
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
255
+ ON CONFLICT(id) DO UPDATE SET provider = excluded.provider, slug = excluded.slug, cwd = excluded.cwd, project = excluded.project, title = excluded.title,
256
+ first_ts = excluded.first_ts, last_ts = excluded.last_ts, cost = excluded.cost, cost_incomplete = excluded.cost_incomplete,
257
+ cost_estimated = excluded.cost_estimated, price_check = excluded.price_check,
258
+ api_ms = excluded.api_ms, tool_ms = excluded.tool_ms, lines_added = excluded.lines_added, lines_removed = excluded.lines_removed,
259
+ carried_from = excluded.carried_from, model_cost = excluded.model_cost, model_tokens = excluded.model_tokens`);
260
+
261
+ const raw = new Map();
262
+ for (const f of files) {
263
+ const c = lastCost.get(f.id);
264
+ raw.set(f.session_id, c ? { ...c, models: JSON.parse(c.model_usage) } : null);
265
+ }
266
+
267
+ db.exec("BEGIN");
268
+ try {
269
+ for (const f of files) {
270
+ const ms = sessionMeta.get(f.session_id);
271
+ const project = resolveSessionProject(f.cwd, ms?.repo_url ?? null, ms?.pathWeights ?? null, existing.get(f.session_id), knownRepos, sortedKnown);
272
+ const t = titles.all(f.id);
273
+ const title = t.find((x) => x.kind === "custom")?.title ?? t.find((x) => x.kind === "ai")?.title ?? (firstOwner.get(f.session_id)?.text ? firstLine(firstOwner.get(f.session_id).text) : null);
274
+
275
+ const c = raw.get(f.session_id);
276
+ let cost = null;
277
+ let models = null;
278
+ let tokens = null;
279
+ let estimated = null;
280
+ let check = null;
281
+ let api = c?.api_ms ?? ms?.api_ms ?? null;
282
+ let tool = c?.tool_ms ?? ms?.tool_ms ?? null;
283
+ let added = c?.lines_added ?? ms?.lines_added ?? null;
284
+ let removed = c?.lines_removed ?? ms?.lines_removed ?? null;
285
+ let carriedFrom = null;
286
+ let prev = null;
287
+ if (c) {
288
+ models = { ...c.models };
289
+ // A host record that started with the earlier session's record is cumulative and holds all of it;
290
+ // a fork or a resume in a new process starts its own record shortly before its first own line.
291
+ const earlier = predecessor.get(f.id, f.session_id);
292
+ prev = earlier ? raw.get(earlier.id) : null;
293
+ if (prev && c.start_ms !== null && prev.start_ms !== null && c.start_ms <= prev.start_ms + 1000) {
294
+ carriedFrom = earlier.id;
295
+ const less = (v, w) => (v === null ? null : Math.max(0, v - (w ?? 0)));
296
+ for (const [m, u] of Object.entries(models)) {
297
+ const was = prev.models[m] ?? {};
298
+ models[m] = { ...u, ...Object.fromEntries(["cost", "input", "output", "read", "write", "w5", "w1", "web"].map((k) => [k, less(u[k], was[k])])) };
299
+ }
300
+ api = less(api, prev.api_ms);
301
+ tool = less(tool, prev.tool_ms);
302
+ added = less(added, prev.lines_added);
303
+ removed = less(removed, prev.lines_removed);
304
+ }
305
+ // Each model's figure against the price table, for a record the host marked complete.
306
+ const day = f.first_ts ? zone(f.first_ts).day : null;
307
+ if (!c.incomplete && day) {
308
+ check = {};
309
+ for (const [m, u] of Object.entries(models)) {
310
+ if (!u.cost) continue;
311
+ const row = priceAt(prices, m, day);
312
+ if (u.web) check[m] = { day, skipped: "web search" };
313
+ else if (!row) check[m] = { day, skipped: "no price" };
314
+ else check[m] = { day, host: u.cost, ...usageCost(row.p, u), miss: missOf(u.cost, usageCost(row.p, u)) };
315
+ }
316
+ }
317
+ const known = Object.values(models).map((u) => u.cost).filter((v) => v !== null);
318
+ if (known.length) cost = known.reduce((a, b) => a + b, 0);
319
+ // The tokens the host priced per model, to split a cost the transcript holds no request for.
320
+ tokens = Object.fromEntries(Object.entries(models).map(([m, u]) => [m, { input: u.input, output: u.output, read: u.read, write: u.write, w5: u.w5, w1: u.w1, split: u.split, web: u.web }]));
321
+ models = Object.fromEntries(Object.entries(models).map(([m, u]) => [m, u.cost]));
322
+ if (!known.length && c.cost !== null) {
323
+ cost = carriedFrom ? Math.max(0, c.cost - (prev.cost ?? 0)) : c.cost;
324
+ models = { unknown: cost };
325
+ }
326
+ } else {
327
+ // No host record: the requests priced on their day, marked as estimated; unknown if a model has no price.
328
+ const reqs = requestsOf.all(f.session_id);
329
+ const rows = reqs.map((r) => [r, priceAt(prices, r.model, r.day)]);
330
+ if (reqs.length && rows.every(([, row]) => row)) {
331
+ models = {};
332
+ for (const [r, row] of rows) models[r.model] = (models[r.model] ?? 0) + requestCost(row.p, r);
333
+ cost = Object.values(models).reduce((a, b) => a + b, 0);
334
+ estimated = 1;
335
+ }
336
+ }
337
+ upsert.run(f.session_id, f.provider, f.path.split(sep)[0], f.cwd, project, title, f.first_ts, f.last_ts, cost,
338
+ c ? (c.incomplete ? 1 : 0) : null, estimated, check ? JSON.stringify(check) : null, api, tool, added, removed, carriedFrom, models ? JSON.stringify(models) : null, tokens ? JSON.stringify(tokens) : null);
339
+ }
340
+ db.exec("COMMIT");
341
+ } catch (err) {
342
+ db.exec("ROLLBACK");
343
+ throw err;
344
+ }
345
+ markRebuilds(db, prices);
346
+ }
package/src/effort.mjs ADDED
@@ -0,0 +1,18 @@
1
+ // Each session's main-transcript requests in time order, cut wherever the effort level changes.
2
+ export function effortRuns(db) {
3
+ const out = new Map();
4
+ for (const r of db.prepare("SELECT session_id, coalesce(effort, '') effort FROM requests WHERE is_sub = 0 ORDER BY session_id, ts, line").iterate()) {
5
+ const list = out.get(r.session_id) ?? out.set(r.session_id, []).get(r.session_id);
6
+ const last = list[list.length - 1];
7
+ if (last?.level === (r.effort || "unknown")) last.requests++;
8
+ else list.push({ level: r.effort || "unknown", requests: 1 });
9
+ }
10
+ return out;
11
+ }
12
+
13
+ // The level that served most of a session's main requests.
14
+ export function mainLevel(runs = []) {
15
+ const n = new Map();
16
+ for (const r of runs) n.set(r.level, (n.get(r.level) ?? 0) + r.requests);
17
+ return [...n].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
18
+ }
package/src/format.mjs ADDED
@@ -0,0 +1,19 @@
1
+ // Plain text tables for the terminal; --json prints the same rows instead.
2
+ export const int = (n) => (n === null || n === undefined ? "—" : Math.round(n).toLocaleString("en-US"));
3
+ export const usd = (n) => (n === null || n === undefined ? "unknown" : `$${n.toFixed(2)}`);
4
+ export const pct = (n) => (n === null || n === undefined ? "—" : `${(n * 100).toFixed(1)}%`);
5
+ export const minutes = (m) => (m >= 60 ? `${Math.floor(m / 60)}h${String(Math.round(m % 60)).padStart(2, "0")}m` : `${Math.round(m)}m`);
6
+
7
+ // "YYYY-MM-DD HH:MM" of an ISO instant in the given time zone.
8
+ export function localTime(timeZone) {
9
+ const f = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
10
+ return (iso) => (iso ? f.format(new Date(iso)) : "");
11
+ }
12
+
13
+ // columns: [header, (row) => text, "r" for right-aligned]
14
+ export function table(rows, columns) {
15
+ const cells = [columns.map(([h]) => h), ...rows.map((r) => columns.map(([, f]) => String(f(r) ?? "")))];
16
+ const width = columns.map((_, i) => Math.max(...cells.map((c) => [...c[i]].length)));
17
+ const pad = (text, i) => (columns[i][2] === "r" ? text.padStart(width[i]) : text.padEnd(width[i]));
18
+ return cells.map((c) => c.map(pad).join(" ").trimEnd()).join("\n");
19
+ }
package/src/paths.mjs ADDED
@@ -0,0 +1,82 @@
1
+ // Machine-independent path normalization, Git URL parsing, and touched-directory weighting for project resolution.
2
+ import { dirname, resolve } from "node:path";
3
+
4
+ const IGNORE_PATH_RE = /(?:^|[/\\])\.(?:codex|claude|gemini|agents)(?:[/\\]|$)|^\/(?:proc|sys|etc)(?:\/|$)|^\/dev(?:\/(?!shm(?:\/|$))|$)/i;
5
+
6
+ export function isAbsPath(p) {
7
+ return typeof p === "string" && (p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p));
8
+ }
9
+
10
+ const GIT_C_RE = /\bgit\s+-C\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|)`"']+))/g;
11
+ const CD_DIR_RE = /(?:^|[;&|(\n])\s*cd\s+(?:--?\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|)`"']+))/g;
12
+
13
+ export function extractCommandDirs(cmdText, baseCwd = null) {
14
+ if (typeof cmdText !== "string" || !cmdText) return [];
15
+ const seen = new Set();
16
+ const push = (raw) => {
17
+ if (!raw) return;
18
+ const val = raw.trim();
19
+ if (!val || val === "-" || val.startsWith("~") || val.startsWith("$") || val.startsWith("-")) return;
20
+ const abs = isAbsPath(val) ? val : (isAbsPath(baseCwd) ? resolve(baseCwd, val) : null);
21
+ if (!abs || IGNORE_PATH_RE.test(abs)) return;
22
+ const dir = stripTrailing(abs);
23
+ if (isAbsPath(dir)) seen.add(dir);
24
+ };
25
+ for (const re of [GIT_C_RE, CD_DIR_RE]) {
26
+ re.lastIndex = 0;
27
+ let m;
28
+ while ((m = re.exec(cmdText)) !== null) push(m[1] ?? m[2] ?? m[3]);
29
+ }
30
+ return [...seen];
31
+ }
32
+
33
+ export function repoFromUrl(url) {
34
+ if (!url || typeof url !== "string") return null;
35
+ const clean = url.trim().replace(/\/+$/, "").replace(/\.git$/i, "");
36
+ const m = clean.match(/[:/]([^/:]+)$/);
37
+ return m ? m[1] : null;
38
+ }
39
+
40
+ const stripTrailing = (p) => (p.length > 1 ? p.replace(/[/\\]+$/, "") || "/" : p);
41
+
42
+ export function createPathTracker(initialJson) {
43
+ const counts = new Map();
44
+ if (initialJson) {
45
+ try {
46
+ const obj = JSON.parse(initialJson);
47
+ if (obj && typeof obj === "object") {
48
+ for (const [k, v] of Object.entries(obj)) {
49
+ if (Array.isArray(v) && v.length >= 2) counts.set(k, [Number(v[0]) || 0, Number(v[1]) || 0]);
50
+ }
51
+ }
52
+ } catch { /* ignore malformed saved counts */ }
53
+ }
54
+ let ops = 0;
55
+
56
+ return {
57
+ add(rawPath, { isFile = false, write = false, baseCwd = null } = {}) {
58
+ if (typeof rawPath !== "string" || !rawPath) return false;
59
+ let abs = rawPath.trim();
60
+ if (!isAbsPath(abs)) {
61
+ if (!isAbsPath(baseCwd)) return false;
62
+ abs = resolve(baseCwd, abs);
63
+ }
64
+ const dir = stripTrailing(isFile ? dirname(abs) : abs);
65
+ if (!isAbsPath(dir) || IGNORE_PATH_RE.test(dir)) return false;
66
+ const isNew = !counts.has(dir);
67
+ const cur = counts.get(dir) ?? [0, 0];
68
+ if (write) cur[0] += 3;
69
+ else cur[1] += 1;
70
+ counts.set(dir, cur);
71
+ ops++;
72
+ return isNew || write || ops <= 15 || ops % 10 === 0;
73
+ },
74
+ toJSON() {
75
+ if (!counts.size) return null;
76
+ const top = [...counts.entries()]
77
+ .sort((a, b) => (b[1][0] - a[1][0]) || ((b[1][0] + b[1][1]) - (a[1][0] + a[1][1])))
78
+ .slice(0, 32);
79
+ return JSON.stringify(Object.fromEntries(top));
80
+ },
81
+ };
82
+ }
@@ -0,0 +1,25 @@
1
+ import { readDb } from "./db.mjs";
2
+ import { int, table } from "./format.mjs";
3
+ import { pricesView } from "./prices.mjs";
4
+
5
+ // The `prices` command: the table, the check per model and the fitted prices.
6
+ export function pricesCommand({ config, options, out }) {
7
+ const db = readDb(config.database);
8
+ const v = pricesView(db, config);
9
+ db.close();
10
+ if (options.json) out.write(`${JSON.stringify(v, null, 1)}\n`);
11
+ else {
12
+ const n = (x) => (x === null ? "—" : Number(x.toPrecision(4)).toString());
13
+ const kinds = ["input", "output", "read", "write 5m", "write 1h"];
14
+ const lines = ["price rows (USD per million tokens)", table(v.rows, [["model", (r) => r.model], ["from", (r) => r.from], ...kinds.map((h, i) => [h, (r) => n(r.p[i]), "r"])]), ""];
15
+ lines.push("check against the host's cost records");
16
+ lines.push(table(v.report, [["model", (m) => m.model], ["checked", (m) => int(m.checked), "r"], ["over 1%", (m) => int(m.misses.length), "r"], ["first miss", (m) => m.since ?? "—"], ["not checked", (m) => Object.entries(m.skipped).map(([k, c]) => `${c} ${k}`).join(", ") || "—"]]));
17
+ for (const m of v.report) for (const x of m.misses) lines.push(` ${m.model} ${x.id.slice(0, 8)} ${x.day} host $${x.host.toFixed(2)} priced $${x.lo.toFixed(2)}${x.hi > x.lo + 0.005 ? `-${x.hi.toFixed(2)}` : ""} (${(x.miss * 100).toFixed(1)}%) ${x.title ?? ""}`);
18
+ if (v.unpriced.length) lines.push("", `no price row: ${v.unpriced.map((r) => `${r.model} (${int(r.n)} requests, ${r.first} to ${r.last})`).join(", ")}; their cost is spread by output tokens`);
19
+ lines.push("", "prices that fit the host's records");
20
+ lines.push(table(v.fits, [["model", (f) => f.model], ["sessions", (f) => int(f.sessions), "r"], ...kinds.map((h, i) => [h, (f) => (f.fit ? n(f.fit.p[i]) : ""), "r"]), ["worst miss", (f) => (f.fit ? `${(f.fit.worst * 100).toFixed(2)}%` : "too few sessions")]]));
21
+ out.write(`${lines.join("\n")}\n`);
22
+ }
23
+ for (const e of v.errors) process.stderr.write(`${e}\n`);
24
+ return v.errors.length ? 1 : 0;
25
+ }
package/src/prices.mjs ADDED
@@ -0,0 +1,146 @@
1
+ // The price table in prices.md: USD per million tokens per model, each row in force from its date.
2
+ // It weighs requests to spread the host's cost, estimates a session the host left without a cost record,
3
+ // and checks the host's figures. It is never the source of a cost the host recorded.
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { basename } from "node:path";
6
+
7
+ export const PRICE_COLUMNS = ["model", "from", "input", "output", "cache read", "cache write 5m", "cache write 1h"];
8
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
9
+
10
+ export function readPrices(config) {
11
+ const path = basename(config.prices);
12
+ const rows = [], errors = [];
13
+ if (!existsSync(config.prices)) return { rows, errors };
14
+ let header = null;
15
+ readFileSync(config.prices, "utf8").split("\n").forEach((line, i) => {
16
+ if (!line.trim().startsWith("|")) return;
17
+ const cells = line.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim());
18
+ if (!header) {
19
+ header = cells;
20
+ if (cells.join("|") !== PRICE_COLUMNS.join("|")) errors.push(`${path}:${i + 1}: expected the columns ${PRICE_COLUMNS.join(", ")}`);
21
+ return;
22
+ }
23
+ if (cells.every((c) => /^:?-+:?$/.test(c))) return;
24
+ const [model, from, ...nums] = cells;
25
+ const p = nums.map(Number);
26
+ if (cells.length !== PRICE_COLUMNS.length || !model || !DAY.test(from) || nums.some((n) => n === "") || p.some((n) => !Number.isFinite(n) || n < 0)) {
27
+ errors.push(`${path}:${i + 1}: expected a model id, a YYYY-MM-DD date and five prices, got: ${line.trim()}`);
28
+ return;
29
+ }
30
+ rows.push({ model, from, p });
31
+ });
32
+ return { rows, errors };
33
+ }
34
+
35
+ // The row in force for a model id on a local day; strips context suffixes, effort suffixes and date snapshots.
36
+ export function priceAt(rows, model, day) {
37
+ const noCtx = model.replace(/\[.*\]$/, "");
38
+ const noEff = noCtx.replace(/-(?:low|medium|high|xhigh|max)$/, "");
39
+ const noDate = noCtx.replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, "");
40
+ const bare = noEff.replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, "");
41
+ for (const id of new Set([model, noCtx, noEff, noDate, bare])) {
42
+ let hit = null;
43
+ for (const r of rows) if (r.model === id && r.from <= day && (!hit || r.from > hit.from)) hit = r;
44
+ if (hit) return hit;
45
+ if (rows.some((r) => r.model === id)) return null;
46
+ }
47
+ return null;
48
+ }
49
+
50
+ // One request priced: a cache write without the 5m/1h split (older hosts) is priced as a 1h write,
51
+ // which is what the host's own figures for those records match on this machine.
52
+ export const requestCost = (p, r) => costKinds(p, r).reduce((a, b) => a + b, 0);
53
+
54
+ // The same price in three parts: reading the context (input and cache reads), writing the cache, output.
55
+ export function costKinds(p, r) {
56
+ const w1 = r.cache_write_1h ?? r.cache_write;
57
+ const w5 = r.cache_write - w1;
58
+ return [(r.input * p[0] + r.cache_read * p[2]) / 1e6, (w5 * p[3] + w1 * p[4]) / 1e6, (r.output * p[1]) / 1e6];
59
+ }
60
+
61
+ // What the cache saved one request: its cache reads priced as input instead, less what its cache writes cost beyond input.
62
+ export function cacheSaving(p, r) {
63
+ const w1 = r.cache_write_1h ?? r.cache_write;
64
+ const w5 = r.cache_write - w1;
65
+ return (r.cache_read * (p[0] - p[2]) - w5 * (p[3] - p[0]) - w1 * (p[4] - p[0])) / 1e6;
66
+ }
67
+
68
+ // A host cost record's tokens for one model, priced and split as costKinds splits a request;
69
+ // writes the host did not split into 5m and 1h are priced as 1h writes.
70
+ export function usageKinds(p, u) {
71
+ const writes = u.split ? u.w5 * p[3] + u.w1 * p[4] : u.write * p[4];
72
+ return [(u.input * p[0] + u.read * p[2]) / 1e6, writes / 1e6, (u.output * p[1]) / 1e6];
73
+ }
74
+
75
+ // A host cost record's tokens for one model, priced; without the split, the range from all-5m to all-1h writes.
76
+ export function usageCost(p, u) {
77
+ const base = (u.input * p[0] + u.output * p[1] + u.read * p[2]) / 1e6;
78
+ if (u.split) return { lo: base + (u.w5 * p[3] + u.w1 * p[4]) / 1e6, hi: base + (u.w5 * p[3] + u.w1 * p[4]) / 1e6 };
79
+ return { lo: base + (u.write * Math.min(p[3], p[4])) / 1e6, hi: base + (u.write * Math.max(p[3], p[4])) / 1e6 };
80
+ }
81
+
82
+ // Relative distance of the host's figure from the priced range; 0 inside it.
83
+ export function missOf(host, { lo, hi }) {
84
+ if (host >= lo && host <= hi) return 0;
85
+ const near = host < lo ? lo : hi;
86
+ return Math.abs(host - near) / (host || 1);
87
+ }
88
+
89
+ // Least-squares prices per million tokens from host records: rows of [input, output, read, w5, w1] and cost.
90
+ // Only columns with tokens are solved; the rest are null. Needs at least two records per solved column.
91
+ export function fitPrices(records) {
92
+ const X = records.map((u) => [u.input, u.output, u.read, u.w5, u.w1].map((v) => v / 1e6));
93
+ const used = [0, 1, 2, 3, 4].filter((j) => X.some((x) => x[j] > 0));
94
+ if (records.length < 2 * used.length) return null;
95
+ const A = used.map(() => used.map(() => 0)), b = used.map(() => 0);
96
+ X.forEach((x, k) => used.forEach((i, a) => { b[a] += x[i] * records[k].cost; used.forEach((j, c) => { A[a][c] += x[i] * x[j]; }); }));
97
+ const n = used.length;
98
+ for (let i = 0; i < n; i++) {
99
+ let p = i;
100
+ for (let k = i + 1; k < n; k++) if (Math.abs(A[k][i]) > Math.abs(A[p][i])) p = k;
101
+ [A[i], A[p], b[i], b[p]] = [A[p], A[i], b[p], b[i]];
102
+ if (Math.abs(A[i][i]) < 1e-12) return null;
103
+ for (let k = i + 1; k < n; k++) { const f = A[k][i] / A[i][i]; for (let j = i; j < n; j++) A[k][j] -= f * A[i][j]; b[k] -= f * b[i]; }
104
+ }
105
+ const sol = new Array(n).fill(0);
106
+ for (let i = n - 1; i >= 0; i--) { let s = b[i]; for (let j = i + 1; j < n; j++) s -= A[i][j] * sol[j]; sol[i] = s / A[i][i]; }
107
+ const p = [null, null, null, null, null];
108
+ used.forEach((i, a) => { p[i] = sol[a]; });
109
+ const worst = Math.max(...X.map((x, k) => Math.abs(x.reduce((s, v, i) => s + v * (p[i] ?? 0), 0) - records[k].cost) / (records[k].cost || 1)));
110
+ return { p, worst, n: records.length };
111
+ }
112
+
113
+ // The price check stored on each session by derive, gathered per model: misses above 1% and the first day of one.
114
+ export function priceReport(db) {
115
+ const models = new Map();
116
+ for (const s of db.prepare("SELECT id, title, price_check FROM sessions WHERE price_check IS NOT NULL").all()) {
117
+ for (const [model, c] of Object.entries(JSON.parse(s.price_check))) {
118
+ const m = models.get(model) ?? models.set(model, { model, checked: 0, misses: [], skipped: {} }).get(model);
119
+ if (c.skipped) { m.skipped[c.skipped] = (m.skipped[c.skipped] ?? 0) + 1; continue; }
120
+ m.checked++;
121
+ if (c.miss > 0.01) m.misses.push({ id: s.id, title: s.title, day: c.day, host: c.host, lo: c.lo, hi: c.hi, miss: c.miss });
122
+ }
123
+ }
124
+ const out = [...models.values()].sort((a, b) => a.model.localeCompare(b.model));
125
+ for (const m of out) { m.misses.sort((a, b) => a.day.localeCompare(b.day)); m.since = m.misses[0]?.day ?? null; }
126
+ return out;
127
+ }
128
+
129
+ // For `prices`: the table, the check per model, models seen in requests without a row, and fitted prices
130
+ // from every complete host record that splits its cache writes and ran no web search.
131
+ export function pricesView(db, config) {
132
+ const { rows, errors } = readPrices(config);
133
+ const last = db.prepare(`SELECT c.model_usage, c.incomplete FROM cost_states c JOIN files f ON f.id = c.file_id AND f.kind = 'main'
134
+ WHERE c.line = (SELECT MAX(line) FROM cost_states d WHERE d.file_id = c.file_id)`).all();
135
+ const samples = new Map();
136
+ for (const c of last) {
137
+ if (c.incomplete) continue;
138
+ for (const [m, u] of Object.entries(JSON.parse(c.model_usage))) {
139
+ if (u?.cost > 0 && u.split && !u.web) (samples.get(m) ?? samples.set(m, []).get(m)).push(u);
140
+ }
141
+ }
142
+ const seen = db.prepare("SELECT model, MIN(day) first, MAX(day) last, COUNT(*) n FROM requests GROUP BY model").all();
143
+ const unpriced = seen.filter((r) => !priceAt(rows, r.model, r.last));
144
+ const fits = [...samples].sort((a, b) => a[0].localeCompare(b[0])).map(([model, list]) => ({ model, fit: fitPrices(list), sessions: list.length }));
145
+ return { rows, errors, report: priceReport(db), unpriced, fits };
146
+ }