@agent-watch-ai/edge 0.7.1 → 0.7.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/capture/capture-env.d.ts +3 -3
  3. package/dist/capture/capture-env.js +5 -5
  4. package/dist/capture/captured-step.js +1 -1
  5. package/dist/cli/constants/cli.constants.js +1 -1
  6. package/dist/cli/setup.js +24 -1
  7. package/dist/cli/types/cli.types.d.ts +2 -0
  8. package/dist/cli.js +4 -1
  9. package/dist/config/config.d.ts +8 -0
  10. package/dist/config/config.js +10 -0
  11. package/dist/config/constants/config.constants.d.ts +5 -0
  12. package/dist/config/constants/config.constants.js +5 -0
  13. package/dist/config/repo-config.js +7 -2
  14. package/dist/config/schemas/config.schema.d.ts +4 -0
  15. package/dist/config/schemas/config.schema.js +7 -1
  16. package/dist/pipeline/hook-pipeline.js +3 -1
  17. package/dist/providers/antigravity/antigravity.adapter.d.ts +14 -0
  18. package/dist/providers/antigravity/antigravity.adapter.js +86 -18
  19. package/dist/providers/antigravity/antigravity.provider.js +7 -4
  20. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +10 -0
  21. package/dist/providers/antigravity/constants/antigravity.constants.js +10 -0
  22. package/dist/providers/antigravity/schemas/antigravity.schema.js +7 -13
  23. package/dist/providers/claude/claude.otel.d.ts +33 -1
  24. package/dist/providers/claude/claude.otel.js +81 -12
  25. package/dist/providers/claude/claude.provider.js +3 -1
  26. package/dist/providers/codex/codex.capture.d.ts +1 -1
  27. package/dist/providers/codex/codex.capture.js +3 -3
  28. package/dist/providers/codex/codex.otel.js +2 -2
  29. package/dist/providers/codex/codex.provider.js +2 -1
  30. package/dist/providers/gemini/gemini.capture.js +2 -2
  31. package/dist/providers/gemini/gemini.otel.js +2 -2
  32. package/dist/providers/gemini/gemini.provider.js +2 -1
  33. package/dist/providers/shared/terminal-capture.js +3 -3
  34. package/dist/turns/antigravity-transcript.d.ts +40 -0
  35. package/dist/turns/antigravity-transcript.js +102 -0
  36. package/dist/turns/claude-transcript.d.ts +35 -1
  37. package/dist/turns/claude-transcript.js +185 -2
  38. package/dist/turns/codex-transcript.d.ts +22 -1
  39. package/dist/turns/codex-transcript.js +161 -2
  40. package/dist/turns/constants/turns.constants.d.ts +51 -0
  41. package/dist/turns/constants/turns.constants.js +51 -0
  42. package/dist/turns/gemini-transcript.d.ts +17 -1
  43. package/dist/turns/gemini-transcript.js +36 -2
  44. package/dist/turns/transcript.d.ts +31 -1
  45. package/dist/turns/transcript.js +74 -0
  46. package/dist/turns/turn-state.d.ts +18 -1
  47. package/dist/turns/turn-state.js +45 -10
  48. package/dist/turns/turn-tracker.js +154 -16
  49. package/dist/turns/types/transcript.types.d.ts +25 -0
  50. package/dist/turns/types/turn-provider.types.d.ts +18 -1
  51. package/dist/turns/types/turn-state.types.d.ts +10 -0
  52. package/docs/DATA_HANDLING.md +3 -0
  53. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
1
3
  import { asRecord, compact } from '../core/object.js';
