@agent-watch-ai/edge 0.7.1 → 0.7.3

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 (56) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +2 -1
  3. package/dist/capture/capture-env.d.ts +3 -3
  4. package/dist/capture/capture-env.js +5 -5
  5. package/dist/capture/captured-step.js +1 -1
  6. package/dist/cli/constants/cli.constants.js +1 -1
  7. package/dist/cli/setup.js +26 -3
  8. package/dist/cli/types/cli.types.d.ts +2 -0
  9. package/dist/cli/uninstall.js +1 -1
  10. package/dist/cli.js +7 -4
  11. package/dist/config/config.d.ts +8 -0
  12. package/dist/config/config.js +10 -0
  13. package/dist/config/constants/config.constants.d.ts +5 -0
  14. package/dist/config/constants/config.constants.js +5 -0
  15. package/dist/config/repo-config.js +7 -2
  16. package/dist/config/schemas/config.schema.d.ts +4 -0
  17. package/dist/config/schemas/config.schema.js +7 -1
  18. package/dist/enrollment/enrollment.js +7 -4
  19. package/dist/pipeline/hook-pipeline.js +3 -1
  20. package/dist/providers/antigravity/antigravity.adapter.d.ts +14 -0
  21. package/dist/providers/antigravity/antigravity.adapter.js +86 -18
  22. package/dist/providers/antigravity/antigravity.provider.js +7 -4
  23. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +10 -0
  24. package/dist/providers/antigravity/constants/antigravity.constants.js +10 -0
  25. package/dist/providers/antigravity/schemas/antigravity.schema.js +7 -13
  26. package/dist/providers/claude/claude.otel.d.ts +33 -1
  27. package/dist/providers/claude/claude.otel.js +81 -12
  28. package/dist/providers/claude/claude.provider.js +3 -1
  29. package/dist/providers/codex/codex.capture.d.ts +1 -1
  30. package/dist/providers/codex/codex.capture.js +3 -3
  31. package/dist/providers/codex/codex.otel.js +2 -2
  32. package/dist/providers/codex/codex.provider.js +2 -1
  33. package/dist/providers/gemini/gemini.capture.js +2 -2
  34. package/dist/providers/gemini/gemini.otel.js +2 -2
  35. package/dist/providers/gemini/gemini.provider.js +2 -1
  36. package/dist/providers/shared/terminal-capture.js +3 -3
  37. package/dist/turns/antigravity-transcript.d.ts +40 -0
  38. package/dist/turns/antigravity-transcript.js +102 -0
  39. package/dist/turns/claude-transcript.d.ts +35 -1
  40. package/dist/turns/claude-transcript.js +185 -2
  41. package/dist/turns/codex-transcript.d.ts +22 -1
  42. package/dist/turns/codex-transcript.js +161 -2
  43. package/dist/turns/constants/turns.constants.d.ts +51 -0
  44. package/dist/turns/constants/turns.constants.js +51 -0
  45. package/dist/turns/gemini-transcript.d.ts +17 -1
  46. package/dist/turns/gemini-transcript.js +36 -2
  47. package/dist/turns/transcript.d.ts +31 -1
  48. package/dist/turns/transcript.js +74 -0
  49. package/dist/turns/turn-state.d.ts +18 -1
  50. package/dist/turns/turn-state.js +45 -10
  51. package/dist/turns/turn-tracker.js +154 -16
  52. package/dist/turns/types/transcript.types.d.ts +25 -0
  53. package/dist/turns/types/turn-provider.types.d.ts +18 -1
  54. package/dist/turns/types/turn-state.types.d.ts +10 -0
  55. package/docs/DATA_HANDLING.md +3 -0
  56. package/package.json +1 -1
@@ -1,10 +1,57 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
1
3
  import { sha256Hex } from '../../events/event-id.js';
2
4
  import { baseEvent, promptPatch, responsePatch, toolPatch, withPatch } from '../shared/event-builder.js';
3
5
  import { asRecord } from '../../core/object.js';
