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.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -2
  3. package/bin/llmtop.mjs +101 -0
  4. package/dashboard/dist/apple-touch-icon.png +0 -0
  5. package/dashboard/dist/assets/index-BVbAwMVB.js +9 -0
  6. package/dashboard/dist/assets/index-Cp7Swcz5.css +1 -0
  7. package/dashboard/dist/assets/llmtop-lockup-DtFPJmhv.svg +1 -0
  8. package/dashboard/dist/assets/llmtop-lockup-reversed-D9OmQIVU.svg +1 -0
  9. package/dashboard/dist/favicon.ico +0 -0
  10. package/dashboard/dist/favicon.svg +1 -0
  11. package/dashboard/dist/index.html +19 -0
  12. package/dashboard/dist/llmtop-mark-192.png +0 -0
  13. package/dashboard/dist/llmtop-mark-512.png +0 -0
  14. package/dashboard/dist/site.webmanifest +11 -0
  15. package/dashboard/src/App.tsx +213 -0
  16. package/dashboard/src/controls/DateRange.tsx +108 -0
  17. package/dashboard/src/controls/Disclosure.tsx +15 -0
  18. package/dashboard/src/controls/Search.tsx +18 -0
  19. package/dashboard/src/controls/Select.tsx +48 -0
  20. package/dashboard/src/controls/popover.tsx +31 -0
  21. package/dashboard/src/dash.ts +23 -0
  22. package/dashboard/src/extra.test.ts +9 -0
  23. package/dashboard/src/extra.ts +16 -0
  24. package/dashboard/src/format.ts +29 -0
  25. package/dashboard/src/i18n.tsx +52 -0
  26. package/dashboard/src/index.ts +7 -0
  27. package/dashboard/src/main.tsx +7 -0
  28. package/dashboard/src/model.test.ts +110 -0
  29. package/dashboard/src/model.ts +255 -0
  30. package/dashboard/src/state.test.ts +48 -0
  31. package/dashboard/src/state.ts +61 -0
  32. package/dashboard/src/styles.css +401 -0
  33. package/dashboard/src/tip.ts +51 -0
  34. package/dashboard/src/treemap.test.ts +23 -0
  35. package/dashboard/src/treemap.ts +30 -0
  36. package/dashboard/src/ui.tsx +327 -0
  37. package/dashboard/src/views/Activity.tsx +177 -0
  38. package/dashboard/src/views/Context.tsx +183 -0
  39. package/dashboard/src/views/Models.tsx +155 -0
  40. package/dashboard/src/views/Overview.tsx +83 -0
  41. package/dashboard/src/views/Projects.tsx +116 -0
  42. package/dashboard/src/views/Sessions.tsx +54 -0
  43. package/dashboard/src/views/Subagents.tsx +102 -0
  44. package/docs/brand/README.md +91 -0
  45. package/docs/brand/brand.json +67 -0
  46. package/docs/brand/favicon.ico +0 -0
  47. package/docs/brand/png/apple-touch-icon.png +0 -0
  48. package/docs/brand/png/favicon-16.png +0 -0
  49. package/docs/brand/png/favicon-32.png +0 -0
  50. package/docs/brand/png/favicon-48.png +0 -0
  51. package/docs/brand/png/llmtop-lockup-reversed@2x.png +0 -0
  52. package/docs/brand/png/llmtop-lockup@2x.png +0 -0
  53. package/docs/brand/png/llmtop-mark-1024.png +0 -0
  54. package/docs/brand/png/llmtop-mark-192.png +0 -0
  55. package/docs/brand/png/llmtop-mark-512.png +0 -0
  56. package/docs/brand/png/llmtop-wordmark@2x.png +0 -0
  57. package/docs/brand/source/build_brand.py +173 -0
  58. package/docs/brand/svg/favicon.svg +1 -0
  59. package/docs/brand/svg/llmtop-glyph.svg +1 -0
  60. package/docs/brand/svg/llmtop-lockup-reversed.svg +1 -0
  61. package/docs/brand/svg/llmtop-lockup.svg +1 -0
  62. package/docs/brand/svg/llmtop-mark-light.svg +1 -0
  63. package/docs/brand/svg/llmtop-mark.svg +1 -0
  64. package/docs/brand/svg/llmtop-wordmark-reversed.svg +1 -0
  65. package/docs/brand/svg/llmtop-wordmark.svg +1 -0
  66. package/llmtop.config.example.json +10 -0
  67. package/package.json +73 -4
  68. package/prices.md +27 -0
  69. package/src/api.mjs +53 -0
  70. package/src/archive.mjs +142 -0
  71. package/src/config.mjs +55 -0
  72. package/src/context.mjs +151 -0
  73. package/src/dashboard.mjs +61 -0
  74. package/src/db.mjs +102 -0
  75. package/src/derive.mjs +346 -0
  76. package/src/effort.mjs +18 -0
  77. package/src/format.mjs +19 -0
  78. package/src/paths.mjs +82 -0
  79. package/src/prices-command.mjs +25 -0
  80. package/src/prices.mjs +146 -0
  81. package/src/providers/agy.mjs +438 -0
  82. package/src/providers/claude.mjs +274 -0
  83. package/src/providers/codex.mjs +589 -0
  84. package/src/providers/index.mjs +25 -0
  85. package/src/rebuilds.mjs +85 -0
  86. package/src/scan.mjs +214 -0
  87. package/src/serve.mjs +44 -0
  88. package/src/show.mjs +20 -0
  89. package/src/usage-command.mjs +110 -0
  90. package/src/usage.mjs +388 -0
  91. package/src/zone.mjs +15 -0
