@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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,29 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.7.2
6
+
7
+ - Google Antigravity turns now report token usage, read from the conversation's own
8
+ transcript (`brain/<conversation>/.system_generated/logs/transcript_full.jsonl`): input,
9
+ cache read and output tokens per model, each model step counted once. Only the counts and
10
+ the model name are read, never the conversation. Builds that write no counts still report
11
+ the turn without usage.
12
+ - Antigravity CLI 1.5.0 hooks are now read. That version sends a flat payload (event name
13
+ and conversation at the top level), which the edge did not recognize, so its hooks
14
+ produced no turns.
15
+ - Claude Code turn summaries now include the tokens the turn's subagents used, read from
16
+ their own transcripts. Before, a turn that handed work to subagents reported only the
17
+ main agent's tokens. A background subagent that is still running when the turn ends
18
+ adds its tokens to that turn when it finishes.
19
+ - Codex and Gemini CLI turn summaries now include the tokens their subagents used, read
20
+ from the subagents' own session files.
21
+ - Counting the provider calls of scripts your coding agent starts (run capture) has its
22
+ own switch now: `capture.runs` in `~/.agentwatch/config.json`, set with
23
+ `agentwatch setup --capture-runs on|off`, on by default. `--otel none` used to turn it
24
+ off too, though those calls never travel over OpenTelemetry. Now it turns off only the
25
+ agents' own telemetry export. Run `agentwatch setup` once after updating if you set
26
+ `--otel none`, to start counting those calls again.
27
+
5
28
  ## 0.7.1
6
29
 
7
30
  - The budget check before each turn now waits up to 500 ms for the platform's answer, up
@@ -57,7 +57,7 @@ export declare function installCaptureCopy(dataDir: string, source?: Shims): Pro
57
57
  *
58
58
  * Every agent shares the one copy, and a missing `--require` target stops every Node an
59
59
  * agent starts, so it stays while either holds. Hooks: `agentwatch off`, the exporter sweep
60
- * and `otel: none` take the env keys out and leave the hooks, with sessions still running
60
+ * and `capture.runs: false` take the env keys out and leave the hooks, with sessions still running
61
61
  * that hold the `--require`; a detection that fails counts as installed. A config naming the
62
62
  * copy: a removal that was refused leaves the keys, and a hook file that does not parse
63
63
  * reads as no hooks. A copy left behind costs nothing.
