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/prices.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Prices
|
|
2
|
+
|
|
3
|
+
USD per million tokens, per model id, each row in force from its date until a later row for the same id. `node bin/llmtop.mjs` uses them to spread the host's recorded cost over requests, to estimate a session the host left without a cost record, and to check the host's figures; it never replaces a cost the host recorded. A cache write the host did not split into 5m and 1h is priced as a 1h write.
|
|
4
|
+
|
|
5
|
+
When `scan` reports that a model misses this table, run `node bin/llmtop.mjs prices`, check the fitted prices against the provider's price list, and add a row from the day the price changed. Never edit a row in place: earlier days keep their price.
|
|
6
|
+
|
|
7
|
+
| model | from | input | output | cache read | cache write 5m | cache write 1h |
|
|
8
|
+
| --- | --- | --- | --- | --- | --- | --- |
|
|
9
|
+
| claude-opus-5-5 | 2026-10-01 | 4 | 20 | 0.20 | 5 | 8 |
|
|
10
|
+
| claude-sonnet-5-5 | 2026-10-01 | 2 | 10 | 0.10 | 2.50 | 4 |
|
|
11
|
+
| claude-haiku-5-5 | 2026-10-01 | 0.10 | 0.50 | 0.01 | 0.125 | 0.20 |
|
|
12
|
+
| claude-fable-5-2 | 2026-11-01 | 8 | 40 | 0.20 | 10 | 16 |
|
|
13
|
+
| gpt-6.2-astra | 2026-08-01 | 8 | 40 | 0.40 | 8 | 8 |
|
|
14
|
+
| gpt-6-astra | 2026-08-01 | 8 | 40 | 0.40 | 8 | 8 |
|
|
15
|
+
| gpt-6.2-sol | 2026-08-01 | 2 | 10 | 0.10 | 2 | 2 |
|
|
16
|
+
| gpt-6.1-sol | 2026-08-01 | 2 | 10 | 0.10 | 2 | 2 |
|
|
17
|
+
| gpt-6-sol | 2026-08-01 | 2 | 10 | 0.10 | 2 | 2 |
|
|
18
|
+
| gpt-6.1-terra | 2026-08-01 | 1 | 5 | 0.05 | 1 | 1 |
|
|
19
|
+
| gpt-5.6-terra | 2026-08-01 | 1 | 5 | 0.05 | 1 | 1 |
|
|
20
|
+
| gpt-6-luna | 2026-08-01 | 0.10 | 0.50 | 0.01 | 0.10 | 0.10 |
|
|
21
|
+
| gpt-5.6-sol | 2026-08-01 | 4 | 20 | 0.40 | 4 | 4 |
|
|
22
|
+
| gpt-5.6-luna | 2026-08-01 | 0.10 | 0.50 | 0.01 | 0.10 | 0.10 |
|
|
23
|
+
| codex-auto-review | 2026-01-01 | 0 | 0 | 0 | 0 | 0 |
|
|
24
|
+
| gemini-4-neon | 2026-10-01 | 3 | 15 | 0.15 | 3 | 3 |
|
|
25
|
+
| gemini-4-carbon | 2026-12-01 | 4 | 20 | 0.20 | 4 | 4 |
|
|
26
|
+
| gemini-4-hydrogen | 2026-10-01 | 1.50 | 7.50 | 0.075 | 1.50 | 1.50 |
|
|
27
|
+
| gemini-4-argon | 2026-12-01 | 4 | 20 | 0.20 | 4 | 4 |
|
package/src/api.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// The dashboard's JSON API, shared by `serve` and the Vite dev server (`npm run dev`).
|
|
2
|
+
// GET /api/data the rows of the views
|
|
3
|
+
// POST /api/scan scans, then answers what it added
|
|
4
|
+
// GET /api/scan/progress the running scan's progress (see scan in scan.mjs), or null; answered at once, outside the queue
|
|
5
|
+
// Other requests run one at a time, so a read never sees a scan half done and two scans never overlap.
|
|
6
|
+
import { buildUsageRows } from "./dashboard.mjs";
|
|
7
|
+
import { scan } from "./scan.mjs";
|
|
8
|
+
|
|
9
|
+
const JSON_TYPE = { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" };
|
|
10
|
+
|
|
11
|
+
// Returns a handler that answers /api/* and resolves true, or resolves false for any other path.
|
|
12
|
+
// onScan receives each scan's totals. `extra` adds handlers, "METHOD /api/path": () => value, that run in the
|
|
13
|
+
// same queue; a built-in route wins over an extra one of the same name.
|
|
14
|
+
export function createApi(config, { onScan = () => {}, routes: extra = {} } = {}) {
|
|
15
|
+
let queue = Promise.resolve();
|
|
16
|
+
let progress = null;
|
|
17
|
+
const routes = {
|
|
18
|
+
...extra,
|
|
19
|
+
"GET /api/data": () => buildUsageRows(config),
|
|
20
|
+
"POST /api/scan": async () => {
|
|
21
|
+
try {
|
|
22
|
+
const t = await scan(config, { onProgress: (p) => { progress = p; } });
|
|
23
|
+
onScan(t);
|
|
24
|
+
return { files: t.files, sessions: t.sessions, records: t.records, errors: t.prices.errors };
|
|
25
|
+
} finally {
|
|
26
|
+
progress = null;
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
return (req, res) => {
|
|
31
|
+
const path = new URL(req.url, "http://localhost").pathname;
|
|
32
|
+
if (!path.startsWith("/api/")) return Promise.resolve(false);
|
|
33
|
+
if (req.method === "GET" && path === "/api/scan/progress") {
|
|
34
|
+
res.writeHead(200, JSON_TYPE).end(JSON.stringify(progress));
|
|
35
|
+
return Promise.resolve(true);
|
|
36
|
+
}
|
|
37
|
+
const route = routes[`${req.method} ${path}`];
|
|
38
|
+
if (!route) {
|
|
39
|
+
res.writeHead(404, JSON_TYPE).end(JSON.stringify({ error: "not found" }));
|
|
40
|
+
return Promise.resolve(true);
|
|
41
|
+
}
|
|
42
|
+
const done = queue.then(async () => {
|
|
43
|
+
try {
|
|
44
|
+
const body = JSON.stringify(await route());
|
|
45
|
+
res.writeHead(200, JSON_TYPE).end(body);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
res.writeHead(500, JSON_TYPE).end(JSON.stringify({ error: err.message }));
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
queue = done;
|
|
51
|
+
return done.then(() => true);
|
|
52
|
+
};
|
|
53
|
+
}
|
package/src/archive.mjs
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// The archive mirrors a provider's transcripts folder: each transcript as zstd frames appended in
|
|
2
|
+
// order, so line numbers never change, and every other session-folder file copied as is.
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { appendFileSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, openSync, readdirSync, readSync, renameSync, statSync, utimesSync } from "node:fs";
|
|
5
|
+
import { dirname, join, relative } from "node:path";
|
|
6
|
+
import { createInterface } from "node:readline";
|
|
7
|
+
import { constants, createZstdDecompress, zstdCompressSync } from "node:zlib";
|
|
8
|
+
|
|
9
|
+
export const HEAD_BYTES = 4096;
|
|
10
|
+
const BLOCK = 64 * 1024 * 1024;
|
|
11
|
+
|
|
12
|
+
const isDir = (p) => {
|
|
13
|
+
try {
|
|
14
|
+
return statSync(p).isDirectory();
|
|
15
|
+
} catch {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const list = (p) => (isDir(p) ? readdirSync(p, { withFileTypes: true }) : []);
|
|
20
|
+
|
|
21
|
+
// Current-generation transcripts present in a provider's archive folder, including ones the host has deleted;
|
|
22
|
+
// `describe` is the provider's reading of a relative path.
|
|
23
|
+
export function listArchived(archiveRoot, describe) {
|
|
24
|
+
const out = [];
|
|
25
|
+
const walk = (dir) => {
|
|
26
|
+
for (const e of list(dir)) {
|
|
27
|
+
const abs = join(dir, e.name);
|
|
28
|
+
if (e.isDirectory()) walk(abs);
|
|
29
|
+
else if (e.name.endsWith(".jsonl.zst") && !/\.g\d+\.jsonl\.zst$/.test(e.name)) {
|
|
30
|
+
const d = describe(relative(archiveRoot, abs).slice(0, -".zst".length));
|
|
31
|
+
if (d) out.push(d);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
walk(archiveRoot);
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const archivePath = (archiveRoot, rel) => join(archiveRoot, `${rel}.zst`);
|
|
40
|
+
|
|
41
|
+
export function sizeOf(path) {
|
|
42
|
+
try {
|
|
43
|
+
return statSync(path).size;
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function readBytes(path, position, length) {
|
|
50
|
+
const fd = openSync(path, "r");
|
|
51
|
+
try {
|
|
52
|
+
const buf = Buffer.alloc(length);
|
|
53
|
+
let done = 0;
|
|
54
|
+
while (done < length) {
|
|
55
|
+
const n = readSync(fd, buf, done, length - done, position + done);
|
|
56
|
+
if (n === 0) break;
|
|
57
|
+
done += n;
|
|
58
|
+
}
|
|
59
|
+
return buf.subarray(0, done);
|
|
60
|
+
} finally {
|
|
61
|
+
closeSync(fd);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const hashHead = (buf) => createHash("sha256").update(buf.subarray(0, HEAD_BYTES)).digest("hex");
|
|
66
|
+
export const liveHead = (path, consumed) => hashHead(readBytes(path, 0, Math.min(HEAD_BYTES, consumed)));
|
|
67
|
+
|
|
68
|
+
// Complete lines after `offset`, in blocks that each end at a newline. An unfinished last line is left.
|
|
69
|
+
export function* newChunks(path, offset, size) {
|
|
70
|
+
let pos = offset;
|
|
71
|
+
let block = BLOCK;
|
|
72
|
+
while (pos < size) {
|
|
73
|
+
const buf = readBytes(path, pos, Math.min(block, size - pos));
|
|
74
|
+
const cut = buf.lastIndexOf(10);
|
|
75
|
+
if (cut < 0) {
|
|
76
|
+
if (pos + buf.length >= size) return;
|
|
77
|
+
block *= 2;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const chunk = buf.subarray(0, cut + 1);
|
|
81
|
+
yield chunk;
|
|
82
|
+
pos += chunk.length;
|
|
83
|
+
block = BLOCK;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Level 3: about half of gzip's size on transcripts heavy with base64 images, and over ten times faster to write.
|
|
88
|
+
export function appendChunk(path, chunk) {
|
|
89
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
90
|
+
appendFileSync(path, zstdCompressSync(chunk, { params: { [constants.ZSTD_c_compressionLevel]: 3 } }));
|
|
91
|
+
return statSync(path).size;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Move the current archive copy aside as the next free generation; returns its number.
|
|
95
|
+
export function rotate(path) {
|
|
96
|
+
const stem = path.slice(0, -".jsonl.zst".length);
|
|
97
|
+
let n = 1;
|
|
98
|
+
while (existsSync(`${stem}.g${n}.jsonl.zst`)) n++;
|
|
99
|
+
renameSync(path, `${stem}.g${n}.jsonl.zst`);
|
|
100
|
+
return n;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Lines of an archive file, numbered from 1, as { line, text, bytes } where bytes counts the newline.
|
|
104
|
+
// Node's decoder stops at the end of a frame, so each frame is read from where the one before it ended.
|
|
105
|
+
export async function* archiveLines(path, from = 1) {
|
|
106
|
+
const size = statSync(path).size;
|
|
107
|
+
let n = 0;
|
|
108
|
+
for (let start = 0; start < size; ) {
|
|
109
|
+
const input = createReadStream(path, { start });
|
|
110
|
+
const unzip = createZstdDecompress();
|
|
111
|
+
input.on("error", (err) => unzip.destroy(err));
|
|
112
|
+
input.pipe(unzip);
|
|
113
|
+
try {
|
|
114
|
+
for await (const text of createInterface({ input: unzip, crlfDelay: Infinity })) {
|
|
115
|
+
n++;
|
|
116
|
+
if (n >= from) yield { line: n, text, bytes: Buffer.byteLength(text) + 1 };
|
|
117
|
+
}
|
|
118
|
+
} finally {
|
|
119
|
+
input.destroy();
|
|
120
|
+
unzip.destroy();
|
|
121
|
+
}
|
|
122
|
+
if (!unzip.bytesWritten) throw new Error(`archive ${path} has bytes that are not a zstd frame at ${start}`);
|
|
123
|
+
start += unzip.bytesWritten;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function readLine(path, wanted) {
|
|
128
|
+
for await (const { line, text } of archiveLines(path, wanted)) if (line === wanted) return text;
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Copy a non-transcript session file when its size or modification time changed.
|
|
133
|
+
export function copyOther(src, dest) {
|
|
134
|
+
const s = statSync(src);
|
|
135
|
+
const d = existsSync(dest) ? statSync(dest) : null;
|
|
136
|
+
if (d && d.size === s.size && Math.abs(d.mtimeMs - s.mtimeMs) < 1) return false;
|
|
137
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
138
|
+
copyFileSync(src, dest);
|
|
139
|
+
utimesSync(dest, s.atimeMs / 1000, s.mtimeMs / 1000);
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
|
package/src/config.mjs
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { PROVIDERS } from "./providers/index.mjs";
|
|
6
|
+
|
|
7
|
+
export const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
8
|
+
|
|
9
|
+
const expand = (path, base) => resolve(base, path.startsWith("~/") || path === "~" ? join(homedir(), path.slice(1)) : path);
|
|
10
|
+
|
|
11
|
+
export function defaultConfigDir(env = process.env, home = homedir()) {
|
|
12
|
+
const xdgHome = env.XDG_CONFIG_HOME;
|
|
13
|
+
if (xdgHome && isAbsolute(xdgHome)) return join(xdgHome, "llmtop");
|
|
14
|
+
return join(home, ".config", "llmtop");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function defaultConfigPath(env = process.env, home = homedir()) {
|
|
18
|
+
if (env.LLMTOP_CONFIG) return env.LLMTOP_CONFIG;
|
|
19
|
+
const xdg = join(defaultConfigDir(env, home), "config.json");
|
|
20
|
+
const local = join(ROOT, "llmtop.config.json");
|
|
21
|
+
if (!existsSync(xdg) && existsSync(local)) return local;
|
|
22
|
+
return xdg;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Reads the optional config file (~/.config/llmtop/config.json by default; LLMTOP_CONFIG points elsewhere).
|
|
26
|
+
// A missing file means all defaults; relative paths resolve against the config's folder. An unknown
|
|
27
|
+
// provider name is an error. Keys this module does not know are returned untouched.
|
|
28
|
+
export function loadConfig(path, env = process.env) {
|
|
29
|
+
const file = resolve(path ?? defaultConfigPath(env));
|
|
30
|
+
const base = dirname(file);
|
|
31
|
+
let raw = {};
|
|
32
|
+
try {
|
|
33
|
+
raw = JSON.parse(readFileSync(file, "utf8"));
|
|
34
|
+
} catch (err) {
|
|
35
|
+
if (err.code !== "ENOENT") throw new Error(`cannot read config ${file}: ${err.message}`);
|
|
36
|
+
}
|
|
37
|
+
const data = expand(raw.data ?? (env.LLMTOP_DATA || "data"), base);
|
|
38
|
+
const configured = raw.providers ?? Object.fromEntries(Object.keys(PROVIDERS).map((k) => [k, {}]));
|
|
39
|
+
const providers = Object.fromEntries(Object.entries(configured).map(([name, p]) => {
|
|
40
|
+
if (!Object.hasOwn(PROVIDERS, name)) throw new Error(`unknown provider "${name}" in ${file}; known: ${Object.keys(PROVIDERS).join(", ")}`);
|
|
41
|
+
return [name, { ...p, transcripts: expand(p?.transcripts ?? PROVIDERS[name].defaultPath, base) }];
|
|
42
|
+
}));
|
|
43
|
+
return {
|
|
44
|
+
...raw,
|
|
45
|
+
configPath: file,
|
|
46
|
+
root: base,
|
|
47
|
+
providers,
|
|
48
|
+
data,
|
|
49
|
+
archive: join(data, "archive"),
|
|
50
|
+
database: join(data, "usage.db"),
|
|
51
|
+
prices: expand(raw.prices ?? join(ROOT, "prices.md"), base),
|
|
52
|
+
timeZone: raw.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
53
|
+
port: raw.port ?? 4310,
|
|
54
|
+
};
|
|
55
|
+
}
|
package/src/context.mjs
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Compactions, the cost of reading the context by its size, and a replay of the same requests under other compaction
|
|
2
|
+
// points. loadRows in usage.mjs calls these per session; the rows they return are summed by the page under any filter.
|
|
3
|
+
import { priceAt, usageKinds } from "./prices.mjs";
|
|
4
|
+
|
|
5
|
+
// Context per request in buckets: under 50K, 50–100K, 100–200K, 200–300K, 300–400K, 400–600K, 600K and over.
|
|
6
|
+
export const EDGES = [50e3, 100e3, 200e3, 300e3, 400e3, 600e3];
|
|
7
|
+
export const BUCKETS = EDGES.length + 1;
|
|
8
|
+
export const bucketOf = (ctx) => { let k = 0; while (k < EDGES.length && ctx >= EDGES[k]) k++; return k; };
|
|
9
|
+
export const contextOf = (r) => r.input + r.cache_read + r.cache_write;
|
|
10
|
+
|
|
11
|
+
// The points a session is replayed at, in tokens of context; the last is where a native 1M model compacts by default.
|
|
12
|
+
// The replay adds one more point: where compaction fires now.
|
|
13
|
+
export const POINTS = [200e3, 250e3, 300e3, 350e3, 400e3, 500e3, 600e3, 800e3, 967e3];
|
|
14
|
+
export const REPLAY = POINTS.length + 1; // the points, then now
|
|
15
|
+
export const PARTS = 4; // per point: compactions, reading the context, compacting, rebuilds after idle
|
|
16
|
+
|
|
17
|
+
export const median = (xs) => {
|
|
18
|
+
const v = xs.filter((x) => x !== null && x !== undefined).sort((a, b) => a - b), m = v.length >> 1;
|
|
19
|
+
return v.length ? (v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2) : null;
|
|
20
|
+
};
|
|
21
|
+
const byTime = (a, b) => Date.parse(a.ts) - Date.parse(b.ts) || a.line - b.line;
|
|
22
|
+
const LAST = 5; // compactions that tell where compaction fires now
|
|
23
|
+
const TAIL = 15; // requests after a session's last compaction under which it ended soon after
|
|
24
|
+
|
|
25
|
+
// One session's compactions, each with the requests around it on its own thread. reqs: the session's requests;
|
|
26
|
+
// comps: its rows of the compactions table; owners: the timestamps of its owner messages.
|
|
27
|
+
export function compactionsOf(reqs, comps, owners) {
|
|
28
|
+
const threads = new Map();
|
|
29
|
+
for (const r of reqs) (threads.get(r.agent_id ?? "") ?? threads.set(r.agent_id ?? "", []).get(r.agent_id ?? "")).push(r);
|
|
30
|
+
for (const list of threads.values()) list.sort(byTime);
|
|
31
|
+
const turns = owners.map((ts) => Date.parse(ts)).sort((a, b) => a - b);
|
|
32
|
+
const out = [];
|
|
33
|
+
const byThread = new Map();
|
|
34
|
+
for (const c of comps) if (c.ts) (byThread.get(c.agent_id ?? "") ?? byThread.set(c.agent_id ?? "", []).get(c.agent_id ?? "")).push(c);
|
|
35
|
+
for (const [agent, list] of byThread) {
|
|
36
|
+
list.sort(byTime);
|
|
37
|
+
const rs = threads.get(agent) ?? [];
|
|
38
|
+
const at = rs.map((r) => Date.parse(r.ts));
|
|
39
|
+
list.forEach((c, k) => {
|
|
40
|
+
const t = Date.parse(c.ts), next = list[k + 1] ? Date.parse(list[k + 1].ts) : Infinity;
|
|
41
|
+
const after = at.findIndex((x) => x > t), i = after < 0 ? rs.length : after;
|
|
42
|
+
const before = rs[i - 1] ?? null, first = rs[i] ?? null;
|
|
43
|
+
const span = at.filter((x) => x > t && x < next).length;
|
|
44
|
+
out.push({
|
|
45
|
+
c, sub: agent !== "", before, after: first, nth: k + 1,
|
|
46
|
+
// Requests and owner turns up to the next compaction on the thread; for the last one, the requests that followed.
|
|
47
|
+
next: k + 1 < list.length ? span : null, tail: k + 1 < list.length ? null : span,
|
|
48
|
+
turns: agent === "" && k + 1 < list.length ? turns.filter((x) => x > t && x < next).length : null,
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// What the request that writes each summary cost. It leaves no record in the transcript, so per model it is the host's
|
|
56
|
+
// tokens less the transcript's, priced as a share of the host's cost and split evenly over that model's compactions.
|
|
57
|
+
// rows: compactionsOf's rows; tokens, costs: the session's host record per model; targets(key): the requests of a model key.
|
|
58
|
+
export function summaryCosts(rows, tokens, costs, targets, prices, day) {
|
|
59
|
+
const out = new Map();
|
|
60
|
+
for (const [key, u] of Object.entries(tokens ?? {})) {
|
|
61
|
+
const reqs = targets(key), mine = rows.filter((x) => x.before && reqs.includes(x.before));
|
|
62
|
+
const row = priceAt(prices, key, day);
|
|
63
|
+
if (!mine.length || !row || !costs?.[key]) continue;
|
|
64
|
+
const sum = (k) => reqs.reduce((n, r) => n + (k(r) ?? 0), 0);
|
|
65
|
+
const w1 = sum((r) => r.cache_write_1h ?? r.cache_write);
|
|
66
|
+
const hidden = {
|
|
67
|
+
input: Math.max(0, u.input - sum((r) => r.input)), output: Math.max(0, u.output - sum((r) => r.output)), read: Math.max(0, u.read - sum((r) => r.cache_read)),
|
|
68
|
+
write: Math.max(0, u.write - sum((r) => r.cache_write)), w1: Math.max(0, (u.w1 ?? 0) - w1), w5: Math.max(0, (u.w5 ?? 0) - (sum((r) => r.cache_write) - w1)), split: u.split,
|
|
69
|
+
};
|
|
70
|
+
const all = usageKinds(row.p, u).reduce((a, b) => a + b, 0), part = usageKinds(row.p, hidden).reduce((a, b) => a + b, 0);
|
|
71
|
+
if (!all) continue;
|
|
72
|
+
const each = (costs[key] * part) / all / mine.length;
|
|
73
|
+
for (const x of mine) out.set(x, { cost: each, input: hidden.input / mine.length, output: hidden.output / mine.length, write: hidden.write / mine.length });
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Where compaction fires now per model family: the median context of the last auto compactions of the main thread.
|
|
79
|
+
// A family that never compacted takes the level of the family that compacted last, as one window usually serves all.
|
|
80
|
+
export function levelsOf(rows) {
|
|
81
|
+
const auto = rows.filter((x) => !x.sub && x.c.trigger === "auto" && x.c.pre_tokens && x.before).sort((a, b) => byTime(a.c, b.c));
|
|
82
|
+
const families = new Map();
|
|
83
|
+
for (const x of auto) (families.get(x.before.family) ?? families.set(x.before.family, []).get(x.before.family)).push(x.c.pre_tokens);
|
|
84
|
+
const levels = {};
|
|
85
|
+
for (const [family, list] of families) levels[family] = Math.round(median(list.slice(-LAST)) / 1000) * 1000;
|
|
86
|
+
const fallback = auto.length ? levels[auto.at(-1).before.family] : null;
|
|
87
|
+
return { levels, fallback };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// What one compaction takes per model family, from the compactions recorded: the context it restarts at, the tokens the
|
|
91
|
+
// summary request writes beyond reading the context, and what the first request after it writes to the cache.
|
|
92
|
+
// Without a record of its own, a family takes these defaults.
|
|
93
|
+
const DEFAULTS = { restart: 106e3, input: 3800, output: 8600, write: 9100, rebuild: 53e3 };
|
|
94
|
+
export function constantsOf(rows, summaries) {
|
|
95
|
+
const by = new Map();
|
|
96
|
+
for (const x of rows) if (x.before) (by.get(x.before.family) ?? by.set(x.before.family, []).get(x.before.family)).push(x);
|
|
97
|
+
const out = {};
|
|
98
|
+
for (const [family, list] of by) {
|
|
99
|
+
const s = list.map((x) => summaries.get(x)).filter(Boolean);
|
|
100
|
+
const main = list.filter((x) => !x.sub && x.after);
|
|
101
|
+
out[family] = {
|
|
102
|
+
restart: median(main.map((x) => contextOf(x.after))) ?? DEFAULTS.restart,
|
|
103
|
+
input: median(s.map((v) => v.input)) ?? DEFAULTS.input, output: median(s.map((v) => v.output)) ?? DEFAULTS.output,
|
|
104
|
+
write: median(s.map((v) => v.write)) ?? DEFAULTS.write,
|
|
105
|
+
rebuild: median(main.filter((x) => x.after.rebuild === "compaction").map((x) => x.after.cache_write)) ?? DEFAULTS.rebuild,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return (family) => out[family] ?? DEFAULTS;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// The main thread replayed at each point: the context grows between requests as it did, a recorded compaction is taken
|
|
112
|
+
// out, a sharp drop that is not one (a rewind) is followed, and whenever the context reaches the point it compacts,
|
|
113
|
+
// charging the summary request and the rewrite after it, and restarts. Every request reads its context, and a request that
|
|
114
|
+
// rebuilt the cache after idle rewrites it. Returns per request a vector of REPLAY × PARTS.
|
|
115
|
+
// reqs: the main thread in order; compactions: their instants (ms); levelOf(family): where it fires now, or null.
|
|
116
|
+
export function replay(reqs, compactions, prices, constants, levelOf) {
|
|
117
|
+
const out = new Map();
|
|
118
|
+
if (!reqs.length) return out;
|
|
119
|
+
const grows = [];
|
|
120
|
+
for (let i = 1; i < reqs.length; i++) { const d = contextOf(reqs[i]) - contextOf(reqs[i - 1]); if (d > 0) grows.push(d); }
|
|
121
|
+
const growth = median(grows) ?? 2000;
|
|
122
|
+
const long = reqs.some((r) => r.cache_write_1h > 0);
|
|
123
|
+
const cur = new Array(REPLAY).fill(contextOf(reqs[0]));
|
|
124
|
+
for (let i = 0; i < reqs.length; i++) {
|
|
125
|
+
const r = reqs[i], v = new Array(REPLAY * PARTS).fill(0), p = priceAt(prices, r.model, r.day)?.p ?? null, k = constants(r.family);
|
|
126
|
+
if (i > 0) {
|
|
127
|
+
const prev = contextOf(reqs[i - 1]), now = contextOf(r), t0 = Date.parse(reqs[i - 1].ts), t1 = Date.parse(r.ts);
|
|
128
|
+
const compacted = compactions.some((c) => c > t0 && c <= t1);
|
|
129
|
+
for (let j = 0; j < REPLAY; j++) {
|
|
130
|
+
if (compacted) cur[j] += growth;
|
|
131
|
+
else if (now < prev * 0.6) cur[j] = now;
|
|
132
|
+
else cur[j] += now - prev;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
for (let j = 0; j < REPLAY; j++) {
|
|
136
|
+
const at = j < POINTS.length ? POINTS[j] : levelOf(r.family);
|
|
137
|
+
if (!at) continue;
|
|
138
|
+
if (cur[j] >= at) {
|
|
139
|
+
v[j * PARTS] += 1;
|
|
140
|
+
if (p) v[j * PARTS + 2] += (at * p[2] + k.input * p[0] + k.output * p[1] + (k.write + k.rebuild) * (long ? p[4] : p[3])) / 1e6;
|
|
141
|
+
cur[j] = Math.min(k.restart, at / 2);
|
|
142
|
+
}
|
|
143
|
+
if (p) {
|
|
144
|
+
v[j * PARTS + 1] += (cur[j] * p[2]) / 1e6;
|
|
145
|
+
if (r.rebuild === "idle") v[j * PARTS + 3] += (cur[j] * ((long ? p[4] : p[3]) - p[2])) / 1e6;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
out.set(r, v);
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { readDb } from "./db.mjs";
|
|
2
|
+
import { effortRuns } from "./effort.mjs";
|
|
3
|
+
import { EDGES, POINTS } from "./context.mjs";
|
|
4
|
+
import { EFFORTS, effortOrder, loadRows } from "./usage.mjs";
|
|
5
|
+
|
|
6
|
+
const round = (n, d = 6) => Math.round(n * 10 ** d) / 10 ** d;
|
|
7
|
+
|
|
8
|
+
export function dashboardData(db, config, now = new Date()) {
|
|
9
|
+
const rows = loadRows(db, config, now);
|
|
10
|
+
const typeCount = new Map();
|
|
11
|
+
for (const a of rows.subagents) typeCount.set(a.type, (typeCount.get(a.type) ?? 0) + 1);
|
|
12
|
+
const types = [...typeCount.keys()].sort((a, b) => typeCount.get(b) - typeCount.get(a));
|
|
13
|
+
// Effort as an index: the five levels first, so a level keeps its color, then any other value seen; none is "unknown".
|
|
14
|
+
const runs = effortRuns(db);
|
|
15
|
+
const seen = new Set([...rows.facts.map((f) => f.e || "unknown"), ...[...runs.values()].flat().map((r) => r.level)]);
|
|
16
|
+
const efforts = [...EFFORTS, ...[...seen].filter((e) => !EFFORTS.includes(e) && e !== "unknown").sort(effortOrder), ...(seen.has("unknown") ? ["unknown"] : [])];
|
|
17
|
+
const ei = (e) => efforts.indexOf(e || "unknown");
|
|
18
|
+
return {
|
|
19
|
+
today: rows.today, scanned: rows.scanned, models: rows.models, providers: rows.providers, projects: rows.projects, types, efforts,
|
|
20
|
+
transcripts: db.prepare("SELECT COUNT(*) n FROM files WHERE kind = 'main'").get().n,
|
|
21
|
+
sessions: rows.sessions.map((s) => ({ ...s, id: s.id.slice(0, 8), dur: round(s.dur, 2), tool: round(s.tool, 1), runs: (runs.get(s.id) ?? []).map((r) => [ei(r.level), r.requests]) })),
|
|
22
|
+
// rb: the rebuild vector of src/usage.mjs, or null when no request of the fact rebuilt the cache.
|
|
23
|
+
// k: the cost split into reading the context, writing the cache, output and web search, or null when nothing of it was priced.
|
|
24
|
+
// sv: what the cache saved; tc, te: tool calls and failed ones; ot: owner turns the fact's requests answered first.
|
|
25
|
+
facts: rows.facts.map((f) => [f.s, f.d, f.h, f.m, f.sub, ei(f.e), f.q, f.i, f.o, f.cr, f.cw, f.th, f.c, f.rb && f.rb.map((x) => round(x)), f.k && f.k.map((x) => round(x)), round(f.sv), f.tc, f.te, f.ot]),
|
|
26
|
+
subagents: rows.subagents.map((a) => ({ ...a, type: types.indexOf(a.type) })),
|
|
27
|
+
tools: rows.tools.map(shortToolNames),
|
|
28
|
+
skills: rows.skills, skillSources: rows.skillSources,
|
|
29
|
+
// One row per compaction: session, day, model, effort, subagent, auto (1), manual (0) or unknown (null), context before,
|
|
30
|
+
// summary tokens, wait (ms), context of the next request, its order on the thread, requests and owner turns to the next one
|
|
31
|
+
// (null for the last), requests after the last one (null otherwise), the summary request's cost and the rewrite after it.
|
|
32
|
+
compactions: rows.compactions.map((x) => [x.s, x.d, x.m, ei(x.e), x.sub, x.auto, x.pre, x.post, x.wait, x.kept, x.nth, x.next, x.turns, x.tail, x.sum === null ? null : round(x.sum), round(x.rb)]),
|
|
33
|
+
// Per session, day, model and effort: the cost of reading the context per size bucket (plus a last part with no
|
|
34
|
+
// request), requests per bucket, and the replay as compactions, reading, compacting and idle rebuilds per point.
|
|
35
|
+
context: rows.context.map((x) => [x.s, x.d, x.m, ei(x.e), x.b.map((v) => round(v)), x.n, x.r && x.r.map((v) => round(v, 4))]),
|
|
36
|
+
edges: EDGES, points: POINTS, fires: rows.levels,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// An MCP tool reads better by its own name than by mcp__<server>__<tool>; tools sharing a name are summed.
|
|
41
|
+
export function shortToolNames(calls) {
|
|
42
|
+
const out = {};
|
|
43
|
+
for (const [name, [n, e]] of Object.entries(calls)) {
|
|
44
|
+
const short = name.startsWith("mcp__") ? name.split("__").at(-1) : name;
|
|
45
|
+
const [pn, pe] = out[short] ?? [0, 0];
|
|
46
|
+
out[short] = [pn + n, pe + e];
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Rows of the views, read from the database as the last scan left it.
|
|
52
|
+
export const buildUsageRows = (config, now = new Date()) => withDb(config, (db) => dashboardData(db, config, now));
|
|
53
|
+
|
|
54
|
+
export function withDb(config, fn) {
|
|
55
|
+
const db = readDb(config.database);
|
|
56
|
+
try {
|
|
57
|
+
return fn(db);
|
|
58
|
+
} finally {
|
|
59
|
+
db.close();
|
|
60
|
+
}
|
|
61
|
+
}
|
package/src/db.mjs
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
|
|
5
|
+
// Bump when the schema changes: the database is then rebuilt from the archive.
|
|
6
|
+
export const SCHEMA_VERSION = 13;
|
|
7
|
+
|
|
8
|
+
const SCHEMA = `
|
|
9
|
+
CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT);
|
|
10
|
+
CREATE TABLE files(id INTEGER PRIMARY KEY, provider TEXT, path TEXT, kind TEXT, session_id TEXT, agent_id TEXT,
|
|
11
|
+
generation INTEGER DEFAULT 0, offset INTEGER DEFAULT 0, lines INTEGER DEFAULT 0, head_hash TEXT,
|
|
12
|
+
archive_size INTEGER DEFAULT 0, first_ts TEXT, own_first TEXT, own_last TEXT, cwd TEXT, live INTEGER DEFAULT 1,
|
|
13
|
+
UNIQUE(provider, path));
|
|
14
|
+
CREATE TABLE records(uuid TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, type TEXT, ts TEXT);
|
|
15
|
+
CREATE INDEX files_session ON files(session_id);
|
|
16
|
+
CREATE INDEX records_file ON records(file_id);
|
|
17
|
+
CREATE TABLE requests(message_id TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, agent_id TEXT,
|
|
18
|
+
ts TEXT, day TEXT, hour INTEGER, model TEXT, family TEXT, effort TEXT, is_sub INTEGER,
|
|
19
|
+
input INTEGER, output INTEGER, thinking INTEGER, cache_read INTEGER, cache_write INTEGER, cache_write_1h INTEGER,
|
|
20
|
+
rebuild TEXT, rebuild_gap INTEGER, rebuild_extra REAL);
|
|
21
|
+
CREATE INDEX requests_session ON requests(session_id);
|
|
22
|
+
CREATE INDEX requests_day ON requests(day);
|
|
23
|
+
CREATE TABLE repeats(file_id INTEGER, message_id TEXT, PRIMARY KEY(file_id, message_id));
|
|
24
|
+
CREATE TABLE owner_messages(uuid TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, ts TEXT,
|
|
25
|
+
kind TEXT, text TEXT);
|
|
26
|
+
CREATE INDEX owner_messages_session ON owner_messages(session_id);
|
|
27
|
+
CREATE VIRTUAL TABLE owner_text USING fts5(text, content='owner_messages', content_rowid='rowid',
|
|
28
|
+
tokenize="unicode61 remove_diacritics 2");
|
|
29
|
+
CREATE TRIGGER owner_messages_ai AFTER INSERT ON owner_messages BEGIN
|
|
30
|
+
INSERT INTO owner_text(rowid, text) VALUES (new.rowid, new.text); END;
|
|
31
|
+
CREATE TRIGGER owner_messages_ad AFTER DELETE ON owner_messages BEGIN
|
|
32
|
+
INSERT INTO owner_text(owner_text, rowid, text) VALUES ('delete', old.rowid, old.text); END;
|
|
33
|
+
CREATE TABLE tool_calls(id TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, agent_id TEXT,
|
|
34
|
+
ts TEXT, name TEXT, model TEXT, is_error INTEGER);
|
|
35
|
+
CREATE INDEX tool_calls_session ON tool_calls(session_id);
|
|
36
|
+
CREATE TABLE skills(id TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, ts TEXT, name TEXT, via TEXT,
|
|
37
|
+
source TEXT, is_error INTEGER DEFAULT 0);
|
|
38
|
+
CREATE INDEX skills_session ON skills(session_id);
|
|
39
|
+
CREATE TABLE subagents(agent_id TEXT PRIMARY KEY, session_id TEXT, type TEXT, tool_use_id TEXT);
|
|
40
|
+
CREATE TABLE file_meta(file_id INTEGER PRIMARY KEY, parent_session_id TEXT, subagent_type TEXT, tool_use_id TEXT,
|
|
41
|
+
api_ms INTEGER, tool_ms INTEGER, lines_added INTEGER, lines_removed INTEGER, repo_url TEXT, target_paths TEXT);
|
|
42
|
+
CREATE TABLE compactions(uuid TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, agent_id TEXT, ts TEXT,
|
|
43
|
+
trigger TEXT, pre_tokens INTEGER, post_tokens INTEGER, duration_ms INTEGER);
|
|
44
|
+
CREATE INDEX compactions_session ON compactions(session_id);
|
|
45
|
+
CREATE TABLE cost_states(file_id INTEGER, line INTEGER, session_id TEXT, start_ms INTEGER, cost REAL,
|
|
46
|
+
incomplete INTEGER, api_ms INTEGER, tool_ms INTEGER, lines_added INTEGER, lines_removed INTEGER,
|
|
47
|
+
model_usage TEXT, PRIMARY KEY(file_id, line));
|
|
48
|
+
CREATE TABLE titles(file_id INTEGER, line INTEGER, session_id TEXT, kind TEXT, title TEXT, PRIMARY KEY(file_id, line));
|
|
49
|
+
CREATE TABLE sessions(id TEXT PRIMARY KEY, provider TEXT, slug TEXT, cwd TEXT, project TEXT, title TEXT, first_ts TEXT,
|
|
50
|
+
last_ts TEXT, cost REAL, cost_incomplete INTEGER, cost_estimated INTEGER, price_check TEXT, api_ms INTEGER, tool_ms INTEGER,
|
|
51
|
+
lines_added INTEGER, lines_removed INTEGER, carried_from TEXT,
|
|
52
|
+
model_cost TEXT, model_tokens TEXT);
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
// Tables holding rows ingested from one transcript file; used when a file starts a new generation.
|
|
56
|
+
export const FILE_TABLES = ["records", "requests", "repeats", "owner_messages", "tool_calls", "skills", "compactions", "cost_states", "titles", "file_meta"];
|
|
57
|
+
|
|
58
|
+
export function openDb(path) {
|
|
59
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
60
|
+
if (existsSync(path)) {
|
|
61
|
+
const old = new DatabaseSync(path);
|
|
62
|
+
const version = (() => {
|
|
63
|
+
try {
|
|
64
|
+
return old.prepare("SELECT value FROM meta WHERE key = 'schema'").get()?.value;
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
})();
|
|
69
|
+
if (version === String(SCHEMA_VERSION)) return old;
|
|
70
|
+
old.close();
|
|
71
|
+
for (const f of [path, `${path}-wal`, `${path}-shm`]) rmSync(f, { force: true });
|
|
72
|
+
}
|
|
73
|
+
const db = new DatabaseSync(path);
|
|
74
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
75
|
+
db.exec(SCHEMA);
|
|
76
|
+
db.prepare("INSERT INTO meta(key, value) VALUES ('schema', ?)").run(String(SCHEMA_VERSION));
|
|
77
|
+
return db;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// For commands that only read: the database must exist at the current schema.
|
|
81
|
+
export function readDb(path) {
|
|
82
|
+
if (!existsSync(path)) throw new Error("no database yet: run `llmtop scan` first");
|
|
83
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
84
|
+
const version = db.prepare("SELECT value FROM meta WHERE key = 'schema'").get()?.value;
|
|
85
|
+
if (version !== String(SCHEMA_VERSION)) {
|
|
86
|
+
db.close();
|
|
87
|
+
throw new Error("the database predates this version of the tool: run `llmtop scan` to rebuild it");
|
|
88
|
+
}
|
|
89
|
+
return db;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function transaction(db, fn) {
|
|
93
|
+
db.exec("BEGIN");
|
|
94
|
+
try {
|
|
95
|
+
const result = fn();
|
|
96
|
+
db.exec("COMMIT");
|
|
97
|
+
return result;
|
|
98
|
+
} catch (err) {
|
|
99
|
+
db.exec("ROLLBACK");
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
}
|