2
- import { CLAUDE_CUSTOM_TITLE_FIELDS, CLAUDE_GENERATED_TITLE_FIELDS, RE_CLAUDE_TITLE_LINE } from './constants/turns.constants.js';
3
- import { accumulateUsage, messageIdFor, parseJsonLine, readTranscriptTail, readUntilSettled, readWindowedTail } from './transcript.js';
4
+ import { CLAUDE_CUSTOM_TITLE_FIELDS, CLAUDE_GENERATED_TITLE_FIELDS, CLAUDE_SUBAGENTS_DIR, PROMPT_SEED_CHUNK_BYTES, PROMPT_SEED_OVERLAP_BYTES, PROMPT_SEED_SCAN_BYTES, RE_CLAUDE_AGENT_ID, RE_CLAUDE_PROMPT_ID, RE_CLAUDE_SUBAGENT_FILE, RE_CLAUDE_TITLE_LINE, TRANSCRIPT_PATH_KEY } from './constants/turns.constants.js';
5
+ import { accumulateUsage, filesWrittenSince, messageIdFor, parseJsonLine, readTailSnapshot, readTranscriptTail, readUntilSettled, readWindowedTail } from './transcript.js';
4
6
  /**
5
7
  * Authoritative per-turn token usage from Claude Code's transcript JSONL.
6
8
  *
@@ -71,6 +73,187 @@ function assistantUsageEntry(line, since, until, excludeMessageIds) {
71
73
  const model = typeof message?.['model'] === 'string' ? message['model'] : undefined;
72
74
  return { id, value: { model, usage } };
73
75
  }
76
+ /**
77
+ * The usage a turn's subagents recorded, out of their own transcripts.
78
+ *
79
+ * Claude Code writes each subagent to `<session>/subagents/agent-<id>.jsonl`,
80
+ * never to the session's own transcript. A subagent's user lines name the
81
+ * parent's prompt id, the one that launched it or a later one that resumed it,
82
+ * so each assistant line belongs to the prompt id of the user line above it.
83
+ * Lines before the first such line (a fork's copy of the parent's last reply)
84
+ * are no one's here; the parent's own read counts that message. A file longer
85
+ * than the tail takes the last prompt id stated before the tail.
86
+ *
87
+ * A Stop reads every subagent file written since the turn began; a subagent's
88
+ * own stop reads only that subagent's file. One pass, no settle loop: a
89
+ * foreground subagent has stopped before its parent does, and a background one
90
+ * re-reads on its own stop. Never throws.
91
+ *
92
+ * @param payload - The raw hook payload.
93
+ * @param turn - The parent turn; its window is not used, the prompt id is exact.
94
+ * @param excludeMessageIds - Messages already claimed.
95
+ * @returns The subagents' usage in this turn, or undefined when there is none.
96
+ */
97
+ export async function readClaudeSubagentUsage(payload, turn, excludeMessageIds) {
98
+ const { turnId, startedAt } = turn;
99
+ // No prompt id (Claude Code before 2.1.196): no subagent line can be matched to the turn.
100
+ if (turnId === undefined)
101
+ return undefined;
102
+ try {
103
+ const files = await subagentFiles(asRecord(payload), Date.parse(startedAt));
104
+ const byMessageId = new Map();
105
+ for (const file of files) {
106
+ const tail = await subagentTail(file);
107
+ // Most files are another turn's: skip them without a parse.
108
+ if (!tail || (tail.seed !== turnId && !tail.raw.includes(turnId)))
109
+ continue;
110
+ for (const { id, value } of subagentEntries(tail.raw, turnId, excludeMessageIds, tail.seed))
111
+ byMessageId.set(id, value);
112
+ }
113
+ return accumulateUsage(byMessageId);
114
+ }
115
+ catch {
116
+ return undefined;
117
+ }
118
+ }
119
+ /**
120
+ * The turns a stopping subagent's lines name, oldest first: the prompt that
121
+ * launched it and any that resumed it.
122
+ *
123
+ * A `SubagentStop` names the session's current prompt (Claude Code 2.1.325),
124
+ * not the one that launched the subagent, so the turn a background subagent's
125
+ * late usage belongs to is read from its own lines.
126
+ *
127
+ * @param payload - The subagent's stop payload.
128
+ * @returns The prompt ids; empty when the payload names no subagent or its file cannot be read.
129
+ */
130
+ export async function readClaudeSubagentTurnIds(payload) {
131
+ const record = asRecord(payload);
132
+ // Only a subagent's own stop: a Stop would list every subagent of the session.
133
+ if (typeof record?.['agent_id'] !== 'string')
134
+ return [];
135
+ try {
136
+ const ids = [];
137
+ for (const file of await subagentFiles(record, Number.NaN)) {
138
+ const tail = await subagentTail(file);
139
+ if (!tail)
140
+ continue;
141
+ if (tail.seed !== undefined)
142
+ ids.push(tail.seed);
143
+ for (const match of tail.raw.matchAll(RE_CLAUDE_PROMPT_ID))
144
+ ids.push(match[1]);
145
+ }
146
+ return [...new Set(ids)];
147
+ }
148
+ catch {
149
+ return [];
150
+ }
151
+ }
152
+ /**
153
+ * A subagent transcript's tail with its seed, both from one size of the file.
154
+ *
155
+ * @param file - A subagent transcript.
156
+ * @returns The tail, or undefined when the file cannot be read.
157
+ */
158
+ async function subagentTail(file) {
159
+ const tail = await readTailSnapshot(file);
160
+ if (!tail)
161
+ return undefined;
162
+ return { raw: tail.raw, seed: tail.start > 0 ? await promptIdBefore(file, tail.start) : undefined };
163
+ }
164
+ /**
165
+ * The last prompt id stated before a byte offset, read backwards a chunk at a time.
166
+ *
167
+ * ponytail: gives up PROMPT_SEED_SCAN_BYTES back; a subagent that ran longer
168
+ * than that on one prompt loses its first tail lines until the next prompt line.
169
+ *
170
+ * @param file - A subagent transcript.
171
+ * @param before - Where the tail starts.
172
+ * @returns The prompt id, or undefined when none is found.
173
+ */
174
+ async function promptIdBefore(file, before) {
175
+ const handle = await fs.open(file, 'r');
176
+ const floor = Math.max(0, before - PROMPT_SEED_SCAN_BYTES);
177
+ try {
178
+ for (let end = before; end > floor;) {
179
+ const start = Math.max(floor, end - PROMPT_SEED_CHUNK_BYTES);
180
+ const buffer = Buffer.allocUnsafe(end - start);
181
+ const { bytesRead } = await handle.read(buffer, 0, end - start, start);
182
+ const found = lastPromptId(buffer.subarray(0, bytesRead).toString('utf8'));
183
+ if (found !== undefined || start === floor)
184
+ return found;
185
+ end = start + PROMPT_SEED_OVERLAP_BYTES;
186
+ }
187
+ return undefined;
188
+ }
189
+ finally {
190
+ await handle.close();
191
+ }
192
+ }
193
+ /**
194
+ * The last prompt id a run of transcript text states.
195
+ *
196
+ * @param text - Transcript text, possibly cut mid-line at either end.
197
+ * @returns The id, or undefined when it states none.
198
+ */
199
+ function lastPromptId(text) {
200
+ let last;
201
+ for (const match of text.matchAll(RE_CLAUDE_PROMPT_ID))
202
+ last = match[1];
203
+ return last;
204
+ }
205
+ /**
206
+ * The subagent transcripts one hook should read.
207
+ *
208
+ * @param payload - The raw hook payload.
209
+ * @param since - Turn start, epoch ms; a file untouched since holds nothing of the turn.
210
+ * @returns Absolute paths; empty when the payload names no transcript.
211
+ */
212
+ async function subagentFiles(payload, since) {
213
+ const transcriptPath = payload?.[TRANSCRIPT_PATH_KEY];
214
+ const own = payload?.['agent_transcript_path'];
215
+ // A subagent's own stop: its file alone, as named, else derived from its id.
216
+ if (typeof own === 'string' && own)
217
+ return [own];
218
+ if (typeof transcriptPath !== 'string' || !transcriptPath.endsWith('.jsonl'))
219
+ return [];
220
+ const dir = path.join(transcriptPath.slice(0, -'.jsonl'.length), CLAUDE_SUBAGENTS_DIR);
221
+ const agentId = payload?.['agent_id'];
222
+ if (typeof agentId === 'string')
223
+ return RE_CLAUDE_AGENT_ID.test(agentId) ? [path.join(dir, `agent-${agentId}.jsonl`)] : [];
224
+ return filesWrittenSince(dir, RE_CLAUDE_SUBAGENT_FILE, since);
225
+ }
226
+ /**
227
+ * One subagent transcript's usage entries of a turn.
228
+ *
229
+ * @param raw - The transcript tail.
230
+ * @param turnId - The parent turn.
231
+ * @param excludeMessageIds - Messages already claimed.
232
+ * @param seed - The prompt the tail's first lines ran under, when the tail is cut.
233
+ * @returns The entries, in file order; a repeated message id repeats.
234
+ */
235
+ function subagentEntries(raw, turnId, excludeMessageIds, seed) {
236
+ const entries = [];
237
+ let promptId = seed;
238
+ for (const line of raw.split('\n')) {
239
+ if (!line.trim())
240
+ continue;
241
+ const entry = parseJsonLine(line);
242
+ if (entry?.['type'] === 'user' && typeof entry['promptId'] === 'string')
243
+ promptId = entry['promptId'];
244
+ if (entry?.['type'] !== 'assistant' || promptId !== turnId)
245
+ continue;
246
+ const message = asRecord(entry['message']);
247
+ const usage = asRecord(message?.['usage']);
248
+ if (!usage)
249
+ continue;
250
+ const id = messageIdFor(typeof message?.['id'] === 'string' ? message['id'] : undefined, line);
251
+ if (excludeMessageIds.has(id))
252
+ continue;
253
+ entries.push({ id, value: { model: typeof message?.['model'] === 'string' ? message['model'] : undefined, usage } });
254
+ }
255
+ return entries;
256
+ }
74
257
  /**
75
258
  * The session's titles, from the tail of Claude Code's transcript.
76
259
  *
@@ -1,4 +1,4 @@
1
- import type { ReadTurnUsageRetry, TurnUsage } from './types/transcript.types.js';
1
+ import type { ReadTurnUsageRetry, SubagentTurn, TurnUsage } from './types/transcript.types.js';
2
2
  /**
3
3
  * Per-turn token usage from a Codex rollout (`~/.codex/sessions/…/rollout-*.jsonl`).
4
4
  *
@@ -28,6 +28,27 @@ import type { ReadTurnUsageRetry, TurnUsage } from './types/transcript.types.js'
28
28
  * @returns The turn's usage, or undefined when the rollout reports none.
29
29
  */