@@ -138,10 +138,10 @@ export declare function withCaptureOutcome(outcome: SetupOutcome, capture: Setup
138
138
  *
139
139
  * @param block - The env block the agent runs with.
140
140
  * @param config - The credential that would deliver what is captured.
141
- * @param telemetryOn - Whether this machine's config allows the agent's telemetry.
141
+ * @param runsOn - Whether this machine's config turns run capture on (`capture.runs`).
142
142
  * @param dataDir - The data dir holding the copy.
143
143
  * @param source - The package's shims, which the copy should match.
144
144
  * @returns On, or off with the reason; on with a warning when the copy is stale.
145
145
  */
146
- export declare function inspectCaptureEnv(block: Record<string, unknown>, config: CredentialFields, telemetryOn: boolean, dataDir: string, source?: Shims): Promise<RunCaptureStatus>;
146
+ export declare function inspectCaptureEnv(block: Record<string, unknown>, config: CredentialFields, runsOn: boolean, dataDir: string, source?: Shims): Promise<RunCaptureStatus>;
147
147
  export {};
@@ -154,7 +154,7 @@ async function configNamesCopy(dataDir, env, agents) {
154
154
  *
155
155
  * Every agent shares the one copy, and a missing `--require` target stops every Node an
156
156
  * agent starts, so it stays while either holds. Hooks: `agentwatch off`, the exporter sweep
157
- * and `otel: none` take the env keys out and leave the hooks, with sessions still running
157
+ * and `capture.runs: false` take the env keys out and leave the hooks, with sessions still running
158
158
  * that hold the `--require`; a detection that fails counts as installed. A config naming the
159
159
  * copy: a removal that was refused leaves the keys, and a hook file that does not parse
160
160
  * reads as no hooks. A copy left behind costs nothing.
@@ -269,19 +269,19 @@ export function withCaptureOutcome(outcome, capture) {
269
269
  *
270
270
  * @param block - The env block the agent runs with.
271
271
  * @param config - The credential that would deliver what is captured.
272
- * @param telemetryOn - Whether this machine's config allows the agent's telemetry.
272
+ * @param runsOn - Whether this machine's config turns run capture on (`capture.runs`).
273
273
  * @param dataDir - The data dir holding the copy.
274
274
  * @param source - The package's shims, which the copy should match.
275
275
  * @returns On, or off with the reason; on with a warning when the copy is stale.
276
276
  */
277
- export async function inspectCaptureEnv(block, config, telemetryOn, dataDir, source = shimPaths()) {
277
+ export async function inspectCaptureEnv(block, config, runsOn, dataDir, source = shimPaths()) {
278
278
  const shims = copiedShims(dataDir);
279
279
  if (path.delimiter === ';')
280
280
  return { on: false, reason: 'not supported on Windows' };
281
281
  if (!hasCredential(config))
282
282
  return { on: false, reason: 'Edge is not signed in, so nothing is captured' };
283
- if (!telemetryOn)
284
- return { on: false, reason: 'telemetry is off in config (otel)' };
283
+ if (!runsOn)
284
+ return { on: false, reason: 'turned off in config (capture.runs)' };
285
285
  const expected = captureEnv(block, {}, shims);
286
286
  if (block[RUN_CAPTURE_ENV_NODE] !== expected[RUN_CAPTURE_ENV_NODE] || block[RUN_CAPTURE_ENV_PYTHON] !== expected[RUN_CAPTURE_ENV_PYTHON]) {
287
287
  return { on: false, reason: 'not configured; run `agentwatch setup` and restart the agent' };
@@ -173,7 +173,7 @@ async function armVenvsOfThisRun(state) {
173
173
  const shimDir = copiedShims(state.paths.dataDir).python;
174
174
  if (pythonInterpreters(call.command, directory).length === 0)
175
175
  return;
176
- // Only while this agent's route loads the copy: `otel: none`, `off`, and a route not
176
+ // Only while this agent's route loads the copy: `capture.runs: false`, `off`, and a route not
177
177
  // yet verified (Cursor, Antigravity) leave its config without it, and the venv alone.
178
178
  const config = runCaptureRoute(state.provider)?.configPath(state.env);
179
179
  if (config === undefined || !(await fs.readFile(config, 'utf8').catch(() => '')).includes(shimDir))
@@ -5,7 +5,7 @@
5
5
  * itself into a boolean — which is how `--otel none` once ignored the selection
6
6
  * entirely.
7
7
  */
8
- export const VALUE_FLAGS = new Set(['agent', 'endpoint', 'token', 'enrollment-code', 'developer-email', 'developer-name', 'otel', 'root', 'replay-days']);
8
+ export const VALUE_FLAGS = new Set(['agent', 'endpoint', 'token', 'enrollment-code', 'developer-email', 'developer-name', 'otel', 'capture-runs', 'root', 'replay-days']);
9
9
  /** The commands that take `--agent`; the help names the same three. Any other command refuses it. */
10
10
  export const AGENT_COMMANDS = new Set(['setup', 'uninstall', 'hook']);
11
11
  export const FLAG_PREFIX = '--';
package/dist/cli/setup.js CHANGED
@@ -123,6 +123,11 @@ async function setup(options, context, cloud) {
123
123
  println(`${symbols.fail} invalid --otel value "${options.otel}" (expected "all", "none" or a comma list of logs,traces,metrics)`);
124
124
  return 1;
125
125
  }
126
+ const runs = resolveCaptureRuns(baseConfig, options.captureRuns);
127
+ if (runs === undefined) {
128
+ println(`${symbols.fail} invalid --capture-runs value "${options.captureRuns}" (expected "on" or "off")`);
129
+ return 1;
130
+ }
126
131
  const replayDays = parseReplayDays(options.replayDays);
127
132
  if (replayDays === undefined) {
128
133
  println(`${symbols.fail} invalid --replay-days "${options.replayDays}" (expected a whole number of days, 1 to 366)`);
@@ -245,7 +250,7 @@ async function setup(options, context, cloud) {
245
250
  const customEndpoints = nextTrustedOrigins(baseConfig.customEndpoints, previous, enrolled.endpoint, options.allowCustomEndpoint === true, withIdentity);
246
251
  // Set by an enrollment URL and cleared by any other machine setup, so it never outlives the backend it belongs to.
247
252
  const organization = rootPath === undefined ? { organizationId: enrolled.signIn?.organizationId } : {};
248
- const config = ensureInstallationId({ ...withIdentity, ...organization, ...(signedIn ? { installationId } : {}), customEndpoints, otel, emit: { ...baseConfig.emit, llmCalls: true } });
253
+ const config = ensureInstallationId({ ...withIdentity, ...organization, ...(signedIn ? { installationId } : {}), customEndpoints, otel, capture: { ...baseConfig.capture, runs }, emit: { ...baseConfig.emit, llmCalls: true } });
249
254
  await reportContentDowngrade(context, config);
250
255
  // Under the config lock and onto the file as it is now: a hook may have
251
256
  // exchanged this key while setup was running.
@@ -275,6 +280,7 @@ async function setup(options, context, cloud) {
275
280
  if (developerName)
276
281
  println(`${symbols.ok} name: ${developerName}`);
277
282
  println(`${symbols.ok} otel signals: ${enabledSignalNames(otel).join(', ') || 'none'}`);
283
+ println(`${symbols.ok} run capture: ${runs ? 'on' : 'off'}`);
278
284
  println(dim(` config: ${context.paths.configFile}`));
279
285
  println();
280
286
  // Setup is the one way back after an uninstall, for the entry it ran for
@@ -528,6 +534,8 @@ async function resolveRoot(options, baseConfig) {
528
534
  return { error: 'set up the machine identity first (agentwatch setup without --root); a project root is an addition to it' };
529
535
  if (options.otel !== undefined)
530
536
  return { error: 'native OTLP signals are machine-wide; run setup without --root to change them' };
537
+ if (options.captureRuns !== undefined)
538
+ return { error: 'run capture is machine-wide; run setup without --root to change it' };
531
539
  try {
532
540
  const root = await fs.realpath(path.resolve(options.env.cwd, options.root));
533
541
  const existing = Object.keys(baseConfig.roots ?? {}).filter((key) => path.isAbsolute(key) && canonicalRoot(key) === root);
@@ -583,6 +591,21 @@ function resolveOtel(baseConfig, flag) {
583
591
  return baseConfig.otel;
584
592
  return parseOtelSignals(flag);
585
593
  }
594
+ /**
595
+ * The run capture switch for this run, validated with the other flags.
596
+ *
597
+ * @param baseConfig - Config the run starts from.
598
+ * @param flag - Raw `--capture-runs` value, when given.
599
+ * @returns On or off, or undefined when the flag is invalid.
600
+ */
601
+ function resolveCaptureRuns(baseConfig, flag) {
602
+ if (flag === undefined)
603
+ return baseConfig.capture.runs;
604
+ const value = flag.trim().toLowerCase();
605
+ if (value === 'on' || value === 'off')
606
+ return value === 'on';
607
+ return undefined;
608
+ }
586
609
  /**
587
610
  * Print the repository context. Informational; never fails the run.
588
611
  *
@@ -75,6 +75,8 @@ export interface SetupOptions {
75
75
  readonly root?: string;
76
76
  /** OTLP signal selection: "all", "none" or a comma list of logs,traces,metrics. */
77
77
  readonly otel?: string;
78
+ /** Run capture (`capture.runs`): "on" or "off". */
79
+ readonly captureRuns?: string;
78
80
  /** The agents `--agent` selected; every registered agent when absent. */
79
81
  readonly agents?: readonly AgentProvider[];
80
82
  readonly hookCommandFor?: (providerId: string) => string;
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { providerIds } from './providers/loaders.js';
11
11
  const HELP = `agentwatch — telemetry edge for AI coding agents
12
12
 
13
13
  Usage:
14
- agentwatch setup [enrollment-url] [--endpoint <url>] [--allow-custom-endpoint] [--no-browser] [--enrollment-code -] [--token <token>] [--developer-email <email>] [--developer-name <name>] [--root <path>] [--otel <signals>] [--replay-days <n>] [--no-replay] [--agent <id>]
14
+ agentwatch setup [enrollment-url] [--endpoint <url>] [--allow-custom-endpoint] [--no-browser] [--enrollment-code -] [--token <token>] [--developer-email <email>] [--developer-name <name>] [--root <path>] [--otel <signals>] [--capture-runs on|off] [--replay-days <n>] [--no-replay] [--agent <id>]
15
15
  agentwatch setup --cloud (a Claude Code cloud session's managed SessionStart hook)
16
16
  agentwatch status
17
17
  agentwatch replay [--machine | --root <path>] [--replay-days <n>] [--resume | --stop] [--dry-run]
@@ -52,6 +52,8 @@ Flags:
52
52
  --otel <signals> native OTLP signals agents export to the backend: comma list of
53
53
  logs,traces,metrics, or "all"/"none" (default: logs — the
54
54
  per-request usage/cost ledger the backend turns into llm.call)
55
+ --capture-runs on|off count the provider calls of scripts an agent starts (default: on).
56
+ Apart from --otel: --otel none leaves it on
55
57
  --defer-sign-in with an enrollment URL, for an MDM run: save the organization and
56
58
  install the hooks with no credential. Nothing is sent until the
57
59
  developer runs \`agentwatch setup\` and signs in as themselves.
@@ -167,6 +169,7 @@ async function main() {
167
169
  developerName: stringFlag(parsed, 'developer-name'),
168
170
  root: stringFlag(parsed, 'root'),
169
171
  otel: stringFlag(parsed, 'otel'),
172
+ captureRuns: stringFlag(parsed, 'capture-runs'),
170
173
  agents: selected.agents,
171
174
  deferSignIn: boolFlag(parsed, 'defer-sign-in'),
172
175
  replayDays: stringFlag(parsed, 'replay-days'),
@@ -12,6 +12,14 @@ export declare function defaultConfig(): AgentWatchConfig;
12
12
  * @returns True when at least one signal is on.
13
13
  */
14
14
  export declare function otelEnabled(config: AgentWatchConfig): boolean;
15
+ /**
16
+ * Whether setup writes run capture into each agent's environment. Apart from
17
+ * `otelEnabled` on purpose: captured calls go out as events, not OTLP.
18
+ *
19
+ * @param config - Effective configuration.
20
+ * @returns True when `capture.runs` is on.
21
+ */
22
+ export declare function runCaptureEnabled(config: AgentWatchConfig): boolean;
15
23
  /**
16
24
  * Names of the enabled OTLP signals, for setup and status messages.
17
25
  *
@@ -17,6 +17,16 @@ export function defaultConfig() {
17
17
  export function otelEnabled(config) {
18
18
  return config.otel.logs || config.otel.traces || config.otel.metrics;
19
19
  }
20
+ /**
21
+ * Whether setup writes run capture into each agent's environment. Apart from
22
+ * `otelEnabled` on purpose: captured calls go out as events, not OTLP.
23
+ *
24
+ * @param config - Effective configuration.
25
+ * @returns True when `capture.runs` is on.
26
+ */
27
+ export function runCaptureEnabled(config) {
28
+ return config.capture.runs;
29
+ }
20
30
  /**
21
31
  * Names of the enabled OTLP signals, for setup and status messages.
22
32
  *
@@ -135,6 +135,11 @@ export declare const GLOBAL_ONLY_BLOCKS: readonly ["delivery", "otel", "enforcem
135
135
  * to silence usage telemetry for everyone who clones the repository.
136
136
  */
137
137
  export declare const GLOBAL_ONLY_EMIT_KEYS: ReadonlySet<string>;
138
+ /**
139
+ * Capture flags a repo file may not set. Run capture is written into each agent's
140
+ * machine-wide environment by setup, so a repository has no say in it.
141
+ */
142
+ export declare const GLOBAL_ONLY_CAPTURE_KEYS: ReadonlySet<string>;
138
143
  /**
139
144
  * The capture flags that carry raw content off the machine: the developer's
140
145
  * prompt text, tool arguments and tool results, and the session's title. Response text is not here
@@ -158,6 +158,11 @@ export const GLOBAL_ONLY_BLOCKS = ['delivery', 'otel', 'enforcement'];
158
158
  * to silence usage telemetry for everyone who clones the repository.
159
159
  */
160
160
  export const GLOBAL_ONLY_EMIT_KEYS = new Set(['llmCalls', 'turnSummaries']);
161
+ /**
162
+ * Capture flags a repo file may not set. Run capture is written into each agent's
163
+ * machine-wide environment by setup, so a repository has no say in it.
164
+ */
165
+ export const GLOBAL_ONLY_CAPTURE_KEYS = new Set(['runs']);
161
166
  /**
162
167
  * The capture flags that carry raw content off the machine: the developer's
163
168
  * prompt text, tool arguments and tool results, and the session's title. Response text is not here
@@ -5,7 +5,7 @@ import { debugLog } from '../core/logger.js';
5
5
  import { readJsonFile } from '../storage/json-file.js';
6
6
  import { loadConfig } from './config-store.js';
7
7
  import { applyRootOverride } from './root-config.js';
8
- import { CAPTURE_KEY, GLOBAL_ONLY_BLOCKS, GLOBAL_ONLY_EMIT_KEYS, GLOBAL_ONLY_KEYS, MAX_WALK_DEPTH, MERGE_BLOCKS, REPO_CONFIG_NAME } from './constants/config.constants.js';
8
+ import { CAPTURE_KEY, GLOBAL_ONLY_BLOCKS, GLOBAL_ONLY_CAPTURE_KEYS, GLOBAL_ONLY_EMIT_KEYS, GLOBAL_ONLY_KEYS, MAX_WALK_DEPTH, MERGE_BLOCKS, REPO_CONFIG_NAME } from './constants/config.constants.js';
9
9
  import { configSchema } from './schemas/config.schema.js';
10
10
  export { REPO_CONFIG_NAME } from './constants/config.constants.js';
11
11
  /**
@@ -125,7 +125,12 @@ function withoutGlobalOnly(repo) {
125
125
  warnings.push(`${REPO_CONFIG_NAME}: "${block}" is global-only and was ignored`);
126
126
  refused.add(block);
127
127
  }
128
- const value = omitKeys(repo, refused);
128
+ const stripped = omitKeys(repo, refused);
129
+ const capture = asRecord(stripped[CAPTURE_KEY]);
130
+ const refusedCaptureKeys = new Set(Object.keys(capture ?? {}).filter((key) => GLOBAL_ONLY_CAPTURE_KEYS.has(key)));
131
+ for (const key of refusedCaptureKeys)
132
+ warnings.push(`${REPO_CONFIG_NAME}: "capture.${key}" is global-only and was ignored`);
133
+ const value = capture && refusedCaptureKeys.size > 0 ? { ...stripped, [CAPTURE_KEY]: omitKeys(capture, refusedCaptureKeys) } : stripped;
129
134
  const emit = asRecord(value['emit']);
130
135
  if (!emit)
131
136
  return { value, warnings };
@@ -33,6 +33,7 @@ export declare const captureSchema: z.ZodObject<{
33
33
  git: z.ZodDefault<z.ZodBoolean>;
34
34
  files: z.ZodDefault<z.ZodBoolean>;
35
35
  mcpNames: z.ZodDefault<z.ZodBoolean>;
36
+ runs: z.ZodDefault<z.ZodBoolean>;
36
37
  }, z.core.$strip>;
37
38
  /** Tuning for the in-hook send and the machine-global offline queue. */
38
39
  export declare const deliverySchema: z.ZodObject<{
@@ -239,6 +240,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
239
240
  git: z.ZodDefault<z.ZodBoolean>;
240
241
  files: z.ZodDefault<z.ZodBoolean>;
241
242
  mcpNames: z.ZodDefault<z.ZodBoolean>;
243
+ runs: z.ZodDefault<z.ZodBoolean>;
242
244
  }, z.core.$strip>>;
243
245
  emit: z.ZodPrefault<z.ZodObject<{
244
246
  turnSummaries: z.ZodDefault<z.ZodBoolean>;
@@ -270,6 +272,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
270
272
  git: boolean;
271
273
  files: boolean;
272
274
  mcpNames: boolean;
275
+ runs: boolean;
273
276
  };
274
277
  schemaVersion: 1;
275
278
  ignoredRoots: string[];
@@ -347,6 +350,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
347
350
  git: boolean;
348
351
  files: boolean;
349
352
  mcpNames: boolean;
353
+ runs: boolean;
350
354
  };
351
355
  emit: {
352
356
  turnSummaries: boolean;
@@ -52,7 +52,13 @@ export const captureSchema = z
52
52
  git: z.boolean().default(true),
53
53
  files: z.boolean().default(true),
54
54
  /** MCP server and tool names in `tools_used`; false folds them into `mcp`. Metadata, not content. */
55
- mcpNames: z.boolean().default(true)
55
+ mcpNames: z.boolean().default(true),
56
+ /**
57
+ * Run capture: the shims each agent's environment loads, counting provider calls of the
58
+ * processes it starts. Its own switch, apart from `otel`: the calls travel as events,
59
+ * not OTLP, so turning native telemetry off must not stop them. Machine-wide, global-only.
60
+ */
61
+ runs: z.boolean().default(true)
56
62
  })
57
63
  .strip();
58
64
  /** Tuning for the in-hook send and the machine-global offline queue. */
@@ -632,7 +632,9 @@ async function snapshot(state) {
632
632
  // Never for an inherited repository: core may drop it when folder evidence
633
633
  // disagrees, and a snapshot of it would mint a work unit for the wrong one.
634
634
  const capture = state.workCapture ?? state.config.capture;
635
- if (!repository || state.summary?.work_evidence === 'inherited' || !capture.git)
635
+ // A turn re-sent on a subagent's stop (late usage) was snapshotted at its close.
636
+ const closed = state.events.some((event) => event.event.type === 'generation.completed');
637
+ if (!repository || !closed || state.summary?.work_evidence === 'inherited' || !capture.git)
636
638
  return stop(state, STOP_NO_SNAPSHOT);
637
639
  const input = {
638
640
  // The checkout the summary named, which need not be the folder the agent sits in.
@@ -1,7 +1,21 @@
1
1
  import type { AgentWatchEvent } from '../../events/types/events.types.js';
2
+ import type { Env } from '../../core/types/core.types.js';
2
3
  import type { HookContext, ShellCall } from '../types/provider.types.js';
3
4
  import type { AntigravityHookEvent } from './types/antigravity.types.js';
4
5
  export type { AntigravityHookEvent, AntigravityPayload } from './types/antigravity.types.js';
6
+ /**
7
+ * The transcript a hook's turn usage is read from.
8
+ *
9
+ * `transcriptPath` when the payload names it; otherwise the transcript under
10
+ * the conversation's brain directory, first through `artifactDirectoryPath`
11
+ * (which is that directory), then through `conversationId` in whichever app
12
+ * directory has it.
13
+ *
14
+ * @param rawPayload - Raw JSON from the hook's stdin.
15
+ * @param env - Where the home directory is.
16
+ * @returns The path, or undefined when the payload names no conversation.
17
+ */
18
+ export declare function antigravityTranscriptPath(rawPayload: unknown, env: Env): string | undefined;
5
19
  /**
6
20
  * Which hook this payload is.
7
21
  *
@@ -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_-]+$/;