@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,19 +1,13 @@
1
1
  import { z } from 'zod';
2
2
  /**
3
- * Antigravity hook payloads.
3
+ * Antigravity hook payloads, in the nested shape.
4
4
  *
5
- * The payload is protojson of `exa.hooks_pb.HookArgs`
6
- * (`third_party/jetski/hooks_pb/hooks.proto`, read off the `agy` binary), and it
7
- * differs from every other agent we support in two ways that no amount of field
8
- * renaming can paper over:
9
- *
10
- * - There is no event-name field. `HookArgs` is a `common` block plus a oneof,
11
- * and the event is whichever member of that oneof is set. Reading a
12
- * `hookEventName` — a field that exists in no version of this schema — is how
13
- * this provider previously produced `agent.other` with no session id for every
14
- * hook, which the turn tracker then discarded.
15
- * - Identity is nested in `common`, and tool arguments are PascalCase
16
- * (`TargetFile`, `CommandLine`) rather than the snake_case used elsewhere.
5
+ * Older builds send protojson of `exa.hooks_pb.HookArgs`
6
+ * (`third_party/jetski/hooks_pb/hooks.proto`, read off the `agy` binary): a
7
+ * `common` block plus a oneof, the event being whichever member is set, with no
8
+ * event-name field. agy 1.5.0 sends a flat object with `hookEventName` instead;
9
+ * the adapter lifts that into this shape before parsing, so one schema serves
10
+ * both. Tool arguments are PascalCase (`TargetFile`, `CommandLine`) in both.
17
11
  */
18
12
  /** proto3 JSON encodes int32 as a number and int64 as a string. */
19
13
  const protoInt = z.union([z.number(), z.string()]).optional();
@@ -48,7 +48,7 @@ export declare class ClaudeOtelConfigurator implements NativeTelemetryConfigurat
48
48
  node: string;
49
49
  python: string;
50
50
  });
