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/usage.mjs ADDED
@@ -0,0 +1,388 @@
1
+ // Usage rows shared by the `usage` command and the dashboard, so their totals cannot differ.
2
+ import { familyOf, modelName, providerLabel } from "./providers/index.mjs";
3
+ import { zoner } from "./zone.mjs";
4
+ import { cacheSaving, costKinds, priceAt, priceReport, readPrices, requestCost, usageKinds } from "./prices.mjs";
5
+ import { CAUSES } from "./rebuilds.mjs";
6
+ import { BUCKETS, PARTS, REPLAY, bucketOf, compactionsOf, constantsOf, contextOf, levelsOf, replay, summaryCosts } from "./context.mjs";
7
+
8
+ export { modelName };
9
+
10
+ // Effort levels from least to most; an unknown value sorts after them as written, a missing one last.
11
+ export const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
12
+ export const effortOrder = (a, b) => {
13
+ const r = (e) => (EFFORTS.includes(e) ? EFFORTS.indexOf(e) : e ? EFFORTS.length : EFFORTS.length + 1);
14
+ return r(a) - r(b) || a.localeCompare(b);
15
+ };
16
+
17
+ // The rebuild figures of one request as a vector: [count, rewritten tokens, extra cost] per cause in CAUSES order,
18
+ // then the idle gaps from 5 to 15 minutes, from 15 to 60 minutes and over an hour. Facts sum these vectors.
19
+ const RB_GAPS = CAUSES.length * 3;
20
+ const gapBucket = (seconds) => (seconds < 900 ? 0 : seconds <= 3600 ? 1 : 2);
21
+ function rebuildVector(r) {
22
+ if (!r.rebuild) return null;
23
+ const v = new Array(RB_GAPS + 3).fill(0);
24
+ const at = CAUSES.indexOf(r.rebuild) * 3;
25
+ v[at] = 1;
26
+ v[at + 1] = r.cache_write > 0 ? r.cache_write : r.input;
27
+ v[at + 2] = r.rebuild_extra ?? 0;
28
+ if (r.rebuild === "idle") v[RB_GAPS + gapBucket(r.rebuild_gap)] = 1;
29
+ return v;
30
+ }
31
+
32
+ // Per cause what the facts hold: { n, tokens, extra }, and for idle the three gap counts.
33
+ export function rebuildTotals(F) {
34
+ const v = new Array(RB_GAPS + 3).fill(0);
35
+ for (const f of F) if (f.rb) f.rb.forEach((x, i) => { v[i] += x; });
36
+ const out = Object.fromEntries(CAUSES.map((c, i) => [c, { n: v[i * 3], tokens: v[i * 3 + 1], extra: v[i * 3 + 2] }]));
37
+ out.idle.gaps = v.slice(RB_GAPS);
38
+ return out;
39
+ }
40
+
41
+ const dayAdd = (day, n) => new Date(Date.parse(`${day}T00:00:00Z`) + n * 864e5).toISOString().slice(0, 10);
42
+ const mostOf = (map) => [...map].sort((a, b) => b[1] - a[1])[0]?.[0];
43
+
44
+ // A host cost key names a model id, sometimes with a suffix such as "[1m]"; match it to the session's requests.
45
+ function spreadTargets(key, reqs) {
46
+ const exact = reqs.filter((r) => r.model === key);
47
+ if (exact.length) return exact;
48
+ const bare = key.replace(/\[.*\]$/, "");
49
+ const stripped = reqs.filter((r) => r.model === bare);
50
+ if (stripped.length) return stripped;
51
+ const family = familyOf(key);
52
+ return reqs.filter((r) => r.family === family);
53
+ }
54
+
55
+ // Rows in the shapes the dashboard's views read: sessions, facts, subagents, tools, skills, compactions and context rows.
56
+ export function loadRows(db, config, now = new Date()) {
57
+ const zone = zoner(config.timeZone);
58
+ const minute = new Intl.DateTimeFormat("en-GB", { timeZone: config.timeZone, minute: "2-digit" });
59
+ const sessionRows = db.prepare(`SELECT s.*, (SELECT MIN(ts) FROM requests r WHERE r.session_id = s.id) first_req
60
+ FROM sessions s ORDER BY coalesce(s.first_ts, first_req)`).all().filter((s) => s.first_ts || s.first_req);
61
+ const requests = db.prepare("SELECT file_id, line, session_id, agent_id, ts, day, hour, model, family, effort, is_sub, input, output, thinking, cache_read, cache_write, cache_write_1h, rebuild, rebuild_gap, rebuild_extra FROM requests").all();
62
+ const prices = readPrices(config).rows;
63
+ // Models whose host cost misses the price table, per session.
64
+ const off = new Map();
65
+ for (const m of priceReport(db)) for (const x of m.misses) off.set(x.id, [...(off.get(x.id) ?? []), m.model]);
66
+ const owners = new Map(db.prepare("SELECT session_id, COUNT(*) n FROM owner_messages GROUP BY session_id").all().map((r) => [r.session_id, r.n]));
67
+ const compactions = new Map(db.prepare("SELECT session_id, COUNT(*) n FROM compactions GROUP BY session_id").all().map((r) => [r.session_id, r.n]));
68
+ const compactionRows = new Map();
69
+ for (const c of db.prepare("SELECT session_id, agent_id, line, ts, trigger, pre_tokens, post_tokens, duration_ms FROM compactions").all()) (compactionRows.get(c.session_id) ?? compactionRows.set(c.session_id, []).get(c.session_id)).push(c);
70
+ const ownerTimes = new Map();
71
+ for (const o of db.prepare("SELECT session_id, ts FROM owner_messages WHERE ts IS NOT NULL").all()) (ownerTimes.get(o.session_id) ?? ownerTimes.set(o.session_id, []).get(o.session_id)).push(o.ts);
72
+ const calls = db.prepare("SELECT session_id, name, COUNT(*) n, SUM(coalesce(is_error, 0)) e FROM tool_calls GROUP BY session_id, name").all();
73
+ const skillUses = db.prepare("SELECT session_id, name, via, source, is_error, ts FROM skills").all();
74
+ const subs = db.prepare(`SELECT f.agent_id, f.session_id, a.type, a.tool_use_id, (SELECT model FROM tool_calls t WHERE t.id = a.tool_use_id) parent_model
75
+ FROM files f LEFT JOIN subagents a ON a.agent_id = f.agent_id WHERE f.kind = 'sub'`).all();
76
+
77
+ // A tool call belongs to the request whose message holds it: the last request of its transcript at or before its line.
78
+ // An owner message opens its turn on the next request of its transcript.
79
+ const byFile = new Map();
80
+ for (const r of requests) { r.tc = 0; r.te = 0; r.ot = 0; (byFile.get(r.file_id) ?? byFile.set(r.file_id, []).get(r.file_id)).push(r); }
81
+ for (const list of byFile.values()) list.sort((a, b) => a.line - b.line);
82
+ const before = (file, line) => {
83
+ const list = byFile.get(file) ?? [];
84
+ let lo = 0, hi = list.length - 1, k = -1;
85
+ while (lo <= hi) { const mid = (lo + hi) >> 1; if (list[mid].line <= line) { k = mid; lo = mid + 1; } else hi = mid - 1; }
86
+ return k;
87
+ };
88
+ for (const c of db.prepare("SELECT file_id, line, coalesce(is_error, 0) e FROM tool_calls").all()) {
89
+ const r = byFile.get(c.file_id)?.[before(c.file_id, c.line)];
90
+ if (r) { r.tc++; r.te += c.e; }
91
+ }
92
+ for (const o of db.prepare("SELECT file_id, line FROM owner_messages").all()) {
93
+ const r = byFile.get(o.file_id)?.[before(o.file_id, o.line) + 1];
94
+ if (r) r.ot++;
95
+ }
96
+
97
+ const bySession = new Map();
98
+ for (const r of requests) (bySession.get(r.session_id) ?? bySession.set(r.session_id, []).get(r.session_id)).push(r);
99
+
100
+ // Families ordered by output over all data, so a family keeps its color under every filter.
101
+ const familyOut = new Map();
102
+ for (const r of requests) familyOut.set(r.family, (familyOut.get(r.family) ?? 0) + r.output);
103
+ const families = [...familyOut.keys()].sort((a, b) => familyOut.get(b) - familyOut.get(a));
104
+ const modelIdx = (family) => {
105
+ if (!families.includes(family)) families.push(family);
106
+ return families.indexOf(family);
107
+ };
108
+
109
+ const projectOut = new Map();
110
+ for (const s of sessionRows) projectOut.set(s.project ?? "(no project)", (projectOut.get(s.project ?? "(no project)") ?? 0) + (bySession.get(s.id) ?? []).reduce((n, r) => n + r.output, 0));
111
+ const projects = [...projectOut.keys()].sort((a, b) => projectOut.get(b) - projectOut.get(a) || a.localeCompare(b));
112
+
113
+ const providerOut = new Map();
114
+ for (const s of sessionRows) providerOut.set(s.provider, (providerOut.get(s.provider) ?? 0) + (bySession.get(s.id) ?? []).reduce((n, r) => n + r.output, 0));
115
+ const providerKeys = [...providerOut.keys()].sort((a, b) => providerOut.get(b) - providerOut.get(a) || a.localeCompare(b));
116
+ const providers = providerKeys.map(providerLabel);
117
+
118
+ // Every compaction with the requests around it, and what its summary request cost, before any session is placed:
119
+ // where compaction fires now and what one takes come from all of them.
120
+ const around = new Map(), summaries = new Map();
121
+ for (const s of sessionRows) {
122
+ const reqs = bySession.get(s.id) ?? [], comps = compactionRows.get(s.id);
123
+ if (!comps) continue;
124
+ const rows = compactionsOf(reqs, comps, ownerTimes.get(s.id) ?? []);
125
+ around.set(s.id, rows);
126
+ const day = zone(s.first_ts ?? s.first_req).day;
127
+ const costs = !s.cost_incomplete && s.model_cost ? JSON.parse(s.model_cost) : null;
128
+ for (const [x, v] of summaryCosts(rows, s.model_tokens ? JSON.parse(s.model_tokens) : null, costs, (key) => spreadTargets(key, reqs), prices, day)) summaries.set(x, v);
129
+ }
130
+ const allAround = [...around.values()].flat();
131
+ const { levels, fallback } = levelsOf(allAround);
132
+ const levelOf = (family) => levels[family] ?? fallback;
133
+ const constants = constantsOf(allAround, summaries);
134
+ // A compaction whose summary request cannot be priced from its session takes the average of its family's.
135
+ const familyCost = new Map();
136
+ for (const [x, v] of summaries) { const a = familyCost.get(x.before.family) ?? familyCost.set(x.before.family, [0, 0]).get(x.before.family); a[0] += v.cost; a[1]++; }
137
+
138
+ const sessions = [];
139
+ const facts = new Map();
140
+ const ctxRows = new Map();
141
+ const compactionList = [];
142
+ const index = new Map();
143
+ for (const s of sessionRows) {
144
+ const reqs = bySession.get(s.id) ?? [];
145
+ const start = s.first_ts ?? s.first_req;
146
+ const { day, hour } = zone(start);
147
+ const mainOut = new Map();
148
+ const efforts = new Map();
149
+ for (const r of reqs) {
150
+ if (r.is_sub) continue;
151
+ mainOut.set(r.family, (mainOut.get(r.family) ?? 0) + r.output);
152
+ if (r.effort) efforts.set(r.effort, (efforts.get(r.effort) ?? 0) + 1);
153
+ }
154
+ const out = reqs.reduce((n, r) => n + r.output, 0);
155
+ const i = sessions.length;
156
+ index.set(s.id, i);
157
+ const costState = s.cost === null ? "unknown" : s.cost_incomplete ? "incomplete" : s.cost_estimated ? "estimated" : "ok";
158
+ sessions.push({
159
+ id: s.id, pr: providerKeys.indexOf(s.provider), p: projects.indexOf(s.project ?? "(no project)"), title: s.title ?? "", day, hour, min: Number(minute.format(new Date(start))),
160
+ dur: s.last_ts && s.first_ts ? (Date.parse(s.last_ts) - Date.parse(s.first_ts)) / 60000 : 0,
161
+ api: (s.api_ms ?? 0) / 1000, tool: (s.tool_ms ?? 0) / 1000, owner: owners.get(s.id) ?? 0, compact: compactions.get(s.id) ?? 0,
162
+ la: s.lines_added ?? 0, lr: s.lines_removed ?? 0, parent: mainOut.size ? modelIdx(mostOf(mainOut)) : -1, effort: mostOf(efforts) ?? "",
163
+ subs: [], cost: s.cost, costState, out, unpriced: [], priceOff: off.get(s.id) ?? [],
164
+ });
165
+
166
+ // Spread each model's host cost over that model's requests by their tokens priced on their day,
167
+ // so a later price never moves cost between earlier days; a model without a price row is spread by output tokens.
168
+ // Cost is split into reading the context, writing the cache, output and web search: web search is what the host
169
+ // charged a model that searched the web beyond its tokens priced from the host record.
170
+ const costOf = new Map();
171
+ const kindsOf = new Map();
172
+ const unplaced = [];
173
+ const tokens = s.model_tokens ? JSON.parse(s.model_tokens) : {};
174
+ for (const [key, value] of Object.entries(s.model_cost ? JSON.parse(s.model_cost) : {})) {
175
+ if (!value) continue;
176
+ const u = tokens[key], row = u && priceAt(prices, key, day);
177
+ const host = row ? usageKinds(row.p, u) : null;
178
+ const priced0 = host ? host.reduce((a, b) => a + b, 0) : 0;
179
+ const web = host && u.web ? Math.max(0, value - priced0) : 0;
180
+ const targets = spreadTargets(key, reqs);
181
+ // A model the host charged with no request in the transcript is split by the host record's own tokens.
182
+ if (!targets.length) unplaced.push([key, value, host && priced0 ? [...host.map((x) => (x * (value - web)) / priced0), web] : null]);
183
+ const rows = targets.map((r) => priceAt(prices, r.model, r.day));
184
+ const priced = rows.every(Boolean);
185
+ if (!priced) for (const r of targets) if (!sessions[i].unpriced.includes(r.model)) sessions[i].unpriced.push(r.model);
186
+ const weight = targets.map((r, k) => (priced ? requestCost(rows[k].p, r) : r.output));
187
+ const total = weight.reduce((a, b) => a + b, 0);
188
+ targets.forEach((r, k) => {
189
+ const share = value * (total ? weight[k] / total : 1 / targets.length);
190
+ costOf.set(r, (costOf.get(r) ?? 0) + share);
191
+ // The share split as the price table splits the request, after its part of the web search.
192
+ if (priced && weight[k]) {
193
+ const kinds = costKinds(rows[k].p, r), had = kindsOf.get(r) ?? [0, 0, 0, 0], tok = share * (1 - web / value);
194
+ kindsOf.set(r, had.map((x, j) => x + (j < 3 ? (tok * kinds[j]) / weight[k] : share - tok)));
195
+ }
196
+ });
197
+ }
198
+ const put = (d, h, family, sub, effort, add, rb = null, kinds = null) => {
199
+ const key = `${i}|${d}|${h}|${family}|${sub}|${effort}`;
200
+ const f = facts.get(key) ?? facts.set(key, { s: i, d, h, m: modelIdx(family), sub, e: effort, q: 0, i: 0, o: 0, cr: 0, cw: 0, th: 0, c: 0, sv: 0, tc: 0, te: 0, ot: 0, rb: null, k: null }).get(key);
201
+ for (const [k, v] of Object.entries(add)) f[k] += v;
202
+ if (kinds) {
203
+ f.k ??= [0, 0, 0, 0];
204
+ kinds.forEach((x, j) => { f.k[j] += x; });
205
+ }
206
+ if (rb) {
207
+ f.rb ??= new Array(rb.length).fill(0);
208
+ rb.forEach((x, k) => { f.rb[k] += x; });
209
+ }
210
+ };
211
+ // Context rows: per session, day, model and effort, the cost of reading the context by context size (the last part is
212
+ // a cost the host charged with no request, whose context is unknown), the requests per size, and the replay.
213
+ const ctxRow = (d, family, effort) => {
214
+ const key = `${i}|${d}|${family}|${effort}`;
215
+ return ctxRows.get(key) ?? ctxRows.set(key, { s: i, d, m: modelIdx(family), e: effort, b: new Array(BUCKETS + 1).fill(0), n: new Array(BUCKETS).fill(0), r: null }).get(key);
216
+ };
217
+ const main = reqs.filter((r) => !r.is_sub).sort((a, b) => Date.parse(a.ts) - Date.parse(b.ts) || a.line - b.line);
218
+ const rows = around.get(s.id) ?? [];
219
+ const replayed = replay(main, rows.filter((x) => !x.sub).map((x) => Date.parse(x.c.ts)), prices, constants, levelOf);
220
+ for (const r of reqs) {
221
+ const p = priceAt(prices, r.model, r.day);
222
+ put(r.day, r.hour, r.family, r.is_sub, r.effort ?? "", { q: 1, i: r.input, o: r.output, cr: r.cache_read, cw: r.cache_write, th: r.thinking, c: costOf.get(r) ?? 0, sv: p ? cacheSaving(p.p, r) : 0, tc: r.tc, te: r.te, ot: r.ot }, rebuildVector(r), kindsOf.get(r));
223
+ const x = ctxRow(r.day, r.family, r.effort ?? ""), k = bucketOf(contextOf(r));
224
+ x.b[k] += kindsOf.get(r)?.[0] ?? 0;
225
+ x.n[k]++;
226
+ const v = replayed.get(r);
227
+ if (v) { x.r ??= new Array(REPLAY * PARTS).fill(0); v.forEach((y, j) => { x.r[j] += y; }); }
228
+ }
229
+ // A model the host charged with no request in the transcript lands on the session's first hour.
230
+ for (const [key, value, kinds] of unplaced) {
231
+ const family = key === "unknown" ? mostOf(mainOut) ?? "unknown" : familyOf(key);
232
+ put(day, hour, family, 0, sessions[i].effort, { c: value }, null, kinds);
233
+ if (kinds) ctxRow(day, family, sessions[i].effort).b[BUCKETS] += kinds[0];
234
+ }
235
+ for (const x of rows) {
236
+ const at = x.before ?? x.after, family = at?.family ?? (mainOut.size ? mostOf(mainOut) : "unknown"), sum = summaries.get(x), avg = familyCost.get(family);
237
+ compactionList.push({
238
+ s: i, d: x.c.ts ? zone(x.c.ts).day : day, m: modelIdx(family), e: at?.effort ?? sessions[i].effort, sub: x.sub ? 1 : 0,
239
+ auto: x.c.trigger === "auto" ? 1 : x.c.trigger === "manual" ? 0 : null, pre: x.c.pre_tokens, post: x.c.post_tokens, wait: x.c.duration_ms,
240
+ kept: x.after ? contextOf(x.after) : null, nth: x.nth, next: x.next, turns: x.turns, tail: x.tail,
241
+ sum: sum ? sum.cost : avg ? avg[0] / avg[1] : null, rb: x.after?.rebuild === "compaction" ? x.after.rebuild_extra ?? 0 : 0,
242
+ });
243
+ }
244
+ }
245
+
246
+ const subagents = [];
247
+ for (const a of subs) {
248
+ const i = index.get(a.session_id);
249
+ if (i === undefined) continue;
250
+ const own = new Map();
251
+ for (const r of bySession.get(a.session_id) ?? []) if (r.agent_id === a.agent_id) own.set(r.family, (own.get(r.family) ?? 0) + r.output);
252
+ sessions[i].subs.push(subagents.length);
253
+ subagents.push({ s: i, type: a.type ?? "unknown", m: own.size ? modelIdx(mostOf(own)) : -1, parent: a.parent_model ? modelIdx(familyOf(a.parent_model)) : -1, o: [...own.values()].reduce((n, v) => n + v, 0) });
254
+ }
255
+ const tools = sessions.map(() => ({}));
256
+ for (const c of calls) {
257
+ const i = index.get(c.session_id);
258
+ if (i !== undefined) tools[i][c.name] = [c.n, c.e];
259
+ }
260
+
261
+ const { skills, skillSources } = skillsBySession(skillUses, sessions.length, index, zone);
262
+
263
+ const factList = [...facts.values()];
264
+ const today = zone(now.toISOString()).day;
265
+ return {
266
+ models: families.map(modelName), providers, providerKeys, projects, sessions, facts: factList, subagents, tools, skills, skillSources, today,
267
+ compactions: compactionList, context: [...ctxRows.values()], levels: Object.fromEntries(families.map((fam, m) => [m, levelOf(fam)])),
268
+ first: factList.reduce((a, f) => (f.d < a ? f.d : a), today), scanned: now.toISOString(),
269
+ };
270
+ }
271
+
272
+ // Where skills come from, in the order they are listed.
273
+ export const SKILL_SOURCES = ["project", "personal", "plugin", "builtin", "other"];
274
+
275
+ // Per session, each skill's [typed as a command, called by the agent, failed calls, last day used]; and each skill's source.
276
+ // A call the host loaded no folder for takes the source the same skill shows elsewhere. A typed command counts only
277
+ // when it is a skill: the host loaded one for it, or the agent called a skill of that name.
278
+ function skillsBySession(uses, count, index, zone) {
279
+ const seen = new Map();
280
+ for (const u of uses) {
281
+ const m = seen.get(u.name) ?? seen.set(u.name, new Map()).get(u.name);
282
+ if (u.source) m.set(u.source, (m.get(u.source) ?? 0) + 1);
283
+ }
284
+ const isSkill = new Set(uses.filter((u) => u.source || u.via === "agent").map((u) => u.name));
285
+ const skillSources = {};
286
+ for (const name of isSkill) skillSources[name] = mostOf(seen.get(name)) ?? "other";
287
+ const skills = Array.from({ length: count }, () => ({}));
288
+ for (const u of uses) {
289
+ const i = index.get(u.session_id);
290
+ if (i === undefined || !isSkill.has(u.name)) continue;
291
+ const r = skills[i][u.name] ?? (skills[i][u.name] = [0, 0, 0, ""]);
292
+ r[u.via === "command" ? 0 : 1]++;
293
+ r[2] += u.is_error ? 1 : 0;
294
+ const day = u.ts ? zone(u.ts).day : "";
295
+ if (day > r[3]) r[3] = day;
296
+ }
297
+ return { skills, skillSources };
298
+ }
299
+
300
+ // The window and filters of a `usage` call, resolved against the rows.
301
+ export function window(rows, { days, since, until }) {
302
+ if (since || until) return { from: since ?? rows.first, to: until ?? rows.today };
303
+ const n = Number(days ?? 14);
304
+ if (!Number.isInteger(n) || n < 1) throw new Error(`--days needs a positive whole number, got ${days}`);
305
+ return { from: dayAdd(rows.today, -(n - 1)), to: rows.today };
306
+ }
307
+
308
+ export function slice(rows, { from, to, project = -1, model = -1, effort = null, provider = -1 }) {
309
+ return rows.facts.filter((f) => f.d >= from && f.d <= to && (project < 0 || rows.sessions[f.s].p === project) && (model < 0 || f.m === model) && (effort === null || f.e === effort) && (provider < 0 || rows.sessions[f.s].pr === provider));
310
+ }
311
+
312
+ export function totals(rows, F) {
313
+ const a = { q: 0, i: 0, o: 0, th: 0, cr: 0, cw: 0, c: 0 };
314
+ const sess = new Set();
315
+ for (const f of F) {
316
+ for (const k of Object.keys(a)) a[k] += f[k];
317
+ sess.add(f.s);
318
+ }
319
+ const ss = [...sess].map((s) => rows.sessions[s]);
320
+ // Speed counts only sessions whose host record gives API time; a running session has none yet.
321
+ const timed = ss.filter((s) => s.api > 0), api = timed.reduce((n, s) => n + s.api, 0);
322
+ return { ...a, rebuild: rebuildTotals(F), sessions: sess.size, hit: a.cr / (a.cr + a.cw + a.i || 1), tps: api ? timed.reduce((n, s) => n + s.out, 0) / api : null, costGaps: ss.filter((s) => s.costState !== "ok"),
323
+ unpriced: [...new Set(ss.flatMap((s) => s.unpriced))].sort() };
324
+ }
325
+
326
+ // Rows of one grouping. Each row carries the token totals of its facts plus its label.
327
+ export function groupBy(rows, F, by) {
328
+ const keyOf = {
329
+ day: (f) => f.d,
330
+ hour: (f) => f.h,
331
+ model: (f) => rows.models[f.m],
332
+ provider: (f) => rows.providers[rows.sessions[f.s].pr],
333
+ effort: (f) => f.e || "unknown",
334
+ project: (f) => rows.projects[rows.sessions[f.s].p],
335
+ session: (f) => f.s,
336
+ }[by];
337
+ if (!keyOf) throw new Error(`--by takes day, model, provider, effort, project, session, hour, tool, skill or subagent, got ${by}`);
338
+ const groups = new Map();
339
+ for (const f of F) {
340
+ const k = keyOf(f);
341
+ (groups.get(k) ?? groups.set(k, []).get(k)).push(f);
342
+ }
343
+ return [...groups].map(([key, list]) => ({ key, ...totals(rows, list) }));
344
+ }
345
+
346
+ // Tool calls and subagents of the sessions that have requests in the window.
347
+ export function toolRows(rows, F) {
348
+ const out = new Map();
349
+ for (const s of new Set(F.map((f) => f.s))) {
350
+ for (const [name, [n, e]] of Object.entries(rows.tools[s])) {
351
+ const r = out.get(name) ?? out.set(name, { key: name, calls: 0, errors: 0 }).get(name);
352
+ r.calls += n;
353
+ r.errors += e;
354
+ }
355
+ }
356
+ return [...out.values()].sort((a, b) => b.calls - a.calls);
357
+ }
358
+
359
+ // Skills used in the sessions that have requests in the window, by source and then most used first.
360
+ export function skillRows(rows, F) {
361
+ const out = new Map();
362
+ for (const s of new Set(F.map((f) => f.s))) {
363
+ for (const [name, [command, agent, errors, last]] of Object.entries(rows.skills[s])) {
364
+ const r = out.get(name) ?? out.set(name, { key: name, source: rows.skillSources[name], uses: 0, command: 0, agent: 0, errors: 0, sessions: 0, last: "" }).get(name);
365
+ r.uses += command + agent;
366
+ r.command += command;
367
+ r.agent += agent;
368
+ r.errors += errors;
369
+ r.sessions++;
370
+ if (last > r.last) r.last = last;
371
+ }
372
+ }
373
+ return [...out.values()].sort((a, b) => SKILL_SOURCES.indexOf(a.source) - SKILL_SOURCES.indexOf(b.source) || b.uses - a.uses || a.key.localeCompare(b.key));
374
+ }
375
+
376
+ export function subagentRows(rows, F) {
377
+ const out = new Map();
378
+ const inWindow = new Set(F.map((f) => f.s));
379
+ for (const a of rows.subagents) {
380
+ if (!inWindow.has(a.s)) continue;
381
+ const r = out.get(a.type) ?? out.set(a.type, { key: a.type, count: 0, o: 0, models: {} }).get(a.type);
382
+ r.count++;
383
+ r.o += a.o;
384
+ const m = a.m < 0 ? "unknown" : rows.models[a.m];
385
+ r.models[m] = (r.models[m] ?? 0) + 1;
386
+ }
387
+ return [...out.values()].sort((a, b) => b.count - a.count);
388
+ }
package/src/zone.mjs ADDED
@@ -0,0 +1,15 @@
1
+ // Day and hour of an ISO instant in the configured time zone.
2
+ export function zoner(timeZone) {
3
+ const fmt = new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hourCycle: "h23" });
4
+ const cache = new Map();
5
+ return (iso) => {
6
+ const key = iso.slice(0, 16);
7
+ let hit = cache.get(key);
8
+ if (!hit) {
9
+ const p = Object.fromEntries(fmt.formatToParts(new Date(iso)).map((x) => [x.type, x.value]));
10
+ hit = { day: `${p.year}-${p.month}-${p.day}`, hour: Number(p.hour) };
11
+ cache.set(key, hit);
12
+ }
13
+ return hit;
14
+ };
15
+ }