@@ -0,0 +1,589 @@
1
+ // Everything that knows the Codex CLI/IDE rollout format under ~/.codex/sessions and session_index.jsonl.
2
+ // Token counts in Codex include cached_input_tokens inside input_tokens, so uncached input is input - cached - write.
3
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
4
+ import { basename, dirname, join, relative, sep } from "node:path";
5
+ import { copyOther } from "../archive.mjs";
6
+ import { createPathTracker, extractCommandDirs, isAbsPath } from "../paths.mjs";
7
+ import { zoner } from "../zone.mjs";
8
+
9
+ export const defaultPath = "~/.codex/sessions";
10
+ export const label = "Codex";
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
+ const UUID_TAIL = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
22
+ export function describe(rel) {
23
+ if (!rel.endsWith(".jsonl")) return null;
24
+ const parts = rel.split(sep);
25
+ const m = rel.match(UUID_TAIL);
26
+ const sessionId = m ? m[1] : basename(rel, ".jsonl");
27
+ return { rel, kind: "main", slug: parts[0] || "codex", sessionId, agentId: null };
28
+ }
29
+
30
+ export function listHost(root) {
31
+ const transcripts = [];
32
+ const walk = (dir) => {
33
+ for (const e of list(dir)) {
34
+ const abs = join(dir, e.name);
35
+ if (e.isDirectory()) walk(abs);
36
+ else if (e.isFile() && e.name.endsWith(".jsonl")) {
37
+ const d = describe(relative(root, abs));
38
+ if (d) transcripts.push(d);
39
+ }
40
+ }
41
+ };
42
+ walk(root);
43
+ return { transcripts, others: [] };
44
+ }
45
+
46
+ // Copy session_index.jsonl (sibling of sessions/) into the archive so titles survive host deletion.
47
+ export function syncMeta(root, archiveDir) {
48
+ const idx = join(dirname(root), "session_index.jsonl");
49
+ if (!existsSync(idx)) return 0;
50
+ return copyOther(idx, join(archiveDir, "session_index.jsonl")) ? 1 : 0;
51
+ }
52
+
53
+ const CODEX_FAMILY_NAMES = {
54
+ sol: "GPT Sol",
55
+ luna: "GPT Luna",
56
+ astra: "GPT Astra",
57
+ terra: "GPT Terra",
58
+ codex: "GPT Codex",
59
+ "codex-mini": "GPT Codex Mini",
60
+ "codex-max": "GPT Codex Max",
61
+ "codex-auto-review": "Codex Review",
62
+ mini: "GPT Mini",
63
+ nano: "GPT Nano",
64
+ pro: "GPT Pro",
65
+ };
66
+
67
+ export function familyOf(model) {
68
+ const clean = model.replace(/\[.*\]$/, "").replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, "");
69
+ const m = clean.match(/^gpt-[\d.]+-([a-z][a-z0-9-]*)$/i);
70
+ if (m) return m[1].toLowerCase();
71
+ return clean;
72
+ }
73
+
74
+ export function displayModel(family) {
75
+ if (CODEX_FAMILY_NAMES[family]) return CODEX_FAMILY_NAMES[family];
76
+ const v = family.match(/^gpt-([\d.]+)$/i);
77
+ if (v) return `GPT-${v[1]}`;
78
+ return family;
79
+ }
80
+
81
+ const HARNESS_PREFIXES = ["<environment_context>", "<permissions instructions>", "<INSTRUCTIONS>", "<collaboration_mode>", "<turn_aborted>", "<subagent_notification>", "# AGENTS.md"];
82
+ function userMessageText(content) {
83
+ const blocks = typeof content === "string" ? [content] : Array.isArray(content) ? content.filter((b) => b?.type === "input_text" || b?.type === "text").map((b) => b.text ?? "") : [];
84
+ const kept = blocks.map((s) => s.trim()).filter((t) => t && !HARNESS_PREFIXES.some((p) => t.startsWith(p)));
85
+ return kept.length ? kept.join("\n\n") : null;
86
+ }
87
+
88
+ function subagentTypeOf(source) {
89
+ const s = source?.subagent;
90
+ if (!s) return null;
91
+ if (typeof s === "string") return s;
92
+ if (s.other) return s.other;
93
+ if (s.thread_spawn?.agent_role) return s.thread_spawn.agent_role;
94
+ const k = Object.keys(s)[0];
95
+ return k ?? "subagent";
96
+ }
97
+
98
+ function toolOutputText(payload) {
99
+ const out = payload?.output;
100
+ if (typeof out === "string") return out;
101
+ if (Array.isArray(out)) return out.map((b) => (typeof b === "string" ? b : b?.text ?? "")).filter(Boolean).join("\n");
102
+ return "";
103
+ }
104
+
105
+ function isToolError(payload, text) {
106
+ if (payload?.is_error) return true;
107
+ if (payload?.status === "error" || payload?.status === "failed") return true;
108
+ if (/^Exit code:\s*[1-9]\d*/m.test(text)) return true;
109
+ if (/^(?:Script failed|Tool call failed|Patch failed|Verification failed|Error:|Process exited with code [1-9]\d*)/m.test(text)) return true;
110
+ if (text.startsWith("{")) {
111
+ try {
112
+ const parsed = JSON.parse(text);
113
+ if (typeof parsed?.metadata?.exit_code === "number" && parsed.metadata.exit_code !== 0) return true;
114
+ if (parsed?.error || parsed?.is_error) return true;
115
+ } catch { /* plain text output */ }
116
+ }
117
+ return false;
118
+ }
119
+
120
+ const WALL_TIME_RE = /\bWall time:?\s+([\d.]+)\s*(ms|milliseconds?|s|sec|seconds?|m|min|minutes?)\b/i;
121
+ function parseToolDurationMs(text, callStartMs, outputTsMs) {
122
+ if (text.startsWith("{")) {
123
+ try {
124
+ const parsed = JSON.parse(text);
125
+ const ms = parsed?.metadata?.duration_ms;
126
+ if (typeof ms === "number" && Number.isFinite(ms) && ms >= 0) return Math.round(ms);
127
+ const sec = parsed?.metadata?.duration_seconds;
128
+ if (typeof sec === "number" && Number.isFinite(sec) && sec >= 0) return Math.round(sec * 1000);
129
+ } catch { /* ignore */ }
130
+ }
131
+ const m = text.match(WALL_TIME_RE);
132
+ if (m) {
133
+ const val = Number(m[1]);
134
+ if (Number.isFinite(val) && val >= 0) {
135
+ const unit = m[2].toLowerCase();
136
+ if (unit.startsWith("ms") || unit.startsWith("milli")) return Math.round(val);
137
+ if (unit.startsWith("m")) return Math.round(val * 60_000);
138
+ return Math.round(val * 1000);
139
+ }
140
+ }
141
+ if (callStartMs !== null && Number.isFinite(outputTsMs)) {
142
+ const dt = outputTsMs - callStartMs;
143
+ if (dt >= 0 && dt < 600_000) return Math.round(dt);
144
+ }
145
+ return 0;
146
+ }
147
+
148
+ function callInputText(payload) {
149
+ const parts = [];
150
+ for (const raw of [payload?.input, payload?.arguments]) {
151
+ if (typeof raw === "string" && raw) {
152
+ parts.push(raw);
153
+ if (raw.trimStart().startsWith("{")) {
154
+ try {
155
+ const o = JSON.parse(raw);
156
+ for (const k of ["cmd", "command", "patch", "input", "path", "file_path", "target_file"]) {
157
+ if (typeof o?.[k] === "string") parts.push(o[k]);
158
+ }
159
+ } catch { /* ignore */ }
160
+ }
161
+ } else if (raw && typeof raw === "object") {
162
+ for (const v of Object.values(raw)) if (typeof v === "string") parts.push(v);
163
+ }
164
+ }
165
+ return parts.join("\n");
166
+ }
167
+
168
+ const lineCount = (s) => (s ? s.replace(/\n$/, "").split("\n").length : 0);
169
+
170
+ function countUnifiedDiff(diff) {
171
+ let added = 0;
172
+ let removed = 0;
173
+ for (const l of diff.split(/\r?\n/)) {
174
+ if (l.startsWith("+++ ") || l.startsWith("--- ") || l.startsWith("@@")) continue;
175
+ if (l.startsWith("+")) added++;
176
+ else if (l.startsWith("-")) removed++;
177
+ }
178
+ return { added, removed };
179
+ }
180
+
181
+ function countPatchLines(text) {
182
+ if (!text.includes("*** Begin Patch")) return { added: 0, removed: 0 };
183
+ let added = 0;
184
+ let removed = 0;
185
+ const unesc = text.includes("*** Begin Patch\\n") ? text.replace(/\\n/g, "\n") : text;
186
+ const re = /\*\*\* Begin Patch\r?\n([\s\S]*?)\*\*\* End Patch/g;
187
+ let m;
188
+ while ((m = re.exec(unesc)) !== null) {
189
+ for (const line of m[1].split(/\r?\n/)) {
190
+ if (line.startsWith("*** ") || line.startsWith("+++ ") || line.startsWith("--- ") || line.startsWith("@@")) continue;
191
+ if (line.startsWith("+")) added++;
192
+ else if (line.startsWith("-")) removed++;
193
+ }
194
+ }
195
+ return { added, removed };
196
+ }
197
+
198
+ const SKILL_PATH_RE = /([^\s"'`<>()\\]*?skills\/([a-z0-9][a-z0-9._-]{0,63})\/SKILL\.md)\b/gi;
199
+ const SKILL_DOLLAR_RE = /(?:^|[\s(`"'])\$([a-z][a-z0-9_-]{1,63})\b/g;
200
+ function skillSourceOf(path) {
201
+ if (/\/builtin\/skills\//i.test(path)) return "builtin";
202
+ if (/^~\/|\/(?:home|Users)\/[^/]+\/\.(?:agents|codex|claude|gemini)\//i.test(path)) return "personal";
203
+ return "project";
204
+ }
205
+
206
+ function extractSkillPaths(text) {
207
+ const seen = new Map();
208
+ SKILL_PATH_RE.lastIndex = 0;
209
+ let m;
210
+ while ((m = SKILL_PATH_RE.exec(text)) !== null) {
211
+ const name = m[2].toLowerCase();
212
+ if (!seen.has(name)) seen.set(name, skillSourceOf(m[1]));
213
+ }
214
+ return [...seen.entries()];
215
+ }
216
+
217
+ function extractDollarSkills(text) {
218
+ const seen = new Set();
219
+ SKILL_DOLLAR_RE.lastIndex = 0;
220
+ let m;
221
+ while ((m = SKILL_DOLLAR_RE.exec(text)) !== null) seen.add(m[1]);
222
+ return [...seen];
223
+ }
224
+
225
+ export function createIngester(db, timeZone) {
226
+ const zone = zoner(timeZone);
227
+ const q = {
228
+ record: db.prepare("INSERT OR IGNORE INTO records(uuid, file_id, line, type, ts) VALUES (?, ?, ?, ?, ?)"),
229
+ request: db.prepare(`INSERT OR IGNORE INTO requests(message_id, file_id, line, session_id, agent_id, ts, day, hour, model, family,
230
+ effort, is_sub, input, output, thinking, cache_read, cache_write, cache_write_1h) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),
231
+ owner: db.prepare("INSERT OR IGNORE INTO owner_messages(uuid, file_id, line, session_id, ts, kind, text) VALUES (?, ?, ?, ?, ?, ?, ?)"),
232
+ call: db.prepare("INSERT OR IGNORE INTO tool_calls(id, file_id, line, session_id, agent_id, ts, name, model, is_error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)"),
233
+ result: db.prepare("UPDATE tool_calls SET is_error = ? WHERE id = ?"),
234
+ skill: db.prepare("INSERT OR IGNORE INTO skills(id, file_id, line, session_id, ts, name, via, source, is_error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"),
235
+ skillErr: db.prepare("UPDATE skills SET is_error = 1 WHERE id = ?"),
236
+ compaction: db.prepare(`INSERT OR IGNORE INTO compactions(uuid, file_id, line, session_id, agent_id, ts, trigger, pre_tokens, post_tokens, duration_ms)
237
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),
238
+ fileMeta: db.prepare(`INSERT INTO file_meta(file_id, parent_session_id, subagent_type, tool_use_id, repo_url) VALUES (?, ?, ?, ?, ?)
239
+ ON CONFLICT(file_id) DO UPDATE SET
240
+ parent_session_id = COALESCE(excluded.parent_session_id, file_meta.parent_session_id),
241
+ subagent_type = COALESCE(excluded.subagent_type, file_meta.subagent_type),
242
+ tool_use_id = COALESCE(excluded.tool_use_id, file_meta.tool_use_id),
243
+ repo_url = COALESCE(excluded.repo_url, file_meta.repo_url)`),
244
+ getStats: db.prepare("SELECT api_ms, tool_ms, lines_added, lines_removed, target_paths FROM file_meta WHERE file_id = ?"),
245
+ upsertStats: db.prepare(`INSERT INTO file_meta(file_id, api_ms, tool_ms, lines_added, lines_removed) VALUES (?, ?, ?, ?, ?)
246
+ ON CONFLICT(file_id) DO UPDATE SET api_ms = excluded.api_ms, tool_ms = excluded.tool_ms,
247
+ lines_added = excluded.lines_added, lines_removed = excluded.lines_removed`),
248
+ upsertTargetPaths: db.prepare(`INSERT INTO file_meta(file_id, target_paths) VALUES (?, ?)
249
+ ON CONFLICT(file_id) DO UPDATE SET target_paths = excluded.target_paths`),
250
+ };
251
+ const stateByFile = new Map();
252
+
253
+ return function ingestLine(file, line, text) {
254
+ let rec;
255
+ try {
256
+ rec = JSON.parse(text);
257
+ } catch {
258
+ return { added: 0 };
259
+ }
260
+ if (!rec || typeof rec !== "object") return { added: 0 };
261
+ let st = stateByFile.get(file.id);
262
+ if (!st) {
263
+ const prevStats = file.lines > 0 ? q.getStats.get(file.id) : null;
264
+ st = {
265
+ launchCwd: file.cwd ?? null,
266
+ cwd: file.cwd ?? null,
267
+ model: null, effort: null, sawTokenRec: false, lastTotal: null, lastCompactionLine: -999,
268
+ callStart: new Map(), callSkills: new Map(),
269
+ turnStartMs: null, turnToolMs: 0, openApiMs: 0, lastWaitFromMs: null,
270
+ completedApiMs: prevStats?.api_ms ?? 0, toolMs: prevStats?.tool_ms ?? 0,
271
+ baseAdded: prevStats?.lines_added ?? 0, baseRemoved: prevStats?.lines_removed ?? 0,
272
+ sawFileChange: false, fcAdded: 0, fcRemoved: 0, patchAdded: 0, patchRemoved: 0,
273
+ paths: createPathTracker(prevStats?.target_paths ?? null),
274
+ };
275
+ stateByFile.set(file.id, st);
276
+ }
277
+ const ownId = file.agent_id ?? file.session_id;
278
+ const session = file.session_id;
279
+ const agent = file.agent_id;
280
+ const isSub = file.kind === "sub" ? 1 : 0;
281
+ const p = rec.payload ?? {};
282
+ const ts = rec.timestamp ?? p.timestamp ?? null;
283
+ const parsedTs = ts ? Date.parse(ts) : NaN;
284
+ const tsMs = Number.isFinite(parsedTs) ? parsedTs : null;
285
+ let cwd = p.cwd ?? null;
286
+ let added = 0;
287
+ let statsDirty = false;
288
+ let pathsDirty = false;
289
+
290
+ const consumeOpenWait = () => {
291
+ if (tsMs !== null && st.lastWaitFromMs !== null) {
292
+ const dt = tsMs - st.lastWaitFromMs;
293
+ if (dt > 0 && dt < 600_000) {
294
+ st.openApiMs += dt;
295
+ statsDirty = true;
296
+ }
297
+ st.lastWaitFromMs = null;
298
+ }
299
+ };
300
+ const recordDollarSkills = (body) => {
301
+ for (const name of extractDollarSkills(body)) {
302
+ q.skill.run(`codex:${ownId}:${line}:cmd:${name}`, file.id, line, session, ts, name, "command", null, 0);
303
+ }
304
+ };
305
+
306
+ const recordUsage = (msgId, u) => {
307
+ if (!ts || !u) return false;
308
+ const cacheRead = u.cached_input_tokens ?? 0;
309
+ const cacheWrite = u.cache_write_input_tokens ?? 0;
310
+ const input = Math.max(0, (u.input_tokens ?? 0) - cacheRead - cacheWrite);
311
+ const output = u.output_tokens ?? 0;
312
+ const thinking = u.reasoning_output_tokens ?? 0;
313
+ if (!input && !output && !cacheRead && !cacheWrite) return false;
314
+ const model = st.model ?? "unknown";
315
+ const { day, hour } = zone(ts);
316
+ q.record.run(`codex:${ownId}:${line}`, file.id, line, rec.type, ts);
317
+ q.request.run(msgId, file.id, line, session, agent, ts, day, hour, model, familyOf(model), st.effort ?? null, isSub,
318
+ input, output, thinking, cacheRead, cacheWrite, cacheWrite ? 0 : null);
319
+ return true;
320
+ };
321
+
322
+ if (rec.type === "session_meta") {
323
+ if (p.cwd) {
324
+ st.launchCwd ??= p.cwd;
325
+ st.cwd = p.cwd;
326
+ }
327
+ const subType = subagentTypeOf(p.source);
328
+ const metaSub = p.parent_thread_id || subType ? (subType ?? "subagent") : null;
329
+ const repoUrl = p.git?.repository_url ?? null;
330
+ if (metaSub || repoUrl) q.fileMeta.run(file.id, p.parent_thread_id ?? null, metaSub, null, repoUrl);
331
+ if (p.model) st.model = p.model;
332
+ } else if (rec.type === "turn_context") {
333
+ if (p.cwd) {
334
+ st.launchCwd ??= p.cwd;
335
+ st.cwd = p.cwd;
336
+ if (p.cwd !== st.launchCwd && st.paths.add(p.cwd, { write: false })) pathsDirty = true;
337
+ }
338
+ if (p.model) st.model = p.model;
339
+ const eff = p.effort ?? p.collaboration_mode?.settings?.reasoning_effort;
340
+ if (eff) st.effort = eff;
341
+ } else if (rec.type === "world_state") {
342
+ if (p.state?.model) st.model = p.state.model;
343
+ if (p.state?.effort) st.effort = p.state.effort;
344
+ } else if (rec.type === "token_usage_record") {
345
+ consumeOpenWait();
346
+ st.sawTokenRec = true;
347
+ const msgId = `codex:${p.response_id || `${ownId}:${line}`}`;
348
+ if (recordUsage(msgId, p.usage)) added = 1;
349
+ } else if (rec.type === "compacted") {
350
+ if (line - st.lastCompactionLine > 5) {
351
+ st.lastCompactionLine = line;
352
+ q.record.run(`codex:${ownId}:${line}`, file.id, line, rec.type, ts);
353
+ q.compaction.run(`codex:${ownId}:${line}`, file.id, line, session, agent, ts, "auto", null, null, null);
354
+ added = 1;
355
+ }
356
+ } else if (rec.type === "response_item") {
357
+ if (p.type === "configuration_update" && p.reasoning?.effort) {
358
+ st.effort = p.reasoning.effort;
359
+ } else if (p.type === "message" && p.role === "user") {
360
+ const msg = userMessageText(p.content);
361
+ if (msg) {
362
+ q.record.run(`codex:${ownId}:${line}`, file.id, line, "user", ts);
363
+ q.owner.run(`codex:${ownId}:${line}`, file.id, line, session, ts, "typed", msg);
364
+ recordDollarSkills(msg);
365
+ if (tsMs !== null && st.turnStartMs === null) {
366
+ st.turnStartMs = tsMs;
367
+ st.turnToolMs = 0;
368
+ st.openApiMs = 0;
369
+ }
370
+ if (tsMs !== null) st.lastWaitFromMs = tsMs;
371
+ added = 1;
372
+ }
373
+ } else if (p.type === "message" || p.type === "reasoning") {
374
+ consumeOpenWait();
375
+ } else if (p.type === "function_call" || p.type === "custom_tool_call") {
376
+ consumeOpenWait();
377
+ q.record.run(`codex:${ownId}:${line}`, file.id, line, p.type, ts);
378
+ q.call.run(`codex:${p.call_id || `${ownId}:${line}`}`, file.id, line, session, agent, ts, p.name ?? "unknown", st.model ?? null);
379
+ if (tsMs !== null && p.call_id) st.callStart.set(p.call_id, tsMs);
380
+ const inputStr = callInputText(p);
381
+ if (inputStr) {
382
+ const patch = countPatchLines(inputStr);
383
+ if (patch.added || patch.removed) {
384
+ st.patchAdded += patch.added;
385
+ st.patchRemoved += patch.removed;
386
+ if (!st.sawFileChange) statsDirty = true;
387
+ }
388
+ if (inputStr.includes("*** ")) {
389
+ const unesc = inputStr.includes("*** Begin Patch\\n") ? inputStr.replace(/\\n/g, "\n") : inputStr;
390
+ 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;
392
+ }
393
+ }
394
+ const vars = new Map();
395
+ for (const m of inputStr.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*["'`]([^"'`\n]+)["'`]/g)) {
396
+ if (isAbsPath(m[2]) || m[2].startsWith(".")) vars.set(m[1], m[2]);
397
+ }
398
+ for (const m of inputStr.matchAll(/(?:workdir|"workdir")\s*:\s*(?:["'`]([^"'`\n]+)["'`]|([A-Za-z_$][\w$]*))/g)) {
399
+ 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;
401
+ }
402
+ for (const dir of extractCommandDirs(inputStr, st.cwd)) {
403
+ if (st.paths.add(dir, { write: false })) pathsDirty = true;
404
+ }
405
+ const loadedSkills = extractSkillPaths(inputStr);
406
+ if (loadedSkills.length) {
407
+ const ids = [];
408
+ for (const [idx, [skillName, source]] of loadedSkills.entries()) {
409
+ const skId = `codex:${ownId}:${line}:agent:${skillName}:${idx}`;
410
+ q.skill.run(skId, file.id, line, session, ts, skillName, "agent", source, 0);
411
+ ids.push(skId);
412
+ }
413
+ if (p.call_id) st.callSkills.set(p.call_id, ids);
414
+ }
415
+ }
416
+ added = 1;
417
+ } else if (p.type === "function_call_output" || p.type === "custom_tool_call_output") {
418
+ const outText = toolOutputText(p);
419
+ const err = isToolError(p, outText);
420
+ if (p.call_id) {
421
+ q.result.run(err ? 1 : 0, `codex:${p.call_id}`);
422
+ if (err && st.callSkills.has(p.call_id)) {
423
+ for (const skId of st.callSkills.get(p.call_id)) q.skillErr.run(skId);
424
+ }
425
+ st.callSkills.delete(p.call_id);
426
+ }
427
+ const dur = parseToolDurationMs(outText, p.call_id ? (st.callStart.get(p.call_id) ?? null) : null, tsMs);
428
+ if (p.call_id) st.callStart.delete(p.call_id);
429
+ if (dur > 0) {
430
+ st.toolMs += dur;
431
+ st.turnToolMs += dur;
432
+ statsDirty = true;
433
+ }
434
+ if (tsMs !== null) st.lastWaitFromMs = tsMs;
435
+ } else if (p.type === "compaction") {
436
+ if (line - st.lastCompactionLine > 5) {
437
+ st.lastCompactionLine = line;
438
+ q.record.run(`codex:${ownId}:${line}`, file.id, line, p.type, ts);
439
+ q.compaction.run(`codex:${ownId}:${line}`, file.id, line, session, agent, ts, "auto", null, null, null);
440
+ added = 1;
441
+ }
442
+ }
443
+ } else if (rec.type === "event_msg") {
444
+ if (p.type === "task_started" || p.type === "turn_started") {
445
+ if (tsMs !== null) {
446
+ st.turnStartMs = tsMs;
447
+ st.turnToolMs = 0;
448
+ st.openApiMs = 0;
449
+ st.lastWaitFromMs = tsMs;
450
+ }
451
+ } else if (p.type === "task_complete" || p.type === "turn_complete") {
452
+ const totalTurn = typeof p.duration_ms === "number" && p.duration_ms >= 0
453
+ ? p.duration_ms
454
+ : (st.turnStartMs !== null && tsMs !== null ? Math.max(0, tsMs - st.turnStartMs) : null);
455
+ if (totalTurn !== null) {
456
+ st.completedApiMs += Math.max(0, totalTurn - Math.min(totalTurn, st.turnToolMs));
457
+ statsDirty = true;
458
+ } else if (st.openApiMs > 0) {
459
+ st.completedApiMs += st.openApiMs;
460
+ statsDirty = true;
461
+ }
462
+ st.turnStartMs = null;
463
+ st.turnToolMs = 0;
464
+ st.openApiMs = 0;
465
+ st.lastWaitFromMs = null;
466
+ } else if (p.type === "user_message" && typeof p.message === "string" && p.message.trim()) {
467
+ const body = p.message.trim();
468
+ q.record.run(`codex:${ownId}:${line}`, file.id, line, "user", ts);
469
+ q.owner.run(`codex:${ownId}:${line}`, file.id, line, session, ts, "typed", body);
470
+ recordDollarSkills(body);
471
+ if (tsMs !== null && st.turnStartMs === null) {
472
+ st.turnStartMs = tsMs;
473
+ st.turnToolMs = 0;
474
+ st.openApiMs = 0;
475
+ }
476
+ if (tsMs !== null) st.lastWaitFromMs = tsMs;
477
+ added = 1;
478
+ } else if (p.type === "item_completed" && p.item?.type === "FileChange") {
479
+ if (!p.item.status || p.item.status === "completed") {
480
+ 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;
482
+ if (ch?.type === "add") st.fcAdded += lineCount(ch.content);
483
+ else if (ch?.type === "delete") st.fcRemoved += lineCount(ch.content);
484
+ else if (ch?.type === "update" && typeof ch.unified_diff === "string") {
485
+ const d = countUnifiedDiff(ch.unified_diff);
486
+ st.fcAdded += d.added;
487
+ st.fcRemoved += d.removed;
488
+ }
489
+ }
490
+ st.sawFileChange = true;
491
+ statsDirty = true;
492
+ }
493
+ } else if (p.type === "token_count" && !st.sawTokenRec && p.info?.last_token_usage) {
494
+ consumeOpenWait();
495
+ const tot = p.info.total_token_usage;
496
+ const totKey = tot ? `${tot.total_tokens}|${tot.input_tokens}|${tot.output_tokens}|${tot.cached_input_tokens}` : null;
497
+ if (!totKey || totKey !== st.lastTotal) {
498
+ st.lastTotal = totKey;
499
+ if (recordUsage(`codex:${ownId}:${line}`, p.info.last_token_usage)) added = 1;
500
+ }
501
+ }
502
+ }
503
+
504
+ const totalApiMs = Math.round(st.completedApiMs + st.openApiMs);
505
+ const linesAdded = st.baseAdded + (st.sawFileChange ? st.fcAdded : st.patchAdded);
506
+ const linesRemoved = st.baseRemoved + (st.sawFileChange ? st.fcRemoved : st.patchRemoved);
507
+ if (statsDirty && (totalApiMs > 0 || st.toolMs > 0 || linesAdded > 0 || linesRemoved > 0)) {
508
+ q.upsertStats.run(file.id, totalApiMs, Math.round(st.toolMs), linesAdded, linesRemoved);
509
+ }
510
+ if (pathsDirty) {
511
+ const json = st.paths.toJSON();
512
+ if (json) q.upsertTargetPaths.run(file.id, json);
513
+ }
514
+
515
+ return { added, cwd, ts, own: true };
516
+ };
517
+ }
518
+
519
+ export function postScan(db, archiveDir) {
520
+ const idxPath = join(archiveDir, "session_index.jsonl");
521
+ const titles = new Map();
522
+ if (existsSync(idxPath)) {
523
+ for (const line of readFileSync(idxPath, "utf8").split("\n")) {
524
+ if (!line) continue;
525
+ try {
526
+ const o = JSON.parse(line);
527
+ if (o.id && o.thread_name) titles.set(o.id, o.thread_name);
528
+ } catch { /* ignore malformed index line */ }
529
+ }
530
+ }
531
+
532
+ const allFiles = db.prepare("SELECT id, kind, session_id, agent_id FROM files WHERE provider = 'codex'").all();
533
+ const byOwn = new Map();
534
+ for (const f of allFiles) byOwn.set(f.agent_id ?? f.session_id, f);
535
+
536
+ 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
+ const parentOf = new Map();
538
+ for (const m of metas) {
539
+ const f = allFiles.find((x) => x.id === m.file_id);
540
+ 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
+ }
542
+ const rootOf = (id) => {
543
+ let cur = id;
544
+ const seen = new Set([cur]);
545
+ while (parentOf.has(cur)) {
546
+ const next = parentOf.get(cur).parent;
547
+ if (!next || seen.has(next) || !byOwn.has(next)) break;
548
+ seen.add(next);
549
+ cur = next;
550
+ }
551
+ return cur === id ? null : cur;
552
+ };
553
+
554
+ const setFileSub = db.prepare("UPDATE files SET kind = 'sub', session_id = ?, agent_id = ? WHERE id = ?");
555
+ const setReqSub = db.prepare("UPDATE requests SET session_id = ?, agent_id = ?, is_sub = 1 WHERE file_id = ?");
556
+ const setCallSub = db.prepare("UPDATE tool_calls SET session_id = ?, agent_id = ? WHERE file_id = ?");
557
+ const setSkillSess = db.prepare("UPDATE skills SET session_id = ? WHERE file_id = ?");
558
+ const setCompSub = db.prepare("UPDATE compactions SET session_id = ?, agent_id = ? WHERE file_id = ?");
559
+ const setTitleSess = db.prepare("UPDATE titles SET session_id = ? WHERE file_id = ?");
560
+ const putSub = db.prepare("INSERT OR REPLACE INTO subagents(agent_id, session_id, type, tool_use_id) VALUES (?, ?, ?, ?)");
561
+ const putTitle = db.prepare("INSERT OR REPLACE INTO titles(file_id, line, session_id, kind, title) VALUES (?, 0, ?, 'custom', ?)");
562
+
563
+ db.exec("BEGIN");
564
+ try {
565
+ for (const f of allFiles) {
566
+ const ownId = f.agent_id ?? f.session_id;
567
+ const root = rootOf(ownId);
568
+ const sess = root ?? f.session_id;
569
+ if (root) {
570
+ setFileSub.run(root, ownId, f.id);
571
+ setReqSub.run(root, ownId, f.id);
572
+ setCallSub.run(root, ownId, f.id);
573
+ setSkillSess.run(root, f.id);
574
+ setCompSub.run(root, ownId, f.id);
575
+ setTitleSess.run(root, f.id);
576
+ const meta = parentOf.get(ownId);
577
+ putSub.run(ownId, root, meta?.type ?? "subagent", meta?.toolUseId ?? null);
578
+ }
579
+ const title = titles.get(ownId);
580
+ if (title) putTitle.run(f.id, sess, title);
581
+ }
582
+ db.exec("COMMIT");
583
+ } catch (err) {
584
+ db.exec("ROLLBACK");
585
+ throw err;
586
+ }
587
+ }
588
+
589
+ export const codex = { name: "codex", label, defaultPath, describe, listHost, syncMeta, createIngester, postScan, familyOf, displayModel };
@@ -0,0 +1,25 @@
1
+ // The providers this tool can read, by the name used in the config.
2
+ import { agy } from "./agy.mjs";
3
+ import { claude } from "./claude.mjs";
4
+ import { codex } from "./codex.mjs";
5
+
6
+ export const PROVIDERS = { claude, codex, agy };
7
+ export const PROVIDER_ORDER = ["claude", "codex", "agy"];
8
+
9
+ export const providerLabel = (name) => PROVIDERS[name]?.label ?? name;
10
+
11
+ export function familyOf(model, provider) {
12
+ if (provider && PROVIDERS[provider]?.familyOf) return PROVIDERS[provider].familyOf(model);
13
+ if (model.includes("claude")) return claude.familyOf(model);
14
+ if (model.startsWith("gemini-")) return agy.familyOf(model);
15
+ if (model.startsWith("gpt-") || model.startsWith("codex-")) return codex.familyOf(model);
16
+ return claude.familyOf(model);
17
+ }
18
+
19
+ export function modelName(family) {
20
+ for (const p of Object.values(PROVIDERS)) {
21
+ const shown = p.displayModel?.(family);
22
+ if (shown && shown !== family) return shown;
23
+ }
24
+ return family;
25
+ }