llmtop 0.1.0 → 0.1.2
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 +59 -204
- package/package.json +4 -2
- package/src/db.mjs +33 -2
- package/src/derive.mjs +110 -27
- package/src/prices.mjs +22 -2
- 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/derive.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Per-session values computed after every scan from the ingested rows. Cheap: one pass over sessions.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
2
3
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
3
4
|
import { homedir, tmpdir } from "node:os";
|
|
4
5
|
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
@@ -12,6 +13,14 @@ const GENERIC_DIR_RE = /^(?:repo|src|worktree|checkout|tmp|temp|home|code|docs|t
|
|
|
12
13
|
const validRepoName = (n) => Boolean(n && n.length >= 3 && !n.startsWith(".") && !GENERIC_DIR_RE.test(n));
|
|
13
14
|
const inTmpDir = (p) => p.startsWith(tmpdir() + sep) || p.startsWith("/tmp/") || p.startsWith("/var/tmp/");
|
|
14
15
|
|
|
16
|
+
const checkExists = (p, existsCache) => {
|
|
17
|
+
if (!existsCache) return existsSync(p);
|
|
18
|
+
if (existsCache.has(p)) return existsCache.get(p);
|
|
19
|
+
const v = existsSync(p);
|
|
20
|
+
existsCache.set(p, v);
|
|
21
|
+
return v;
|
|
22
|
+
};
|
|
23
|
+
|
|
15
24
|
function manifestNameOf(dir) {
|
|
16
25
|
try {
|
|
17
26
|
const pkg = join(dir, "package.json");
|
|
@@ -75,15 +84,29 @@ function resolveGitDirName(dir, gitDir, depth = 0) {
|
|
|
75
84
|
return base;
|
|
76
85
|
}
|
|
77
86
|
|
|
78
|
-
function gitRepoOf(p) {
|
|
79
|
-
if (!p
|
|
87
|
+
function gitRepoOf(p, gitCache = null, existsCache = null) {
|
|
88
|
+
if (!p) return null;
|
|
89
|
+
if (gitCache?.has(p)) return gitCache.get(p);
|
|
90
|
+
const save = (val) => {
|
|
91
|
+
gitCache?.set(p, val);
|
|
92
|
+
return val;
|
|
93
|
+
};
|
|
94
|
+
if (!checkExists(p, existsCache)) return save(null);
|
|
80
95
|
let dir = p;
|
|
81
96
|
try {
|
|
82
97
|
if (!statSync(dir).isDirectory()) dir = dirname(dir);
|
|
83
98
|
} catch {
|
|
84
|
-
return null;
|
|
99
|
+
return save(null);
|
|
85
100
|
}
|
|
101
|
+
if (dir !== p && gitCache?.has(dir)) return save(gitCache.get(dir));
|
|
102
|
+
const walked = [];
|
|
103
|
+
let hit = null;
|
|
86
104
|
for (; ; dir = dirname(dir)) {
|
|
105
|
+
if (gitCache?.has(dir)) {
|
|
106
|
+
hit = gitCache.get(dir);
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
walked.push(dir);
|
|
87
110
|
if (!IGNORE_GIT_ROOTS.has(dir)) {
|
|
88
111
|
const g = join(dir, ".git");
|
|
89
112
|
if (existsSync(g)) {
|
|
@@ -98,28 +121,32 @@ function gitRepoOf(p) {
|
|
|
98
121
|
const mainRoot = wt[1];
|
|
99
122
|
let name = resolveGitDirName(mainRoot, join(mainRoot, ".git"));
|
|
100
123
|
if (GENERIC_DIR_RE.test(name)) name = manifestNameOf(dir) || name;
|
|
101
|
-
|
|
124
|
+
hit = { root: mainRoot, name };
|
|
125
|
+
break;
|
|
102
126
|
}
|
|
103
127
|
}
|
|
104
128
|
} else if (st.isDirectory()) {
|
|
105
|
-
|
|
129
|
+
hit = { root: dir, name: resolveGitDirName(dir, g) };
|
|
130
|
+
break;
|
|
106
131
|
}
|
|
107
132
|
} catch { /* unreadable .git metadata; fall back to dir name */ }
|
|
108
|
-
|
|
133
|
+
hit = { root: dir, name: basename(dir) };
|
|
134
|
+
break;
|
|
109
135
|
}
|
|
110
136
|
}
|
|
111
137
|
if (dirname(dir) === dir) break;
|
|
112
138
|
}
|
|
113
|
-
|
|
139
|
+
for (const w of walked) gitCache?.set(w, hit);
|
|
140
|
+
return save(hit);
|
|
114
141
|
}
|
|
115
142
|
|
|
116
143
|
// The nearest directory at or above cwd that holds .git (skipping root/home/tmp, resolving worktrees/temp clones), else cwd's own name.
|
|
117
144
|
// onDisk tells whether cwd still exists, so a session whose folder is gone keeps the project it had without climbing parent repos.
|
|
118
|
-
export function projectOf(cwd) {
|
|
145
|
+
export function projectOf(cwd, gitCache = null, existsCache = null) {
|
|
119
146
|
if (!cwd) return null;
|
|
120
|
-
const onDisk =
|
|
147
|
+
const onDisk = checkExists(cwd, existsCache);
|
|
121
148
|
if (onDisk) {
|
|
122
|
-
const g = gitRepoOf(cwd);
|
|
149
|
+
const g = gitRepoOf(cwd, gitCache, existsCache);
|
|
123
150
|
if (g) return { name: g.name, onDisk: true };
|
|
124
151
|
}
|
|
125
152
|
return { name: basename(cwd) || "(no project)", onDisk };
|
|
@@ -152,13 +179,13 @@ function matchFallbackPath(dir, cwdRepo, knownRepos, sortedKnown) {
|
|
|
152
179
|
return null;
|
|
153
180
|
}
|
|
154
181
|
|
|
155
|
-
function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, knownRepos, sortedKnown) {
|
|
156
|
-
const cwdRepo = cwd ? gitRepoOf(cwd) : null;
|
|
182
|
+
function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, knownRepos, sortedKnown, gitCache, existsCache) {
|
|
183
|
+
const cwdRepo = cwd ? gitRepoOf(cwd, gitCache, existsCache) : null;
|
|
157
184
|
const urlRepo = repoFromUrl(repoUrl);
|
|
158
185
|
const byRepo = new Map();
|
|
159
186
|
for (const [dir, [w, r]] of Object.entries(pathWeights ?? {})) {
|
|
160
|
-
let name = gitRepoOf(dir)?.name ?? null;
|
|
161
|
-
if (!name && (!
|
|
187
|
+
let name = gitRepoOf(dir, gitCache, existsCache)?.name ?? null;
|
|
188
|
+
if (!name && (!checkExists(dir, existsCache) || inTmpDir(dir))) name = matchFallbackPath(dir, cwdRepo, knownRepos, sortedKnown);
|
|
162
189
|
if (!name) continue;
|
|
163
190
|
const cur = byRepo.get(name) ?? { name, w: 0, r: 0 };
|
|
164
191
|
cur.w += w;
|
|
@@ -189,7 +216,7 @@ function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, known
|
|
|
189
216
|
return cwdRepo.name;
|
|
190
217
|
}
|
|
191
218
|
if (urlRepo) return urlRepo;
|
|
192
|
-
const p = projectOf(cwd);
|
|
219
|
+
const p = projectOf(cwd, gitCache, existsCache);
|
|
193
220
|
if (p && !p.onDisk) {
|
|
194
221
|
const segHit = matchSeg(basename(cwd), new Set(), knownRepos, sortedKnown);
|
|
195
222
|
if (segHit) return segHit;
|
|
@@ -198,8 +225,52 @@ function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, known
|
|
|
198
225
|
}
|
|
199
226
|
|
|
200
227
|
const firstLine = (text) => text.split("\n").find((l) => l.trim())?.trim().slice(0, 80) ?? null;
|
|
228
|
+
const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
229
|
+
|
|
230
|
+
function expandDirtySessions(db, dirtySessions) {
|
|
231
|
+
const expanded = new Set(dirtySessions);
|
|
232
|
+
const dependents = new Map();
|
|
233
|
+
const addEdge = (prev, next) => {
|
|
234
|
+
if (!prev || !next || prev === next) return;
|
|
235
|
+
let set = dependents.get(prev);
|
|
236
|
+
if (!set) dependents.set(prev, (set = new Set()));
|
|
237
|
+
set.add(next);
|
|
238
|
+
};
|
|
239
|
+
for (const r of db.prepare("SELECT id, carried_from FROM sessions WHERE carried_from IS NOT NULL").all()) {
|
|
240
|
+
addEdge(r.carried_from, r.id);
|
|
241
|
+
}
|
|
242
|
+
for (const r of db.prepare(`SELECT DISTINCT f.session_id id, q.session_id prev_id FROM repeats p
|
|
243
|
+
JOIN requests q ON q.message_id = p.message_id JOIN files f ON f.id = p.file_id AND f.kind = 'main'`).all()) {
|
|
244
|
+
addEdge(r.prev_id, r.id);
|
|
245
|
+
}
|
|
246
|
+
const queue = [...expanded];
|
|
247
|
+
while (queue.length) {
|
|
248
|
+
const cur = queue.pop();
|
|
249
|
+
const nexts = dependents.get(cur);
|
|
250
|
+
if (!nexts) continue;
|
|
251
|
+
for (const n of nexts) {
|
|
252
|
+
if (!expanded.has(n)) {
|
|
253
|
+
expanded.add(n);
|
|
254
|
+
queue.push(n);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return expanded;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function derive(db, config, { dirtySessions = null, full = false } = {}) {
|
|
262
|
+
const pricesText = existsSync(config.prices) ? readFileSync(config.prices, "utf8") : "";
|
|
263
|
+
const deriveKey = sha256(`${config.timeZone}\n${pricesText}`);
|
|
264
|
+
const getMeta = db.prepare("SELECT value FROM meta WHERE key = ?");
|
|
265
|
+
const putMeta = db.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
|
|
266
|
+
const prevKey = getMeta.get("derive_key")?.value;
|
|
267
|
+
const forceFull = full || dirtySessions === null || prevKey !== deriveKey;
|
|
268
|
+
if (!forceFull && dirtySessions.size === 0) return;
|
|
269
|
+
|
|
270
|
+
const expandedDirty = forceFull ? null : expandDirtySessions(db, dirtySessions);
|
|
271
|
+
const gitCache = new Map();
|
|
272
|
+
const existsCache = new Map();
|
|
201
273
|
|
|
202
|
-
export function derive(db, config) {
|
|
203
274
|
const files = db.prepare("SELECT id, provider, session_id, path, cwd, own_first first_ts, own_last last_ts FROM files WHERE kind = 'main'").all();
|
|
204
275
|
const existing = new Map(db.prepare("SELECT id, project FROM sessions").all().map((s) => [s.id, s.project]));
|
|
205
276
|
const titles = db.prepare("SELECT kind, title FROM titles WHERE file_id = ? ORDER BY line DESC");
|
|
@@ -207,7 +278,7 @@ export function derive(db, config) {
|
|
|
207
278
|
const lastCost = db.prepare("SELECT * FROM cost_states WHERE file_id = ? ORDER BY line DESC LIMIT 1");
|
|
208
279
|
const knownRepos = new Set();
|
|
209
280
|
for (const f of files) {
|
|
210
|
-
const g = f.cwd ? gitRepoOf(f.cwd) : null;
|
|
281
|
+
const g = f.cwd ? gitRepoOf(f.cwd, gitCache, existsCache) : null;
|
|
211
282
|
if (g && validRepoName(g.name)) knownRepos.add(g.name);
|
|
212
283
|
}
|
|
213
284
|
const sessionMeta = new Map();
|
|
@@ -234,13 +305,18 @@ export function derive(db, config) {
|
|
|
234
305
|
const prev = cur.pathWeights[dir] ?? (cur.pathWeights[dir] = [0, 0]);
|
|
235
306
|
prev[0] += Number(pair[0]) || 0;
|
|
236
307
|
prev[1] += Number(pair[1]) || 0;
|
|
237
|
-
const g = gitRepoOf(dir);
|
|
308
|
+
const g = gitRepoOf(dir, gitCache, existsCache);
|
|
238
309
|
if (g && validRepoName(g.name)) knownRepos.add(g.name);
|
|
239
310
|
}
|
|
240
311
|
} catch { /* ignore malformed json */ }
|
|
241
312
|
}
|
|
242
313
|
}
|
|
243
314
|
const sortedKnown = [...knownRepos].sort((a, b) => b.length - a.length);
|
|
315
|
+
const knownReposHash = sha256(sortedKnown.join("\n"));
|
|
316
|
+
const prevReposHash = getMeta.get("known_repos_hash")?.value;
|
|
317
|
+
const deriveAll = forceFull || knownReposHash !== prevReposHash;
|
|
318
|
+
const targetFiles = deriveAll ? files : files.filter((f) => expandedDirty.has(f.session_id));
|
|
319
|
+
|
|
244
320
|
// The session this file continues or forks: of the sessions owning the requests it repeats, the latest to start.
|
|
245
321
|
// CROSS JOIN keeps the order from the file's few repeats; left to the planner it scanned every file and request per file.
|
|
246
322
|
const predecessor = db.prepare(`SELECT f.session_id id FROM repeats p CROSS JOIN requests q ON q.message_id = p.message_id
|
|
@@ -258,21 +334,26 @@ export function derive(db, config) {
|
|
|
258
334
|
api_ms = excluded.api_ms, tool_ms = excluded.tool_ms, lines_added = excluded.lines_added, lines_removed = excluded.lines_removed,
|
|
259
335
|
carried_from = excluded.carried_from, model_cost = excluded.model_cost, model_tokens = excluded.model_tokens`);
|
|
260
336
|
|
|
337
|
+
const fileBySession = new Map(files.map((f) => [f.session_id, f]));
|
|
261
338
|
const raw = new Map();
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
339
|
+
const rawOf = (sessionId) => {
|
|
340
|
+
if (raw.has(sessionId)) return raw.get(sessionId);
|
|
341
|
+
const f = fileBySession.get(sessionId);
|
|
342
|
+
const c = f ? lastCost.get(f.id) : null;
|
|
343
|
+
const val = c ? { ...c, models: JSON.parse(c.model_usage) } : null;
|
|
344
|
+
raw.set(sessionId, val);
|
|
345
|
+
return val;
|
|
346
|
+
};
|
|
266
347
|
|
|
267
348
|
db.exec("BEGIN");
|
|
268
349
|
try {
|
|
269
|
-
for (const f of
|
|
350
|
+
for (const f of targetFiles) {
|
|
270
351
|
const ms = sessionMeta.get(f.session_id);
|
|
271
|
-
const project = resolveSessionProject(f.cwd, ms?.repo_url ?? null, ms?.pathWeights ?? null, existing.get(f.session_id), knownRepos, sortedKnown);
|
|
352
|
+
const project = resolveSessionProject(f.cwd, ms?.repo_url ?? null, ms?.pathWeights ?? null, existing.get(f.session_id), knownRepos, sortedKnown, gitCache, existsCache);
|
|
272
353
|
const t = titles.all(f.id);
|
|
273
354
|
const title = t.find((x) => x.kind === "custom")?.title ?? t.find((x) => x.kind === "ai")?.title ?? (firstOwner.get(f.session_id)?.text ? firstLine(firstOwner.get(f.session_id).text) : null);
|
|
274
355
|
|
|
275
|
-
const c =
|
|
356
|
+
const c = rawOf(f.session_id);
|
|
276
357
|
let cost = null;
|
|
277
358
|
let models = null;
|
|
278
359
|
let tokens = null;
|
|
@@ -289,7 +370,7 @@ export function derive(db, config) {
|
|
|
289
370
|
// A host record that started with the earlier session's record is cumulative and holds all of it;
|
|
290
371
|
// a fork or a resume in a new process starts its own record shortly before its first own line.
|
|
291
372
|
const earlier = predecessor.get(f.id, f.session_id);
|
|
292
|
-
prev = earlier ?
|
|
373
|
+
prev = earlier ? rawOf(earlier.id) : null;
|
|
293
374
|
if (prev && c.start_ms !== null && prev.start_ms !== null && c.start_ms <= prev.start_ms + 1000) {
|
|
294
375
|
carriedFrom = earlier.id;
|
|
295
376
|
const less = (v, w) => (v === null ? null : Math.max(0, v - (w ?? 0)));
|
|
@@ -337,10 +418,12 @@ export function derive(db, config) {
|
|
|
337
418
|
upsert.run(f.session_id, f.provider, f.path.split(sep)[0], f.cwd, project, title, f.first_ts, f.last_ts, cost,
|
|
338
419
|
c ? (c.incomplete ? 1 : 0) : null, estimated, check ? JSON.stringify(check) : null, api, tool, added, removed, carriedFrom, models ? JSON.stringify(models) : null, tokens ? JSON.stringify(tokens) : null);
|
|
339
420
|
}
|
|
421
|
+
putMeta.run("derive_key", deriveKey);
|
|
422
|
+
putMeta.run("known_repos_hash", knownReposHash);
|
|
340
423
|
db.exec("COMMIT");
|
|
341
424
|
} catch (err) {
|
|
342
425
|
db.exec("ROLLBACK");
|
|
343
426
|
throw err;
|
|
344
427
|
}
|
|
345
|
-
markRebuilds(db, prices);
|
|
428
|
+
markRebuilds(db, prices, forceFull ? null : expandedDirty);
|
|
346
429
|
}
|
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
|
|
63
|
+
for (const r of cand) if (r.from <= day && (!hit || r.from > hit.from)) hit = r;
|
|
44
64
|
if (hit) return hit;
|
|
45
|
-
|
|
65
|
+
return null;
|
|
46
66
|
}
|
|
47
67
|
return null;
|
|
48
68
|
}
|
package/src/providers/agy.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
366
|
-
|
|
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(
|
|
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
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
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 };
|
package/src/providers/claude.mjs
CHANGED
|
@@ -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
|
-
|
|
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)
|
|
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.
|