30
30
  export declare function readCodexTurnUsage(transcriptPath: string, sinceIso: string, retry?: ReadTurnUsageRetry, untilIso?: string, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
31
+ /**
32
+ * The usage of the session's subagent threads inside the turn's window, out of
33
+ * their own rollouts.
34
+ *
35
+ * A `spawn_agent` child is a thread of its own, writing its own rollout beside
36
+ * the parent's, whose `session_meta` names the parent (`source.subagent.
37
+ * thread_spawn.parent_thread_id`). It fires no Stop and no prompt hook (only
38
+ * SubagentStart and SubagentStop on the parent's session, verified on
39
+ * codex-cli 0.166.0), and its own turn ids are not the parent's, so its rows
40
+ * join the parent's turn by window. Children of children are followed. Never throws.
41
+ *
42
+ * ponytail: rows a background child writes after the parent's Stop and before
43
+ * its next prompt fall in no window and stay uncounted; native OTel still has
44
+ * them. Upgrade path: a re-send on that child's SubagentStop, as Claude does.
45
+ *
46
+ * @param payload - The raw hook payload, naming the parent rollout and session.
47
+ * @param turn - The parent turn's window.
48
+ * @param excludeMessageIds - Rows already claimed.
49
+ * @returns The children's usage in the window, or undefined when there is none.
50
+ */
51
+ export declare function readCodexSubagentUsage(payload: unknown, turn: SubagentTurn, excludeMessageIds: ReadonlySet<string>): Promise<TurnUsage | undefined>;
31
52
  /**
32
53
  * The counts one rollout row carries, when it is an `event_msg` / `token_count` row.
33
54
  *
@@ -1,6 +1,8 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
1
3
  import { asRecord, firstStringOf } from '../core/object.js';
2
- import { accumulateUsage, messageIdFor, parseJsonLine, readUntilSettled, readWindowedTail } from './transcript.js';
3
- import { CODEX_CACHED_INPUT_TOKENS, CODEX_LAST_TOKEN_USAGE, CODEX_TOKEN_COUNT, CODEX_TURN_CONTEXT, TRANSCRIPT_CACHE_READ_TOKENS, TRANSCRIPT_INPUT_TOKENS, TRANSCRIPT_OUTPUT_TOKENS } from './constants/turns.constants.js';
4
+ import { accumulateUsage, mergeUsage, messageIdFor, parseJsonLine, readUntilSettled, readWindowedTail } from './transcript.js';
5
+ import { CODEX_CACHED_INPUT_TOKENS, CODEX_MAX_SCAN_DAYS, CODEX_MAX_SPAWN_DEPTH, CODEX_META_HEAD_BYTES, DAY_MS, RE_CODEX_ROLLOUT, TRANSCRIPT_PATH_KEY, CODEX_LAST_TOKEN_USAGE, CODEX_TOKEN_COUNT, CODEX_TURN_CONTEXT, TRANSCRIPT_CACHE_READ_TOKENS, TRANSCRIPT_INPUT_TOKENS, TRANSCRIPT_OUTPUT_TOKENS } from './constants/turns.constants.js';
4
6
  /**
5
7
  * Per-turn token usage from a Codex rollout (`~/.codex/sessions/…/rollout-*.jsonl`).
6
8
  *
@@ -74,6 +76,163 @@ async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
74
76
  }
75
77
  return accumulateUsage(byRowId);
76
78
  }
79
+ /**
80
+ * The usage of the session's subagent threads inside the turn's window, out of
81
+ * their own rollouts.
82
+ *
83
+ * A `spawn_agent` child is a thread of its own, writing its own rollout beside
84
+ * the parent's, whose `session_meta` names the parent (`source.subagent.
85
+ * thread_spawn.parent_thread_id`). It fires no Stop and no prompt hook (only
86
+ * SubagentStart and SubagentStop on the parent's session, verified on
87
+ * codex-cli 0.166.0), and its own turn ids are not the parent's, so its rows
88
+ * join the parent's turn by window. Children of children are followed. Never throws.
89
+ *
90
+ * ponytail: rows a background child writes after the parent's Stop and before
91
+ * its next prompt fall in no window and stay uncounted; native OTel still has
92
+ * them. Upgrade path: a re-send on that child's SubagentStop, as Claude does.
93
+ *
94
+ * @param payload - The raw hook payload, naming the parent rollout and session.
95
+ * @param turn - The parent turn's window.
96
+ * @param excludeMessageIds - Rows already claimed.
97
+ * @returns The children's usage in the window, or undefined when there is none.
98
+ */
99
+ export async function readCodexSubagentUsage(payload, turn, excludeMessageIds) {
100
+ const record = asRecord(payload);
101
+ const transcriptPath = record?.[TRANSCRIPT_PATH_KEY];
102
+ // Codex has named the session both ways, as the adapter reads it.
103
+ const sessionId = firstStringOf(record?.['session_id'], record?.['thread_id']);
104
+ if (typeof transcriptPath !== 'string' || !sessionId)
105
+ return undefined;
106
+ try {
107
+ let usage;
108
+ for (const child of await childRollouts(transcriptPath, sessionId, Date.parse(turn.startedAt))) {
109
+ usage = mergeUsage(usage, await readOnce(child, turn.startedAt, turn.untilIso, excludeMessageIds));
110
+ }
111
+ return usage;
112
+ }
113
+ catch {
114
+ return undefined;
115
+ }
116
+ }
117
+ /**
118
+ * The rollouts of the session's descendant threads written since the turn began.
119
+ *
120
+ * Codex files a rollout under the local date its thread started, so every
121
+ * descendant sits in a day folder from the parent's to today's. Only a file
122
+ * written since the turn began can hold its rows; whether it descends from the
123
+ * session is followed up its chain of parents, found by the thread id that ends
124
+ * every rollout name, so an idle child still links a busy grandchild.
125
+ *
126
+ * @param transcriptPath - The parent rollout.
127
+ * @param sessionId - The parent thread id.
128
+ * @param since - Turn start, epoch ms.
129
+ * @returns The descendants' rollout paths.
130
+ */
131
+ async function childRollouts(transcriptPath, sessionId, since) {
132
+ const byThread = new Map();
133
+ const candidates = [];
134
+ for (const dir of dayFolders(transcriptPath)) {
135
+ for (const name of await fs.readdir(dir).catch(() => [])) {
136
+ const thread = RE_CODEX_ROLLOUT.exec(name)?.[1];
137
+ const file = path.join(dir, name);
138
+ if (!thread || file === transcriptPath)
139
+ continue;
140
+ byThread.set(thread, file);
141
+ const stat = await fs.stat(file).catch(() => undefined);
142
+ if (stat && !(stat.mtimeMs < since))
143
+ candidates.push(file);
144
+ }
145
+ }
146
+ // A shared ancestor's head is read once.
147
+ const heads = new Map();
148
+ const headOf = (file) => heads.get(file) ?? heads.set(file, rolloutThread(file)).get(file);
149
+ const picked = [];
150
+ for (const file of candidates) {
151
+ if (await descendsFrom(file, sessionId, byThread, headOf))
152
+ picked.push(file);
153
+ }
154
+ return picked;
155
+ }
156
+ /**
157
+ * Whether a rollout's thread descends from the session, walking up its parents.
158
+ *
159
+ * @param file - A rollout.
160
+ * @param sessionId - The root thread.
161
+ * @param byThread - Rollout path per thread id, from the file names.
162
+ * @param headOf - A rollout's threads, read from its head.
163
+ * @returns True when the chain reaches the session.
164
+ */
165
+ async function descendsFrom(file, sessionId, byThread, headOf) {
166
+ let current = file;
167
+ for (let depth = 0; current !== undefined && depth < CODEX_MAX_SPAWN_DEPTH; depth++) {
168
+ const parent = (await headOf(current))?.parent;
169
+ if (parent === undefined)
170
+ return false;
171
+ if (parent === sessionId)
172
+ return true;
173
+ current = byThread.get(parent);
174
+ }
175
+ return false;
176
+ }
177
+ /**
178
+ * A rollout's own thread and the thread that spawned it, from its first line.
179
+ *
180
+ * @param file - A rollout.
181
+ * @returns Both ids, or undefined for a rollout no thread spawned.
182
+ */
183
+ async function rolloutThread(file) {
184
+ const handle = await fs.open(file, 'r').catch(() => undefined);
185
+ if (!handle)
186
+ return undefined;
187
+ try {
188
+ const buffer = Buffer.allocUnsafe(CODEX_META_HEAD_BYTES);
189
+ const { bytesRead } = await handle.read(buffer, 0, CODEX_META_HEAD_BYTES, 0);
190
+ const head = buffer.subarray(0, bytesRead).toString('utf8');
191
+ const end = head.indexOf('\n');
192
+ // ponytail: a first line longer than the head is skipped; raise CODEX_META_HEAD_BYTES if one shows up.
193
+ const meta = asRecord(parseJsonLine(end < 0 ? head : head.slice(0, end))?.['payload']);
194
+ const spawn = asRecord(asRecord(asRecord(meta?.['source'])?.['subagent'])?.['thread_spawn']);
195
+ const thread = firstStringOf(meta?.['id']);
196
+ const parent = firstStringOf(spawn?.['parent_thread_id']);
197
+ return thread && parent ? { thread, parent } : undefined;
198
+ }
199
+ finally {
200
+ await handle.close();
201
+ }
202
+ }
203
+ /**
204
+ * The day folders a descendant of the session can sit in: the parent rollout's
205
+ * through today's, at most CODEX_MAX_SCAN_DAYS of them.
206
+ *
207
+ * ponytail: a session older than CODEX_MAX_SCAN_DAYS loses the children filed
208
+ * in its first days; raise the cap if long-lived sessions spawn across weeks.
209
+ *
210
+ * @param transcriptPath - The parent rollout, `<root>/YYYY/MM/DD/rollout-…`.
211
+ * @returns The folders, oldest first.
212
+ */
213
+ function dayFolders(transcriptPath) {
214
+ const dir = path.dirname(transcriptPath);
215
+ const sessionsRoot = path.resolve(dir, '..', '..', '..');
216
+ const [year, month, day] = path.relative(sessionsRoot, dir).split(path.sep).map(Number);
217
+ const today = new Date();
218
+ const first = new Date(year, month - 1, day);
219
+ const start = Number.isNaN(first.getTime()) || first > today ? today : first;
220
+ const folders = [];
221
+ for (let at = new Date(Math.max(start.getTime(), today.getTime() - (CODEX_MAX_SCAN_DAYS - 1) * DAY_MS)); at <= today; at = new Date(at.getFullYear(), at.getMonth(), at.getDate() + 1)) {
222
+ folders.push(dayFolder(sessionsRoot, at));
223
+ }
224
+ return [...new Set([dir, ...folders])];
225
+ }
226
+ /**
227
+ * The folder Codex files a thread started on a day under.
228
+ *
229
+ * @param sessionsRoot - `~/.codex/sessions`.
230
+ * @param day - The day, local time as Codex names it.
231
+ * @returns `<root>/YYYY/MM/DD`.
232
+ */
233
+ function dayFolder(sessionsRoot, day) {
234
+ return path.join(sessionsRoot, String(day.getFullYear()), String(day.getMonth() + 1).padStart(2, '0'), String(day.getDate()).padStart(2, '0'));
235
+ }
77
236
  /**
78
237
  * The counts one rollout row carries, when it is an `event_msg` / `token_count` row.
79
238
  *
@@ -35,6 +35,26 @@ export declare const USAGE_RETRY: ReadTurnUsageRetry;
35
35
  * parsing tens of megabytes each pass would be pure waste on long sessions.
36
36
  */
37
37
  export declare const TRANSCRIPT_TAIL_BYTES: number;
38
+ /** Claude Code's folder of subagent transcripts, beside the session's own (`<session>/subagents/`). */
39
+ export declare const CLAUDE_SUBAGENTS_DIR = "subagents";
40
+ /** Claude Code names a subagent's transcript `agent-<agentId>.jsonl`. */
41
+ export declare const RE_CLAUDE_SUBAGENT_FILE: RegExp;
42
+ /**
43
+ * A prompt id as a Claude Code user line states it. Assistant lines say
44
+ * `"promptId":null`, and one quoted inside message content is escaped, so
45
+ * neither matches.
46
+ */
47
+ export declare const RE_CLAUDE_PROMPT_ID: RegExp;
48
+ /**
49
+ * How far back before a subagent transcript's tail to look for the prompt its
50
+ * first tail lines ran under, in chunks, overlapping so a match split across
51
+ * two chunks is still seen.
52
+ */
53
+ export declare const PROMPT_SEED_SCAN_BYTES: number;
54
+ export declare const PROMPT_SEED_CHUNK_BYTES: number;
55
+ export declare const PROMPT_SEED_OVERLAP_BYTES = 256;
56
+ /** An agent id safe to put in a file name: no separators, no dots. */
57
+ export declare const RE_CLAUDE_AGENT_ID: RegExp;
38
58
  /** Payload key every supported agent reports its transcript path under. */
39
59
  export declare const TRANSCRIPT_PATH_KEY = "transcript_path";
40
60
  /** Marker of a closed turn; no `.json`, so it is never read as a record (AWT-701). */
@@ -55,6 +75,11 @@ export declare const SESSION_ENDED_FILE = "session-ended";
55
75
  * must not keep the state from clearing.
56
76
  */
57
77
  export declare const DETACHED_CLOSE_MAX_AGE_MS = 60000;
78
+ /**
79
+ * The summary a turn closed with, kept so a background subagent finishing later
80
+ * can re-send it with its usage added. No `.json`, so it is never read as a record.
81
+ */
82
+ export declare const SENT_TURN_PREFIX = "sent-turn--";
58
83
  /** Prefix distinguishing usage-claim files from turn records in a session dir. */
59
84
  export declare const USAGE_CLAIM_PREFIX = "usage-claim--";
60
85
  /**
@@ -214,12 +239,38 @@ export declare const TRANSCRIPT_CACHE_READ_TOKENS = "cache_read_input_tokens";
214
239
  export declare const TRANSCRIPT_CACHE_CREATION_TOKENS = "cache_creation_input_tokens";
215
240
  /** Codex rollout rows the usage reader needs; every other row is skipped unparsed. */
216
241
  export declare const CODEX_TOKEN_COUNT = "token_count";
242
+ /** A Codex rollout's file name; a child thread's is one too, in the same day folders. */
243
+ export declare const RE_CODEX_ROLLOUT: RegExp;
244
+ /** How many spawn levels a descendant is followed up; Codex reports `depth` 1 for a direct child. */
245
+ export declare const CODEX_MAX_SPAWN_DEPTH = 8;
246
+ /** How many day folders, back from today, a session's descendants are looked for in. */
247
+ export declare const CODEX_MAX_SCAN_DAYS = 7;
248
+ export declare const DAY_MS: number;
249
+ /** How much of a rollout's head to read for its `session_meta` line (about 20 KB, 2026-11). */
250
+ export declare const CODEX_META_HEAD_BYTES: number;
251
+ /** Gemini CLI 0.46 writes a subagent's chat to `chats/<parent session id>/<agent id>.jsonl`. */
252
+ export declare const RE_GEMINI_CHAT_FILE: RegExp;
217
253
  export declare const CODEX_TURN_CONTEXT = "turn_context";
218
254
  export declare const CODEX_LAST_TOKEN_USAGE = "last_token_usage";
219
255
  export declare const CODEX_CACHED_INPUT_TOKENS = "cached_input_tokens";
220
256
  /** Gemini CLI chat-file row type that carries a model reply, and its usage block. */
221
257
  export declare const GEMINI_REPLY_TYPE = "gemini";
222
258
  export declare const GEMINI_TOKENS = "tokens";
259
+ /**
260
+ * Antigravity transcript (`brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`)
261
+ * model-step fields. Its counts are disjoint: `input_tokens` excludes
262
+ * `cache_read_tokens` (an 11-04 IDE transcript's input drops 16896 -> 3374 as
263
+ * 14865 cache reads appear), so they map onto the Anthropic-style fields as is.
264
+ */
265
+ export declare const ANTIGRAVITY_MODEL_SOURCE = "MODEL";
266
+ export declare const ANTIGRAVITY_INPUT_TOKENS = "input_tokens";
267
+ export declare const ANTIGRAVITY_OUTPUT_TOKENS = "output_tokens";
268
+ export declare const ANTIGRAVITY_CACHE_READ_TOKENS = "cache_read_tokens";
269
+ /** The count fields; a transcript line with none of them is skipped unparsed. */
270
+ export declare const ANTIGRAVITY_COUNT_FIELDS: readonly ["input_tokens", "output_tokens", "cache_read_tokens"];
271
+ export declare const ANTIGRAVITY_STEP_ID_PREFIX = "step-";
272
+ /** Antigravity's `created_at` has whole-second precision. */
273
+ export declare const ANTIGRAVITY_TIMESTAMP_RESOLUTION_MS = 1000;
223
274
  /** Every transcript token field, for weighting which model dominated a turn. */
224
275
  export declare const TRANSCRIPT_TOKEN_FIELDS: readonly ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"];
225
276
  /** Prefix for the content-hash id given to a transcript entry without one. */
@@ -41,6 +41,26 @@ export const USAGE_RETRY = { attempts: 6, delayMs: 250, minSettleMs: 500 };
41
41
  * parsing tens of megabytes each pass would be pure waste on long sessions.
42
42
  */
43
43
  export const TRANSCRIPT_TAIL_BYTES = 4 * 1024 * 1024;
44
+ /** Claude Code's folder of subagent transcripts, beside the session's own (`<session>/subagents/`). */
45
+ export const CLAUDE_SUBAGENTS_DIR = 'subagents';
46
+ /** Claude Code names a subagent's transcript `agent-<agentId>.jsonl`. */
47
+ export const RE_CLAUDE_SUBAGENT_FILE = /^agent-[A-Za-z0-9_-]+\.jsonl$/;
48
+ /**
49
+ * A prompt id as a Claude Code user line states it. Assistant lines say
50
+ * `"promptId":null`, and one quoted inside message content is escaped, so
51
+ * neither matches.
52
+ */
53
+ export const RE_CLAUDE_PROMPT_ID = /"promptId":"([0-9A-Za-z-]+)"/g;
54
+ /**
55
+ * How far back before a subagent transcript's tail to look for the prompt its
56
+ * first tail lines ran under, in chunks, overlapping so a match split across
57
+ * two chunks is still seen.
58
+ */
59
+ export const PROMPT_SEED_SCAN_BYTES = 16 * 1024 * 1024;
60
+ export const PROMPT_SEED_CHUNK_BYTES = 1024 * 1024;
61
+ export const PROMPT_SEED_OVERLAP_BYTES = 256;
62
+ /** An agent id safe to put in a file name: no separators, no dots. */
63
+ export const RE_CLAUDE_AGENT_ID = /^[A-Za-z0-9_-]+$/;
44
64
  /** Payload key every supported agent reports its transcript path under. */
45
65
  export const TRANSCRIPT_PATH_KEY = 'transcript_path';
46
66
  /** Marker of a closed turn; no `.json`, so it is never read as a record (AWT-701). */
@@ -61,6 +81,11 @@ export const SESSION_ENDED_FILE = 'session-ended';
61
81
  * must not keep the state from clearing.
62
82
  */
63
83
  export const DETACHED_CLOSE_MAX_AGE_MS = 60_000;
84
+ /**
85
+ * The summary a turn closed with, kept so a background subagent finishing later
86
+ * can re-send it with its usage added. No `.json`, so it is never read as a record.
87
+ */
88
+ export const SENT_TURN_PREFIX = 'sent-turn--';
64
89
  /** Prefix distinguishing usage-claim files from turn records in a session dir. */
65
90
  export const USAGE_CLAIM_PREFIX = 'usage-claim--';
66
91
  /**
@@ -230,12 +255,38 @@ export const TRANSCRIPT_CACHE_READ_TOKENS = 'cache_read_input_tokens';
230
255
  export const TRANSCRIPT_CACHE_CREATION_TOKENS = 'cache_creation_input_tokens';
231
256
  /** Codex rollout rows the usage reader needs; every other row is skipped unparsed. */
232
257
  export const CODEX_TOKEN_COUNT = 'token_count';
258
+ /** A Codex rollout's file name; a child thread's is one too, in the same day folders. */
259
+ export const RE_CODEX_ROLLOUT = /^rollout-.+-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/;
260
+ /** How many spawn levels a descendant is followed up; Codex reports `depth` 1 for a direct child. */
261
+ export const CODEX_MAX_SPAWN_DEPTH = 8;
262
+ /** How many day folders, back from today, a session's descendants are looked for in. */
263
+ export const CODEX_MAX_SCAN_DAYS = 7;
264
+ export const DAY_MS = 24 * 60 * 60 * 1000;
265
+ /** How much of a rollout's head to read for its `session_meta` line (about 20 KB, 2026-11). */
266
+ export const CODEX_META_HEAD_BYTES = 64 * 1024;
267
+ /** Gemini CLI 0.46 writes a subagent's chat to `chats/<parent session id>/<agent id>.jsonl`. */
268
+ export const RE_GEMINI_CHAT_FILE = /^[^/]+\.jsonl$/;
233
269
  export const CODEX_TURN_CONTEXT = 'turn_context';
234
270
  export const CODEX_LAST_TOKEN_USAGE = 'last_token_usage';
235
271
  export const CODEX_CACHED_INPUT_TOKENS = 'cached_input_tokens';
236
272
  /** Gemini CLI chat-file row type that carries a model reply, and its usage block. */
237
273
  export const GEMINI_REPLY_TYPE = 'gemini';
238
274
  export const GEMINI_TOKENS = 'tokens';
275
+ /**
276
+ * Antigravity transcript (`brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`)
277
+ * model-step fields. Its counts are disjoint: `input_tokens` excludes
278
+ * `cache_read_tokens` (an 11-04 IDE transcript's input drops 16896 -> 3374 as
279
+ * 14865 cache reads appear), so they map onto the Anthropic-style fields as is.
280
+ */
281
+ export const ANTIGRAVITY_MODEL_SOURCE = 'MODEL';
282
+ export const ANTIGRAVITY_INPUT_TOKENS = 'input_tokens';
283
+ export const ANTIGRAVITY_OUTPUT_TOKENS = 'output_tokens';
284
+ export const ANTIGRAVITY_CACHE_READ_TOKENS = 'cache_read_tokens';
285
+ /** The count fields; a transcript line with none of them is skipped unparsed. */
286
+ export const ANTIGRAVITY_COUNT_FIELDS = [ANTIGRAVITY_INPUT_TOKENS, ANTIGRAVITY_OUTPUT_TOKENS, ANTIGRAVITY_CACHE_READ_TOKENS];
287
+ export const ANTIGRAVITY_STEP_ID_PREFIX = 'step-';
288
+ /** Antigravity's `created_at` has whole-second precision. */
289
+ export const ANTIGRAVITY_TIMESTAMP_RESOLUTION_MS = 1000;
239
290
  /** Every transcript token field, for weighting which model dominated a turn. */
240
291
  export const TRANSCRIPT_TOKEN_FIELDS = [
241
292
  TRANSCRIPT_INPUT_TOKENS,
@@ -1,4 +1,4 @@
1
- import type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
1
+ import type { ReadTurnUsageRetry, SubagentTurn, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
2
2
  /**
3
3
  * Per-turn token usage from a Gemini CLI chat file
4
4
  * (`~/.gemini/tmp/<project>/chats/session-*.jsonl`).
@@ -28,6 +28,22 @@ import type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './type
28
28
  * @returns The turn's usage, or undefined when the file reports none.
29
29
  */
30
30
  export declare function readGeminiTurnUsage(transcriptPath: string, sinceIso: string, retry?: ReadTurnUsageRetry, untilIso?: string, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
31
+ /**
32
+ * The usage of the session's subagents inside the turn's window, out of their
33
+ * own chat files.
34
+ *
35
+ * Gemini CLI 0.46 writes a subagent's chat to `chats/<session id>/<agent
36
+ * id>.jsonl`, beside the session's own chat file, and fires no hook for it. Its
37
+ * rows carry no prompt id, so they join the turn by window, read the way the
38
+ * session's own file is. Not seen on a real machine yet (2026-11): written from
39
+ * the 0.46 source layout and checked against a fixture. Never throws.
40
+ *
41
+ * @param payload - The raw hook payload, naming the session's chat file and id.
42
+ * @param turn - The turn's window.
43
+ * @param excludeMessageIds - Replies already claimed.
44
+ * @returns The subagents' usage in the window, or undefined when there is none.
45
+ */
46
+ export declare function readGeminiSubagentUsage(payload: unknown, turn: SubagentTurn, excludeMessageIds: ReadonlySet<string>): Promise<TurnUsage | undefined>;
31
47
  /**
32
48
  * The usage one chat-file record carries, when it is a reply with `tokens`.
33
49
  *
@@ -1,7 +1,8 @@
1
+ import path from 'node:path';
1
2
  import { asRecord, firstStringOf } from '../core/object.js';
2
3
  import { finiteOrZero } from '../core/number.js';
3
- import { accumulateUsage, parseJsonLine, readUntilSettled, readWindowedTail } from './transcript.js';
4
- import { GEMINI_REPLY_TYPE, GEMINI_TOKENS, TRANSCRIPT_CACHE_READ_TOKENS, TRANSCRIPT_INPUT_TOKENS, TRANSCRIPT_OUTPUT_TOKENS } from './constants/turns.constants.js';
4
+ import { accumulateUsage, filesWrittenSince, mergeUsage, parseJsonLine, readUntilSettled, readWindowedTail } from './transcript.js';
5
+ import { RE_GEMINI_CHAT_FILE, TRANSCRIPT_PATH_KEY, GEMINI_REPLY_TYPE, GEMINI_TOKENS, TRANSCRIPT_CACHE_READ_TOKENS, TRANSCRIPT_INPUT_TOKENS, TRANSCRIPT_OUTPUT_TOKENS } from './constants/turns.constants.js';
5
6
  /**
6
7
  * Per-turn token usage from a Gemini CLI chat file
7
8
  * (`~/.gemini/tmp/<project>/chats/session-*.jsonl`).
@@ -65,6 +66,39 @@ async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
65
66
  }
66
67
  return accumulateUsage(byId);
67
68
  }
69
+ /**
70
+ * The usage of the session's subagents inside the turn's window, out of their
71
+ * own chat files.
72
+ *
73
+ * Gemini CLI 0.46 writes a subagent's chat to `chats/<session id>/<agent
74
+ * id>.jsonl`, beside the session's own chat file, and fires no hook for it. Its
75
+ * rows carry no prompt id, so they join the turn by window, read the way the
76
+ * session's own file is. Not seen on a real machine yet (2026-11): written from
77
+ * the 0.46 source layout and checked against a fixture. Never throws.
78
+ *
79
+ * @param payload - The raw hook payload, naming the session's chat file and id.
80
+ * @param turn - The turn's window.
81
+ * @param excludeMessageIds - Replies already claimed.
82
+ * @returns The subagents' usage in the window, or undefined when there is none.
83
+ */
84
+ export async function readGeminiSubagentUsage(payload, turn, excludeMessageIds) {
85
+ const record = asRecord(payload);
86
+ const transcriptPath = record?.[TRANSCRIPT_PATH_KEY];
87
+ const sessionId = record?.['session_id'];
88
+ // The session id becomes a folder name: one path segment, nothing more.
89
+ if (typeof transcriptPath !== 'string' || typeof sessionId !== 'string' || !sessionId || path.basename(sessionId) !== sessionId || sessionId.startsWith('.'))
90
+ return undefined;
91
+ try {
92
+ let usage;
93
+ for (const file of await filesWrittenSince(path.join(path.dirname(transcriptPath), sessionId), RE_GEMINI_CHAT_FILE, Date.parse(turn.startedAt))) {
94
+ usage = mergeUsage(usage, await readOnce(file, turn.startedAt, turn.untilIso, excludeMessageIds));
95
+ }
96
+ return usage;
97
+ }
98
+ catch {
99
+ return undefined;
100
+ }
101
+ }
68
102
  /**
69
103
  * The usage one chat-file record carries, when it is a reply with `tokens`.
70
104
  *