4
6
  import { classifyTool, extractCommand, parseMcpToolName, shellCallOf, toolCompleteType, toolStartType } from '../shared/tooling.js';
5
- import { ANTIGRAVITY_CWD_KEY, ANTIGRAVITY_DISPLAY_NAME, ANTIGRAVITY_HOOK_EVENT_BY_ARGS, ANTIGRAVITY_PROVIDER_ID, DOTLESS_MODEL_FAMILY, RE_MODEL_QUALIFIER, RE_MODEL_VERSION_DOT, RE_MODEL_WHITESPACE } from './constants/antigravity.constants.js';
7
+ import { ANTIGRAVITY_APP_DIRS, ANTIGRAVITY_ARGS_KEY_BY_EVENT, ANTIGRAVITY_BRAIN_DIR, ANTIGRAVITY_GEMINI_DIR, ANTIGRAVITY_TRANSCRIPT_SEGMENTS, RE_SAFE_CONVERSATION_ID, ANTIGRAVITY_CWD_KEY, ANTIGRAVITY_DISPLAY_NAME, ANTIGRAVITY_HOOK_EVENT_BY_ARGS, ANTIGRAVITY_PROVIDER_ID, DOTLESS_MODEL_FAMILY, RE_MODEL_QUALIFIER, RE_MODEL_VERSION_DOT, RE_MODEL_WHITESPACE } from './constants/antigravity.constants.js';
6
8
  import { antigravityPayloadSchema } from './schemas/antigravity.schema.js';
7
9
  const ARGS_KEYS = Object.keys(ANTIGRAVITY_HOOK_EVENT_BY_ARGS);
10
+ /**
11
+ * Parse a hook payload in either shape Antigravity has written.
12
+ *
13
+ * agy 1.5.0 sends a flat object: the common fields at the top level and a
14
+ * `hookEventName`, with no `common` block and no oneof member (captured
15
+ * 2026-11-14). Older builds send the nested `HookArgs` protojson. A flat
16
+ * payload is lifted into the nested shape by placing the whole object in both
17
+ * `common` and the member its event names; the passthrough schemas ignore the
18
+ * extra keys. Any other shape is left alone and yields no hook.
19
+ *
20
+ * @param rawPayload - Raw JSON from the hook's stdin.
21
+ * @returns The schema's parse result.
22
+ */
23
+ function parsePayload(rawPayload) {
24
+ const record = asRecord(rawPayload);
25
+ const event = record?.['hookEventName'];
26
+ const key = typeof event === 'string' && record?.['common'] === undefined ? ANTIGRAVITY_ARGS_KEY_BY_EVENT.get(event) : undefined;
27
+ return antigravityPayloadSchema.safeParse(key ? { common: record, [key]: record } : rawPayload);
28
+ }
29
+ /**
30
+ * The transcript a hook's turn usage is read from.
31
+ *
32
+ * `transcriptPath` when the payload names it; otherwise the transcript under
33
+ * the conversation's brain directory, first through `artifactDirectoryPath`
34
+ * (which is that directory), then through `conversationId` in whichever app
35
+ * directory has it.
36
+ *
37
+ * @param rawPayload - Raw JSON from the hook's stdin.
38
+ * @param env - Where the home directory is.
39
+ * @returns The path, or undefined when the payload names no conversation.
40
+ */
41
+ export function antigravityTranscriptPath(rawPayload, env) {
42
+ const parsed = parsePayload(rawPayload);
43
+ const common = parsed.success ? parsed.data.common : undefined;
44
+ if (common?.transcriptPath)
45
+ return common.transcriptPath;
46
+ if (common?.artifactDirectoryPath)
47
+ return path.join(common.artifactDirectoryPath, ...ANTIGRAVITY_TRANSCRIPT_SEGMENTS);
48
+ const conversationId = common?.conversationId;
49
+ // A path segment from the payload: never let it climb out of brain/.
50
+ if (!conversationId || !RE_SAFE_CONVERSATION_ID.test(conversationId))
51
+ return undefined;
52
+ const candidates = ANTIGRAVITY_APP_DIRS.map((app) => path.join(env.home, ANTIGRAVITY_GEMINI_DIR, app, ANTIGRAVITY_BRAIN_DIR, conversationId, ...ANTIGRAVITY_TRANSCRIPT_SEGMENTS));
53
+ return candidates.find((candidate) => existsSync(candidate));
54
+ }
8
55
  /**
9
56
  * Which hook this payload is.
10
57
  *
@@ -17,7 +64,7 @@ const ARGS_KEYS = Object.keys(ANTIGRAVITY_HOOK_EVENT_BY_ARGS);
17
64
  * @returns The hook name, or undefined.
18
65
  */
