llmtop 0.1.1 → 0.1.3
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/README.md +5 -1
- package/bin/llmtop.mjs +44 -4
- package/dashboard/dist/assets/index-NQzaBVIY.css +1 -0
- package/dashboard/dist/assets/montserrat-cyrillic-ext-wght-normal-CO5hGrJv.woff2 +0 -0
- package/dashboard/dist/assets/montserrat-cyrillic-wght-normal-EAA9jha_.woff2 +0 -0
- package/dashboard/dist/assets/montserrat-latin-ext-wght-normal-BsZE-iaG.woff2 +0 -0
- package/dashboard/dist/assets/montserrat-latin-wght-normal-l_AIctKy.woff2 +0 -0
- package/dashboard/dist/assets/montserrat-vietnamese-wght-normal-k7S-YeeD.woff2 +0 -0
- package/dashboard/dist/assets/roboto-mono-cyrillic-ext-wght-normal-BUDPrIko.woff2 +0 -0
- package/dashboard/dist/assets/roboto-mono-cyrillic-wght-normal-HUlVHixE.woff2 +0 -0
- package/dashboard/dist/assets/roboto-mono-greek-wght-normal-BJJTbwTT.woff2 +0 -0
- package/dashboard/dist/assets/roboto-mono-latin-ext-wght-normal-QAYlOegK.woff2 +0 -0
- package/dashboard/dist/assets/roboto-mono-latin-wght-normal-CZtBPCCa.woff2 +0 -0
- package/dashboard/dist/assets/roboto-mono-vietnamese-wght-normal-DlC-zuDL.woff2 +0 -0
- package/dashboard/dist/index.html +2 -2
- package/dashboard/src/main.tsx +2 -0
- package/dashboard/src/styles.css +2 -2
- package/package.json +3 -1
- package/src/db.mjs +33 -2
- package/src/derive.mjs +110 -27
- package/src/install.mjs +58 -0
- package/src/prices.mjs +22 -2
- package/src/process.mjs +237 -0
- package/src/providers/agy.mjs +60 -26
- package/src/providers/claude.mjs +17 -18
- package/src/providers/codex.mjs +68 -33
- package/src/rebuilds.mjs +35 -11
- package/src/scan.mjs +104 -22
- package/src/uninstall.mjs +179 -0
- package/src/update.mjs +140 -0
- package/dashboard/dist/assets/index-Cp7Swcz5.css +0 -1
- /package/dashboard/dist/assets/{index-BVbAwMVB.js → index-Ba0kF2tG.js} +0 -0
package/src/providers/codex.mjs
CHANGED
|
@@ -250,7 +250,7 @@ export function createIngester(db, timeZone) {
|
|
|
250
250
|
};
|
|
251
251
|
const stateByFile = new Map();
|
|
252
252
|
|
|
253
|
-
|
|
253
|
+
function ingestLine(file, line, text) {
|
|
254
254
|
let rec;
|
|
255
255
|
try {
|
|
256
256
|
rec = JSON.parse(text);
|
|
@@ -271,6 +271,7 @@ export function createIngester(db, timeZone) {
|
|
|
271
271
|
baseAdded: prevStats?.lines_added ?? 0, baseRemoved: prevStats?.lines_removed ?? 0,
|
|
272
272
|
sawFileChange: false, fcAdded: 0, fcRemoved: 0, patchAdded: 0, patchRemoved: 0,
|
|
273
273
|
paths: createPathTracker(prevStats?.target_paths ?? null),
|
|
274
|
+
statsDirty: false, pathsDirty: false,
|
|
274
275
|
};
|
|
275
276
|
stateByFile.set(file.id, st);
|
|
276
277
|
}
|
|
@@ -284,15 +285,13 @@ export function createIngester(db, timeZone) {
|
|
|
284
285
|
const tsMs = Number.isFinite(parsedTs) ? parsedTs : null;
|
|
285
286
|
let cwd = p.cwd ?? null;
|
|
286
287
|
let added = 0;
|
|
287
|
-
let statsDirty = false;
|
|
288
|
-
let pathsDirty = false;
|
|
289
288
|
|
|
290
289
|
const consumeOpenWait = () => {
|
|
291
290
|
if (tsMs !== null && st.lastWaitFromMs !== null) {
|
|
292
291
|
const dt = tsMs - st.lastWaitFromMs;
|
|
293
292
|
if (dt > 0 && dt < 600_000) {
|
|
294
293
|
st.openApiMs += dt;
|
|
295
|
-
statsDirty = true;
|
|
294
|
+
st.statsDirty = true;
|
|
296
295
|
}
|
|
297
296
|
st.lastWaitFromMs = null;
|
|
298
297
|
}
|
|
@@ -333,7 +332,7 @@ export function createIngester(db, timeZone) {
|
|
|
333
332
|
if (p.cwd) {
|
|
334
333
|
st.launchCwd ??= p.cwd;
|
|
335
334
|
st.cwd = p.cwd;
|
|
336
|
-
if (p.cwd !== st.launchCwd && st.paths.add(p.cwd, { write: false })) pathsDirty = true;
|
|
335
|
+
if (p.cwd !== st.launchCwd && st.paths.add(p.cwd, { write: false })) st.pathsDirty = true;
|
|
337
336
|
}
|
|
338
337
|
if (p.model) st.model = p.model;
|
|
339
338
|
const eff = p.effort ?? p.collaboration_mode?.settings?.reasoning_effort;
|
|
@@ -383,12 +382,12 @@ export function createIngester(db, timeZone) {
|
|
|
383
382
|
if (patch.added || patch.removed) {
|
|
384
383
|
st.patchAdded += patch.added;
|
|
385
384
|
st.patchRemoved += patch.removed;
|
|
386
|
-
if (!st.sawFileChange) statsDirty = true;
|
|
385
|
+
if (!st.sawFileChange) st.statsDirty = true;
|
|
387
386
|
}
|
|
388
387
|
if (inputStr.includes("*** ")) {
|
|
389
388
|
const unesc = inputStr.includes("*** Begin Patch\\n") ? inputStr.replace(/\\n/g, "\n") : inputStr;
|
|
390
389
|
for (const m of unesc.matchAll(/^\*\*\* (?:Update|Add|Delete) File:\s*([^\r\n`"]+)/gm)) {
|
|
391
|
-
if (st.paths.add(m[1].trim(), { isFile: true, write: true, baseCwd: st.cwd })) pathsDirty = true;
|
|
390
|
+
if (st.paths.add(m[1].trim(), { isFile: true, write: true, baseCwd: st.cwd })) st.pathsDirty = true;
|
|
392
391
|
}
|
|
393
392
|
}
|
|
394
393
|
const vars = new Map();
|
|
@@ -397,10 +396,10 @@ export function createIngester(db, timeZone) {
|
|
|
397
396
|
}
|
|
398
397
|
for (const m of inputStr.matchAll(/(?:workdir|"workdir")\s*:\s*(?:["'`]([^"'`\n]+)["'`]|([A-Za-z_$][\w$]*))/g)) {
|
|
399
398
|
const wd = m[1] ?? (m[2] ? vars.get(m[2]) : null);
|
|
400
|
-
if (wd && st.paths.add(wd, { write: false, baseCwd: st.cwd })) pathsDirty = true;
|
|
399
|
+
if (wd && st.paths.add(wd, { write: false, baseCwd: st.cwd })) st.pathsDirty = true;
|
|
401
400
|
}
|
|
402
401
|
for (const dir of extractCommandDirs(inputStr, st.cwd)) {
|
|
403
|
-
if (st.paths.add(dir, { write: false })) pathsDirty = true;
|
|
402
|
+
if (st.paths.add(dir, { write: false })) st.pathsDirty = true;
|
|
404
403
|
}
|
|
405
404
|
const loadedSkills = extractSkillPaths(inputStr);
|
|
406
405
|
if (loadedSkills.length) {
|
|
@@ -429,7 +428,7 @@ export function createIngester(db, timeZone) {
|
|
|
429
428
|
if (dur > 0) {
|
|
430
429
|
st.toolMs += dur;
|
|
431
430
|
st.turnToolMs += dur;
|
|
432
|
-
statsDirty = true;
|
|
431
|
+
st.statsDirty = true;
|
|
433
432
|
}
|
|
434
433
|
if (tsMs !== null) st.lastWaitFromMs = tsMs;
|
|
435
434
|
} else if (p.type === "compaction") {
|
|
@@ -454,10 +453,10 @@ export function createIngester(db, timeZone) {
|
|
|
454
453
|
: (st.turnStartMs !== null && tsMs !== null ? Math.max(0, tsMs - st.turnStartMs) : null);
|
|
455
454
|
if (totalTurn !== null) {
|
|
456
455
|
st.completedApiMs += Math.max(0, totalTurn - Math.min(totalTurn, st.turnToolMs));
|
|
457
|
-
statsDirty = true;
|
|
456
|
+
st.statsDirty = true;
|
|
458
457
|
} else if (st.openApiMs > 0) {
|
|
459
458
|
st.completedApiMs += st.openApiMs;
|
|
460
|
-
statsDirty = true;
|
|
459
|
+
st.statsDirty = true;
|
|
461
460
|
}
|
|
462
461
|
st.turnStartMs = null;
|
|
463
462
|
st.turnToolMs = 0;
|
|
@@ -478,7 +477,7 @@ export function createIngester(db, timeZone) {
|
|
|
478
477
|
} else if (p.type === "item_completed" && p.item?.type === "FileChange") {
|
|
479
478
|
if (!p.item.status || p.item.status === "completed") {
|
|
480
479
|
for (const [fp, ch] of Object.entries(p.item.changes ?? {})) {
|
|
481
|
-
if (st.paths.add(fp, { isFile: true, write: true, baseCwd: st.cwd })) pathsDirty = true;
|
|
480
|
+
if (st.paths.add(fp, { isFile: true, write: true, baseCwd: st.cwd })) st.pathsDirty = true;
|
|
482
481
|
if (ch?.type === "add") st.fcAdded += lineCount(ch.content);
|
|
483
482
|
else if (ch?.type === "delete") st.fcRemoved += lineCount(ch.content);
|
|
484
483
|
else if (ch?.type === "update" && typeof ch.unified_diff === "string") {
|
|
@@ -488,7 +487,7 @@ export function createIngester(db, timeZone) {
|
|
|
488
487
|
}
|
|
489
488
|
}
|
|
490
489
|
st.sawFileChange = true;
|
|
491
|
-
statsDirty = true;
|
|
490
|
+
st.statsDirty = true;
|
|
492
491
|
}
|
|
493
492
|
} else if (p.type === "token_count" && !st.sawTokenRec && p.info?.last_token_usage) {
|
|
494
493
|
consumeOpenWait();
|
|
@@ -501,19 +500,28 @@ export function createIngester(db, timeZone) {
|
|
|
501
500
|
}
|
|
502
501
|
}
|
|
503
502
|
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
503
|
+
return { added, cwd, ts, own: true };
|
|
504
|
+
}
|
|
505
|
+
ingestLine.flush = (fileId) => {
|
|
506
|
+
const st = stateByFile.get(fileId);
|
|
507
|
+
if (!st) return;
|
|
508
|
+
if (st.statsDirty) {
|
|
509
|
+
st.statsDirty = false;
|
|
510
|
+
const totalApiMs = Math.round(st.completedApiMs + st.openApiMs);
|
|
511
|
+
const linesAdded = st.baseAdded + (st.sawFileChange ? st.fcAdded : st.patchAdded);
|
|
512
|
+
const linesRemoved = st.baseRemoved + (st.sawFileChange ? st.fcRemoved : st.patchRemoved);
|
|
513
|
+
if (totalApiMs > 0 || st.toolMs > 0 || linesAdded > 0 || linesRemoved > 0) {
|
|
514
|
+
q.upsertStats.run(fileId, totalApiMs, Math.round(st.toolMs), linesAdded, linesRemoved);
|
|
515
|
+
}
|
|
509
516
|
}
|
|
510
|
-
if (pathsDirty) {
|
|
517
|
+
if (st.pathsDirty) {
|
|
518
|
+
st.pathsDirty = false;
|
|
511
519
|
const json = st.paths.toJSON();
|
|
512
|
-
if (json) q.upsertTargetPaths.run(
|
|
520
|
+
if (json) q.upsertTargetPaths.run(fileId, json);
|
|
513
521
|
}
|
|
514
|
-
|
|
515
|
-
return { added, cwd, ts, own: true };
|
|
516
522
|
};
|
|
523
|
+
ingestLine.reset = (fileId) => { stateByFile.delete(fileId); };
|
|
524
|
+
return ingestLine;
|
|
517
525
|
}
|
|
518
526
|
|
|
519
527
|
export function postScan(db, archiveDir) {
|
|
@@ -530,13 +538,17 @@ export function postScan(db, archiveDir) {
|
|
|
530
538
|
}
|
|
531
539
|
|
|
532
540
|
const allFiles = db.prepare("SELECT id, kind, session_id, agent_id FROM files WHERE provider = 'codex'").all();
|
|
541
|
+
const byFileId = new Map();
|
|
533
542
|
const byOwn = new Map();
|
|
534
|
-
for (const f of allFiles)
|
|
543
|
+
for (const f of allFiles) {
|
|
544
|
+
byFileId.set(f.id, f);
|
|
545
|
+
byOwn.set(f.agent_id ?? f.session_id, f);
|
|
546
|
+
}
|
|
535
547
|
|
|
536
548
|
const metas = db.prepare("SELECT m.file_id, m.parent_session_id, m.subagent_type, m.tool_use_id FROM file_meta m JOIN files f ON f.id = m.file_id WHERE f.provider = 'codex'").all();
|
|
537
549
|
const parentOf = new Map();
|
|
538
550
|
for (const m of metas) {
|
|
539
|
-
const f =
|
|
551
|
+
const f = byFileId.get(m.file_id);
|
|
540
552
|
if (f && m.parent_session_id) parentOf.set(f.agent_id ?? f.session_id, { parent: m.parent_session_id, type: m.subagent_type, toolUseId: m.tool_use_id });
|
|
541
553
|
}
|
|
542
554
|
const rootOf = (id) => {
|
|
@@ -551,15 +563,20 @@ export function postScan(db, archiveDir) {
|
|
|
551
563
|
return cur === id ? null : cur;
|
|
552
564
|
};
|
|
553
565
|
|
|
566
|
+
const existingSubs = new Map(db.prepare("SELECT agent_id, session_id, type, tool_use_id FROM subagents").all().map((s) => [s.agent_id, s]));
|
|
567
|
+
const existingTitles = new Map(db.prepare("SELECT file_id, session_id, title FROM titles WHERE line = 0 AND kind = 'custom'").all().map((t) => [t.file_id, t]));
|
|
568
|
+
|
|
554
569
|
const setFileSub = db.prepare("UPDATE files SET kind = 'sub', session_id = ?, agent_id = ? WHERE id = ?");
|
|
555
570
|
const setReqSub = db.prepare("UPDATE requests SET session_id = ?, agent_id = ?, is_sub = 1 WHERE file_id = ?");
|
|
556
571
|
const setCallSub = db.prepare("UPDATE tool_calls SET session_id = ?, agent_id = ? WHERE file_id = ?");
|
|
557
572
|
const setSkillSess = db.prepare("UPDATE skills SET session_id = ? WHERE file_id = ?");
|
|
558
573
|
const setCompSub = db.prepare("UPDATE compactions SET session_id = ?, agent_id = ? WHERE file_id = ?");
|
|
559
574
|
const setTitleSess = db.prepare("UPDATE titles SET session_id = ? WHERE file_id = ?");
|
|
575
|
+
const delSession = db.prepare("DELETE FROM sessions WHERE id = ?");
|
|
560
576
|
const putSub = db.prepare("INSERT OR REPLACE INTO subagents(agent_id, session_id, type, tool_use_id) VALUES (?, ?, ?, ?)");
|
|
561
577
|
const putTitle = db.prepare("INSERT OR REPLACE INTO titles(file_id, line, session_id, kind, title) VALUES (?, 0, ?, 'custom', ?)");
|
|
562
578
|
|
|
579
|
+
const dirty = new Set();
|
|
563
580
|
db.exec("BEGIN");
|
|
564
581
|
try {
|
|
565
582
|
for (const f of allFiles) {
|
|
@@ -567,23 +584,41 @@ export function postScan(db, archiveDir) {
|
|
|
567
584
|
const root = rootOf(ownId);
|
|
568
585
|
const sess = root ?? f.session_id;
|
|
569
586
|
if (root) {
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
587
|
+
if (f.kind !== "sub" || f.session_id !== root || f.agent_id !== ownId) {
|
|
588
|
+
setFileSub.run(root, ownId, f.id);
|
|
589
|
+
setReqSub.run(root, ownId, f.id);
|
|
590
|
+
setCallSub.run(root, ownId, f.id);
|
|
591
|
+
setSkillSess.run(root, f.id);
|
|
592
|
+
setCompSub.run(root, ownId, f.id);
|
|
593
|
+
setTitleSess.run(root, f.id);
|
|
594
|
+
if (f.kind === "main") delSession.run(f.session_id);
|
|
595
|
+
dirty.add(f.session_id);
|
|
596
|
+
dirty.add(root);
|
|
597
|
+
}
|
|
576
598
|
const meta = parentOf.get(ownId);
|
|
577
|
-
|
|
599
|
+
const type = meta?.type ?? "subagent";
|
|
600
|
+
const toolUseId = meta?.toolUseId ?? null;
|
|
601
|
+
const curSub = existingSubs.get(ownId);
|
|
602
|
+
if (!curSub || curSub.session_id !== root || curSub.type !== type || curSub.tool_use_id !== toolUseId) {
|
|
603
|
+
putSub.run(ownId, root, type, toolUseId);
|
|
604
|
+
dirty.add(root);
|
|
605
|
+
}
|
|
578
606
|
}
|
|
579
607
|
const title = titles.get(ownId);
|
|
580
|
-
if (title)
|
|
608
|
+
if (title) {
|
|
609
|
+
const curTitle = existingTitles.get(f.id);
|
|
610
|
+
if (!curTitle || curTitle.session_id !== sess || curTitle.title !== title) {
|
|
611
|
+
putTitle.run(f.id, sess, title);
|
|
612
|
+
dirty.add(sess);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
581
615
|
}
|
|
582
616
|
db.exec("COMMIT");
|
|
583
617
|
} catch (err) {
|
|
584
618
|
db.exec("ROLLBACK");
|
|
585
619
|
throw err;
|
|
586
620
|
}
|
|
621
|
+
return dirty;
|
|
587
622
|
}
|
|
588
623
|
|
|
589
624
|
export const codex = { name: "codex", label, defaultPath, describe, listHost, syncMeta, createIngester, postScan, familyOf, displayModel };
|
package/src/rebuilds.mjs
CHANGED
|
@@ -30,18 +30,20 @@ export function classify(requests, compactions, prices) {
|
|
|
30
30
|
for (const r of requests) {
|
|
31
31
|
if (r.model === "<synthetic>") continue;
|
|
32
32
|
const key = `${r.session_id}\n${r.agent_id ?? ""}`;
|
|
33
|
-
|
|
33
|
+
let list = threads.get(key);
|
|
34
|
+
if (!list) threads.set(key, (list = []));
|
|
35
|
+
list.push({ r, at: Date.parse(r.ts) });
|
|
34
36
|
}
|
|
35
37
|
const out = new Map();
|
|
36
|
-
for (const list of threads
|
|
37
|
-
list.sort((a, b) =>
|
|
38
|
+
for (const [key, list] of threads) {
|
|
39
|
+
list.sort((a, b) => a.at - b.at || a.r.line - b.r.line);
|
|
40
|
+
const comps = compactions.get(key) ?? [];
|
|
38
41
|
let prev = null;
|
|
39
42
|
let lifetime = SHORT_LIFETIME;
|
|
40
|
-
for (const r of list) {
|
|
41
|
-
const at = Date.parse(r.ts);
|
|
43
|
+
for (const { r, at } of list) {
|
|
42
44
|
// The first request after a compaction rewrites the new short history while it still reads the system prompt and
|
|
43
45
|
// 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 &&
|
|
46
|
+
const compacted = prev !== null && comps.some((c) => c > prev && c <= at);
|
|
45
47
|
if (isRebuild(r) || (compacted && rewrittenTokens(r) >= MIN_REWRITE)) {
|
|
46
48
|
const gap = prev === null ? null : Math.round((at - prev) / 1000);
|
|
47
49
|
let cause;
|
|
@@ -60,12 +62,34 @@ export function classify(requests, compactions, prices) {
|
|
|
60
62
|
return out;
|
|
61
63
|
}
|
|
62
64
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
65
|
+
const CHUNK = 500;
|
|
66
|
+
|
|
67
|
+
function queryBySessions(db, buildSql, sessions) {
|
|
68
|
+
const rows = [];
|
|
69
|
+
for (let i = 0; i < sessions.length; i += CHUNK) {
|
|
70
|
+
const slice = sessions.slice(i, i + CHUNK);
|
|
71
|
+
const placeholders = slice.map(() => "?").join(",");
|
|
72
|
+
for (const r of db.prepare(buildSql(placeholders)).all(...slice)) rows.push(r);
|
|
73
|
+
}
|
|
74
|
+
return rows;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Recompute the rebuild columns of requests (all or only `dirtySessions`), writing only the rows that changed.
|
|
78
|
+
export function markRebuilds(db, prices, dirtySessions = null) {
|
|
79
|
+
if (dirtySessions instanceof Set && dirtySessions.size === 0) return;
|
|
80
|
+
const reqCols = "message_id, session_id, agent_id, ts, line, model, day, input, cache_read, cache_write, cache_write_1h, rebuild, rebuild_gap, rebuild_extra";
|
|
81
|
+
let requests;
|
|
82
|
+
let compRows;
|
|
83
|
+
if (dirtySessions instanceof Set) {
|
|
84
|
+
const list = [...dirtySessions];
|
|
85
|
+
requests = queryBySessions(db, (ph) => `SELECT ${reqCols} FROM requests WHERE session_id IN (${ph})`, list);
|
|
86
|
+
compRows = queryBySessions(db, (ph) => `SELECT session_id, agent_id, ts FROM compactions WHERE ts IS NOT NULL AND session_id IN (${ph})`, list);
|
|
87
|
+
} else {
|
|
88
|
+
requests = db.prepare(`SELECT ${reqCols} FROM requests`).all();
|
|
89
|
+
compRows = db.prepare("SELECT session_id, agent_id, ts FROM compactions WHERE ts IS NOT NULL").all();
|
|
90
|
+
}
|
|
67
91
|
const compactions = new Map();
|
|
68
|
-
for (const c of
|
|
92
|
+
for (const c of compRows) {
|
|
69
93
|
const key = `${c.session_id}\n${c.agent_id ?? ""}`;
|
|
70
94
|
(compactions.get(key) ?? compactions.set(key, []).get(key)).push(Date.parse(c.ts));
|
|
71
95
|
}
|
package/src/scan.mjs
CHANGED
|
@@ -42,17 +42,22 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
42
42
|
|
|
43
43
|
const getFile = db.prepare("SELECT * FROM files WHERE provider = ? AND path = ?");
|
|
44
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 = ?");
|
|
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 = ?, ctime_ms = ? 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, ctime_ms = NULL WHERE id = ?");
|
|
47
|
+
const stampCtime = db.prepare("UPDATE files SET ctime_ms = ? WHERE id = ?");
|
|
48
|
+
const setOffline = db.prepare("UPDATE files SET live = 0 WHERE id = ?");
|
|
47
49
|
const clear = FILE_TABLES.map((t) => db.prepare(`DELETE FROM ${t} WHERE file_id = ?`));
|
|
48
50
|
|
|
49
51
|
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
52
|
|
|
51
53
|
// Every transcript a provider's host still has or its archive holds, oldest first.
|
|
54
|
+
const hostLists = new Map();
|
|
52
55
|
const work = new Map();
|
|
53
56
|
for (const p of providers) {
|
|
54
57
|
const base = { provider: p.name, dir: p.archive };
|
|
55
|
-
|
|
58
|
+
const listed = p.listHost(p.root);
|
|
59
|
+
hostLists.set(p.name, listed);
|
|
60
|
+
for (const d of listed.transcripts) if (!work.has(`${p.name}/${d.rel}`)) work.set(`${p.name}/${d.rel}`, { ...d, ...base, src: join(p.root, d.rel) });
|
|
56
61
|
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
62
|
}
|
|
58
63
|
for (const d of work.values()) if (d.kind === "main") mains.add(d.sessionId);
|
|
@@ -66,9 +71,10 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
66
71
|
const row = getFile.get(d.provider, d.rel);
|
|
67
72
|
const src = d.src ?? archivePath(d.dir, d.rel);
|
|
68
73
|
const stat = statSync(src);
|
|
69
|
-
const
|
|
74
|
+
const arc = archivePath(d.dir, d.rel);
|
|
75
|
+
const arcSize = sizeOf(arc) ?? 0;
|
|
70
76
|
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 });
|
|
77
|
+
jobs.push({ d, row, stat, arc, arcSize, ts: row?.first_ts ?? (d.src ? peekFirstTs(d.src) : null) ?? "~", mtime: stat.mtimeMs, weight });
|
|
72
78
|
}
|
|
73
79
|
// A continuation starts with the same records as the file it continues, so ties go to the file last written first.
|
|
74
80
|
jobs.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : a.mtime - b.mtime));
|
|
@@ -76,13 +82,39 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
76
82
|
let bytes = 0, next = 0;
|
|
77
83
|
const report = (done, extra = 0) => onProgress({ reason, step: "read", done, total: jobs.length, bytes: bytes + extra, totalBytes });
|
|
78
84
|
|
|
79
|
-
|
|
85
|
+
const dirtyFiles = new Set();
|
|
86
|
+
const dirtySessions = new Set();
|
|
87
|
+
const ctimeUpdates = [];
|
|
88
|
+
const offlineUpdates = [];
|
|
89
|
+
const nowMs = Date.now();
|
|
90
|
+
const safeCtime = (ms, refNow = Date.now()) => (ms !== null && (refNow - ms) > 2000 ? ms : null);
|
|
91
|
+
|
|
92
|
+
for (const [done, { d, row, stat, arc, arcSize, weight }] of jobs.entries()) {
|
|
80
93
|
bytes = next;
|
|
81
94
|
next += weight;
|
|
95
|
+
|
|
96
|
+
// Racy-clean fast-path: skip liveHead and newChunks for quiescent live files whose size and ctime match.
|
|
97
|
+
if (row && arcSize === row.archive_size && d.src && row.offset > 0 && stat.size === row.offset && row.ctime_ms !== null && row.ctime_ms === stat.ctimeMs && (nowMs - stat.ctimeMs) > 2000) {
|
|
98
|
+
if (done % 256 === 0) {
|
|
99
|
+
report(done);
|
|
100
|
+
await yieldToLoop();
|
|
101
|
+
}
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Fast-path for unchanged archived-only files.
|
|
106
|
+
if (row && arcSize === row.archive_size && !d.src) {
|
|
107
|
+
if (row.live) offlineUpdates.push(row.id);
|
|
108
|
+
if (done % 256 === 0) {
|
|
109
|
+
report(done);
|
|
110
|
+
await yieldToLoop();
|
|
111
|
+
}
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
82
115
|
report(done);
|
|
83
116
|
await yieldToLoop();
|
|
84
|
-
let file = fileRow(d);
|
|
85
|
-
const arc = archivePath(d.dir, d.rel);
|
|
117
|
+
let file = row ?? fileRow(d);
|
|
86
118
|
const ingest = ingesters.get(d.provider);
|
|
87
119
|
let firstTs = null;
|
|
88
120
|
let cwd = null;
|
|
@@ -101,13 +133,13 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
101
133
|
|
|
102
134
|
// The archive is ahead of the cursor when a scan died between the append and the commit,
|
|
103
135
|
// or when the database was rebuilt: ingest what the archive holds beyond the cursor, in batches.
|
|
104
|
-
const arcSize = sizeOf(arc) ?? 0;
|
|
105
136
|
if (arcSize !== file.archive_size) {
|
|
106
137
|
if (arcSize < file.archive_size) throw new Error(`archive ${arc} is shorter than recorded; refusing to continue`);
|
|
107
138
|
let { offset, lines } = file;
|
|
108
139
|
const head = [];
|
|
109
140
|
let headBytes = 0;
|
|
110
141
|
let batch = 0;
|
|
142
|
+
const curCtime = d.src ? safeCtime(stat.ctimeMs) : null;
|
|
111
143
|
db.exec("BEGIN");
|
|
112
144
|
try {
|
|
113
145
|
for await (const l of archiveLines(arc)) {
|
|
@@ -120,26 +152,36 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
120
152
|
offset += l.bytes;
|
|
121
153
|
lines = l.line;
|
|
122
154
|
if (++batch % 5000 === 0) {
|
|
123
|
-
|
|
155
|
+
ingest.flush?.(file.id);
|
|
156
|
+
saveCursor.run(offset, lines, hashHead(Buffer.concat(head)), file.archive_size, firstTs, cwd, file.live, ownFirst, ownLast, curCtime, file.id);
|
|
124
157
|
db.exec("COMMIT");
|
|
125
158
|
db.exec("BEGIN");
|
|
126
159
|
}
|
|
127
160
|
}
|
|
128
|
-
|
|
161
|
+
ingest.flush?.(file.id);
|
|
162
|
+
saveCursor.run(offset, lines, hashHead(Buffer.concat(head)), arcSize, firstTs, cwd, d.src ? 1 : 0, ownFirst, ownLast, curCtime, file.id);
|
|
129
163
|
db.exec("COMMIT");
|
|
130
164
|
} catch (err) {
|
|
131
165
|
db.exec("ROLLBACK");
|
|
132
166
|
throw err;
|
|
133
167
|
}
|
|
168
|
+
dirtyFiles.add(file.id);
|
|
169
|
+
dirtySessions.add(file.session_id);
|
|
134
170
|
file = getFile.get(d.provider, d.rel);
|
|
135
171
|
}
|
|
136
172
|
|
|
137
173
|
if (!d.src) {
|
|
138
|
-
if (file.live)
|
|
174
|
+
if (file.live) offlineUpdates.push(file.id);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
let curStat;
|
|
178
|
+
try {
|
|
179
|
+
curStat = statSync(d.src);
|
|
180
|
+
} catch {
|
|
139
181
|
continue;
|
|
140
182
|
}
|
|
141
|
-
const size =
|
|
142
|
-
|
|
183
|
+
const size = curStat.size;
|
|
184
|
+
const ctimeMs = curStat.ctimeMs;
|
|
143
185
|
|
|
144
186
|
// A file that shrank or whose consumed head changed was rewritten: keep the old copy as a generation.
|
|
145
187
|
if (file.offset > 0 && (size < file.offset || liveHead(d.src, file.offset) !== file.head_hash)) {
|
|
@@ -148,7 +190,10 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
148
190
|
for (const c of clear) c.run(file.id);
|
|
149
191
|
resetFile.run(file.id);
|
|
150
192
|
});
|
|
193
|
+
ingest.reset?.(file.id);
|
|
151
194
|
totals.generations++;
|
|
195
|
+
dirtyFiles.add(file.id);
|
|
196
|
+
dirtySessions.add(file.session_id);
|
|
152
197
|
file = getFile.get(d.provider, d.rel);
|
|
153
198
|
firstTs = cwd = ownFirst = ownLast = null;
|
|
154
199
|
}
|
|
@@ -158,6 +203,7 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
158
203
|
const archived = appendChunk(arc, chunk);
|
|
159
204
|
const count = lineCount(chunk);
|
|
160
205
|
const text = chunk.toString("utf8");
|
|
206
|
+
const stamped = safeCtime(ctimeMs);
|
|
161
207
|
transaction(db, () => {
|
|
162
208
|
let start = 0;
|
|
163
209
|
for (let i = 0; i < count; i++) {
|
|
@@ -167,13 +213,27 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
167
213
|
}
|
|
168
214
|
offset += chunk.length;
|
|
169
215
|
lines += count;
|
|
170
|
-
|
|
216
|
+
ingest.flush?.(file.id);
|
|
217
|
+
saveCursor.run(offset, lines, liveHead(d.src, offset), archived, firstTs, cwd, 1, ownFirst, ownLast, stamped, file.id);
|
|
171
218
|
});
|
|
172
219
|
totals.bytes += chunk.length;
|
|
220
|
+
dirtyFiles.add(file.id);
|
|
221
|
+
dirtySessions.add(file.session_id);
|
|
173
222
|
report(done, Math.max(0, weight - (size - offset)));
|
|
174
223
|
await yieldToLoop();
|
|
175
224
|
}
|
|
176
|
-
if (offset > file.offset)
|
|
225
|
+
if (offset > file.offset) {
|
|
226
|
+
totals.files++;
|
|
227
|
+
} else if (offset === file.offset && file.offset > 0 && file.ctime_ms !== ctimeMs) {
|
|
228
|
+
const stamped = safeCtime(ctimeMs);
|
|
229
|
+
if (stamped !== null) ctimeUpdates.push([stamped, file.id]);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (ctimeUpdates.length || offlineUpdates.length) {
|
|
233
|
+
transaction(db, () => {
|
|
234
|
+
for (const [ms, id] of ctimeUpdates) stampCtime.run(ms, id);
|
|
235
|
+
for (const id of offlineUpdates) setOffline.run(id);
|
|
236
|
+
});
|
|
177
237
|
}
|
|
178
238
|
onProgress({ reason, step: "finish", done: jobs.length, total: jobs.length, bytes: totalBytes, totalBytes });
|
|
179
239
|
await yieldToLoop();
|
|
@@ -181,23 +241,45 @@ export async function scan(config, { onProgress = () => {} } = {}) {
|
|
|
181
241
|
// Other session-folder files; the subagent meta files among them give each subagent its type.
|
|
182
242
|
const activeProviders = new Set(jobs.map((j) => j.d.provider));
|
|
183
243
|
const copied = new Set();
|
|
244
|
+
const copiedMeta = new Set();
|
|
184
245
|
for (const p of providers) {
|
|
185
|
-
for (const rel of
|
|
246
|
+
for (const rel of hostLists.get(p.name).others) {
|
|
186
247
|
if (copied.has(`${p.name}/${rel}`)) continue;
|
|
187
248
|
copied.add(`${p.name}/${rel}`);
|
|
188
|
-
if (copyOther(join(p.root, rel), join(p.archive, rel)))
|
|
249
|
+
if (copyOther(join(p.root, rel), join(p.archive, rel))) {
|
|
250
|
+
totals.copied++;
|
|
251
|
+
copiedMeta.add(`${p.name}/${rel}`);
|
|
252
|
+
}
|
|
189
253
|
}
|
|
190
254
|
if (p.syncMeta && activeProviders.has(p.name)) totals.copied += p.syncMeta(p.root, p.archive) ?? 0;
|
|
191
255
|
}
|
|
256
|
+
const existingSubs = new Map(db.prepare("SELECT agent_id, session_id, type, tool_use_id FROM subagents").all().map((s) => [s.agent_id, s]));
|
|
192
257
|
const putSub = db.prepare("INSERT OR REPLACE INTO subagents(agent_id, session_id, type, tool_use_id) VALUES (?, ?, ?, ?)");
|
|
193
|
-
|
|
258
|
+
const subUpdates = [];
|
|
259
|
+
for (const { d, row } of jobs) {
|
|
194
260
|
if (d.kind !== "sub") continue;
|
|
261
|
+
const known = existingSubs.get(d.agentId);
|
|
262
|
+
const metaRel = `${d.provider}/${d.rel.replace(/\.jsonl$/, ".meta.json")}`;
|
|
263
|
+
if (known && !(row && dirtyFiles.has(row.id)) && !copiedMeta.has(metaRel)) continue;
|
|
195
264
|
const meta = PROVIDERS[d.provider].subagentMeta?.(d.dir, d);
|
|
196
|
-
if (meta)
|
|
265
|
+
if (!meta) continue;
|
|
266
|
+
if (!known || known.session_id !== d.sessionId || known.type !== meta.type || known.tool_use_id !== meta.toolUseId) {
|
|
267
|
+
subUpdates.push([d.agentId, d.sessionId, meta.type, meta.toolUseId]);
|
|
268
|
+
dirtySessions.add(d.sessionId);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (subUpdates.length) {
|
|
272
|
+
transaction(db, () => {
|
|
273
|
+
for (const args of subUpdates) putSub.run(...args);
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
for (const p of providers) {
|
|
277
|
+
if (!activeProviders.has(p.name)) continue;
|
|
278
|
+
const d = p.postScan?.(db, p.archive);
|
|
279
|
+
if (d) for (const s of d) dirtySessions.add(s);
|
|
197
280
|
}
|
|
198
|
-
for (const p of providers) if (activeProviders.has(p.name)) p.postScan?.(db, p.archive);
|
|
199
281
|
|
|
200
|
-
derive(db, config);
|
|
282
|
+
derive(db, config, { dirtySessions, full: reason !== "update" });
|
|
201
283
|
const sessionsAfter = db.prepare("SELECT COUNT(DISTINCT session_id) n FROM files WHERE kind = 'main' AND lines > 0").get().n;
|
|
202
284
|
totals.sessions = sessionsAfter - sessionsBefore;
|
|
203
285
|
totals.prices = { report: priceReport(db), errors: readPrices(config).errors };
|