wrapped-agents 0.0.0-stage → 1.0.0

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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/SKILL.md +38 -0
  4. package/package.json +40 -4
  5. package/page/assets/fonts/NOTICE.md +1 -0
  6. package/page/assets/fonts/commit-mono/commit-mono-400-italic.woff2 +0 -0
  7. package/page/assets/fonts/commit-mono/commit-mono-400-normal.woff2 +0 -0
  8. package/page/assets/fonts/commit-mono/commit-mono-700-italic.woff2 +0 -0
  9. package/page/assets/fonts/commit-mono/commit-mono-700-normal.woff2 +0 -0
  10. package/page/assets/fonts/dm-mono/dm-mono-400-italic.woff2 +0 -0
  11. package/page/assets/fonts/dm-mono/dm-mono-400-normal.woff2 +0 -0
  12. package/page/assets/fonts/dm-mono/dm-mono-500-italic.woff2 +0 -0
  13. package/page/assets/fonts/dm-mono/dm-mono-500-normal.woff2 +0 -0
  14. package/page/assets/fonts/lora/lora-400-italic.woff2 +0 -0
  15. package/page/assets/fonts/lora/lora-400-normal.woff2 +0 -0
  16. package/page/assets/fonts/lora/lora-500-italic.woff2 +0 -0
  17. package/page/assets/fonts/lora/lora-500-normal.woff2 +0 -0
  18. package/page/assets/fonts/lora/lora-600-italic.woff2 +0 -0
  19. package/page/assets/fonts/lora/lora-600-normal.woff2 +0 -0
  20. package/page/assets/fonts/mona-sans/mona-sans-400-italic.woff2 +0 -0
  21. package/page/assets/fonts/mona-sans/mona-sans-400-normal.woff2 +0 -0
  22. package/page/assets/fonts/mona-sans/mona-sans-700-italic.woff2 +0 -0
  23. package/page/assets/fonts/mona-sans/mona-sans-700-normal.woff2 +0 -0
  24. package/page/assets/fonts/mona-sans/mona-sans-900-italic.woff2 +0 -0
  25. package/page/assets/fonts/mona-sans/mona-sans-900-normal.woff2 +0 -0
  26. package/page/assets/fonts/openmono/OFL.txt +94 -0
  27. package/page/assets/fonts/openmono/OpenMono-Bold.woff2 +0 -0
  28. package/page/assets/fonts/openmono/OpenMono-ExtraBold.woff2 +0 -0
  29. package/page/assets/fonts/openmono/OpenMono-Regular.woff2 +0 -0
  30. package/page/assets/fonts/oswald/oswald-400-normal.woff2 +0 -0
  31. package/page/assets/fonts/oswald/oswald-600-normal.woff2 +0 -0
  32. package/page/assets/fonts/poppins/poppins-400-italic.woff2 +0 -0
  33. package/page/assets/fonts/poppins/poppins-400-normal.woff2 +0 -0
  34. package/page/assets/fonts/poppins/poppins-600-italic.woff2 +0 -0
  35. package/page/assets/fonts/poppins/poppins-600-normal.woff2 +0 -0
  36. package/page/assets/fonts/poppins/poppins-700-italic.woff2 +0 -0
  37. package/page/assets/fonts/poppins/poppins-700-normal.woff2 +0 -0
  38. package/page/assets/fonts/poppins/poppins-800-italic.woff2 +0 -0
  39. package/page/assets/fonts/poppins/poppins-800-normal.woff2 +0 -0
  40. package/page/assets/fonts/source-serif-4/source-serif-4-400-italic.woff2 +0 -0
  41. package/page/assets/fonts/source-serif-4/source-serif-4-400-normal.woff2 +0 -0
  42. package/page/assets/fonts/source-serif-4/source-serif-4-600-italic.woff2 +0 -0
  43. package/page/assets/fonts/source-serif-4/source-serif-4-600-normal.woff2 +0 -0
  44. package/page/assets/logos/anthropic.svg +4 -0
  45. package/page/assets/logos/claude-code.svg +3 -0
  46. package/page/assets/logos/codex.svg +1 -0
  47. package/page/assets/logos/cursor.svg +1 -0
  48. package/page/assets/logos/gemini-cli.svg +1 -0
  49. package/page/assets/logos/github.svg +1 -0
  50. package/page/assets/logos/hermes.svg +1 -0
  51. package/page/assets/logos/mistral-vibe.svg +12 -0
  52. package/page/assets/logos/opencode.svg +16 -0
  53. package/page/assets/logos/pi.svg +6 -0
  54. package/page/assets/logos/qwen-code.svg +1 -0
  55. package/page/story.html +993 -0
  56. package/src/cli.mjs +122 -0
  57. package/src/data/prices.json +67 -0
  58. package/src/privacy.mjs +39 -0
  59. package/src/readers/_pool.mjs +32 -0
  60. package/src/readers/_prompts.mjs +54 -0
  61. package/src/readers/_util.mjs +182 -0
  62. package/src/readers/_worker.mjs +7 -0
  63. package/src/readers/claude-code.mjs +330 -0
  64. package/src/readers/codex.mjs +162 -0
  65. package/src/readers/index.mjs +8 -0
  66. package/src/readers/mistral-vibe.mjs +156 -0
  67. package/src/readers/pi.mjs +154 -0
  68. package/src/render.mjs +65 -0
  69. package/src/site.mjs +62 -0
  70. package/src/stats/age.mjs +36 -0
  71. package/src/stats/awards.mjs +132 -0
  72. package/src/stats/git.mjs +161 -0
  73. package/src/stats/index.mjs +253 -0
  74. package/src/stats/roast.mjs +6 -0
  75. package/src/stats/spendings.mjs +99 -0
  76. package/src/stats/tiers.mjs +16 -0
  77. package/src/stats/twin.mjs +37 -0