19
66
  export function antigravityHookEvent(rawPayload) {
20
- const parsed = antigravityPayloadSchema.safeParse(rawPayload);
67
+ const parsed = parsePayload(rawPayload);
21
68
  if (!parsed.success)
22
69
  return undefined;
23
70
  const key = ARGS_KEYS.find((candidate) => parsed.data[candidate] !== undefined);
@@ -33,7 +80,7 @@ export function antigravityHookEvent(rawPayload) {
33
80
  * @returns The primary workspace path, or undefined.
34
81
  */
35
82
  export function antigravityCwd(rawPayload) {
36
- const parsed = antigravityPayloadSchema.safeParse(rawPayload);
83
+ const parsed = parsePayload(rawPayload);
37
84
  if (!parsed.success)
38
85
  return undefined;
39
86
  return parsed.data.common?.workspacePaths?.[0];
@@ -49,7 +96,7 @@ export function antigravityCwd(rawPayload) {
49
96
  * @returns The call, or undefined for any other payload.
50
97
  */
51
98
  export function antigravityShellCall(rawPayload) {
52
- const parsed = antigravityPayloadSchema.safeParse(rawPayload);
99
+ const parsed = parsePayload(rawPayload);
53
100
  const toolCall = parsed.success ? (parsed.data.preToolHookArgs ?? parsed.data.postToolHookArgs)?.toolCall : undefined;
54
101
  if (classifyTool(toolCall?.name) !== 'shell')
55
102
  return undefined;
@@ -69,7 +116,7 @@ export function antigravityShellCall(rawPayload) {
69
116
  * @returns The canonical events, or an empty list for an unusable payload.
70
117
  */
71
118
  export function parseAntigravityHookEvent(rawPayload, context) {
72
- const parsed = antigravityPayloadSchema.safeParse(rawPayload);
119
+ const parsed = parsePayload(rawPayload);
73
120
  if (!parsed.success)
74
121
  return [];
75
122
  const payload = parsed.data;
@@ -156,7 +203,7 @@ function hookPatch(payload, hook, context) {
156
203
  // `common.lastUserInput` by every hook of the execution. The first
157
204
  // invocation is therefore where the turn's prompt is recorded; later
158
205
  // invocations are model calls inside the same turn.
159
- if (!isFirstInvocation(payload.preInvocationHookArgs?.invocationNum))
206
+ if (!isFirstInvocation(payload))
160
207
  return {};
161
208
  return promptPatch(payload.common?.lastUserInput ?? '', context.config.capture);
162
209
  }
@@ -180,7 +227,7 @@ function hookPatch(payload, hook, context) {
180
227
  function antigravityToolPatch(payload, hook, context) {
181
228
  const toolCall = toolCallOf(payload, hook);
182
229
  const kind = classifyTool(toolCall?.name);
183
- const failed = hook === 'PostToolUse' && payload.postToolHookArgs?.error !== undefined;
230
+ const failed = hook === 'PostToolUse' && toolFailed(payload);
184
231
  const mcp = kind === 'mcp' && toolCall?.name ? parseMcpToolName(toolCall.name) : undefined;
185
232
  return toolPatch({
186
233
  name: toolCall?.name,
@@ -220,29 +267,50 @@ function canonicalType(payload, hook) {
220
267
  if (hook === 'Stop')
221
268
  return 'generation.completed';
222
269
  if (hook === 'PreInvocation') {
223
- return isFirstInvocation(payload.preInvocationHookArgs?.invocationNum) ? 'prompt.submitted' : 'agent.other';
270
+ return isFirstInvocation(payload) ? 'prompt.submitted' : 'agent.other';
224
271
  }
225
272
  if (hook === 'PostInvocation')
226
273
  return 'agent.other';
227
274
  if (hook === 'PreToolUse')
228
275
  return toolStartType(classifyTool(payload.preToolHookArgs?.toolCall?.name));
229
- if (payload.postToolHookArgs?.error !== undefined)
276
+ if (toolFailed(payload))
230
277
  return 'tool.failed';
231
278
  return toolCompleteType(classifyTool(payload.postToolHookArgs?.toolCall?.name));
232
279
  }
233
280
  /**
234
- * Whether an invocation counter names the execution's first model call.
281
+ * Whether a post-tool payload reports a failure.
282
+ *
283
+ * agy 1.5.0 sends `error: ""` on success (an unset proto string), so only a
284
+ * non-empty error is one; older builds omit the field.
285
+ *
286
+ * @param payload - Parsed hook payload.
287
+ * @returns True when the tool call failed.
288
+ */
289
+ function toolFailed(payload) {
290
+ const error = payload.postToolHookArgs?.error;
291
+ return error !== undefined && error !== '';
292
+ }
293
+ /**
294
+ * Whether a `PreInvocation` names the execution's first model call.
235
295
  *
236
- * The counter's base is not documented, so both 0 and 1 are treated as first. A
237
- * repeat is harmless: the prompt record is keyed by the event id, which is
238
- * stable for one execution and one prompt.
296
+ * agy 1.5.0's flat payload counts from 0 and restarts at 0 on every turn of a
297
+ * conversation (captured 2026-11-14, two turns of one conversation), so there
298
+ * only 0 is first: invocation 1 is the second model call, and with no `executionId` a
299
+ * second prompt record would not dedupe. The nested shape's base is not
300
+ * documented, so both 0 and 1 count as first there; its records carry the
301
+ * execution id, so a repeat is harmless.
239
302
  *
240
- * @param invocationNum - The reported counter, in either proto3 JSON encoding.
303
+ * @param payload - Parsed hook payload.
241
304
  * @returns True when this is the first invocation.
242
305
  */
243
- function isFirstInvocation(invocationNum) {
244
- const value = numeric(invocationNum);
245
- return value === undefined || value <= 1;
306
+ function isFirstInvocation(payload) {
307
+ const args = payload.preInvocationHookArgs;
308
+ const value = numeric(args?.invocationNum);
309
+ if (value === undefined)
310
+ return true;
311
+ if (args?.['hookEventName'] !== undefined)
312
+ return value === 0;
313
+ return value <= 1;
246
314
  }
247
315
  /**
248
316
  * The tool call one of the tool hooks carries.
@@ -297,7 +365,7 @@ function rawStepIdx(payload, hook) {
297
365
  * @returns The parts to hash.
298
366
  */
299
367
  function fingerprintParts(payload, hook) {
300
- if (hook === 'PreInvocation' && isFirstInvocation(payload.preInvocationHookArgs?.invocationNum)) {
368
+ if (hook === 'PreInvocation' && isFirstInvocation(payload)) {
301
369
  return ['prompt', payload.common?.lastUserInput ?? ''];
302
370
  }
303
371
  return [payload.common?.modelName, toolCallOf(payload, hook)?.name, invocationOf(payload, hook)];
@@ -1,6 +1,7 @@
1
1
  import { googleAccountBillingMode } from '../../billing/billing-mode.js';
2
+ import { readAntigravityTurnUsage } from '../../turns/antigravity-transcript.js';
2
3
  import { IDE_SURFACE } from '../../turns/constants/turns.constants.js';
3
- import { antigravityCwd, antigravityHookEvent, antigravityShellCall, parseAntigravityHookEvent } from './antigravity.adapter.js';
4
+ import { antigravityCwd, antigravityHookEvent, antigravityShellCall, antigravityTranscriptPath, parseAntigravityHookEvent } from './antigravity.adapter.js';
4
5
  import { antigravityCapture } from './antigravity.capture.js';
5
6
  import { detectAntigravity } from './antigravity.detect.js';
6
7
  import { installAntigravityHooks, uninstallAntigravityHooks } from './antigravity.hooks.js';
@@ -20,11 +21,13 @@ export const antigravityProvider = {
20
21
  },
21
22
  resolveCwd: antigravityCwd,
22
23
  shellCall: antigravityShellCall,
24
+ readTurnUsage: readAntigravityTurnUsage,
25
+ transcriptPath: antigravityTranscriptPath,
23
26
  surface: async () => IDE_SURFACE,
24
27
  /** Signed in through the shared `~/.gemini` Google account, as Gemini CLI is. */
25
28
  billingMode: googleAccountBillingMode
26
29
  // No nativeTelemetry: Antigravity exposes no OTLP exporter configuration, so
27
- // there is no llm.call ledger source and turn summaries stay
28
- // usage_status=pending. Adding a configurator would claim a capability the
29
- // agent does not have.
30
+ // there is no llm.call ledger source; the transcript's step counts are the
31
+ // only usage. Adding a configurator would claim a capability the agent does
32
+ // not have.
30
33
  };
@@ -73,3 +73,13 @@ export declare const ANTIGRAVITY_HOOK_EVENT_BY_ARGS: {
73
73
  readonly stopHookArgs: "Stop";
74
74
  readonly sessionStartHookArgs: "SessionStart";
75
75
  };
76
+ /** hooks.json event name -> the `HookArgs` oneof member carrying it, for flat payloads. */
77
+ export declare const ANTIGRAVITY_ARGS_KEY_BY_EVENT: ReadonlyMap<string, keyof typeof ANTIGRAVITY_HOOK_EVENT_BY_ARGS>;
78
+ /** The transcript under a conversation's brain directory (`artifactDirectoryPath`). */
79
+ export declare const ANTIGRAVITY_TRANSCRIPT_SEGMENTS: readonly [".system_generated", "logs", "transcript_full.jsonl"];
80
+ /** App directories under `~/.gemini` that hold `brain/`: CLI, Antigravity 2.0, IDE. */
81
+ export declare const ANTIGRAVITY_APP_DIRS: readonly ["antigravity-cli", "antigravity", "antigravity-ide"];
82
+ export declare const ANTIGRAVITY_GEMINI_DIR = ".gemini";
83
+ export declare const ANTIGRAVITY_BRAIN_DIR = "brain";
84
+ /** A conversation id safe to use as one path segment. */
85
+ export declare const RE_SAFE_CONVERSATION_ID: RegExp;
@@ -76,3 +76,13 @@ export const ANTIGRAVITY_HOOK_EVENT_BY_ARGS = {
76
76
  stopHookArgs: 'Stop',
77
77
  sessionStartHookArgs: 'SessionStart'
78
78
  };
79
+ /** hooks.json event name -> the `HookArgs` oneof member carrying it, for flat payloads. */
80
+ export const ANTIGRAVITY_ARGS_KEY_BY_EVENT = new Map(Object.entries(ANTIGRAVITY_HOOK_EVENT_BY_ARGS).map(([key, event]) => [event, key]));
81
+ /** The transcript under a conversation's brain directory (`artifactDirectoryPath`). */
82
+ export const ANTIGRAVITY_TRANSCRIPT_SEGMENTS = ['.system_generated', 'logs', 'transcript_full.jsonl'];
83
+ /** App directories under `~/.gemini` that hold `brain/`: CLI, Antigravity 2.0, IDE. */
84
+ export const ANTIGRAVITY_APP_DIRS = ['antigravity-cli', 'antigravity', 'antigravity-ide'];
85
+ export const ANTIGRAVITY_GEMINI_DIR = '.gemini';
86
+ export const ANTIGRAVITY_BRAIN_DIR = 'brain';
87
+ /** A conversation id safe to use as one path segment. */
88
+ export const RE_SAFE_CONVERSATION_ID = /^[A-Za-z0-9_-]+$/;
@@ -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()