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.
Files changed (32) hide show
  1. package/README.md +5 -1
  2. package/bin/llmtop.mjs +44 -4
  3. package/dashboard/dist/assets/index-NQzaBVIY.css +1 -0
  4. package/dashboard/dist/assets/montserrat-cyrillic-ext-wght-normal-CO5hGrJv.woff2 +0 -0
  5. package/dashboard/dist/assets/montserrat-cyrillic-wght-normal-EAA9jha_.woff2 +0 -0
  6. package/dashboard/dist/assets/montserrat-latin-ext-wght-normal-BsZE-iaG.woff2 +0 -0
  7. package/dashboard/dist/assets/montserrat-latin-wght-normal-l_AIctKy.woff2 +0 -0
  8. package/dashboard/dist/assets/montserrat-vietnamese-wght-normal-k7S-YeeD.woff2 +0 -0
  9. package/dashboard/dist/assets/roboto-mono-cyrillic-ext-wght-normal-BUDPrIko.woff2 +0 -0
  10. package/dashboard/dist/assets/roboto-mono-cyrillic-wght-normal-HUlVHixE.woff2 +0 -0
  11. package/dashboard/dist/assets/roboto-mono-greek-wght-normal-BJJTbwTT.woff2 +0 -0
  12. package/dashboard/dist/assets/roboto-mono-latin-ext-wght-normal-QAYlOegK.woff2 +0 -0
  13. package/dashboard/dist/assets/roboto-mono-latin-wght-normal-CZtBPCCa.woff2 +0 -0
  14. package/dashboard/dist/assets/roboto-mono-vietnamese-wght-normal-DlC-zuDL.woff2 +0 -0
  15. package/dashboard/dist/index.html +2 -2
  16. package/dashboard/src/main.tsx +2 -0
  17. package/dashboard/src/styles.css +2 -2
  18. package/package.json +3 -1
  19. package/src/db.mjs +33 -2
  20. package/src/derive.mjs +110 -27
  21. package/src/install.mjs +58 -0
  22. package/src/prices.mjs +22 -2
  23. package/src/process.mjs +237 -0
  24. package/src/providers/agy.mjs +60 -26
  25. package/src/providers/claude.mjs +17 -18
  26. package/src/providers/codex.mjs +68 -33
  27. package/src/rebuilds.mjs +35 -11
  28. package/src/scan.mjs +104 -22
  29. package/src/uninstall.mjs +179 -0
  30. package/src/update.mjs +140 -0
  31. package/dashboard/dist/assets/index-Cp7Swcz5.css +0 -1
  32. /package/dashboard/dist/assets/{index-BVbAwMVB.js → index-Ba0kF2tG.js} +0 -0