@@ -0,0 +1,330 @@
1
+ // Claude Code reader: ~/.claude/history.jsonl (prompts), stats-cache.json (daily aggregates before transcripts),
2
+ // projects/**/*.jsonl transcripts incl. subagents/ (tokens, tools, sessions, markers).
3
+ import path from 'node:path';
4
+ import {
5
+ eachLine, parse, readJSON, isDir, exists, walk, localDate, localMonth, utcDate, toMs, windowOf, inWin, basename,
6
+ maxConcurrent, gitUndoKinds, emptyUndos, phraseCounts, emptyAssistant, addPhrases, hash, inc, tokBucket,
7
+ emptyFacts, day, countPromptTime, finishCoverage, longestSession, mostResumed,
8
+ } from './_util.mjs';
9
+ import { PromptStats } from './_prompts.mjs';
10
+ import { mapFiles } from './_pool.mjs';
11
+
12
+ export const id = 'claude-code';
13
+ export const label = 'Claude Code';
14
+
15
+ const BUILTIN_THEMES = new Set(['dark', 'light', 'dark-daltonized', 'light-daltonized', 'dark-ansi', 'light-ansi', 'auto']);
16
+ // per-field de-dup factors measured on one machine; used only when no overlap exists to measure them locally
17
+ const DEFAULT_FACTOR = { input: 0.52, output: 0.45, cacheRead: 0.52, cacheWrite: 0.54 };
18
+ const F = ['input', 'output', 'cacheRead', 'cacheWrite'];
19
+
20
+ const root = env => path.join(env.home, '.claude');
21
+
22
+ export async function detect(env) {
23
+ const r = root(env); const roots = [];
24
+ for (const p of ['history.jsonl', 'stats-cache.json', 'projects']) if (await exists(path.join(r, p))) roots.push(path.join(r, p));
25
+ return { found: roots.length > 0, roots };
26
+ }
27
+
28
+ // ------------------------------------------------------------------ one transcript file (runs in a worker)
29
+
30
+ const RE_TS = /"timestamp":"([^"]+)"/;
31
+ const RE_SID = /"sessionId":"([^"]+)"/;
32
+
33
+ export async function scanFile(file, ctx) {
34
+ const side = /[\\/]subagents[\\/]/.test(file);
35
+ const r = {
36
+ side, bad: 0, msgs: {}, rawUtc: {}, rawToolsUtc: {}, tools: {}, prompts: [], sess: {}, phr: [], patches: [],
37
+ intr: [], compact: [], apimsg: [], kids: [], version: null, versionTs: 0, minTs: Infinity,
38
+ };
39
+ const win = ms => ms >= ctx.start && ms < ctx.end;
40
+ const sessT = (sid, ms, cwd) => { if (!sid) return; const s = r.sess[sid] ||= { t: [], cwd: null }; s.t.push(ms); if (cwd && !s.cwd) s.cwd = cwd; };
41
+ await eachLine(file, line => {
42
+ const isA = line.includes('"type":"assistant"');
43
+ const isU = !isA && line.includes('"type":"user"');
44
+ if (isA) {
45
+ const o = parse(line); if (!o) { r.bad++; return; }
46
+ if (o.type !== 'assistant') return;
47
+ const ms = toMs(o.timestamp); if (!win(ms)) return;
48
+ if (ms < r.minTs) r.minTs = ms;
49
+ if (!side && !o.isSidechain) sessT(o.sessionId, ms, o.cwd);
50
+ if (o.version && ms >= r.versionTs) { r.version = o.version; r.versionTs = ms; }
51
+ const m = o.message || {};
52
+ if (o.isApiErrorMessage) { r.apimsg.push([o.uuid, ms, o.error || null]); return; }
53
+ const model = m.model; const mid = m.id || o.uuid; const ud = (o.timestamp || '').slice(0, 10);
54
+ if (model && model !== '<synthetic>') {
55
+ const u = m.usage || {};
56
+ const v = [u.input_tokens || 0, u.output_tokens || 0, u.cache_read_input_tokens || 0, u.cache_creation_input_tokens || 0];
57
+ const ru = (r.rawUtc[ud] ||= {})[model] ||= [0, 0, 0, 0];
58
+ for (let i = 0; i < 4; i++) ru[i] += v[i];
59
+ if (!(mid in r.msgs)) r.msgs[mid] = [ms, model, ...v];
60
+ }
61
+ const content = Array.isArray(m.content) ? m.content : [];
62
+ for (const c of content) {
63
+ if (!c || typeof c !== 'object') continue;
64
+ if (c.type === 'tool_use') {
65
+ r.rawToolsUtc[ud] = (r.rawToolsUtc[ud] || 0) + 1;
66
+ if (c.id in r.tools) continue;
67
+ const name = c.name || '?'; const inp = c.input || {}; let extra = null;
68
+ if (name === 'Skill') extra = String(inp.skill || inp.command || '?');
69
+ else if (name === 'Bash') extra = gitUndoKinds(String(inp.command || ''));
70
+ r.tools[c.id || hash(line)] = [name, extra, ms];
71
+ } else if (c.type === 'text' && model !== '<synthetic>') {
72
+ const pc = phraseCounts(c.text);
73
+ if (pc) r.phr.push([hash(String(mid) + c.text), pc]);
74
+ }
75
+ }
76
+ return;
77
+ }
78
+ if (isU) {
79
+ const hasTUR = line.includes('"toolUseResult"');
80
+ const wantPatch = hasTUR && line.includes('"structuredPatch"');
81
+ const wantIntr = line.includes('Request interrupted by user');
82
+ if (hasTUR && !wantPatch && !wantIntr) { // cheap path: only time + session for activity
83
+ if (side || line.includes('"isSidechain":true')) return;
84
+ const t = RE_TS.exec(line); const s = RE_SID.exec(line); if (!t || !s) return;
85
+ const ms = Date.parse(t[1]); if (win(ms)) sessT(s[1], ms, null);
86
+ return;
87
+ }
88
+ const o = parse(line); if (!o) { r.bad++; return; }
89
+ if (o.type !== 'user') return;
90
+ const ms = toMs(o.timestamp); if (!win(ms)) return;
91
+ if (!side && !o.isSidechain) sessT(o.sessionId, ms, o.cwd);
92
+ const m = o.message || {}; const ct = m.content;
93
+ const blocks = Array.isArray(ct) ? ct.filter(x => x && typeof x === 'object') : [];
94
+ const tur = o.toolUseResult;
95
+ if (tur && typeof tur === 'object' && 'structuredPatch' in tur) {
96
+ let tid = null; for (const b of blocks) if (b.type === 'tool_result') tid = b.tool_use_id;
97
+ let add = 0, rem = 0;
98
+ if (tur.type === 'create' && !(tur.structuredPatch && tur.structuredPatch.length)) add = String(tur.content || '').split(/\r?\n/).filter((x, i, a) => i < a.length - 1 || x).length;
99
+ else for (const h of tur.structuredPatch || []) for (const ln of (h && h.lines) || []) { if (ln[0] === '+') add++; else if (ln[0] === '-') rem++; }
100
+ r.patches.push([tid || o.uuid, add, rem]);
101
+ return;
102
+ }
103
+ const texts = typeof ct === 'string' ? [ct] : blocks.filter(b => b.type === 'text').map(b => b.text || '');
104
+ if (!side) for (const t of texts) if (t.startsWith('[Request interrupted by user')) r.intr.push(o.uuid);
105
+ if (side || o.isSidechain || o.isMeta || o.isCompactSummary || 'toolUseResult' in o) return;
106
+ if (blocks.some(b => b.type === 'tool_result')) return;
107
+ const txt = texts.join('') || (blocks.some(b => b.type === 'image') ? 'img' : '');
108
+ const kind = o.origin && o.origin.kind; let ok = false;
109
+ if (kind === 'human' || o.promptSource === 'typed' || o.promptSource === 'queued') ok = true;
110
+ else if (kind == null && o.promptSource == null && txt) ok = !txt.startsWith('<') || txt.startsWith('<command-name>');
111
+ if (ok) { r.prompts.push([o.uuid, ms]); if (o.parentUuid) r.kids.push([o.parentUuid, o.uuid]); }
112
+ return;
113
+ }
114
+ if (!side && line.includes('"compact_boundary"') && line.includes('"type":"system"')) {
115
+ const o = parse(line); if (!o) { r.bad++; return; }
116
+ if (o.subtype === 'compact_boundary' && win(toMs(o.timestamp))) r.compact.push(o.uuid);
117
+ }
118
+ });
119
+ return r;
120
+ }
121
+
122
+ // ------------------------------------------------------------------ main read
123
+
124
+ export async function read(env, opts = {}) {
125
+ const w = windowOf(env, opts); const progress = opts.onProgress || (() => {});
126
+ const base = root(env); const f = emptyFacts(id, label);
127
+ const ps = new PromptStats();
128
+
129
+ // ---- history.jsonl: every prompt typed in the REPL
130
+ const histFile = path.join(base, 'history.jsonl');
131
+ const hist = { n: 0, days: new Set() }; const bySession = new Map(); const concEv = [];
132
+ if (await exists(histFile)) {
133
+ f.coverage.sources.push('history.jsonl');
134
+ await eachLine(histFile, line => {
135
+ const o = parse(line); if (!o) return;
136
+ const ms = toMs(o.timestamp); if (!inWin(w, ms)) return;
137
+ const text = String(o.display || '');
138
+ const images = (text.match(/\[Image #\d+\]/g) || []).length;
139
+ ps.add(text, { images });
140
+ countPromptTime(f, ms); hist.n++;
141
+ const proj = basename(o.project); if (proj) inc(f.projects, proj);
142
+ if (o.sessionId) {
143
+ const s = bySession.get(o.sessionId) || { days: new Set(), project: proj }; s.days.add(localDate(ms)); bySession.set(o.sessionId, s);
144
+ concEv.push([ms, o.sessionId]);
145
+ }
146
+ });
147
+ }
148
+
149
+ // ---- transcripts
150
+ const proj = path.join(base, 'projects');
151
+ const files = (await isDir(proj)) ? await walk(proj, n => n.endsWith('.jsonl')) : [];
152
+ let firstTs = Infinity; // earliest transcript line in the window: older transcripts were pruned
153
+ const seenMsg = new Map(); // mid -> [ms, model, i, o, cr, cw]
154
+ const rawUtc = {}; const rawToolsUtc = {};
155
+ const seenTool = new Set(); const seenPhr = new Set(); const seenPatch = new Set(); const seenIntr = new Set();
156
+ const seenCompact = new Set(); const seenApi = new Set(); const kids = new Map();
157
+ const sessions = new Map(); const txPromptIds = new Set(); const txPromptDays = new Set();
158
+ const assistant = emptyAssistant(); const undos = emptyUndos(); const lines = { added: 0, removed: 0 };
159
+ let interrupts = 0, compactions = 0, rlHits = 0, subagents = 0, bad = 0, sideFiles = 0, version = null, versionTs = 0;
160
+ const rlDays = new Set(); const toolTimes = [];
161
+ if (files.length) {
162
+ f.coverage.sources.push('projects/*.jsonl');
163
+ progress(`Claude Code: ${files.length} transcript files`);
164
+ await mapFiles(import.meta.url, 'scanFile', files, { start: w.start, end: w.end }, r => {
165
+ bad += r.bad; if (r.side) sideFiles++; if (r.minTs < firstTs) firstTs = r.minTs;
166
+ if (r.version && r.versionTs >= versionTs) { version = r.version; versionTs = r.versionTs; }
167
+ for (const ud in r.rawUtc) { const d = rawUtc[ud] ||= {}; for (const m in r.rawUtc[ud]) { const a = d[m] ||= [0, 0, 0, 0]; const b = r.rawUtc[ud][m]; for (let i = 0; i < 4; i++) a[i] += b[i]; } }
168
+ for (const ud in r.rawToolsUtc) rawToolsUtc[ud] = (rawToolsUtc[ud] || 0) + r.rawToolsUtc[ud];
169
+ for (const mid in r.msgs) if (!seenMsg.has(mid)) seenMsg.set(mid, r.msgs[mid]);
170
+ for (const tid in r.tools) {
171
+ if (seenTool.has(tid)) continue; seenTool.add(tid);
172
+ const [name, extra, tms] = r.tools[tid]; inc(f.tools, name); toolTimes.push(tms);
173
+ if (name === 'Skill') inc(f.skills, extra);
174
+ else if (name === 'Bash' && extra) for (const k of extra) undos[k]++;
175
+ else if (name === 'Agent' || name === 'Task') subagents++;
176
+ if (name.startsWith('mcp__')) inc(f.mcp, name.split('__')[1] || '?');
177
+ }
178
+ for (const [k, c] of r.phr) { if (seenPhr.has(k)) continue; seenPhr.add(k); addPhrases(assistant, c); }
179
+ for (const [k, a, b] of r.patches) { if (seenPatch.has(k)) continue; seenPatch.add(k); lines.added += a; lines.removed += b; }
180
+ for (const u of r.intr) { if (seenIntr.has(u)) continue; seenIntr.add(u); interrupts++; }
181
+ for (const u of r.compact) { if (seenCompact.has(u)) continue; seenCompact.add(u); compactions++; }
182
+ for (const [u, ms, err] of r.apimsg) { if (seenApi.has(u)) continue; seenApi.add(u); if (err === 'rate_limit') { rlHits++; rlDays.add(localDate(ms)); } }
183
+ for (const [u, ms] of r.prompts) { if (txPromptIds.has(u)) continue; txPromptIds.add(u); txPromptDays.add(localDate(ms)); }
184
+ for (const [p, u] of r.kids) { const s = kids.get(p) || new Set(); s.add(u); kids.set(p, s); }
185
+ for (const sid in r.sess) {
186
+ const s = sessions.get(sid) || { t: [], project: null }; const x = r.sess[sid];
187
+ for (const t of x.t) s.t.push(t); if (!s.project && x.cwd) s.project = basename(x.cwd); sessions.set(sid, s);
188
+ }
189
+ }, { onProgress: m => progress('Claude Code transcripts: ' + m) });
190
+ }
191
+ f.version = version;
192
+
193
+ const oldestTx = firstTs < Infinity ? localDate(firstTs) : null;
194
+
195
+ // ---- stats-cache.json: daily aggregates for the time before transcripts are complete
196
+ const sc = await readJSON(path.join(base, 'stats-cache.json'));
197
+ const yr = String(w.year); const endDay = localDate(w.end - 1);
198
+ const scDays = {};
199
+ if (sc && Array.isArray(sc.dailyActivity)) {
200
+ f.coverage.sources.push('stats-cache.json');
201
+ for (const x of sc.dailyActivity) if (x && String(x.date).startsWith(yr) && x.date <= endDay) scDays[x.date] = x;
202
+ }
203
+ const lastSc = sc && sc.lastComputedDate ? sc.lastComputedDate : null;
204
+
205
+ // cutover: earliest UTC day from which every stats-cache day up to lastComputedDate has at least as many
206
+ // transcript tool_use lines as stats-cache counted (-1%). Before it, transcripts are partial (pruned).
207
+ let cut;
208
+ if (!lastSc || !Object.keys(scDays).length) cut = '0000-00-00';
209
+ else if (!files.length) cut = nextDay(lastSc);
210
+ else {
211
+ const ov = Object.keys(scDays).filter(d => oldestTx && d >= oldestTx && d <= lastSc).sort();
212
+ cut = nextDay(lastSc);
213
+ for (let i = ov.length - 1; i >= 0; i--) {
214
+ const ds = ov[i]; const sct = scDays[ds].toolCallCount || 0;
215
+ if ((rawToolsUtc[ds] || 0) >= sct - Math.max(2, 0.01 * sct)) cut = ds; else break;
216
+ }
217
+ }
218
+
219
+ // de-dup factors on the complete overlap [cut, lastSc]: stats-cache counts tokens per line like the raw sums
220
+ const rawOv = {}; const rawOvSum = [0, 0, 0, 0]; const dedOvSum = [0, 0, 0, 0];
221
+ for (const ud in rawUtc) if (ud >= cut && lastSc && ud <= lastSc) for (const m in rawUtc[ud]) {
222
+ const a = rawOv[m] ||= [0, 0, 0, 0]; for (let i = 0; i < 4; i++) a[i] += rawUtc[ud][m][i];
223
+ }
224
+ // Forked subagents copy the parent's lines (same ids, old timestamps), so raw transcript sums on the overlap grow
225
+ // with every fork created after stats-cache was computed. Scale each model's raw overlap to what stats-cache itself
226
+ // counted on those days (dailyModelTokens), which makes the factor independent of later copies.
227
+ const scOv = {};
228
+ if (sc && lastSc) for (const x of sc.dailyModelTokens || []) if (x && x.date >= cut && x.date <= lastSc) for (const m in x.tokensByModel || {}) inc(scOv, m, x.tokensByModel[m] || 0);
229
+ for (const m in rawOv) {
230
+ const a = rawOv[m]; const s = a[0] + a[1] + a[2] + a[3];
231
+ if (scOv[m] && s > scOv[m]) for (let i = 0; i < 4; i++) a[i] *= scOv[m] / s;
232
+ for (let i = 0; i < 4; i++) rawOvSum[i] += a[i];
233
+ }
234
+ for (const [, v] of seenMsg) { const ud = utcDate(v[0]); if (ud >= cut && lastSc && ud <= lastSc) for (let i = 0; i < 4; i++) dedOvSum[i] += v[2 + i]; }
235
+ const measured = rawOvSum.some(x => x > 0);
236
+ const factor = {}; F.forEach((k, i) => { factor[k] = rawOvSum[i] ? dedOvSum[i] / rawOvSum[i] : DEFAULT_FACTOR[k]; });
237
+ const fAll = rawOvSum.reduce((a, b) => a + b, 0) ? dedOvSum.reduce((a, b) => a + b, 0) / rawOvSum.reduce((a, b) => a + b, 0) : 0.52;
238
+
239
+ // ---- tokens after cutover: de-duplicated transcripts
240
+ for (const [, [ms, model, i, o, cr, cw]] of seenMsg) {
241
+ if (utcDate(ms) < cut) continue;
242
+ const b = f.models[model] ||= tokBucket();
243
+ b.input += i; b.output += o; b.cacheRead += cr; b.cacheWrite += cw; inc(b.byMonth, localMonth(ms), i + o + cr + cw);
244
+ day(f, localDate(ms)).tokens += i + o + cr + cw;
245
+ }
246
+
247
+ // ---- tokens before cutover: stats-cache aggregates × de-dup factor (estimate)
248
+ if (sc && cut > '0000') {
249
+ const dmt = (sc.dailyModelTokens || []).filter(x => x && String(x.date).startsWith(yr) && x.date < cut);
250
+ const firstDaily = (sc.dailyModelTokens || []).reduce((a, x) => (!a || x.date < a ? x.date : a), null);
251
+ const datedPre = {}; const dayShape = {};
252
+ for (const x of dmt) for (const m in x.tokensByModel || {}) {
253
+ const v = x.tokensByModel[m] || 0; datedPre[m] = (datedPre[m] || 0) + v; inc(dayShape[m] ||= {}, x.date, v);
254
+ }
255
+ const firstSession = sc.firstSessionDate ? localDate(Date.parse(sc.firstSessionDate)) : null;
256
+ const usageIsThisYear = !!firstSession && firstSession >= localDate(w.start);
257
+ // days before dailyModelTokens starts have only message counts: the undated remainder is spread by them
258
+ const act = {}; let actSum = 0;
259
+ for (const ds in scDays) if (ds < cut && (!firstDaily || ds < firstDaily)) { act[ds] = scDays[ds].messageCount || 0; actSum += act[ds]; }
260
+ for (const m in sc.modelUsage || {}) {
261
+ const u = sc.modelUsage[m] || {};
262
+ const raw = [u.inputTokens || 0, u.outputTokens || 0, u.cacheReadInputTokens || 0, u.cacheCreationInputTokens || 0];
263
+ const rawTot = raw.reduce((a, b) => a + b, 0); if (!rawTot) continue;
264
+ const ov = rawOv[m] || [0, 0, 0, 0];
265
+ const pre = usageIsThisYear
266
+ ? raw.map((v, i) => Math.max(0, v - ov[i])) // all-time aggregate (this year only) minus the overlap
267
+ : raw.map(v => (datedPre[m] || 0) * v / rawTot); // older usage exists too: dated days of this year only
268
+ const est = F.map((k, i) => Math.round(pre[i] * factor[k]));
269
+ const tot = est.reduce((a, b) => a + b, 0); if (!tot) continue;
270
+ const b = f.models[m] ||= tokBucket();
271
+ F.forEach((k, i) => { b[k] += est[i]; }); b.estimated = true;
272
+ const shape = { ...(dayShape[m] || {}) };
273
+ const rest = rawTot - (datedPre[m] || 0) - ov.reduce((a, b) => a + b, 0);
274
+ if (usageIsThisYear && actSum && rest > 0) for (const ds in act) inc(shape, ds, rest * act[ds] / actSum);
275
+ const sSum = Object.values(shape).reduce((a, b) => a + b, 0); if (!sSum) continue;
276
+ for (const ds in shape) { const v = Math.round(tot * shape[ds] / sSum); if (!v) continue; inc(b.byMonth, ds.slice(0, 7), v); day(f, ds).tokens += v; }
277
+ }
278
+ if (Object.keys(scDays).some(d => d < cut)) f.coverage.notes.push(`tokens before ${cut} estimated from stats-cache × measured de-dup factor ${fAll.toFixed(2)}${measured ? '' : ' (default)'}; before ${firstDaily || cut} spread over days by message count`);
279
+ }
280
+
281
+ // ---- sessions, days
282
+ let postSessions = 0;
283
+ for (const [, s] of sessions) {
284
+ if (!s.t.length) continue; let mn = Infinity; for (const t of s.t) if (t < mn) mn = t;
285
+ if (utcDate(mn) >= cut) { postSessions++; day(f, localDate(mn)).sessions++; }
286
+ for (const t of s.t) { const ds = localDate(t); if (ds >= cut) day(f, ds); }
287
+ }
288
+ let preSessions = 0;
289
+ for (const ds in scDays) if (ds < cut) {
290
+ const x = scDays[ds]; preSessions += x.sessionCount || 0;
291
+ if (x.messageCount || x.sessionCount) day(f, ds).sessions += x.sessionCount || 0;
292
+ f.toolCalls += x.toolCallCount || 0;
293
+ }
294
+ for (const [, v] of seenMsg) { const ds = localDate(v[0]); if (ds >= cut) day(f, ds); }
295
+ for (const ds of txPromptDays) day(f, ds);
296
+ f.sessions.count = preSessions + postSessions;
297
+ f.sessions.longest = longestSession(sessions);
298
+ f.sessions.mostResumed = mostResumed(bySession);
299
+ f.sessions.maxConcurrent = maxConcurrent(concEv);
300
+
301
+ // ---- the rest
302
+ const pj = ps.toJSON(); f.slash = ps.slash; f.prompts = pj;
303
+ for (const t of toolTimes) if (utcDate(t) >= cut) f.toolCalls++; // tool names exist only in transcripts; totals before cut from stats-cache
304
+ f.subagents = files.length ? subagents : null;
305
+ f.interrupts = files.length ? interrupts : null;
306
+ f.compactions = files.length ? compactions : null;
307
+ f.rateLimits = files.length ? { hits: rlHits, days: rlDays.size } : null;
308
+ f.lines = files.length ? lines : null;
309
+ f.gitUndos = files.length ? undos : null;
310
+ let rewinds = 0; for (const [, s] of kids) if (s.size > 1) rewinds += s.size - 1;
311
+ f.rewinds = files.length ? rewinds : null;
312
+ f.assistant = files.length ? assistant : null;
313
+ f.projects = Object.fromEntries(Object.entries(f.projects).sort((a, b) => b[1] - a[1]).slice(0, 20));
314
+
315
+ // ---- theme
316
+ const settings = await readJSON(path.join(base, 'settings.json'));
317
+ const tname = (settings && typeof settings.theme === 'string' && settings.theme) || 'dark';
318
+ f.theme = { name: tname, builtin: BUILTIN_THEMES.has(tname), colors: null };
319
+
320
+ if (files.length) {
321
+ f.coverage.notes.push(`transcripts on disk since ${oldestTx} (older ones pruned): tool names, lines, interrupts, phrases and other markers cover only that span`);
322
+ if (cut > '0000' && lastSc) f.coverage.notes.push(`complete transcripts from ${cut}; before that, stats-cache daily aggregates`);
323
+ }
324
+ f.coverage.notes.push('prompts from history.jsonl (interactive prompts only; SDK/headless prompts missing)');
325
+ if (bad) f.coverage.notes.push(`${bad} unparseable lines skipped`);
326
+ Object.defineProperty(f, '_debug', { enumerable: false, value: { cut, lastSc, factor, fAll, rawOvSum, dedOvSum, rawToolsUtc, files: files.length, sideFiles, historyPrompts: hist.n, txPrompts: txPromptIds.size } });
327
+ return finishCoverage(f);
328
+ }
329
+
330
+ function nextDay(ds) { const d = new Date(ds + 'T00:00:00Z'); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); }
@@ -0,0 +1,162 @@
1
+ // Codex reader: ~/.codex/sessions/**/rollout-*.jsonl and ~/.codex/archived_sessions/*.jsonl.
2
+ // Sessions, prompts and projects come from top-level threads; tokens, tools and markers from every thread.
3
+ import path from 'node:path';
4
+ import {
5
+ eachLine, parse, readText, isDir, walk, localDate, localMonth, toMs, windowOf, basename, maxConcurrent,
6
+ gitUndoKinds, emptyUndos, phraseCounts, emptyAssistant, addPhrases, hash, inc, tokBucket, emptyFacts, day,
7
+ countPromptTime, finishCoverage, longestSession, mostResumed,
8
+ } from './_util.mjs';
9
+ import { PromptStats } from './_prompts.mjs';
10
+ import { mapFiles } from './_pool.mjs';
11
+
12
+ export const id = 'codex';
13
+ export const label = 'Codex';
14
+
15
+ const dirs = env => [path.join(env.home, '.codex', 'sessions'), path.join(env.home, '.codex', 'archived_sessions')];
16
+
17
+ export async function detect(env) {
18
+ const roots = []; for (const d of dirs(env)) if (await isDir(d)) roots.push(d);
19
+ return { found: roots.length > 0, roots };
20
+ }
21
+
22
+ const PATCH = /\*\*\* Begin Patch([\s\S]*?)\*\*\* End Patch/g;
23
+
24
+ export async function scanFile(file, ctx) {
25
+ const r = {
26
+ meta: null, ts: [], prompts: [], tools: [], tok: {}, days: {}, final: 0, aborted: [], patches: [], undo: [],
27
+ phr: [], compacted: [], rl: [], version: null, models: {},
28
+ };
29
+ const win = ms => ms >= ctx.start && ms < ctx.end;
30
+ let model = null, prev = null, sawKinds = false; const um = [];
31
+ await eachLine(file, line => {
32
+ const o = parse(line); if (!o) return;
33
+ const t = o.type; const p = o.payload || {};
34
+ if (t === 'session_meta') { // forked/subagent rollouts embed copies of the parent's meta: the first one is authoritative
35
+ if (!r.meta) r.meta = { id: p.id, cwd: p.cwd || null, sub: !!(p.source && typeof p.source === 'object' && 'subagent' in p.source), version: p.cli_version || null, provider: p.model_provider || null };
36
+ return;
37
+ }
38
+ const ms = toMs(o.timestamp); if (!win(ms)) return;
39
+ r.ts.push(ms);
40
+ if (t === 'turn_context') { model = p.model || model; return; }
41
+ if (t === 'compacted') { r.compacted.push(o.timestamp); return; }
42
+ if (t === 'response_item') {
43
+ const pt = p.type;
44
+ if (pt === 'function_call' || pt === 'custom_tool_call' || pt === 'local_shell_call' || pt === 'web_search_call') {
45
+ const cid = p.call_id || p.id || hash(line);
46
+ let inp = p.input ?? p.arguments ?? ''; if (typeof inp !== 'string') inp = JSON.stringify(inp);
47
+ r.tools.push([cid, p.name || pt]);
48
+ const u = gitUndoKinds(inp.includes('\\"') ? inp.replace(/\\"/g, '"') : inp); if (u) r.undo.push([cid, u]);
49
+ if (inp.includes('Begin Patch')) {
50
+ let add = 0, rem = 0;
51
+ for (const m of inp.matchAll(PATCH)) {
52
+ let blk = m[1]; if (!blk.includes('\n')) blk = blk.replace(/\\n/g, '\n');
53
+ for (const ln of blk.split('\n')) { if (ln.startsWith('***') || ln.startsWith('@@')) continue; if (ln[0] === '+') add++; else if (ln[0] === '-') rem++; }
54
+ }
55
+ r.patches.push([cid, add, rem]);
56
+ }
57
+ } else if (pt === 'message' && p.role === 'user') {
58
+ const kinds = (p.internal_chat_message_metadata_passthrough || {}).content_item_kinds || [];
59
+ if (kinds.length) sawKinds = true;
60
+ if (kinds.includes('user.text')) {
61
+ const c = Array.isArray(p.content) ? p.content : [];
62
+ r.prompts.push([ms, c.filter(x => x && x.type === 'input_text').map(x => x.text || '').join(' '), c.filter(x => x && x.type === 'input_image').length]);
63
+ }
64
+ } else if (pt === 'message' && p.role === 'assistant') {
65
+ inc(r.models, model || '?');
66
+ const txt = (Array.isArray(p.content) ? p.content : []).map(x => (x && x.text) || '').join(' ');
67
+ const pc = phraseCounts(txt); if (pc) r.phr.push([p.id || hash(o.timestamp + txt), pc]);
68
+ }
69
+ return;
70
+ }
71
+ if (t === 'event_msg') {
72
+ const et = p.type;
73
+ if (et === 'user_message') um.push([ms, String(p.message || ''), (p.images || []).length || 0]);
74
+ else if (et === 'turn_aborted') r.aborted.push(p.turn_id || hash(line));
75
+ else if (et === 'token_count') {
76
+ const rl = p.rate_limits || {};
77
+ for (const k of ['primary', 'secondary']) { const x = rl[k] || {}; if ((x.used_percent || 0) >= 100) r.rl.push([`${k}:${x.window_minutes}:${x.resets_at}`, ms]); }
78
+ const tu = p.info && p.info.total_token_usage; if (!tu) return;
79
+ const cur = [tu.input_tokens || 0, tu.cached_input_tokens || 0, tu.output_tokens || 0];
80
+ const d = prev ? cur.map((c, i) => Math.max(0, c - prev[i])) : cur; prev = cur;
81
+ const m = model || '?'; const b = r.tok[m] ||= { input: 0, cached: 0, output: 0, byMonth: {} };
82
+ b.input += d[0] - Math.min(d[0], d[1]); b.cached += Math.min(d[0], d[1]); b.output += d[2];
83
+ inc(b.byMonth, localMonth(ms), d[0] + d[2]);
84
+ inc(r.days, localDate(ms), d[0] + d[2]);
85
+ r.final = cur[0] + cur[2];
86
+ }
87
+ }
88
+ });
89
+ if (!sawKinds && !r.prompts.length) r.prompts = um; // older builds: event_msg/user_message
90
+ if (r.meta && !(r.meta.sub)) { /* keep text */ } else r.prompts = r.prompts.map(([ms]) => [ms, '', 0]);
91
+ return r;
92
+ }
93
+
94
+ export async function read(env, opts = {}) {
95
+ const w = windowOf(env, opts); const progress = opts.onProgress || (() => {});
96
+ const f = emptyFacts(id, label); const ps = new PromptStats();
97
+ let files = [];
98
+ for (const d of dirs(env)) if (await isDir(d)) { files = files.concat(await walk(d, n => n.endsWith('.jsonl'))); f.coverage.sources.push(path.relative(path.join(env.home, '.codex'), d) + '/'); }
99
+ const seen = new Set(); const sessions = new Map(); const bySession = new Map(); const concEv = [];
100
+ const undos = emptyUndos(); const assistant = emptyAssistant(); const lines = { added: 0, removed: 0 };
101
+ const rlKeys = new Set(); const rlDays = new Set();
102
+ let top = 0, sub = 0, interrupts = 0, compactions = 0, subagents = 0, version = null, noMeta = 0;
103
+ progress(`Codex: ${files.length} rollout files`);
104
+ await mapFiles(import.meta.url, 'scanFile', files, { start: w.start, end: w.end }, r => {
105
+ const m = r.meta; if (!m) { noMeta++; return; }
106
+ if (m.version && (!version || cmpVer(m.version, version) > 0)) version = m.version;
107
+ const isTop = !m.sub; if (isTop) top++; else sub++;
108
+ for (const [cid, name] of r.tools) { if (seen.has('u' + cid)) continue; seen.add('u' + cid); inc(f.tools, name); if (name === 'spawn_agent') subagents++; }
109
+ for (const [cid, u] of r.undo) { if (seen.has('g' + cid)) continue; seen.add('g' + cid); for (const k of u) undos[k]++; }
110
+ for (const [cid, a, b] of r.patches) { if (seen.has('p' + cid)) continue; seen.add('p' + cid); lines.added += a; lines.removed += b; }
111
+ for (const [k, c] of r.phr) { if (seen.has('t' + k)) continue; seen.add('t' + k); addPhrases(assistant, c); }
112
+ for (const [k, ms] of r.rl) { if (rlKeys.has(k)) continue; rlKeys.add(k); rlDays.add(localDate(ms)); }
113
+ for (const mo in r.tok) {
114
+ const s = r.tok[mo]; const b = f.models[mo] ||= tokBucket(); if (m.provider && !b.provider) b.provider = m.provider;
115
+ b.input += s.input; b.cacheRead += s.cached; b.output += s.output;
116
+ for (const mon in s.byMonth) inc(b.byMonth, mon, s.byMonth[mon]);
117
+ }
118
+ for (const ds in r.days) day(f, ds).tokens += r.days[ds];
119
+ if (!isTop) return;
120
+ for (const t of r.aborted) { if (seen.has('a' + t)) continue; seen.add('a' + t); interrupts++; }
121
+ for (const t of r.compacted) { if (seen.has('c' + t)) continue; seen.add('c' + t); compactions++; }
122
+ if (r.ts.length) {
123
+ const s = sessions.get(m.id) || { t: [], project: basename(m.cwd) }; for (const t of r.ts) s.t.push(t); sessions.set(m.id, s);
124
+ }
125
+ for (const [ms, text, images] of r.prompts) {
126
+ ps.add(text, { images }); countPromptTime(f, ms); concEv.push([ms, m.id]);
127
+ const proj = basename(m.cwd); if (proj) inc(f.projects, proj);
128
+ const s = bySession.get(m.id) || { days: new Set(), project: proj }; s.days.add(localDate(ms)); bySession.set(m.id, s);
129
+ }
130
+ }, { onProgress: m => progress('Codex: ' + m) });
131
+
132
+ for (const [, s] of sessions) {
133
+ if (!s.t.length) continue; let mn = Infinity; for (const t of s.t) { if (t < mn) mn = t; day(f, localDate(t)); }
134
+ day(f, localDate(mn)).sessions++; f.sessions.count++;
135
+ }
136
+ f.sessions.longest = longestSession(sessions);
137
+ f.sessions.mostResumed = mostResumed(bySession);
138
+ f.sessions.maxConcurrent = maxConcurrent(concEv);
139
+ f.prompts = ps.toJSON(); f.slash = ps.slash;
140
+ f.version = version;
141
+ f.subagents = subagents; f.interrupts = interrupts; f.compactions = compactions;
142
+ f.rateLimits = { hits: rlKeys.size, days: rlDays.size };
143
+ f.lines = lines; f.gitUndos = undos; f.assistant = assistant; f.rewinds = null;
144
+ f.projects = Object.fromEntries(Object.entries(f.projects).sort((a, b) => b[1] - a[1]).slice(0, 20));
145
+ const cfg = await readText(path.join(env.home, '.codex', 'config.toml'));
146
+ const tm = cfg && /^\s*theme\s*=\s*"([^"]+)"/m.exec(cfg);
147
+ f.theme = tm ? { name: tm[1], builtin: true, colors: null } : null;
148
+ if (files.length) f.coverage.notes.push(`${top} top-level threads (sessions, prompts) and ${sub} subagent threads (tokens, tools)`);
149
+ f.coverage.notes.push('lines = apply_patch bodies proposed in tool calls (success not checked)');
150
+ if (noMeta) f.coverage.notes.push(`${noMeta} rollout files without session_meta skipped`);
151
+ Object.defineProperty(f, '_debug', { enumerable: false, value: { files: files.length, top, sub } });
152
+ return finishCoverage(f);
153
+ }
154
+
155
+ function cmpVer(a, b) {
156
+ const pa = String(a).split(/[.-]/), pb = String(b).split(/[.-]/);
157
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
158
+ const x = pa[i] ?? '', y = pb[i] ?? ''; const nx = +x, ny = +y;
159
+ if (!isNaN(nx) && !isNaN(ny) && x !== '' && y !== '') { if (nx !== ny) return nx - ny; } else if (x !== y) return x < y ? -1 : 1;
160
+ }
161
+ return 0;
162
+ }
@@ -0,0 +1,8 @@
1
+ // All harness readers, in display order. Each: { id, label, detect(env), read(env, opts) } (docs/CONTRACT.md §1).
2
+ import * as claudeCode from './claude-code.mjs';
3
+ import * as codex from './codex.mjs';
4
+ import * as pi from './pi.mjs';
5
+ import * as mistralVibe from './mistral-vibe.mjs';
6
+
7
+ export const readers = [claudeCode, codex, pi, mistralVibe];
8
+ export { claudeCode, codex, pi, mistralVibe };