llmtop 0.0.0-stage → 0.1.1
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.
- package/LICENSE +21 -0
- package/README.md +114 -2
- package/bin/llmtop.mjs +101 -0
- package/dashboard/dist/apple-touch-icon.png +0 -0
- package/dashboard/dist/assets/index-BVbAwMVB.js +9 -0
- package/dashboard/dist/assets/index-Cp7Swcz5.css +1 -0
- package/dashboard/dist/assets/llmtop-lockup-DtFPJmhv.svg +1 -0
- package/dashboard/dist/assets/llmtop-lockup-reversed-D9OmQIVU.svg +1 -0
- package/dashboard/dist/favicon.ico +0 -0
- package/dashboard/dist/favicon.svg +1 -0
- package/dashboard/dist/index.html +19 -0
- package/dashboard/dist/llmtop-mark-192.png +0 -0
- package/dashboard/dist/llmtop-mark-512.png +0 -0
- package/dashboard/dist/site.webmanifest +11 -0
- package/dashboard/src/App.tsx +213 -0
- package/dashboard/src/controls/DateRange.tsx +108 -0
- package/dashboard/src/controls/Disclosure.tsx +15 -0
- package/dashboard/src/controls/Search.tsx +18 -0
- package/dashboard/src/controls/Select.tsx +48 -0
- package/dashboard/src/controls/popover.tsx +31 -0
- package/dashboard/src/dash.ts +23 -0
- package/dashboard/src/extra.test.ts +9 -0
- package/dashboard/src/extra.ts +16 -0
- package/dashboard/src/format.ts +29 -0
- package/dashboard/src/i18n.tsx +52 -0
- package/dashboard/src/index.ts +7 -0
- package/dashboard/src/main.tsx +7 -0
- package/dashboard/src/model.test.ts +110 -0
- package/dashboard/src/model.ts +255 -0
- package/dashboard/src/state.test.ts +48 -0
- package/dashboard/src/state.ts +61 -0
- package/dashboard/src/styles.css +401 -0
- package/dashboard/src/tip.ts +51 -0
- package/dashboard/src/treemap.test.ts +23 -0
- package/dashboard/src/treemap.ts +30 -0
- package/dashboard/src/ui.tsx +327 -0
- package/dashboard/src/views/Activity.tsx +177 -0
- package/dashboard/src/views/Context.tsx +183 -0
- package/dashboard/src/views/Models.tsx +155 -0
- package/dashboard/src/views/Overview.tsx +83 -0
- package/dashboard/src/views/Projects.tsx +116 -0
- package/dashboard/src/views/Sessions.tsx +54 -0
- package/dashboard/src/views/Subagents.tsx +102 -0
- package/docs/brand/README.md +91 -0
- package/docs/brand/brand.json +67 -0
- package/docs/brand/favicon.ico +0 -0
- package/docs/brand/png/apple-touch-icon.png +0 -0
- package/docs/brand/png/favicon-16.png +0 -0
- package/docs/brand/png/favicon-32.png +0 -0
- package/docs/brand/png/favicon-48.png +0 -0
- package/docs/brand/png/llmtop-lockup-reversed@2x.png +0 -0
- package/docs/brand/png/llmtop-lockup@2x.png +0 -0
- package/docs/brand/png/llmtop-mark-1024.png +0 -0
- package/docs/brand/png/llmtop-mark-192.png +0 -0
- package/docs/brand/png/llmtop-mark-512.png +0 -0
- package/docs/brand/png/llmtop-wordmark@2x.png +0 -0
- package/docs/brand/source/build_brand.py +173 -0
- package/docs/brand/svg/favicon.svg +1 -0
- package/docs/brand/svg/llmtop-glyph.svg +1 -0
- package/docs/brand/svg/llmtop-lockup-reversed.svg +1 -0
- package/docs/brand/svg/llmtop-lockup.svg +1 -0
- package/docs/brand/svg/llmtop-mark-light.svg +1 -0
- package/docs/brand/svg/llmtop-mark.svg +1 -0
- package/docs/brand/svg/llmtop-wordmark-reversed.svg +1 -0
- package/docs/brand/svg/llmtop-wordmark.svg +1 -0
- package/llmtop.config.example.json +10 -0
- package/package.json +73 -4
- package/prices.md +27 -0
- package/src/api.mjs +53 -0
- package/src/archive.mjs +142 -0
- package/src/config.mjs +55 -0
- package/src/context.mjs +151 -0
- package/src/dashboard.mjs +61 -0
- package/src/db.mjs +102 -0
- package/src/derive.mjs +346 -0
- package/src/effort.mjs +18 -0
- package/src/format.mjs +19 -0
- package/src/paths.mjs +82 -0
- package/src/prices-command.mjs +25 -0
- package/src/prices.mjs +146 -0
- package/src/providers/agy.mjs +438 -0
- package/src/providers/claude.mjs +274 -0
- package/src/providers/codex.mjs +589 -0
- package/src/providers/index.mjs +25 -0
- package/src/rebuilds.mjs +85 -0
- package/src/scan.mjs +214 -0
- package/src/serve.mjs +44 -0
- package/src/show.mjs +20 -0
- package/src/usage-command.mjs +110 -0
- package/src/usage.mjs +388 -0
- package/src/zone.mjs +15 -0
package/src/rebuilds.mjs
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Cache rebuilds: requests that write most of their context into the prompt cache again.
|
|
2
|
+
import { priceAt } from "./prices.mjs";
|
|
3
|
+
|
|
4
|
+
export const MIN_REWRITE = 20000; // tokens written to the cache for a request to count
|
|
5
|
+
export const SHARE = 0.5; // ...and more than this share of everything the request read or wrote
|
|
6
|
+
export const CAUSES = ["start", "compaction", "idle", "other"];
|
|
7
|
+
const SHORT_LIFETIME = 5 * 60; // seconds a cache write lives, without the 1h option
|
|
8
|
+
const LONG_LIFETIME = 60 * 60;
|
|
9
|
+
|
|
10
|
+
export const rewrittenTokens = (r) => (r.cache_write > 0 ? r.cache_write : r.input);
|
|
11
|
+
export const isRebuild = (r) => {
|
|
12
|
+
const rw = rewrittenTokens(r);
|
|
13
|
+
return rw >= MIN_REWRITE && rw > SHARE * (r.input + r.cache_read + r.cache_write);
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// Rewritten tokens priced as cache writes (5m/1h by the split, as requestCost does) minus the same tokens priced as reads.
|
|
17
|
+
export function extraCost(p, r) {
|
|
18
|
+
if (r.cache_write > 0) {
|
|
19
|
+
const w1 = r.cache_write_1h ?? r.cache_write;
|
|
20
|
+
return ((r.cache_write - w1) * p[3] + w1 * p[4] - r.cache_write * p[2]) / 1e6;
|
|
21
|
+
}
|
|
22
|
+
return (r.input * (p[0] - p[2])) / 1e6;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// requests: { session_id, agent_id, ts, line, model, day, input, cache_read, cache_write, cache_write_1h } in any order.
|
|
26
|
+
// compactions: Map of thread (session id, newline, agent id or "") to its compaction instants (ms).
|
|
27
|
+
// Returns Map of request to { rebuild, gap, extra } for rebuilds.
|
|
28
|
+
export function classify(requests, compactions, prices) {
|
|
29
|
+
const threads = new Map();
|
|
30
|
+
for (const r of requests) {
|
|
31
|
+
if (r.model === "<synthetic>") continue;
|
|
32
|
+
const key = `${r.session_id}\n${r.agent_id ?? ""}`;
|
|
33
|
+
(threads.get(key) ?? threads.set(key, []).get(key)).push(r);
|
|
34
|
+
}
|
|
35
|
+
const out = new Map();
|
|
36
|
+
for (const list of threads.values()) {
|
|
37
|
+
list.sort((a, b) => Date.parse(a.ts) - Date.parse(b.ts) || a.line - b.line);
|
|
38
|
+
let prev = null;
|
|
39
|
+
let lifetime = SHORT_LIFETIME;
|
|
40
|
+
for (const r of list) {
|
|
41
|
+
const at = Date.parse(r.ts);
|
|
42
|
+
// The first request after a compaction rewrites the new short history while it still reads the system prompt and
|
|
43
|
+
// tools from the cache, so it often writes less than half of what it carries: it counts once it rewrites enough.
|
|
44
|
+
const compacted = prev !== null && (compactions.get(`${r.session_id}\n${r.agent_id ?? ""}`) ?? []).some((c) => c > prev && c <= at);
|
|
45
|
+
if (isRebuild(r) || (compacted && rewrittenTokens(r) >= MIN_REWRITE)) {
|
|
46
|
+
const gap = prev === null ? null : Math.round((at - prev) / 1000);
|
|
47
|
+
let cause;
|
|
48
|
+
if (prev === null) cause = "start";
|
|
49
|
+
else if (compacted) cause = "compaction";
|
|
50
|
+
else if (gap > lifetime) cause = "idle";
|
|
51
|
+
else cause = "other";
|
|
52
|
+
const row = priceAt(prices, r.model, r.day);
|
|
53
|
+
out.set(r, { rebuild: cause, gap, extra: row ? extraCost(row.p, r) : null });
|
|
54
|
+
}
|
|
55
|
+
// The cache a thread holds lives as long as its latest write promised.
|
|
56
|
+
if (r.cache_write > 0) lifetime = r.cache_write_1h > 0 ? LONG_LIFETIME : SHORT_LIFETIME;
|
|
57
|
+
prev = at;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Recompute the rebuild columns of every request, writing only the rows that changed.
|
|
64
|
+
export function markRebuilds(db, prices) {
|
|
65
|
+
const requests = db.prepare(`SELECT message_id, session_id, agent_id, ts, line, model, day, input, cache_read, cache_write, cache_write_1h,
|
|
66
|
+
rebuild, rebuild_gap, rebuild_extra FROM requests`).all();
|
|
67
|
+
const compactions = new Map();
|
|
68
|
+
for (const c of db.prepare("SELECT session_id, agent_id, ts FROM compactions WHERE ts IS NOT NULL").all()) {
|
|
69
|
+
const key = `${c.session_id}\n${c.agent_id ?? ""}`;
|
|
70
|
+
(compactions.get(key) ?? compactions.set(key, []).get(key)).push(Date.parse(c.ts));
|
|
71
|
+
}
|
|
72
|
+
const found = classify(requests, compactions, prices);
|
|
73
|
+
const set = db.prepare("UPDATE requests SET rebuild = ?, rebuild_gap = ?, rebuild_extra = ? WHERE message_id = ?");
|
|
74
|
+
db.exec("BEGIN");
|
|
75
|
+
try {
|
|
76
|
+
for (const r of requests) {
|
|
77
|
+
const c = found.get(r) ?? { rebuild: null, gap: null, extra: null };
|
|
78
|
+
if (c.rebuild !== r.rebuild || c.gap !== r.rebuild_gap || c.extra !== r.rebuild_extra) set.run(c.rebuild, c.gap, c.extra, r.message_id);
|
|
79
|
+
}
|
|
80
|
+
db.exec("COMMIT");
|
|
81
|
+
} catch (err) {
|
|
82
|
+
db.exec("ROLLBACK");
|
|
83
|
+
throw err;
|
|
84
|
+
}
|
|
85
|
+
}
|
package/src/scan.mjs
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { closeSync, existsSync, openSync, readSync, statSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { appendChunk, archiveLines, archivePath, hashHead, HEAD_BYTES, listArchived, liveHead, newChunks, rotate, sizeOf, copyOther } from "./archive.mjs";
|
|
4
|
+
import { FILE_TABLES, openDb, transaction } from "./db.mjs";
|
|
5
|
+
import { derive } from "./derive.mjs";
|
|
6
|
+
import { priceReport, readPrices } from "./prices.mjs";
|
|
7
|
+
import { PROVIDERS } from "./providers/index.mjs";
|
|
8
|
+
|
|
9
|
+
// First timestamp in the opening bytes of a transcript; orders new files so the earlier file owns copied records.
|
|
10
|
+
function peekFirstTs(path) {
|
|
11
|
+
const fd = openSync(path, "r");
|
|
12
|
+
try {
|
|
13
|
+
const buf = Buffer.alloc(256 * 1024);
|
|
14
|
+
const n = readSync(fd, buf, 0, buf.length, 0);
|
|
15
|
+
return buf.subarray(0, n).toString("utf8").match(/"(?:timestamp|created_at)":"([^"]+)"/)?.[1] ?? null;
|
|
16
|
+
} finally {
|
|
17
|
+
closeSync(fd);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function lineCount(chunk) {
|
|
22
|
+
let n = 0;
|
|
23
|
+
for (let i = chunk.indexOf(10); i >= 0; i = chunk.indexOf(10, i + 1)) n++;
|
|
24
|
+
return n;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Lets the server answer other requests, such as the progress, between steps of a long scan.
|
|
28
|
+
const yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
|
|
29
|
+
|
|
30
|
+
// onProgress({ reason, step, done, total, bytes, totalBytes }) follows the scan: step "find" opens each transcript to order
|
|
31
|
+
// them, "read" ingests them (bytes ingested of totalBytes), "finish" builds the figures. reason is "first" for a new
|
|
32
|
+
// database, "rebuild" when a schema change emptied it, "update" otherwise.
|
|
33
|
+
export async function scan(config, { onProgress = () => {} } = {}) {
|
|
34
|
+
const providers = Object.entries(config.providers).map(([name, p]) => ({ ...PROVIDERS[name], root: p.transcripts, archive: join(config.archive, name) }));
|
|
35
|
+
const had = existsSync(config.database);
|
|
36
|
+
const db = openDb(config.database);
|
|
37
|
+
const reason = db.prepare("SELECT COUNT(*) n FROM files").get().n ? "update" : had ? "rebuild" : "first";
|
|
38
|
+
const mains = new Set(db.prepare("SELECT session_id FROM files WHERE kind = 'main'").all().map((r) => r.session_id));
|
|
39
|
+
const ingesters = new Map(providers.map((p) => [p.name, p.createIngester(db, config.timeZone, (id) => mains.has(id))]));
|
|
40
|
+
const totals = { files: 0, bytes: 0, sessions: 0, records: 0, generations: 0, copied: 0 };
|
|
41
|
+
const sessionsBefore = db.prepare("SELECT COUNT(DISTINCT session_id) n FROM files WHERE kind = 'main' AND lines > 0").get().n;
|
|
42
|
+
|
|
43
|
+
const getFile = db.prepare("SELECT * FROM files WHERE provider = ? AND path = ?");
|
|
44
|
+
const addFile = db.prepare("INSERT INTO files(provider, path, kind, session_id, agent_id) VALUES (?, ?, ?, ?, ?)");
|
|
45
|
+
const saveCursor = db.prepare("UPDATE files SET offset = ?, lines = ?, head_hash = ?, archive_size = ?, first_ts = coalesce(first_ts, ?), cwd = coalesce(cwd, ?), live = ?, own_first = ?, own_last = ? WHERE id = ?");
|
|
46
|
+
const resetFile = db.prepare("UPDATE files SET generation = generation + 1, offset = 0, lines = 0, head_hash = NULL, archive_size = 0, first_ts = NULL, own_first = NULL, own_last = NULL, cwd = NULL WHERE id = ?");
|
|
47
|
+
const clear = FILE_TABLES.map((t) => db.prepare(`DELETE FROM ${t} WHERE file_id = ?`));
|
|
48
|
+
|
|
49
|
+
const fileRow = (d) => getFile.get(d.provider, d.rel) ?? (addFile.run(d.provider, d.rel, d.kind, d.sessionId, d.agentId), getFile.get(d.provider, d.rel));
|
|
50
|
+
|
|
51
|
+
// Every transcript a provider's host still has or its archive holds, oldest first.
|
|
52
|
+
const work = new Map();
|
|
53
|
+
for (const p of providers) {
|
|
54
|
+
const base = { provider: p.name, dir: p.archive };
|
|
55
|
+
for (const d of p.listHost(p.root).transcripts) if (!work.has(`${p.name}/${d.rel}`)) work.set(`${p.name}/${d.rel}`, { ...d, ...base, src: join(p.root, d.rel) });
|
|
56
|
+
for (const d of listArchived(p.archive, p.describe)) if (!work.has(`${p.name}/${d.rel}`)) work.set(`${p.name}/${d.rel}`, { ...d, ...base, src: null });
|
|
57
|
+
}
|
|
58
|
+
for (const d of work.values()) if (d.kind === "main") mains.add(d.sessionId);
|
|
59
|
+
// Each job weighs the bytes it still has to ingest: the archive when it is ahead of the cursor, then the host's new bytes.
|
|
60
|
+
const jobs = [];
|
|
61
|
+
for (const d of work.values()) {
|
|
62
|
+
if (jobs.length % 100 === 0) {
|
|
63
|
+
onProgress({ reason, step: "find", done: jobs.length, total: work.size, bytes: 0, totalBytes: 0 });
|
|
64
|
+
await yieldToLoop();
|
|
65
|
+
}
|
|
66
|
+
const row = getFile.get(d.provider, d.rel);
|
|
67
|
+
const src = d.src ?? archivePath(d.dir, d.rel);
|
|
68
|
+
const stat = statSync(src);
|
|
69
|
+
const arcSize = sizeOf(archivePath(d.dir, d.rel)) ?? 0;
|
|
70
|
+
const weight = (arcSize !== (row?.archive_size ?? 0) ? arcSize : 0) + (d.src ? Math.max(0, stat.size - (row?.offset ?? 0)) : 0);
|
|
71
|
+
jobs.push({ d, ts: row?.first_ts ?? (d.src ? peekFirstTs(d.src) : null) ?? "~", mtime: stat.mtimeMs, weight });
|
|
72
|
+
}
|
|
73
|
+
// A continuation starts with the same records as the file it continues, so ties go to the file last written first.
|
|
74
|
+
jobs.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : a.mtime - b.mtime));
|
|
75
|
+
const totalBytes = jobs.reduce((n, j) => n + j.weight, 0);
|
|
76
|
+
let bytes = 0, next = 0;
|
|
77
|
+
const report = (done, extra = 0) => onProgress({ reason, step: "read", done, total: jobs.length, bytes: bytes + extra, totalBytes });
|
|
78
|
+
|
|
79
|
+
for (const [done, { d, weight }] of jobs.entries()) {
|
|
80
|
+
bytes = next;
|
|
81
|
+
next += weight;
|
|
82
|
+
report(done);
|
|
83
|
+
await yieldToLoop();
|
|
84
|
+
let file = fileRow(d);
|
|
85
|
+
const arc = archivePath(d.dir, d.rel);
|
|
86
|
+
const ingest = ingesters.get(d.provider);
|
|
87
|
+
let firstTs = null;
|
|
88
|
+
let cwd = null;
|
|
89
|
+
let ownFirst = file.own_first;
|
|
90
|
+
let ownLast = file.own_last;
|
|
91
|
+
const take = (line, text) => {
|
|
92
|
+
const r = ingest(file, line, text);
|
|
93
|
+
totals.records += r.added;
|
|
94
|
+
firstTs ??= r.ts ?? null;
|
|
95
|
+
cwd ??= r.cwd ?? null;
|
|
96
|
+
if (r.own && r.ts) {
|
|
97
|
+
if (!ownFirst || r.ts < ownFirst) ownFirst = r.ts;
|
|
98
|
+
if (!ownLast || r.ts > ownLast) ownLast = r.ts;
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// The archive is ahead of the cursor when a scan died between the append and the commit,
|
|
103
|
+
// or when the database was rebuilt: ingest what the archive holds beyond the cursor, in batches.
|
|
104
|
+
const arcSize = sizeOf(arc) ?? 0;
|
|
105
|
+
if (arcSize !== file.archive_size) {
|
|
106
|
+
if (arcSize < file.archive_size) throw new Error(`archive ${arc} is shorter than recorded; refusing to continue`);
|
|
107
|
+
let { offset, lines } = file;
|
|
108
|
+
const head = [];
|
|
109
|
+
let headBytes = 0;
|
|
110
|
+
let batch = 0;
|
|
111
|
+
db.exec("BEGIN");
|
|
112
|
+
try {
|
|
113
|
+
for await (const l of archiveLines(arc)) {
|
|
114
|
+
if (headBytes < HEAD_BYTES) {
|
|
115
|
+
head.push(Buffer.from(`${l.text}\n`));
|
|
116
|
+
headBytes += l.bytes;
|
|
117
|
+
}
|
|
118
|
+
if (l.line <= lines) continue;
|
|
119
|
+
take(l.line, l.text);
|
|
120
|
+
offset += l.bytes;
|
|
121
|
+
lines = l.line;
|
|
122
|
+
if (++batch % 5000 === 0) {
|
|
123
|
+
saveCursor.run(offset, lines, hashHead(Buffer.concat(head)), file.archive_size, firstTs, cwd, file.live, ownFirst, ownLast, file.id);
|
|
124
|
+
db.exec("COMMIT");
|
|
125
|
+
db.exec("BEGIN");
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
saveCursor.run(offset, lines, hashHead(Buffer.concat(head)), arcSize, firstTs, cwd, d.src ? 1 : 0, ownFirst, ownLast, file.id);
|
|
129
|
+
db.exec("COMMIT");
|
|
130
|
+
} catch (err) {
|
|
131
|
+
db.exec("ROLLBACK");
|
|
132
|
+
throw err;
|
|
133
|
+
}
|
|
134
|
+
file = getFile.get(d.provider, d.rel);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (!d.src) {
|
|
138
|
+
if (file.live) db.prepare("UPDATE files SET live = 0 WHERE id = ?").run(file.id);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const size = sizeOf(d.src);
|
|
142
|
+
if (size === null) continue;
|
|
143
|
+
|
|
144
|
+
// A file that shrank or whose consumed head changed was rewritten: keep the old copy as a generation.
|
|
145
|
+
if (file.offset > 0 && (size < file.offset || liveHead(d.src, file.offset) !== file.head_hash)) {
|
|
146
|
+
if (existsSync(arc)) rotate(arc);
|
|
147
|
+
transaction(db, () => {
|
|
148
|
+
for (const c of clear) c.run(file.id);
|
|
149
|
+
resetFile.run(file.id);
|
|
150
|
+
});
|
|
151
|
+
totals.generations++;
|
|
152
|
+
file = getFile.get(d.provider, d.rel);
|
|
153
|
+
firstTs = cwd = ownFirst = ownLast = null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
let { offset, lines } = file;
|
|
157
|
+
for (const chunk of newChunks(d.src, offset, size)) {
|
|
158
|
+
const archived = appendChunk(arc, chunk);
|
|
159
|
+
const count = lineCount(chunk);
|
|
160
|
+
const text = chunk.toString("utf8");
|
|
161
|
+
transaction(db, () => {
|
|
162
|
+
let start = 0;
|
|
163
|
+
for (let i = 0; i < count; i++) {
|
|
164
|
+
const end = text.indexOf("\n", start);
|
|
165
|
+
take(lines + i + 1, text.slice(start, end));
|
|
166
|
+
start = end + 1;
|
|
167
|
+
}
|
|
168
|
+
offset += chunk.length;
|
|
169
|
+
lines += count;
|
|
170
|
+
saveCursor.run(offset, lines, liveHead(d.src, offset), archived, firstTs, cwd, 1, ownFirst, ownLast, file.id);
|
|
171
|
+
});
|
|
172
|
+
totals.bytes += chunk.length;
|
|
173
|
+
report(done, Math.max(0, weight - (size - offset)));
|
|
174
|
+
await yieldToLoop();
|
|
175
|
+
}
|
|
176
|
+
if (offset > file.offset) totals.files++;
|
|
177
|
+
}
|
|
178
|
+
onProgress({ reason, step: "finish", done: jobs.length, total: jobs.length, bytes: totalBytes, totalBytes });
|
|
179
|
+
await yieldToLoop();
|
|
180
|
+
|
|
181
|
+
// Other session-folder files; the subagent meta files among them give each subagent its type.
|
|
182
|
+
const activeProviders = new Set(jobs.map((j) => j.d.provider));
|
|
183
|
+
const copied = new Set();
|
|
184
|
+
for (const p of providers) {
|
|
185
|
+
for (const rel of p.listHost(p.root).others) {
|
|
186
|
+
if (copied.has(`${p.name}/${rel}`)) continue;
|
|
187
|
+
copied.add(`${p.name}/${rel}`);
|
|
188
|
+
if (copyOther(join(p.root, rel), join(p.archive, rel))) totals.copied++;
|
|
189
|
+
}
|
|
190
|
+
if (p.syncMeta && activeProviders.has(p.name)) totals.copied += p.syncMeta(p.root, p.archive) ?? 0;
|
|
191
|
+
}
|
|
192
|
+
const putSub = db.prepare("INSERT OR REPLACE INTO subagents(agent_id, session_id, type, tool_use_id) VALUES (?, ?, ?, ?)");
|
|
193
|
+
for (const { d } of jobs) {
|
|
194
|
+
if (d.kind !== "sub") continue;
|
|
195
|
+
const meta = PROVIDERS[d.provider].subagentMeta?.(d.dir, d);
|
|
196
|
+
if (meta) putSub.run(d.agentId, d.sessionId, meta.type, meta.toolUseId);
|
|
197
|
+
}
|
|
198
|
+
for (const p of providers) if (activeProviders.has(p.name)) p.postScan?.(db, p.archive);
|
|
199
|
+
|
|
200
|
+
derive(db, config);
|
|
201
|
+
const sessionsAfter = db.prepare("SELECT COUNT(DISTINCT session_id) n FROM files WHERE kind = 'main' AND lines > 0").get().n;
|
|
202
|
+
totals.sessions = sessionsAfter - sessionsBefore;
|
|
203
|
+
totals.prices = { report: priceReport(db), errors: readPrices(config).errors };
|
|
204
|
+
db.close();
|
|
205
|
+
return totals;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// What a scan added and the price check's misses, one line each; errors are reported apart.
|
|
209
|
+
export function scanReport(t) {
|
|
210
|
+
const fresh = t.files + t.records + t.copied + t.generations === 0;
|
|
211
|
+
const lines = [fresh ? "nothing new" : `added ${t.files} transcript files, ${t.bytes} bytes, ${t.sessions} sessions, ${t.records} records; copied ${t.copied} other files${t.generations ? `; ${t.generations} rewritten files kept as generations` : ""}`];
|
|
212
|
+
for (const m of t.prices.report.filter((x) => x.misses.length)) lines.push(`price check: ${m.model} misses the price table by more than 1% in ${m.misses.length} of ${m.checked} sessions, first on ${m.since}; see \`prices\``);
|
|
213
|
+
return { lines, errors: t.prices.errors };
|
|
214
|
+
}
|
package/src/serve.mjs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// The dashboard over HTTP, on this machine only: the JSON API and the built app in dashboard/dist.
|
|
2
|
+
// Any other GET path answers the app's index.html, so a view's own URL loads it.
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { dirname, extname, join, normalize, sep } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { createApi } from "./api.mjs";
|
|
8
|
+
|
|
9
|
+
const DIST = join(dirname(fileURLToPath(import.meta.url)), "..", "dashboard", "dist");
|
|
10
|
+
const TYPES = {
|
|
11
|
+
".html": "text/html; charset=utf-8",
|
|
12
|
+
".js": "text/javascript",
|
|
13
|
+
".css": "text/css",
|
|
14
|
+
".svg": "image/svg+xml",
|
|
15
|
+
".ico": "image/x-icon",
|
|
16
|
+
".png": "image/png",
|
|
17
|
+
".webmanifest": "application/manifest+json",
|
|
18
|
+
".json": "application/json",
|
|
19
|
+
};
|
|
20
|
+
const TEXT = { "content-type": "text/plain; charset=utf-8" };
|
|
21
|
+
|
|
22
|
+
// Resolves with the listening server; onScan receives each scan's totals, routes are extra API handlers (see createApi).
|
|
23
|
+
export function serve(config, { port, onScan = () => {}, dist = DIST, routes }) {
|
|
24
|
+
const api = createApi(config, { onScan, routes });
|
|
25
|
+
const server = createServer(async (req, res) => {
|
|
26
|
+
if (await api(req, res)) return;
|
|
27
|
+
if (req.method !== "GET") return res.writeHead(405, TEXT).end("method not allowed\n");
|
|
28
|
+
const path = normalize(decodeURIComponent(new URL(req.url, "http://localhost").pathname));
|
|
29
|
+
const file = join(dist, path);
|
|
30
|
+
const asset = file.startsWith(dist + sep) && extname(path) ? file : join(dist, "index.html");
|
|
31
|
+
try {
|
|
32
|
+
const body = await readFile(asset);
|
|
33
|
+
const cacheControl = asset.startsWith(join(dist, "assets") + sep) ? "max-age=31536000, immutable" : "no-store";
|
|
34
|
+
res.writeHead(200, { "content-type": TYPES[extname(asset)] ?? "application/octet-stream", "cache-control": cacheControl }).end(body);
|
|
35
|
+
} catch {
|
|
36
|
+
if (asset.endsWith("index.html")) res.writeHead(503, TEXT).end("the dashboard is not built: run npm run build, or npm run dev\n");
|
|
37
|
+
else res.writeHead(404, TEXT).end("not found\n");
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
server.once("error", (err) => reject(err.code === "EADDRINUSE" ? new Error(`port ${port} is in use: pass --port or change port in ~/.config/llmtop/config.json`) : err));
|
|
42
|
+
server.listen(port, "127.0.0.1", () => resolve(server));
|
|
43
|
+
});
|
|
44
|
+
}
|
package/src/show.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { archivePath, readLine } from "./archive.mjs";
|
|
3
|
+
import { readDb } from "./db.mjs";
|
|
4
|
+
|
|
5
|
+
// <session>[/<agent-id>]:<line>, where <session> is an id or an unambiguous prefix.
|
|
6
|
+
export async function show(config, ref) {
|
|
7
|
+
const m = ref?.match(/^([0-9a-f-]+)(?:\/([\w-]+))?:(\d+)$/);
|
|
8
|
+
if (!m) throw new Error(`expected <session>:<line> or <session>/<agent-id>:<line>, got ${ref ?? "nothing"}`);
|
|
9
|
+
const [, prefix, agent, line] = m;
|
|
10
|
+
const db = readDb(config.database);
|
|
11
|
+
const rows = agent
|
|
12
|
+
? db.prepare("SELECT provider, path FROM files WHERE kind = 'sub' AND session_id LIKE ? AND agent_id = ?").all(`${prefix}%`, agent)
|
|
13
|
+
: db.prepare("SELECT provider, path FROM files WHERE kind = 'main' AND session_id LIKE ?").all(`${prefix}%`);
|
|
14
|
+
db.close();
|
|
15
|
+
if (rows.length === 0) throw new Error(`no archived transcript matches ${prefix}${agent ? `/${agent}` : ""}`);
|
|
16
|
+
if (rows.length > 1) throw new Error(`${prefix} matches ${rows.length} sessions; give more of the id`);
|
|
17
|
+
const text = await readLine(archivePath(join(config.archive, rows[0].provider), rows[0].path), Number(line));
|
|
18
|
+
if (text === null) throw new Error(`${ref}: the archive has no line ${line}`);
|
|
19
|
+
return text;
|
|
20
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { readDb } from "./db.mjs";
|
|
2
|
+
import { int, minutes, pct, table, usd } from "./format.mjs";
|
|
3
|
+
import { effortOrder, groupBy, loadRows, skillRows, slice, subagentRows, toolRows, totals, window } from "./usage.mjs";
|
|
4
|
+
|
|
5
|
+
const TOKENS = [
|
|
6
|
+
["requests", (r) => int(r.q), "r"],
|
|
7
|
+
["input", (r) => int(r.i), "r"],
|
|
8
|
+
["output", (r) => int(r.o), "r"],
|
|
9
|
+
["thinking", (r) => int(r.th), "r"],
|
|
10
|
+
["cache read", (r) => int(r.cr), "r"],
|
|
11
|
+
["cache write", (r) => int(r.cw), "r"],
|
|
12
|
+
["from cache", (r) => pct(r.hit), "r"],
|
|
13
|
+
["cost", (r) => `${usd(r.c)}${r.costGaps.length ? "*" : ""}`, "r"],
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
// Resolve --project, --model and --provider to the indexes the rows use; an unknown name is an error, not an empty result.
|
|
17
|
+
function filters(rows, options) {
|
|
18
|
+
const project = options.project === undefined ? -1 : rows.projects.indexOf(options.project);
|
|
19
|
+
if (project < 0 && options.project !== undefined) throw new Error(`no project named ${options.project}; known: ${rows.projects.join(", ")}`);
|
|
20
|
+
const wanted = options.model?.toLowerCase();
|
|
21
|
+
const model = wanted === undefined ? -1 : rows.models.findIndex((m) => m.toLowerCase() === wanted);
|
|
22
|
+
if (model < 0 && wanted !== undefined) throw new Error(`no model family named ${options.model}; known: ${rows.models.join(", ")}`);
|
|
23
|
+
const effort = options.effort === undefined ? null : options.effort.toLowerCase();
|
|
24
|
+
if (effort !== null && !rows.facts.some((f) => f.e === effort)) throw new Error(`no request at effort ${options.effort}; seen: ${[...new Set(rows.facts.map((f) => f.e).filter(Boolean))].sort(effortOrder).join(", ")}`);
|
|
25
|
+
const wantedProvider = options.provider?.toLowerCase();
|
|
26
|
+
const provider = wantedProvider === undefined ? -1
|
|
27
|
+
: rows.providerKeys.findIndex((k, i) => k.toLowerCase() === wantedProvider || rows.providers[i].toLowerCase() === wantedProvider);
|
|
28
|
+
if (provider < 0 && wantedProvider !== undefined) throw new Error(`no provider named ${options.provider}; known: ${rows.providerKeys.join(", ")}`);
|
|
29
|
+
return { project, model, effort, provider };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const tokens = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}K` : String(n));
|
|
33
|
+
const WHEN = { idle: "after idle", compaction: "at compaction", other: "other", start: "at session start" };
|
|
34
|
+
|
|
35
|
+
// "cache rebuilt: 59 after idle (12.6M tokens, ~$86 extra), ..."; the cost of a start is not avoidable, so it shows none.
|
|
36
|
+
export function rebuildLine({ rebuild }) {
|
|
37
|
+
const parts = ["idle", "compaction", "other", "start"].filter((c) => rebuild[c].n).map((c) => {
|
|
38
|
+
const { n, tokens: t, extra } = rebuild[c];
|
|
39
|
+
return `${int(n)} ${WHEN[c]} (${tokens(t)} tokens${c === "start" ? "" : `, ~$${extra.toFixed(extra < 10 ? 2 : 0)} extra`})`;
|
|
40
|
+
});
|
|
41
|
+
return parts.length ? `cache rebuilt: ${parts.join(", ")}` : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function usageCommand({ config, options, out }) {
|
|
45
|
+
const db = readDb(config.database);
|
|
46
|
+
const rows = loadRows(db, config);
|
|
47
|
+
db.close();
|
|
48
|
+
const range = window(rows, options);
|
|
49
|
+
const filter = { ...range, ...filters(rows, options) };
|
|
50
|
+
const F = slice(rows, filter);
|
|
51
|
+
const total = totals(rows, F);
|
|
52
|
+
const by = options.by ? [options.by] : ["day", "model"];
|
|
53
|
+
|
|
54
|
+
const sections = by.map((b) => {
|
|
55
|
+
if (b === "tool") return { by: b, rows: toolRows(rows, F) };
|
|
56
|
+
if (b === "skill") return { by: b, rows: skillRows(rows, F) };
|
|
57
|
+
if (b === "subagent") return { by: b, rows: subagentRows(rows, F) };
|
|
58
|
+
const grouped = groupBy(rows, F, b);
|
|
59
|
+
if (b === "session") {
|
|
60
|
+
for (const g of grouped) {
|
|
61
|
+
const s = rows.sessions[g.key];
|
|
62
|
+
Object.assign(g, { key: s.id, title: s.title, project: rows.projects[s.p], start: `${s.day} ${String(s.hour).padStart(2, "0")}:${String(s.min).padStart(2, "0")}`,
|
|
63
|
+
duration: s.dur, owner: s.owner, compactions: s.compact, added: s.la, removed: s.lr, costState: s.costState });
|
|
64
|
+
}
|
|
65
|
+
grouped.sort((a, b2) => (a.start < b2.start ? -1 : 1));
|
|
66
|
+
} else if (b === "effort") grouped.sort((a, b2) => effortOrder(a.key === "unknown" ? "" : a.key, b2.key === "unknown" ? "" : b2.key));
|
|
67
|
+
else grouped.sort((a, b2) => (b === "day" || b === "hour" ? (a.key < b2.key ? -1 : 1) : b2.o - a.o));
|
|
68
|
+
return { by: b, rows: grouped };
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
if (options.json) {
|
|
72
|
+
const clean = (r) => ({ ...r, costGaps: r.costGaps?.map((s) => ({ id: s.id, costState: s.costState })) });
|
|
73
|
+
out.write(`${JSON.stringify({ from: range.from, to: range.to, provider: options.provider ?? null, project: options.project ?? null, model: options.model ?? null, effort: filter.effort, unpriced: total.unpriced, total: clean(total), groups: sections.map((s) => ({ by: s.by, rows: s.rows.map(clean) })) }, null, 1)}\n`);
|
|
74
|
+
return 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const lines = [`Usage ${range.from} to ${range.to}${options.provider ? `, provider ${options.provider}` : ""}${options.project ? `, project ${options.project}` : ""}${options.model ? `, model ${options.model}` : ""}${filter.effort ? `, effort ${filter.effort}` : ""}: ${int(total.sessions)} sessions`, ""];
|
|
78
|
+
for (const s of sections) {
|
|
79
|
+
let columns;
|
|
80
|
+
if (s.by === "tool") columns = [["tool", (r) => r.key], ["calls", (r) => int(r.calls), "r"], ["errors", (r) => int(r.errors), "r"]];
|
|
81
|
+
else if (s.by === "skill")
|
|
82
|
+
columns = [["skill", (r) => r.key], ["source", (r) => r.source], ["uses", (r) => int(r.uses), "r"], ["typed", (r) => int(r.command), "r"], ["by agent", (r) => int(r.agent), "r"],
|
|
83
|
+
["errors", (r) => int(r.errors), "r"], ["sessions", (r) => int(r.sessions), "r"], ["last used", (r) => r.last]];
|
|
84
|
+
else if (s.by === "subagent") columns = [["subagent type", (r) => r.key], ["count", (r) => int(r.count), "r"], ["output", (r) => int(r.o), "r"], ["models", (r) => Object.entries(r.models).map(([m, n]) => `${m} ${n}`).join(", ")]];
|
|
85
|
+
else if (s.by === "session")
|
|
86
|
+
columns = [["session", (r) => r.key.slice(0, 8)], ["start", (r) => r.start], ["project", (r) => r.project], ["title", (r) => (r.title.length > 40 ? `${r.title.slice(0, 39)}…` : r.title)],
|
|
87
|
+
["duration", (r) => minutes(r.duration), "r"], ["owner", (r) => int(r.owner), "r"], ["compact", (r) => int(r.compactions), "r"], ["+lines", (r) => int(r.added), "r"],
|
|
88
|
+
["-lines", (r) => int(r.removed), "r"], ["output", (r) => int(r.o), "r"], ["tok/s", (r) => (r.tps === null ? "—" : r.tps.toFixed(0)), "r"], ["cost", (r) => (r.costState === "unknown" ? "unknown" : `${usd(r.c)}${r.costState === "ok" ? "" : "*"}`), "r"]];
|
|
89
|
+
else {
|
|
90
|
+
const label = { day: "day", hour: "hour", model: "model", provider: "provider", effort: "effort", project: "project" }[s.by];
|
|
91
|
+
const rowsWithTotal = [...s.rows, { key: "total", ...total }];
|
|
92
|
+
lines.push(table(rowsWithTotal, [[label, (r) => (s.by === "hour" && r.key !== "total" ? `${String(r.key).padStart(2, "0")}:00` : r.key)], ...TOKENS]), "");
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
lines.push(table(s.rows, columns), "");
|
|
96
|
+
}
|
|
97
|
+
if (!by.some((b) => b === "tool" || b === "skill" || b === "subagent")) {
|
|
98
|
+
lines.push(`output tokens per second of API time: ${total.tps === null ? "—" : total.tps.toFixed(1)}`);
|
|
99
|
+
const rebuilt = rebuildLine(total);
|
|
100
|
+
if (rebuilt) lines.push(rebuilt);
|
|
101
|
+
}
|
|
102
|
+
if (total.costGaps.length) {
|
|
103
|
+
lines.push(`* cost unknown, incomplete or estimated for ${total.costGaps.length} sessions; their known or estimated part is counted:`);
|
|
104
|
+
const why = { unknown: "no cost record and no price for a model", incomplete: "host marked cost incomplete", estimated: "no cost record; estimated from prices.md" };
|
|
105
|
+
for (const g of total.costGaps) lines.push(` ${g.id.slice(0, 8)} ${why[g.costState]} ${g.title}`);
|
|
106
|
+
}
|
|
107
|
+
if (total.unpriced.length) lines.push(`no price row for ${total.unpriced.join(", ")} in prices.md: their cost is spread by output tokens`);
|
|
108
|
+
out.write(`${lines.join("\n").trimEnd()}\n`);
|
|
109
|
+
return 0;
|
|
110
|
+
}
|