51
- /** Run capture rides in the same env block, and comes and goes with the exporters. */
51
+ /** Run capture rides in the same env block, on its own switch (`capture.runs`), not the exporters'. */
52
52
  readonly runCapture: {
53
53
  configPath: typeof claudeSettingsPath;
54
54
  inspect: (context: SetupContext) => Promise<import("../types/provider.types.js").RunCaptureStatus>;
@@ -94,6 +94,14 @@ export declare class ClaudeOtelConfigurator implements NativeTelemetryConfigurat
94
94
  * install state.
95
95
  */
96
96
  uninstall(context: SetupContext): Promise<SetupOutcome>;
97
+ /**
98
+ * Uninstall's work, optionally leaving run capture's part of the env block.
99
+ *
100
+ * @param context - Environment, paths, config and install state.
101
+ * @param keepCapture - Leave run capture in: `otel: none` with `capture.runs` on.
102
+ * @returns As `uninstall`.
103
+ */
104
+ private removeTelemetry;
97
105
  /**
98
106
  * Where the exporter setup recorded as AgentWatch's sends. Nothing without
99
107
  * that record: the endpoint may then be the developer's own.
@@ -109,6 +117,30 @@ export declare class ClaudeOtelConfigurator implements NativeTelemetryConfigurat
109
117
  * @returns The outcome.
110
118
  */
111
119
  private configureDisabled;
120
+ /**
121
+ * The env block with run capture in or out, as `capture.runs` says.
122
+ *
123
+ * @param envBlock - The env block as it stands.
124
+ * @param context - Environment, paths and config.
125
+ * @returns The next env block.
126
+ */
127
+ private capturedEnv;
128
+ /**
129
+ * Run capture alone, as a step that says rather than throws when it cannot write: an
130
+ * optional key must never fail setup or `agentwatch on` (`withCaptureOutcome`).
131
+ *
132
+ * @param context - Environment, paths and config.
133
+ * @returns Whether the file changed, and what to tell the user.
134
+ */
135
+ private captureOnly;
136
+ /**
137
+ * Write run capture alone, in or out as `capture.runs` says, when the exporters are
138
+ * off or skipped over a conflict.
139
+ *
140
+ * @param context - Environment, paths and config.
141
+ * @returns Whether the file changed; an unreadable or non-object file is left alone.
142
+ */
143
+ private writeCaptureOnly;
112
144
  /**
113
145
  * Add the header-helper command when a token needs one.
114
146
  *
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
- import { copiedShims, inspectCaptureEnv, installedCaptureEnv, removeCaptureCopy, shimPaths, withoutCaptureEnv } from '../../capture/capture-env.js';
2
+ import { copiedShims, inspectCaptureEnv, installedCaptureEnv, removeCaptureCopy, shimPaths, skippedOnError, withoutCaptureEnv } from '../../capture/capture-env.js';
3
3
  import { asRecord, omitKeys } from '../../core/object.js';
4
- import { enabledSignalNames, otelEnabled, otlpBaseUrl } from '../../config/config.js';
4
+ import { enabledSignalNames, otelEnabled, otlpBaseUrl, runCaptureEnabled } from '../../config/config.js';
5
5
  import { isAgentWatchEndpoint } from '../../config/schemas/config.schema.js';
6
6
  import { backupFile } from '../../storage/atomic-file.js';
7
7
  import { hasCredential } from '../../credentials/identity.js';
@@ -116,13 +116,13 @@ export class ClaudeOtelConfigurator {
116
116
  constructor(captureSource = shimPaths()) {
117
117
  this.captureSource = captureSource;
118
118
  }
119
- /** Run capture rides in the same env block, and comes and goes with the exporters. */
119
+ /** Run capture rides in the same env block, on its own switch (`capture.runs`), not the exporters'. */
120
120
  runCapture = {
121
121
  configPath: claudeSettingsPath,
122
122
  inspect: async (context) => {
123
123
  const read = await readJsonFile(claudeSettingsPath(context.env));
124
124
  const block = asRecord(read.state === 'ok' ? asRecord(read.value)?.[ENV_BLOCK_KEY] : undefined) ?? {};
125
- return inspectCaptureEnv(block, context.config, otelEnabled(context.config), context.paths.dataDir, this.captureSource);
125
+ return inspectCaptureEnv(block, context.config, runCaptureEnabled(context.config), context.paths.dataDir, this.captureSource);
126
126
  }
127
127
  };
128
128
  /**
@@ -195,11 +195,13 @@ export class ClaudeOtelConfigurator {
195
195
  const ownedKeys = this.ownedKeys(context);
196
196
  const conflicting = foreignKeys(envBlock, desired, ownedKeys, context);
197
197
  if (conflicting.length > 0) {
198
+ // The developer's own exporter skips ours, never the capture switch.
199
+ const capture = await this.captureOnly(context);
198
200
  return {
199
201
  ok: false,
200
- changed: false,
202
+ changed: capture.changed,
201
203
  conflict: true,
202
- messages: [`skipping native OpenTelemetry: ${conflicting.join(', ')} already set in ${settingsPath} (not AgentWatch-owned)`]
204
+ messages: [`skipping native OpenTelemetry: ${conflicting.join(', ')} already set in ${settingsPath} (not AgentWatch-owned)`, ...capture.messages]
203
205
  };
204
206
  }
205
207
  // Signals disabled since the previous run leave stale AgentWatch-owned keys
@@ -208,10 +210,11 @@ export class ClaudeOtelConfigurator {
208
210
  const previous = otelPriorValuesOf(context.installState, CLAUDE_PROVIDER_ID);
209
211
  const stale = new Set(ownedKeys.filter((key) => key !== HEADERS_HELPER_KEY && desired[key] === undefined));
210
212
  // Merged, never recorded as owned: uninstall takes our part of these two, not the keys.
211
- const withEnv = { ...settings, [ENV_BLOCK_KEY]: { ...withRestored(await installedCaptureEnv(envBlock, context.env.vars, context.paths.dataDir, this.captureSource), stale, restoredEnv(previous, stale)), ...desired } };
213
+ const withEnv = { ...settings, [ENV_BLOCK_KEY]: { ...withRestored(await this.capturedEnv(envBlock, context), stale, restoredEnv(previous, stale)), ...desired } };
212
214
  const helper = this.applyHeadersHelper(withEnv, context);
213
215
  if ('conflict' in helper) {
214
- return { ok: false, changed: false, conflict: true, messages: [helper.conflict] };
216
+ const capture = await this.captureOnly(context);
217
+ return { ok: false, changed: capture.changed, conflict: true, messages: [helper.conflict, ...capture.messages] };
215
218
  }
216
219
  const changed = JSON.stringify(helper.settings) !== JSON.stringify(settings);
217
220
  if (changed) {
@@ -246,6 +249,16 @@ export class ClaudeOtelConfigurator {
246
249
  * install state.
247
250
  */
248
251
  async uninstall(context) {
252
+ return this.removeTelemetry(context, false);
253
+ }
254
+ /**
255
+ * Uninstall's work, optionally leaving run capture's part of the env block.
256
+ *
257
+ * @param context - Environment, paths, config and install state.
258
+ * @param keepCapture - Leave run capture in: `otel: none` with `capture.runs` on.
259
+ * @returns As `uninstall`.
260
+ */
261
+ async removeTelemetry(context, keepCapture) {
249
262
  const settingsPath = claudeSettingsPath(context.env);
250
263
  const read = await readJsonFile(settingsPath);
251
264
  if (read.state === 'missing') {
@@ -258,7 +271,7 @@ export class ClaudeOtelConfigurator {
258
271
  const envBlock = asRecord(settings[ENV_BLOCK_KEY]);
259
272
  const { removable, kept, reason } = removableEnvKeys(envBlock ?? {}, this.ownedKeys(context), context);
260
273
  const restored = restoredEnv(otelPriorValuesOf(context.installState, CLAUDE_PROVIDER_ID), removable);
261
- const next = strippedSettings(settings, envBlock && withoutCaptureEnv(envBlock, copiedShims(context.paths.dataDir)), restored, removable, isOurHelper(settings[HEADERS_HELPER_KEY]));
274
+ const next = strippedSettings(settings, envBlock && (keepCapture ? envBlock : withoutCaptureEnv(envBlock, copiedShims(context.paths.dataDir))), restored, removable, isOurHelper(settings[HEADERS_HELPER_KEY]));
262
275
  const changed = JSON.stringify(next) !== JSON.stringify(settings);
263
276
  const left = keptMessages(kept, reason, settingsPath);
264
277
  if (changed) {
@@ -297,22 +310,78 @@ export class ClaudeOtelConfigurator {
297
310
  return { ok: false, changed: false, messages: ['no backend endpoint configured'] };
298
311
  // Deliberately off: the desired state is "no AgentWatch telemetry", which
299
312
  // means removing whatever a previous setup left behind.
300
- const removed = await this.uninstall(context);
313
+ // Capture is not telemetry: its calls go out as events, so `otel: none` leaves it on.
314
+ const keepCapture = runCaptureEnabled(context.config);
315
+ const removed = await this.removeTelemetry(context, keepCapture);
301
316
  if (!removed.ok)
302
317
  return removed;
318
+ const capture = keepCapture ? await this.captureOnly(context) : undefined;
303
319
  return {
304
320
  ok: true,
305
- changed: removed.changed,
321
+ changed: removed.changed || capture?.changed === true,
306
322
  messages: [
307
323
  removed.changed
308
324
  ? 'native OpenTelemetry disabled in config; previous configuration removed'
309
325
  : 'native OpenTelemetry disabled in config (otel: none)',
310
326
  // Past uninstall's own headline: the keys it left and why.
311
- ...removed.messages.slice(1)
327
+ ...removed.messages.slice(1),
328
+ ...(capture?.messages ?? [])
312
329
  ],
313
330
  installState: removed.installState
314
331
  };
315
332
  }
333
+ /**
334
+ * The env block with run capture in or out, as `capture.runs` says.
335
+ *
336
+ * @param envBlock - The env block as it stands.
337
+ * @param context - Environment, paths and config.
338
+ * @returns The next env block.
339
+ */
340
+ async capturedEnv(envBlock, context) {
341
+ if (!runCaptureEnabled(context.config))
342
+ return withoutCaptureEnv(envBlock, copiedShims(context.paths.dataDir));
343
+ return installedCaptureEnv(envBlock, context.env.vars, context.paths.dataDir, this.captureSource);
344
+ }
345
+ /**
346
+ * Run capture alone, as a step that says rather than throws when it cannot write: an
347
+ * optional key must never fail setup or `agentwatch on` (`withCaptureOutcome`).
348
+ *
349
+ * @param context - Environment, paths and config.
350
+ * @returns Whether the file changed, and what to tell the user.
351
+ */
352
+ captureOnly(context) {
353
+ const step = this.writeCaptureOnly(context).then((changed) => ({
354
+ ok: true,
355
+ changed,
356
+ messages: changed ? [`run capture ${runCaptureEnabled(context.config) ? 'configured' : 'removed'} (capture.runs); restart running Claude Code sessions to pick it up`] : []
357
+ }));
358
+ return skippedOnError(step);
359
+ }
360
+ /**
361
+ * Write run capture alone, in or out as `capture.runs` says, when the exporters are
362
+ * off or skipped over a conflict.
363
+ *
364
+ * @param context - Environment, paths and config.
365
+ * @returns Whether the file changed; an unreadable or non-object file is left alone.
366
+ */
367
+ async writeCaptureOnly(context) {
368
+ const settingsPath = claudeSettingsPath(context.env);
369
+ const read = await readJsonFile(settingsPath);
370
+ if (read.state === 'invalid')
371
+ return false;
372
+ const settings = read.state === 'ok' ? asRecord(read.value) : {};
373
+ if (!settings)
374
+ return false;
375
+ const envBlock = asRecord(settings[ENV_BLOCK_KEY]) ?? {};
376
+ const nextEnv = await this.capturedEnv(envBlock, context);
377
+ // Compared on the block, so a file with nothing to add never gains an empty `env`.
378
+ if (JSON.stringify(nextEnv) === JSON.stringify(envBlock))
379
+ return false;
380
+ const next = { ...settings, [ENV_BLOCK_KEY]: nextEnv };
381
+ await backupFile(settingsPath, context.paths.backupsDir, context.env.now());
382
+ await writeJsonValidated(settingsPath, next);
383
+ return true;
384
+ }
316
385
  /**
317
386
  * Add the header-helper command when a token needs one.
318
387
  *
@@ -1,7 +1,7 @@
1
1
  import { claudeBillingMode } from '../../billing/billing-mode.js';
2
2
  import { asRecord, firstStringOf } from '../../core/object.js';
3
3
  import { hookNotice, hookRefusal } from '../shared/hook-refusal.js';
4
- import { readClaudeSessionTitles, readTurnUsage } from '../../turns/claude-transcript.js';
4
+ import { readClaudeSessionTitles, readClaudeSubagentTurnIds, readClaudeSubagentUsage, readTurnUsage } from '../../turns/claude-transcript.js';
5
5
  import { CLAUDE_DETACHED_EVENTS, CLAUDE_ENTRYPOINT_VAR, CLAUDE_INTERACTIVE_ENTRYPOINTS, CLAUDE_PROMPT_SUBMIT_EVENTS } from './constants/claude.constants.js';
6
6
  import { detectClaude } from './claude.detect.js';
7
7
  import { installClaudeHooks, uninstallClaudeHooks } from './claude.hooks.js';
@@ -41,6 +41,8 @@ export const claudeProvider = {
41
41
  },
42
42
  shellCall: claudeShellCall,
43
43
  readTurnUsage,
44
+ readSubagentUsage: readClaudeSubagentUsage,
45
+ readSubagentTurnIds: readClaudeSubagentTurnIds,
44
46
  billingMode: claudeBillingMode,
45
47
  readTranscriptTitles: readClaudeSessionTitles,
46
48
  /** Claude Code names its own entrypoint (`cli`, `claude-vscode`, `sdk-ts`, ...). */
@@ -63,7 +63,7 @@ export declare function filteredCaptureKeys(policy: UnknownRecord): {
63
63
  /**
64
64
  * Whether what Codex's shell tool starts loads the shims, and when not, why.
65
65
  *
66
- * Gated on `otel` as Claude Code's is, not on the tool-content consent that holds Codex's
66
+ * Gated on `capture.runs` as every route is, not on `otel` or the tool-content consent that holds Codex's
67
67
  * own export back: a captured call is usage only, it carries no tool content.
68
68
  *
69
69
  * @param context - Environment, paths and config.
@@ -4,7 +4,7 @@ import { isDeepStrictEqual } from 'node:util';
4
4
  import { parse as parseToml, stringify as stringifyToml } from 'smol-toml';
5
5
  import { copiedShims, inspectCaptureEnv, installedCaptureEnv, isLinkedConfig, linkedConfigReason, removeCaptureCopy, shimPaths, withoutCaptureEnv } from '../../capture/capture-env.js';
6
6
  import { RUN_CAPTURE_ENV_NODE, RUN_CAPTURE_ENV_PYTHON, SPOOL_DIR_NAME } from '../../capture/constants/capture.constants.js';
7
- import { otelEnabled } from '../../config/config.js';
7
+ import { runCaptureEnabled } from '../../config/config.js';
8
8
  import { asRecord } from '../../core/object.js';
9
9
  import { backupFile, currentMode, writeFileAtomic, writeIfUnchanged } from '../../storage/atomic-file.js';
10
10
  import { SECRET_FILE_MODE } from '../../storage/constants/storage.constants.js';
@@ -386,7 +386,7 @@ export function filteredCaptureKeys(policy) {
386
386
  /**
387
387
  * Whether what Codex's shell tool starts loads the shims, and when not, why.
388
388
  *
389
- * Gated on `otel` as Claude Code's is, not on the tool-content consent that holds Codex's
389
+ * Gated on `capture.runs` as every route is, not on `otel` or the tool-content consent that holds Codex's
390
390
  * own export back: a captured call is usage only, it carries no tool content.
391
391
  *
392
392
  * @param context - Environment, paths and config.
@@ -399,7 +399,7 @@ export async function inspectCodexCapture(context, source = shimPaths()) {
399
399
  const parsed = raw ? tryParse(raw) : {};
400
400
  if (raw === null || parsed === undefined)
401
401
  return { on: false, reason: `${file} cannot be read as TOML` };
402
- const status = await inspectCaptureEnv(setBlock(parsed), context.config, otelEnabled(context.config), context.paths.dataDir, source);
402
+ const status = await inspectCaptureEnv(setBlock(parsed), context.config, runCaptureEnabled(context.config), context.paths.dataDir, source);
403
403
  if (!status.on && (await isLinkedConfig(file)))
404
404
  return { on: false, reason: linkedConfigReason(file) };
405
405
  if (!status.on)
@@ -2,7 +2,7 @@ import fs from 'node:fs/promises';
2
2
  import { parse as parseToml } from 'smol-toml';
3
3
  import { shimPaths, skippedOnError, withCaptureOutcome } from '../../capture/capture-env.js';
4
4
  import { asRecord } from '../../core/object.js';
5
- import { joinUrl, otelEnabled, otlpBaseUrl, toolContentConsented } from '../../config/config.js';
5
+ import { joinUrl, otlpBaseUrl, runCaptureEnabled, toolContentConsented } from '../../config/config.js';
6
6
  import { backupFile, currentMode, writeFileAtomic, writeIfUnchanged } from '../../storage/atomic-file.js';
7
7
  import { SECRET_FILE_MODE } from '../../storage/constants/storage.constants.js';
8
8
  import { deviceFor, hasCredential } from '../../credentials/identity.js';
@@ -86,7 +86,7 @@ export class CodexOtelConfigurator {
86
86
  */
87
87
  async configure(context) {
88
88
  const outcome = await this.configureExport(context);
89
- const capture = otelEnabled(context.config) ? await skippedOnError(applyCodexCapture(context, this.captureSource)) : await removeCodexCapture(context);
89
+ const capture = runCaptureEnabled(context.config) ? await skippedOnError(applyCodexCapture(context, this.captureSource)) : await removeCodexCapture(context);
90
90
  return withCaptureOutcome(outcome, capture);
91
91
  }
92
92
  /**
@@ -1,6 +1,6 @@
1
1
  import { codexBillingMode } from '../../billing/billing-mode.js';
2
2
  import { hookNotice, hookRefusal } from '../shared/hook-refusal.js';
3
- import { readCodexTurnUsage } from '../../turns/codex-transcript.js';
3
+ import { readCodexSubagentUsage, readCodexTurnUsage } from '../../turns/codex-transcript.js';
4
4
  import { CODEX_PROMPT_SUBMIT_EVENTS } from './constants/codex.constants.js';
5
5
  import { detectCodex } from './codex.detect.js';
6
6
  import { installCodexHooks, uninstallCodexHooks } from './codex.hooks.js';
@@ -29,6 +29,7 @@ export const codexProvider = {
29
29
  getNoticeResponse: (payload, message) => hookNotice(payload, message),
30
30
  shellCall: codexShellCall,
31
31
  readTurnUsage: readCodexTurnUsage,
32
+ readSubagentUsage: readCodexSubagentUsage,
32
33
  billingMode: codexBillingMode,
33
34
  readSessionTitles: readCodexSessionTitles,
34
35
  surface: codexSurface,
@@ -3,7 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { copiedShims, inspectCaptureEnv, installedCaptureEnv, isLinkedConfig, linkedConfigReason, removeCaptureCopy, shimPaths, withoutCaptureEnv } from '../../capture/capture-env.js';
5
5
  import { RUN_CAPTURE_ENV_NODE, RUN_CAPTURE_ENV_PYTHON } from '../../capture/constants/capture.constants.js';
6
- import { otelEnabled } from '../../config/config.js';
6
+ import { runCaptureEnabled } from '../../config/config.js';
7
7
  import { backupFile, writeFileAtomic } from '../../storage/atomic-file.js';
8
8
  import { GEMINI_ENV_FILE, GEMINI_HOME_DIR } from './constants/gemini.constants.js';
9
9
  import { RE_ENV_LINE } from './constants/gemini.otel.constants.js';
@@ -197,7 +197,7 @@ export async function inspectGeminiCapture(context, source = shimPaths()) {
197
197
  return { on: false, reason: `${file} cannot be read` };
198
198
  if (wouldHideHomeEnv(context, raw))
199
199
  return { on: false, reason: hidesHomeEnv(context, file) };
200
- const status = await inspectCaptureEnv(parseEnv(raw ?? ''), context.config, otelEnabled(context.config), context.paths.dataDir, source);
200
+ const status = await inspectCaptureEnv(parseEnv(raw ?? ''), context.config, runCaptureEnabled(context.config), context.paths.dataDir, source);
201
201
  if (!status.on)
202
202
  return (await isLinkedConfig(file)) ? { on: false, reason: linkedConfigReason(file) } : status;
203
203
  const shadow = shadowingEnvFile(context.env.cwd, file);
@@ -2,7 +2,7 @@ import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { shimPaths, skippedOnError, withCaptureOutcome } from '../../capture/capture-env.js';
4
4
  import { asRecord, omitKeys } from '../../core/object.js';
5
- import { enabledSignalNames, otelEnabled, otlpBaseUrl, toolContentConsented } from '../../config/config.js';
5
+ import { enabledSignalNames, otlpBaseUrl, runCaptureEnabled, toolContentConsented } from '../../config/config.js';
6
6
  import { INSTALLATION_HEADER } from '../../transport/constants/transport.constants.js';
7
7
  import { backupFile, currentMode, writeFileAtomic, writeIfUnchanged } from '../../storage/atomic-file.js';
8
8
  import { SECRET_FILE_MODE } from '../../storage/constants/storage.constants.js';
@@ -204,7 +204,7 @@ export class GeminiOtelConfigurator {
204
204
  */
205
205
  async configure(context) {
206
206
  const outcome = await this.configureExport(context);
207
- const capture = otelEnabled(context.config) ? await skippedOnError(applyGeminiCapture(context, this.captureSource)) : await removeGeminiCapture(context);
207
+ const capture = runCaptureEnabled(context.config) ? await skippedOnError(applyGeminiCapture(context, this.captureSource)) : await removeGeminiCapture(context);
208
208
  return withCaptureOutcome(outcome, capture);
209
209
  }
210
210
  /**
@@ -1,6 +1,6 @@
1
1
  import { googleAccountBillingMode } from '../../billing/billing-mode.js';
2
2
  import { hookRefusal } from '../shared/hook-refusal.js';
3
- import { readGeminiTurnUsage } from '../../turns/gemini-transcript.js';
3
+ import { readGeminiSubagentUsage, readGeminiTurnUsage } from '../../turns/gemini-transcript.js';
4
4
  import { GEMINI_PROMPT_EVENTS } from './constants/gemini.constants.js';
5
5
  import { detectGemini } from './gemini.detect.js';
6
6
  import { installGeminiHooks, uninstallGeminiHooks } from './gemini.hooks.js';
@@ -22,6 +22,7 @@ export const geminiProvider = {
22
22
  getBlockResponse: (payload, message) => hookRefusal(payload, GEMINI_PROMPT_EVENTS, { decision: 'deny', reason: message }),
23
23
  shellCall: geminiShellCall,
24
24
  readTurnUsage: readGeminiTurnUsage,
25
+ readSubagentUsage: readGeminiSubagentUsage,
25
26
  /** Signed in through the shared `~/.gemini` Google account, as Antigravity is. */
26
27
  billingMode: googleAccountBillingMode,
27
28
  nativeTelemetry: new GeminiOtelConfigurator()
@@ -2,7 +2,7 @@ import fs from 'node:fs/promises';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { copiedShims, inspectCaptureEnv, installedCaptureEnv, removeCaptureCopy, shimPaths, skippedOnError, withCaptureOutcome, withoutCaptureEnv } from '../../capture/capture-env.js';
5
- import { otelEnabled } from '../../config/config.js';
5
+ import { runCaptureEnabled } from '../../config/config.js';
6
6
  import { asRecord, omitKeys } from '../../core/object.js';
7
7
  import { backupFile } from '../../storage/atomic-file.js';
8
8
  import { readJsonFile } from '../../storage/json-file.js';
@@ -97,12 +97,12 @@ export function terminalCapture(app, verified, source = shimPaths()) {
97
97
  if (read.state === 'invalid')
98
98
  return { on: false, reason: `${file} is not plain JSON, so Edge cannot edit it` };
99
99
  const block = asRecord(asRecord(read.state === 'ok' ? read.value : undefined)?.[terminalEnvKey(context.env)]) ?? {};
100
- return inspectCaptureEnv(block, context.config, otelEnabled(context.config), context.paths.dataDir, source);
100
+ return inspectCaptureEnv(block, context.config, runCaptureEnabled(context.config), context.paths.dataDir, source);
101
101
  }
102
102
  },
103
103
  install: (inner) => async (context) => {
104
104
  const outcome = await inner(context);
105
- return withCaptureOutcome(outcome, await (verified && otelEnabled(context.config) ? skippedOnError(apply(context)) : remove(context)));
105
+ return withCaptureOutcome(outcome, await (verified && runCaptureEnabled(context.config) ? skippedOnError(apply(context)) : remove(context)));
106
106
  },
107
107
  uninstall: (inner) => async (context) => withCaptureOutcome(await inner(context), await remove(context))
108
108
  };
@@ -0,0 +1,40 @@
1
+ import type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
2
+ /**
3
+ * Per-turn token usage from an Antigravity transcript
4
+ * (`<app dir>/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`).
5
+ *
6
+ * Antigravity has no OTel export and no usage API, so this file is its only
7
+ * money source. One line per step; model steps (`source: "MODEL"`) carry
8
+ * `step_index`, `created_at`, `model`, `input_tokens`, `cache_read_tokens` and
9
+ * `output_tokens` (agy 1.5.0). Only those fields are read; content, thinking
10
+ * and tool calls are never looked at, so nothing a developer wrote leaves here.
11
+ *
12
+ * Older builds wrote the tokens without `model` (the summary then keeps the
13
+ * hook's model), and older still no tokens at all: a step without any count is
14
+ * skipped, so such a turn stays `pending` rather than reporting zero.
15
+ *
16
+ * Exactly once: each step is claimed by its `step_index`, unique within the
17
+ * conversation, through the tracker's claim ledger under the session usage lock.
18
+ *
19
+ * ponytail: `created_at` is whole seconds, so the lower bound is floored to the
20
+ * second, or a step written in the prompt's own second would be missed. An
21
+ * unclaimed step of the previous turn from that same second can join this one;
22
+ * claimed steps never do. The upper bound stays exact: a racing next prompt's
23
+ * step stamped in that prompt's own second goes to this turn (still once).
24
+ * Same 4 MiB tail ceiling as the other readers.
25
+ *
26
+ * @param transcriptPath - The transcript the hook named, or the brain-directory fallback.
27
+ * @param sinceIso - When the turn started.
28
+ * @param retry - How long to wait for the transcript flush to settle.
29
+ * @param untilIso - Upper bound, keeping a racing next prompt's steps out.
30
+ * @param excludeMessageIds - Steps another turn already claimed.
31
+ * @returns The turn's usage, or undefined when the transcript reports none.
32
+ */
33
+ export declare function readAntigravityTurnUsage(transcriptPath: string, sinceIso: string, retry?: ReadTurnUsageRetry, untilIso?: string, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
34
+ /**
35
+ * The usage one transcript step carries, when it is a model step with counts.
36
+ *
37
+ * @param row - One parsed transcript line.
38
+ * @returns The step's model and counts under the transcript field names, or undefined.
39
+ */
40
+ export declare function antigravityStepUsage(row: Readonly<Record<string, unknown>>): TranscriptUsageEntry | undefined;
@@ -0,0 +1,102 @@
1
+ import { firstStringOf } from '../core/object.js';
2
+ import { accumulateUsage, messageIdFor, parseJsonLine, readUntilSettled, readWindowedTail } from './transcript.js';
3
+ import { ANTIGRAVITY_CACHE_READ_TOKENS, ANTIGRAVITY_COUNT_FIELDS, ANTIGRAVITY_INPUT_TOKENS, ANTIGRAVITY_MODEL_SOURCE, ANTIGRAVITY_OUTPUT_TOKENS, ANTIGRAVITY_STEP_ID_PREFIX, ANTIGRAVITY_TIMESTAMP_RESOLUTION_MS, TRANSCRIPT_CACHE_READ_TOKENS, TRANSCRIPT_INPUT_TOKENS, TRANSCRIPT_OUTPUT_TOKENS } from './constants/turns.constants.js';
4
+ /**
5
+ * Per-turn token usage from an Antigravity transcript
6
+ * (`<app dir>/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`).
7
+ *
8
+ * Antigravity has no OTel export and no usage API, so this file is its only
9
+ * money source. One line per step; model steps (`source: "MODEL"`) carry
10
+ * `step_index`, `created_at`, `model`, `input_tokens`, `cache_read_tokens` and
11
+ * `output_tokens` (agy 1.5.0). Only those fields are read; content, thinking
12
+ * and tool calls are never looked at, so nothing a developer wrote leaves here.
13
+ *
14
+ * Older builds wrote the tokens without `model` (the summary then keeps the
15
+ * hook's model), and older still no tokens at all: a step without any count is
16
+ * skipped, so such a turn stays `pending` rather than reporting zero.
17
+ *
18
+ * Exactly once: each step is claimed by its `step_index`, unique within the
19
+ * conversation, through the tracker's claim ledger under the session usage lock.
20
+ *
21
+ * ponytail: `created_at` is whole seconds, so the lower bound is floored to the
22
+ * second, or a step written in the prompt's own second would be missed. An
23
+ * unclaimed step of the previous turn from that same second can join this one;
24
+ * claimed steps never do. The upper bound stays exact: a racing next prompt's
25
+ * step stamped in that prompt's own second goes to this turn (still once).
26
+ * Same 4 MiB tail ceiling as the other readers.
27
+ *
28
+ * @param transcriptPath - The transcript the hook named, or the brain-directory fallback.
29
+ * @param sinceIso - When the turn started.
30
+ * @param retry - How long to wait for the transcript flush to settle.
31
+ * @param untilIso - Upper bound, keeping a racing next prompt's steps out.
32
+ * @param excludeMessageIds - Steps another turn already claimed.
33
+ * @returns The turn's usage, or undefined when the transcript reports none.
34
+ */
35
+ export async function readAntigravityTurnUsage(transcriptPath, sinceIso, retry, untilIso, excludeMessageIds) {
36
+ return readUntilSettled(() => readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds), retry);
37
+ }
38
+ /**
39
+ * One pass over the transcript tail.
40
+ *
41
+ * @param transcriptPath - Transcript file.
42
+ * @param sinceIso - Lower bound of the turn's window.
43
+ * @param untilIso - Upper bound, or undefined for "no upper bound".
44
+ * @param excludeMessageIds - Steps another turn already claimed.
45
+ * @returns The usage found in this pass.
46
+ */
47
+ async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
48
+ const tail = await readWindowedTail(transcriptPath, sinceIso, untilIso);
49
+ if (tail === undefined)
50
+ return undefined;
51
+ const { raw, until } = tail;
52
+ const since = Math.floor(tail.since / ANTIGRAVITY_TIMESTAMP_RESOLUTION_MS) * ANTIGRAVITY_TIMESTAMP_RESOLUTION_MS;
53
+ const byStep = new Map();
54
+ for (const line of raw.split('\n')) {
55
+ // Cheap prefilter: user, tool and system steps carry no counts.
56
+ if (!ANTIGRAVITY_COUNT_FIELDS.some((field) => line.includes(`"${field}"`)))
57
+ continue;
58
+ const row = parseJsonLine(line);
59
+ const entry = row ? antigravityStepUsage(row) : undefined;
60
+ const timestamp = typeof row?.['created_at'] === 'string' ? Date.parse(row['created_at']) : NaN;
61
+ if (!row || !entry || Number.isNaN(timestamp) || timestamp < since || timestamp > until)
62
+ continue;
63
+ const step = row['step_index'];
64
+ const id = Number.isInteger(step) ? `${ANTIGRAVITY_STEP_ID_PREFIX}${String(step)}` : messageIdFor(undefined, line);
65
+ if (excludeMessageIds?.has(id))
66
+ continue;
67
+ byStep.set(id, entry);
68
+ }
69
+ return accumulateUsage(byStep);
70
+ }
71
+ /**
72
+ * The usage one transcript step carries, when it is a model step with counts.
73
+ *
74
+ * @param row - One parsed transcript line.
75
+ * @returns The step's model and counts under the transcript field names, or undefined.
76
+ */
77
+ export function antigravityStepUsage(row) {
78
+ if (row['source'] !== ANTIGRAVITY_MODEL_SOURCE)
79
+ return undefined;
80
+ const input = finiteOrUndefined(row[ANTIGRAVITY_INPUT_TOKENS]);
81
+ const output = finiteOrUndefined(row[ANTIGRAVITY_OUTPUT_TOKENS]);
82
+ const cacheRead = finiteOrUndefined(row[ANTIGRAVITY_CACHE_READ_TOKENS]);
83
+ if (input === undefined && output === undefined && cacheRead === undefined)
84
+ return undefined;
85
+ return {
86
+ model: firstStringOf(row['model']),
87
+ usage: {
88
+ [TRANSCRIPT_INPUT_TOKENS]: input,
89
+ [TRANSCRIPT_OUTPUT_TOKENS]: output,
90
+ [TRANSCRIPT_CACHE_READ_TOKENS]: cacheRead
91
+ }
92
+ };
93
+ }
94
+ /**
95
+ * A count as a number, or undefined when it is missing or not a finite number.
96
+ *
97
+ * @param value - Candidate count.
98
+ * @returns The finite number, or undefined.
99
+ */
100
+ function finiteOrUndefined(value) {
101
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
102
+ }
@@ -1,4 +1,4 @@
1
- import type { ReadTurnUsageRetry, SessionTitles, TurnUsage } from './types/transcript.types.js';
1
+ import type { ReadTurnUsageRetry, SessionTitles, SubagentTurn, TurnUsage } from './types/transcript.types.js';
2
2
  export type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
3
3
  /**
4
4
  * Authoritative per-turn token usage from Claude Code's transcript JSONL.
@@ -16,6 +16,40 @@ export type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './type
16
16
  * @returns The turn's usage, or undefined when the transcript reports none.
17
17
  */
18
18
  export declare function readTurnUsage(transcriptPath: string, sinceIso: string, retry?: ReadTurnUsageRetry, untilIso?: string, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
19
+ /**
20
+ * The usage a turn's subagents recorded, out of their own transcripts.
21
+ *
22
+ * Claude Code writes each subagent to `<session>/subagents/agent-<id>.jsonl`,
23
+ * never to the session's own transcript. A subagent's user lines name the
24
+ * parent's prompt id, the one that launched it or a later one that resumed it,
25
+ * so each assistant line belongs to the prompt id of the user line above it.
26
+ * Lines before the first such line (a fork's copy of the parent's last reply)
27
+ * are no one's here; the parent's own read counts that message. A file longer
28
+ * than the tail takes the last prompt id stated before the tail.
29
+ *
30
+ * A Stop reads every subagent file written since the turn began; a subagent's
31
+ * own stop reads only that subagent's file. One pass, no settle loop: a
32
+ * foreground subagent has stopped before its parent does, and a background one
33
+ * re-reads on its own stop. Never throws.
34
+ *
35
+ * @param payload - The raw hook payload.
36
+ * @param turn - The parent turn; its window is not used, the prompt id is exact.
37
+ * @param excludeMessageIds - Messages already claimed.
38
+ * @returns The subagents' usage in this turn, or undefined when there is none.
39
+ */
40
+ export declare function readClaudeSubagentUsage(payload: unknown, turn: SubagentTurn, excludeMessageIds: ReadonlySet<string>): Promise<TurnUsage | undefined>;
41
+ /**
42
+ * The turns a stopping subagent's lines name, oldest first: the prompt that
43
+ * launched it and any that resumed it.
44
+ *
45
+ * A `SubagentStop` names the session's current prompt (Claude Code 2.1.325),
46
+ * not the one that launched the subagent, so the turn a background subagent's
47
+ * late usage belongs to is read from its own lines.
48
+ *
49
+ * @param payload - The subagent's stop payload.
50
+ * @returns The prompt ids; empty when the payload names no subagent or its file cannot be read.
51
+ */
52
+ export declare function readClaudeSubagentTurnIds(payload: unknown): Promise<string[]>;
19
53
  /**
20
54
  * The session's titles, from the tail of Claude Code's transcript.
21
55
  *