@@ -0,0 +1,58 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { ROOT } from "./config.mjs";
5
+
6
+ export function detectInstallMode({ root = ROOT, exists = existsSync } = {}) {
7
+ const normalized = root.replace(/\\/g, "/");
8
+ if (normalized.includes("/_npx/")) return { mode: "npx", packageManager: "npm", root };
9
+ if (!normalized.includes("/node_modules/") && exists(join(root, ".git"))) return { mode: "local", packageManager: null, root };
10
+ if (normalized.includes("/pnpm/") || normalized.includes("/pnpm-global/")) return { mode: "global", packageManager: "pnpm", root };
11
+ if (normalized.includes("/yarn/") || normalized.includes("/.yarn/")) return { mode: "global", packageManager: "yarn", root };
12
+ if (normalized.includes("/.bun/")) return { mode: "global", packageManager: "bun", root };
13
+ if (normalized.includes("/node_modules/")) return { mode: "global", packageManager: "npm", root };
14
+ return { mode: "unknown", packageManager: "npm", root };
15
+ }
16
+
17
+ export function packageManagerCommand(pm, action, spec) {
18
+ const table = {
19
+ npm: { install: ["npm", ["install", "-g", spec]], uninstall: ["npm", ["uninstall", "-g", spec]] },
20
+ pnpm: { install: ["pnpm", ["add", "-g", spec]], uninstall: ["pnpm", ["remove", "-g", spec]] },
21
+ yarn: { install: ["yarn", ["global", "add", spec]], uninstall: ["yarn", ["global", "remove", spec]] },
22
+ bun: { install: ["bun", ["add", "-g", spec]], uninstall: ["bun", ["remove", "-g", spec]] },
23
+ };
24
+ const manager = table[pm] ?? table.npm;
25
+ return manager[action];
26
+ }
27
+
28
+ export function formatCommand(cmd, args) {
29
+ return [cmd, ...args].join(" ");
30
+ }
31
+
32
+ export function runPackageManager(pm, action, spec, { spawn = spawnSync, platform = process.platform } = {}) {
33
+ const [cmd, args] = packageManagerCommand(pm, action, spec);
34
+ const command = formatCommand(cmd, args);
35
+ const res = spawn(cmd, args, { encoding: "utf8", stdio: "pipe", shell: platform === "win32" });
36
+ const stdout = res.stdout ?? "";
37
+ const stderr = res.stderr ?? "";
38
+ const error = res.error ? res.error.message : "";
39
+ const ok = !res.error && res.status === 0;
40
+ const permissionDenied = /EACCES|EPERM|permission denied/i.test(`${stderr}\n${error}`);
41
+ return { ok, code: res.status ?? 1, stdout, stderr, error, command, permissionDenied };
42
+ }
43
+
44
+ export function hasGlobalPackage(pm = "npm", pkgName = "llmtop", { spawn = spawnSync, platform = process.platform } = {}) {
45
+ if (pm !== "npm") return false;
46
+ try {
47
+ const res = spawn("npm", ["list", "-g", pkgName, "--depth=0", "--json"], {
48
+ encoding: "utf8",
49
+ stdio: "pipe",
50
+ shell: platform === "win32",
51
+ });
52
+ if (res.status !== 0 || !res.stdout?.trim()) return false;
53
+ const parsed = JSON.parse(res.stdout);
54
+ return Boolean(parsed?.dependencies?.[pkgName]);
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
package/src/prices.mjs CHANGED
@@ -32,17 +32,37 @@ export function readPrices(config) {
32
32
  return { rows, errors };
33
33
  }
34
34
 
35
+ const PRICE_INDEX = new WeakMap();
36
+
37
+ function indexPrices(rows) {
38
+ let entry = PRICE_INDEX.get(rows);
39
+ if (!entry || entry.len !== rows.length) {
40
+ const byModel = new Map();
41
+ for (const r of rows) {
42
+ let list = byModel.get(r.model);
43
+ if (!list) byModel.set(r.model, (list = []));
44
+ list.push(r);
45
+ }
46
+ entry = { len: rows.length, byModel };
47
+ PRICE_INDEX.set(rows, entry);
48
+ }
49
+ return entry.byModel;
50
+ }
51
+
35
52
  // The row in force for a model id on a local day; strips context suffixes, effort suffixes and date snapshots.
36
53
  export function priceAt(rows, model, day) {
54
+ const byModel = indexPrices(rows);
37
55
  const noCtx = model.replace(/\[.*\]$/, "");
38
56
  const noEff = noCtx.replace(/-(?:low|medium|high|xhigh|max)$/, "");
39
57
  const noDate = noCtx.replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, "");
40
58
  const bare = noEff.replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, "");
41
59
  for (const id of new Set([model, noCtx, noEff, noDate, bare])) {
60
+ const cand = byModel.get(id);
61
+ if (!cand) continue;
42
62
  let hit = null;
43
- for (const r of rows) if (r.model === id && r.from <= day && (!hit || r.from > hit.from)) hit = r;
63
+ for (const r of cand) if (r.from <= day && (!hit || r.from > hit.from)) hit = r;
44
64
  if (hit) return hit;
45
- if (rows.some((r) => r.model === id)) return null;
65
+ return null;
46
66
  }
47
67
  return null;
48
68
  }
@@ -0,0 +1,237 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { ROOT } from "./config.mjs";
5
+
6
+ export function serverStatePath(config) {
7
+ return join(config.data, "serve.json");
8
+ }
9
+
10
+ // Writes serve.json atomically and returns a cleanup callback that removes it only if the PID still matches.
11
+ export function writeServerState(config, { pid = process.pid, port, version }) {
12
+ const path = serverStatePath(config);
13
+ mkdirSync(config.data, { recursive: true });
14
+ const tmp = join(config.data, `.serve.${pid}.${process.hrtime.bigint()}.tmp`);
15
+ const payload = JSON.stringify({ pid, port, startedAt: new Date().toISOString(), version }, null, 2);
16
+ writeFileSync(tmp, `${payload}\n`);
17
+ renameSync(tmp, path);
18
+ return () => {
19
+ try {
20
+ const current = JSON.parse(readFileSync(path, "utf8"));
21
+ if (current?.pid === pid) unlinkSync(path);
22
+ } catch {
23
+ // Missing or already replaced state file needs no cleanup.
24
+ }
25
+ };
26
+ }
27
+
28
+ export function readServerState(config, { exists = existsSync, readFile = readFileSync } = {}) {
29
+ const path = serverStatePath(config);
30
+ if (!exists(path)) return null;
31
+ try {
32
+ const parsed = JSON.parse(readFile(path, "utf8"));
33
+ return parsed && typeof parsed === "object" ? parsed : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ export function isPidAlive(pid) {
40
+ if (!Number.isInteger(pid) || pid <= 0) return false;
41
+ try {
42
+ process.kill(pid, 0);
43
+ return true;
44
+ } catch (err) {
45
+ return err?.code === "EPERM";
46
+ }
47
+ }
48
+
49
+ export function isLlmtopServeCommand(command) {
50
+ if (typeof command !== "string") return false;
51
+ const trimmed = command.trim();
52
+ if (!trimmed) return false;
53
+ if (/^(?:\/[\w/.-]*\/)?(?:sh|bash|zsh|fish|grep|rg|awk|sed)\b/.test(trimmed)) return false;
54
+ return /(?:^|[\s"'/\\])llmtop(?:\.mjs|\.cmd|\.ps1)?["']?\s+serve(?:\s|$)/.test(trimmed);
55
+ }
56
+
57
+ export function listOsProcesses({ spawn = spawnSync, platform = process.platform } = {}) {
58
+ try {
59
+ if (platform === "win32") {
60
+ const res = spawn(
61
+ "powershell.exe",
62
+ ["-NoProfile", "-Command", "Get-CimInstance Win32_Process | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"],
63
+ { encoding: "utf8", stdio: "pipe" },
64
+ );
65
+ if (res.status !== 0 || !res.stdout?.trim()) return [];
66
+ const parsed = JSON.parse(res.stdout);
67
+ const list = Array.isArray(parsed) ? parsed : [parsed];
68
+ return list
69
+ .filter((item) => item && Number.isInteger(Number(item.ProcessId)) && Number(item.ProcessId) > 0)
70
+ .map((item) => ({ pid: Number(item.ProcessId), command: String(item.CommandLine || "") }));
71
+ }
72
+ const res = spawn("ps", ["-eo", "pid=,args="], { encoding: "utf8", stdio: "pipe" });
73
+ if (res.status !== 0 || !res.stdout) return [];
74
+ const processes = [];
75
+ for (const line of res.stdout.split(/\r?\n/)) {
76
+ const match = line.match(/^\s*(\d+)\s+(.+)$/);
77
+ if (!match) continue;
78
+ processes.push({ pid: Number(match[1]), command: match[2].trim() });
79
+ }
80
+ return processes;
81
+ } catch {
82
+ return [];
83
+ }
84
+ }
85
+
86
+ function parsePortFromCommand(command) {
87
+ const match = command.match(/(?:^|\s)--port(?:=|\s+)(\d+)\b/);
88
+ return match ? Number(match[1]) : null;
89
+ }
90
+
91
+ export function findRunningServers(config, deps = {}) {
92
+ const {
93
+ listProcesses = listOsProcesses,
94
+ isAlive = isPidAlive,
95
+ selfPid = process.pid,
96
+ root = ROOT,
97
+ exists = existsSync,
98
+ readFile = readFileSync,
99
+ } = deps;
100
+ const osList = listProcesses();
101
+ const osByPid = new Map(osList.map((p) => [p.pid, p]));
102
+ const byPid = new Map();
103
+ let staleState = false;
104
+
105
+ const statePath = serverStatePath(config);
106
+ if (exists(statePath)) {
107
+ const state = readServerState(config, { exists, readFile });
108
+ if (state && Number.isInteger(state.pid) && state.pid > 0) {
109
+ if (state.pid !== selfPid) {
110
+ const osEntry = osByPid.get(state.pid);
111
+ const matchesOs = osList.length === 0 || (osEntry && isLlmtopServeCommand(osEntry.command));
112
+ if (isAlive(state.pid) && matchesOs) {
113
+ byPid.set(state.pid, { pid: state.pid, port: state.port ?? null, source: "state" });
114
+ } else {
115
+ staleState = true;
116
+ }
117
+ }
118
+ } else {
119
+ staleState = true;
120
+ }
121
+ }
122
+
123
+ const pidFile = join(root, "data", "serve.pid");
124
+ if (exists(pidFile)) {
125
+ try {
126
+ const pid = Number(readFile(pidFile, "utf8").trim());
127
+ if (Number.isInteger(pid) && pid > 0 && pid !== selfPid && isAlive(pid)) {
128
+ const osEntry = osByPid.get(pid);
129
+ if (osEntry && isLlmtopServeCommand(osEntry.command)) {
130
+ const existing = byPid.get(pid);
131
+ if (existing) existing.pidFile = pidFile;
132
+ else byPid.set(pid, { pid, port: parsePortFromCommand(osEntry.command), source: "pidfile", pidFile });
133
+ }
134
+ }
135
+ } catch {
136
+ // Ignore unreadable legacy pidfile.
137
+ }
138
+ }
139
+
140
+ for (const proc of osList) {
141
+ if (proc.pid === selfPid || byPid.has(proc.pid) || !isLlmtopServeCommand(proc.command)) continue;
142
+ byPid.set(proc.pid, { pid: proc.pid, port: parsePortFromCommand(proc.command), source: "process" });
143
+ }
144
+
145
+ return { servers: [...byPid.values()].sort((a, b) => a.pid - b.pid), staleState };
146
+ }
147
+
148
+ async function waitForExit(pid, isAlive, sleep, timeoutMs) {
149
+ const deadline = Date.now() + timeoutMs;
150
+ while (isAlive(pid)) {
151
+ if (Date.now() >= deadline) return false;
152
+ await sleep(50);
153
+ }
154
+ return true;
155
+ }
156
+
157
+ export async function stopRunningServers(config, deps = {}) {
158
+ const {
159
+ kill = process.kill,
160
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
161
+ timeoutMs = 3000,
162
+ unlink = unlinkSync,
163
+ isAlive = isPidAlive,
164
+ exists = existsSync,
165
+ readFile = readFileSync,
166
+ } = deps;
167
+ const { servers, staleState } = findRunningServers(config, { ...deps, isAlive, exists, readFile });
168
+ const stopped = [];
169
+ const failed = [];
170
+
171
+ for (const server of servers) {
172
+ try {
173
+ kill(server.pid, "SIGTERM");
174
+ } catch (err) {
175
+ if (err?.code !== "ESRCH") {
176
+ failed.push({ ...server, error: err?.message ?? String(err) });
177
+ continue;
178
+ }
179
+ }
180
+ let exited = await waitForExit(server.pid, isAlive, sleep, timeoutMs);
181
+ if (!exited) {
182
+ try {
183
+ kill(server.pid, "SIGKILL");
184
+ } catch (err) {
185
+ if (err?.code !== "ESRCH") {
186
+ failed.push({ ...server, error: err?.message ?? String(err) });
187
+ continue;
188
+ }
189
+ }
190
+ exited = await waitForExit(server.pid, isAlive, sleep, 500);
191
+ }
192
+ if (!exited && isAlive(server.pid)) {
193
+ failed.push({ ...server, error: "process did not exit" });
194
+ continue;
195
+ }
196
+ stopped.push(server);
197
+ if (server.pidFile) {
198
+ try {
199
+ unlink(server.pidFile);
200
+ } catch {
201
+ // Ignore missing legacy pidfile.
202
+ }
203
+ }
204
+ }
205
+
206
+ let cleanedState = false;
207
+ const statePath = serverStatePath(config);
208
+ if (exists(statePath)) {
209
+ const state = readServerState(config, { exists, readFile });
210
+ if (!state || !Number.isInteger(state.pid) || !isAlive(state.pid) || staleState) {
211
+ try {
212
+ unlink(statePath);
213
+ cleanedState = true;
214
+ } catch {
215
+ // Ignore already-deleted state file.
216
+ }
217
+ }
218
+ }
219
+
220
+ return { stopped, failed, cleanedState };
221
+ }
222
+
223
+ export async function stopCommand({ config, out, err = process.stderr, deps = {} }) {
224
+ const { stopped, failed } = await stopRunningServers(config, deps);
225
+ if (failed.length) {
226
+ for (const f of failed) err.write(`error: could not stop llmtop serve (pid ${f.pid}): ${f.error}\n`);
227
+ return 1;
228
+ }
229
+ if (!stopped.length) {
230
+ out.write("llmtop serve is not running\n");
231
+ return 0;
232
+ }
233
+ for (const s of stopped) {
234
+ out.write(`stopped llmtop serve (pid ${s.pid}${s.port ? `, port ${s.port}` : ""})\n`);
235
+ }
236
+ return 0;
237
+ }
@@ -232,7 +232,7 @@ export function createIngester(db, timeZone) {
232
232
  const AGY_WRITE_TOOLS = new Set(["edit_file", "write_file", "replace_file_content", "multi_replace_file_content", "write_to_file"]);
233
233
  const AGY_READ_TOOLS = new Set(["read_file", "view_file", "grep_search", "find_by_name", "list_dir", "run_command"]);
234
234
 
235
- return function ingestLine(file, line, text) {
235
+ function ingestLine(file, line, text) {
236
236
  let rec;
237
237
  try {
238
238
  rec = JSON.parse(text);
@@ -248,6 +248,7 @@ export function createIngester(db, timeZone) {
248
248
  apiMs: prevStats?.api_ms ?? 0, toolMs: prevStats?.tool_ms ?? 0,
249
249
  linesAdded: prevStats?.lines_added ?? 0, linesRemoved: prevStats?.lines_removed ?? 0,
250
250
  paths: createPathTracker(prevStats?.target_paths ?? null),
251
+ statsDirty: false, pathsDirty: false,
251
252
  };
252
253
  stateByFile.set(file.id, st);
253
254
  }
@@ -261,18 +262,16 @@ export function createIngester(db, timeZone) {
261
262
  const tsMs = Number.isFinite(parsedTs) ? parsedTs : null;
262
263
  const uuid = `agy:${ownId}:${step}`;
263
264
  let added = 0;
264
- let statsDirty = false;
265
- let pathsDirty = false;
266
265
 
267
266
  if (tsMs !== null && st.lastTsMs !== null) {
268
267
  const dt = tsMs - st.lastTsMs;
269
268
  if (dt > 0 && dt < 600_000) {
270
269
  if (rec.type === "PLANNER_RESPONSE" && (st.lastType === "USER_INPUT" || st.lastType === "GENERIC" || st.lastType === "SYSTEM_MESSAGE")) {
271
270
  st.apiMs += Math.round(dt);
272
- statsDirty = true;
271
+ st.statsDirty = true;
273
272
  } else if (rec.type === "GENERIC" && st.lastType === "PLANNER_RESPONSE") {
274
273
  st.toolMs += Math.round(dt);
275
- statsDirty = true;
274
+ st.statsDirty = true;
276
275
  }
277
276
  }
278
277
  }
@@ -298,28 +297,28 @@ export function createIngester(db, timeZone) {
298
297
  if (diff.added || diff.removed) {
299
298
  st.linesAdded += diff.added;
300
299
  st.linesRemoved += diff.removed;
301
- statsDirty = true;
300
+ st.statsDirty = true;
302
301
  }
303
302
  if (tc.args && typeof tc.args === "object") {
304
303
  if (AGY_WRITE_TOOLS.has(tc.name)) {
305
304
  for (const k of ["Path", "TargetFile", "AbsolutePath"]) {
306
305
  const val = unquote(tc.args[k]);
307
- if (val && st.paths.add(val, { isFile: true, write: true })) pathsDirty = true;
306
+ if (val && st.paths.add(val, { isFile: true, write: true })) st.pathsDirty = true;
308
307
  }
309
308
  } else if (AGY_READ_TOOLS.has(tc.name)) {
310
309
  for (const k of ["Path", "AbsolutePath"]) {
311
310
  const val = unquote(tc.args[k]);
312
- if (val && st.paths.add(val, { isFile: true, write: false })) pathsDirty = true;
311
+ if (val && st.paths.add(val, { isFile: true, write: false })) st.pathsDirty = true;
313
312
  }
314
313
  for (const k of ["SearchPath", "DirectoryPath", "Cwd"]) {
315
314
  const val = unquote(tc.args[k]);
316
- if (val && st.paths.add(val, { isFile: false, write: false })) pathsDirty = true;
315
+ if (val && st.paths.add(val, { isFile: false, write: false })) st.pathsDirty = true;
317
316
  }
318
317
  if (tc.name === "run_command" && tc.args.CommandLine) {
319
318
  const cmd = unquote(tc.args.CommandLine);
320
319
  const cmdCwd = unquote(tc.args.Cwd) || null;
321
320
  for (const dir of extractCommandDirs(cmd, cmdCwd)) {
322
- if (st.paths.add(dir, { write: false })) pathsDirty = true;
321
+ if (st.paths.add(dir, { write: false })) st.pathsDirty = true;
323
322
  }
324
323
  }
325
324
  }
@@ -362,26 +361,36 @@ export function createIngester(db, timeZone) {
362
361
  st.lastTsMs = tsMs;
363
362
  st.lastType = rec.type;
364
363
  }
365
- if (statsDirty && (st.apiMs > 0 || st.toolMs > 0 || st.linesAdded > 0 || st.linesRemoved > 0)) {
366
- q.upsertStats.run(file.id, st.apiMs, st.toolMs, st.linesAdded, st.linesRemoved);
364
+
365
+ return { added, cwd: null, ts, own: true };
366
+ }
367
+ ingestLine.flush = (fileId) => {
368
+ const st = stateByFile.get(fileId);
369
+ if (!st) return;
370
+ if (st.statsDirty) {
371
+ st.statsDirty = false;
372
+ if (st.apiMs > 0 || st.toolMs > 0 || st.linesAdded > 0 || st.linesRemoved > 0) {
373
+ q.upsertStats.run(fileId, st.apiMs, st.toolMs, st.linesAdded, st.linesRemoved);
374
+ }
367
375
  }
368
- if (pathsDirty) {
376
+ if (st.pathsDirty) {
377
+ st.pathsDirty = false;
369
378
  const json = st.paths.toJSON();
370
- if (json) q.upsertTargetPaths.run(file.id, json);
379
+ if (json) q.upsertTargetPaths.run(fileId, json);
371
380
  }
372
-
373
- return { added, cwd: null, ts, own: true };
374
381
  };
382
+ ingestLine.reset = (fileId) => { stateByFile.delete(fileId); };
383
+ return ingestLine;
375
384
  }
376
385
 
377
386
  export function postScan(db, archiveDir) {
378
387
  const path = join(archiveDir, "summaries.json");
379
- if (!existsSync(path)) return;
388
+ if (!existsSync(path)) return new Set();
380
389
  let meta;
381
390
  try {
382
391
  meta = JSON.parse(readFileSync(path, "utf8"));
383
392
  } catch {
384
- return;
393
+ return new Set();
385
394
  }
386
395
 
387
396
  const allFiles = db.prepare("SELECT id, kind, session_id, agent_id, cwd FROM files WHERE provider = 'agy'").all();
@@ -400,39 +409,64 @@ export function postScan(db, archiveDir) {
400
409
  return cur === id ? null : cur;
401
410
  };
402
411
 
412
+ const existingSubs = new Map(db.prepare("SELECT agent_id, session_id, type, tool_use_id FROM subagents").all().map((s) => [s.agent_id, s]));
413
+ const existingTitles = new Map(db.prepare("SELECT file_id, session_id, title FROM titles WHERE line = 0 AND kind = 'ai'").all().map((t) => [t.file_id, t]));
414
+
403
415
  const setCwd = db.prepare("UPDATE files SET cwd = ? WHERE id = ?");
404
416
  const setFileSub = db.prepare("UPDATE files SET kind = 'sub', session_id = ?, agent_id = ? WHERE id = ?");
405
417
  const setReqSub = db.prepare("UPDATE requests SET session_id = ?, agent_id = ?, is_sub = 1 WHERE file_id = ?");
406
418
  const setCallSub = db.prepare("UPDATE tool_calls SET session_id = ?, agent_id = ? WHERE file_id = ?");
407
419
  const setSkillSess = db.prepare("UPDATE skills SET session_id = ? WHERE file_id = ?");
408
420
  const setTitleSess = db.prepare("UPDATE titles SET session_id = ? WHERE file_id = ?");
421
+ const delSession = db.prepare("DELETE FROM sessions WHERE id = ?");
409
422
  const putSub = db.prepare("INSERT OR REPLACE INTO subagents(agent_id, session_id, type, tool_use_id) VALUES (?, ?, ?, NULL)");
410
423
  const putTitle = db.prepare("INSERT OR REPLACE INTO titles(file_id, line, session_id, kind, title) VALUES (?, 0, ?, 'ai', ?)");
411
424
 
425
+ const dirty = new Set();
412
426
  db.exec("BEGIN");
413
427
  try {
414
428
  for (const f of allFiles) {
415
429
  const ownId = f.agent_id ?? f.session_id;
416
430
  const m = meta[ownId];
417
431
  if (!m) continue;
418
- if (m.cwd && !f.cwd) setCwd.run(m.cwd, f.id);
419
432
  const root = rootOf(ownId);
420
433
  const sess = root ?? f.session_id;
434
+ if (m.cwd && !f.cwd) {
435
+ setCwd.run(m.cwd, f.id);
436
+ dirty.add(sess);
437
+ }
421
438
  if (root) {
422
- setFileSub.run(root, ownId, f.id);
423
- setReqSub.run(root, ownId, f.id);
424
- setCallSub.run(root, ownId, f.id);
425
- setSkillSess.run(root, f.id);
426
- setTitleSess.run(root, f.id);
427
- putSub.run(ownId, root, m.agentName || "subagent");
439
+ if (f.kind !== "sub" || f.session_id !== root || f.agent_id !== ownId) {
440
+ setFileSub.run(root, ownId, f.id);
441
+ setReqSub.run(root, ownId, f.id);
442
+ setCallSub.run(root, ownId, f.id);
443
+ setSkillSess.run(root, f.id);
444
+ setTitleSess.run(root, f.id);
445
+ if (f.kind === "main") delSession.run(f.session_id);
446
+ dirty.add(f.session_id);
447
+ dirty.add(root);
448
+ }
449
+ const type = m.agentName || "subagent";
450
+ const curSub = existingSubs.get(ownId);
451
+ if (!curSub || curSub.session_id !== root || curSub.type !== type || curSub.tool_use_id !== null) {
452
+ putSub.run(ownId, root, type);
453
+ dirty.add(root);
454
+ }
455
+ }
456
+ if (m.title) {
457
+ const curTitle = existingTitles.get(f.id);
458
+ if (!curTitle || curTitle.session_id !== sess || curTitle.title !== m.title) {
459
+ putTitle.run(f.id, sess, m.title);
460
+ dirty.add(sess);
461
+ }
428
462
  }
429
- if (m.title) putTitle.run(f.id, sess, m.title);
430
463
  }
431
464
  db.exec("COMMIT");
432
465
  } catch (err) {
433
466
  db.exec("ROLLBACK");
434
467
  throw err;
435
468
  }
469
+ return dirty;
436
470
  }
437
471
 
438
472
  export const agy = { name: "agy", label, defaultPath, describe, listHost, syncMeta, createIngester, postScan, familyOf, displayModel };
@@ -128,7 +128,7 @@ export function createIngester(db, timeZone, hasFile = () => false) {
128
128
  const CLAUDE_READ_TOOLS = new Set(["Read", "Grep", "Glob"]);
129
129
 
130
130
  // file: { id, kind, session_id, agent_id }. Returns how many records were added, and the line's cwd and timestamp.
131
- return function ingestLine(file, line, text) {
131
+ function ingestLine(file, line, text) {
132
132
  let rec;
133
133
  try {
134
134
  rec = JSON.parse(text);
@@ -144,20 +144,14 @@ export function createIngester(db, timeZone, hasFile = () => false) {
144
144
  let st = stateByFile.get(file.id);
145
145
  if (!st) {
146
146
  const prev = file.lines > 0 ? q.getTargetPaths.get(file.id) : null;
147
- st = { launchCwd: file.cwd ?? null, cwd: file.cwd ?? null, paths: createPathTracker(prev?.target_paths ?? null) };
147
+ st = { launchCwd: file.cwd ?? null, cwd: file.cwd ?? null, paths: createPathTracker(prev?.target_paths ?? null), pathsDirty: false };
148
148
  stateByFile.set(file.id, st);
149
149
  }
150
- let pathsDirty = false;
151
150
  if (!foreign && rec.cwd) {
152
151
  st.launchCwd ??= rec.cwd;
153
152
  st.cwd = rec.cwd;
154
- if (rec.cwd !== st.launchCwd && st.paths.add(rec.cwd, { write: false })) pathsDirty = true;
153
+ if (rec.cwd !== st.launchCwd && st.paths.add(rec.cwd, { write: false })) st.pathsDirty = true;
155
154
  }
156
- const flushPaths = () => {
157
- if (!pathsDirty) return;
158
- const json = st.paths.toJSON();
159
- if (json) q.upsertTargetPaths.run(file.id, json);
160
- };
161
155
 
162
156
  if (rec.type === "cost-state") {
163
157
  // Per model: the host's cost and the tokens it priced; `split` tells whether 5m and 1h cache writes are told apart.
@@ -168,20 +162,17 @@ export function createIngester(db, timeZone, hasFile = () => false) {
168
162
  }]));
169
163
  q.cost.run(file.id, line, session, rec.startTime ?? null, rec.totalCostUSD ?? null, rec.hasUnknownModelCost ? 1 : 0,
170
164
  rec.totalAPIDuration ?? null, rec.totalToolDuration ?? null, rec.totalLinesAdded ?? null, rec.totalLinesRemoved ?? null, JSON.stringify(models));
171
- flushPaths();
172
165
  return { added: 1, ...seen };
173
166
  }
174
167
  if (rec.type === "custom-title" && rec.customTitle) {
175
168
  q.title.run(file.id, line, session, "custom", rec.customTitle);
176
- flushPaths();
177
169
  return { added: 1, ...seen };
178
170
  }
179
171
  if (rec.type === "ai-title" && rec.aiTitle) {
180
172
  q.title.run(file.id, line, session, "ai", rec.aiTitle);
181
- flushPaths();
182
173
  return { added: 1, ...seen };
183
174
  }
184
- if (!rec.uuid) { flushPaths(); return { added: 0, ...seen }; }
175
+ if (!rec.uuid) return { added: 0, ...seen };
185
176
 
186
177
  // A copied record belongs to the file of the session that wrote it, whichever file is read first;
187
178
  // here only note which requests it repeats. A copy whose original file is gone is kept here.
@@ -211,13 +202,13 @@ export function createIngester(db, timeZone, hasFile = () => false) {
211
202
  q.call.run(b.id, file.id, line, session, agent, rec.timestamp ?? null, b.name ?? "unknown", msg.model ?? null);
212
203
  if (CLAUDE_WRITE_TOOLS.has(b.name)) {
213
204
  const fp = b.input?.file_path ?? b.input?.notebook_path;
214
- if (st.paths.add(fp, { isFile: true, write: true, baseCwd: st.cwd })) pathsDirty = true;
205
+ if (st.paths.add(fp, { isFile: true, write: true, baseCwd: st.cwd })) st.pathsDirty = true;
215
206
  } else if (CLAUDE_READ_TOOLS.has(b.name)) {
216
- if (b.input?.file_path && st.paths.add(b.input.file_path, { isFile: true, write: false, baseCwd: st.cwd })) pathsDirty = true;
217
- if (b.input?.path && st.paths.add(b.input.path, { isFile: false, write: false, baseCwd: st.cwd })) pathsDirty = true;
207
+ if (b.input?.file_path && st.paths.add(b.input.file_path, { isFile: true, write: false, baseCwd: st.cwd })) st.pathsDirty = true;
208
+ if (b.input?.path && st.paths.add(b.input.path, { isFile: false, write: false, baseCwd: st.cwd })) st.pathsDirty = true;
218
209
  } else if (b.name === "Bash" && typeof b.input?.command === "string") {
219
210
  for (const dir of extractCommandDirs(b.input.command, st.cwd)) {
220
- if (st.paths.add(dir, { write: false })) pathsDirty = true;
211
+ if (st.paths.add(dir, { write: false })) st.pathsDirty = true;
221
212
  }
222
213
  }
223
214
  }
@@ -255,9 +246,17 @@ export function createIngester(db, timeZone, hasFile = () => false) {
255
246
  }
256
247
  }
257
248
  }
258
- flushPaths();
259
249
  return { added: 1, ...seen };
250
+ }
251
+ ingestLine.flush = (fileId) => {
252
+ const st = stateByFile.get(fileId);
253
+ if (!st || !st.pathsDirty) return;
254
+ st.pathsDirty = false;
255
+ const json = st.paths.toJSON();
256
+ if (json) q.upsertTargetPaths.run(fileId, json);
260
257
  };
258
+ ingestLine.reset = (fileId) => { stateByFile.delete(fileId); };
259
+ return ingestLine;
261
260
  }
262
261
 
263
262
  // The type and parent tool call of a subagent, from the meta file archived beside its transcript.