@agent-watch-ai/edge 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +7 -3
  3. package/SECURITY.md +7 -4
  4. package/dist/cli/constants/cli.constants.d.ts +2 -0
  5. package/dist/cli/constants/cli.constants.js +3 -1
  6. package/dist/cli/doctor.js +13 -2
  7. package/dist/cli/setup.js +138 -29
  8. package/dist/cli/toggle.js +5 -1
  9. package/dist/cli/types/cli.types.d.ts +6 -0
  10. package/dist/cli/uninstall.js +1 -1
  11. package/dist/cli.js +14 -3
  12. package/dist/config/config-store.d.ts +1 -1
  13. package/dist/config/config-store.js +1 -1
  14. package/dist/config/constants/config.constants.d.ts +4 -1
  15. package/dist/config/constants/config.constants.js +7 -2
  16. package/dist/config/schemas/config.schema.d.ts +110 -0
  17. package/dist/config/schemas/config.schema.js +12 -3
  18. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  19. package/dist/credentials/constants/credentials.constants.js +9 -1
  20. package/dist/credentials/credential-status.js +8 -4
  21. package/dist/credentials/credentials.d.ts +16 -2
  22. package/dist/credentials/credentials.js +28 -3
  23. package/dist/credentials/device-api.d.ts +10 -1
  24. package/dist/credentials/device-api.js +12 -1
  25. package/dist/credentials/identity.d.ts +12 -1
  26. package/dist/credentials/identity.js +12 -1
  27. package/dist/credentials/migration.d.ts +1 -1
  28. package/dist/credentials/migration.js +1 -1
  29. package/dist/credentials/sign-in.d.ts +14 -1
  30. package/dist/credentials/sign-in.js +24 -5
  31. package/dist/credentials/types/credentials.types.d.ts +12 -1
  32. package/dist/enforcement/decision-client.js +2 -1
  33. package/dist/enforcement/enforcement.js +7 -5
  34. package/dist/enforcement/types/enforcement.types.d.ts +2 -2
  35. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  36. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  37. package/dist/pipeline/hook-pipeline.js +56 -7
  38. package/dist/privacy/product-capture.js +2 -0
  39. package/dist/providers/codex/codex.otel.d.ts +12 -1
  40. package/dist/providers/codex/codex.otel.js +61 -11
  41. package/dist/providers/codex/constants/codex.otel.constants.d.ts +5 -0
  42. package/dist/providers/codex/constants/codex.otel.constants.js +5 -0
  43. package/dist/providers/constants/provider.constants.d.ts +8 -0
  44. package/dist/providers/constants/provider.constants.js +8 -0
  45. package/dist/providers/cursor/constants/cursor.constants.d.ts +2 -0
  46. package/dist/providers/cursor/constants/cursor.constants.js +2 -0
  47. package/dist/providers/cursor/cursor.adapter.js +79 -3
  48. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +6 -0
  49. package/dist/providers/gemini/constants/gemini.otel.constants.js +6 -0
  50. package/dist/providers/gemini/gemini.otel.d.ts +11 -1
  51. package/dist/providers/gemini/gemini.otel.js +52 -12
  52. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  53. package/dist/providers/shared/bearer-rewrite.js +46 -0
  54. package/dist/providers/shared/constants/tooling.constants.d.ts +6 -0
  55. package/dist/providers/shared/constants/tooling.constants.js +6 -0
  56. package/dist/providers/shared/tooling.d.ts +28 -0
  57. package/dist/providers/shared/tooling.js +52 -1
  58. package/dist/providers/types/provider.types.d.ts +24 -0
  59. package/dist/storage/atomic-file.d.ts +14 -0
  60. package/dist/storage/atomic-file.js +19 -0
  61. package/dist/storage/constants/storage.constants.d.ts +2 -0
  62. package/dist/storage/constants/storage.constants.js +2 -0
  63. package/dist/turns/work-checkout.d.ts +5 -3
  64. package/dist/turns/work-checkout.js +46 -12
  65. package/docs/DATA_HANDLING.md +11 -4
  66. package/docs/ENTERPRISE_DEPLOYMENT.md +19 -4
  67. package/package.json +1 -1
@@ -2,13 +2,15 @@ import fs from 'node:fs/promises';
2
2
  import { parse as parseToml } from 'smol-toml';
3
3
  import { asRecord } from '../../core/object.js';
4
4
  import { joinUrl, otlpBaseUrl, toolContentConsented } from '../../config/config.js';
5
- import { backupFile, currentMode, writeFileAtomic } from '../../storage/atomic-file.js';
5
+ import { backupFile, currentMode, writeFileAtomic, writeIfUnchanged } from '../../storage/atomic-file.js';
6
6
  import { SECRET_FILE_MODE } from '../../storage/constants/storage.constants.js';
7
+ import { deviceFor, hasCredential } from '../../credentials/identity.js';
8
+ import { BEARER_PLACEHOLDER } from '../constants/provider.constants.js';
7
9
  import { withOtelInstall, withoutOtelInstall } from '../shared/install-record.js';
8
10
  import { INSTALLATION_HEADER } from '../../transport/constants/transport.constants.js';
9
11
  import { codexConfigTomlPath } from './codex.detect.js';
10
12
  import { CODEX_PROVIDER_ID } from './constants/codex.constants.js';
11
- import { BLOCK_END, BLOCK_START, CODEX_EXPORTER_KEYS, CODEX_OTEL_SIGNALS, LOGS_PATH, OTEL_TABLE_KEY, OTLP_HTTP_KEY, RE_LEADING_NEWLINE, RE_TOML_BACKSLASH, RE_TOML_QUOTE, RE_TOML_TABLE_HEADER, RE_TRAILING_NEWLINES, TRACES_PATH } from './constants/codex.otel.constants.js';
13
+ import { BLOCK_END, BLOCK_START, CODEX_EXPORTER_KEYS, CODEX_OTEL_SIGNALS, LOGS_PATH, OTEL_TABLE_KEY, OTLP_HTTP_KEY, RE_BEARER_HEADER, RE_LEADING_NEWLINE, RE_TOML_BACKSLASH, RE_TOML_QUOTE, RE_TOML_TABLE_HEADER, RE_TRAILING_NEWLINES, TRACES_PATH } from './constants/codex.otel.constants.js';
12
14
  /**
13
15
  * Configures Codex's own OTLP export.
14
16
  *
@@ -70,7 +72,7 @@ export class CodexOtelConfigurator {
70
72
  return { ok: false, changed: false, messages: ['no backend endpoint configured'] };
71
73
  const configPath = codexConfigTomlPath(context.env);
72
74
  const raw = (await readFileOrUndefined(configPath)) ?? '';
73
- const block = renderBlock(otlpBase, context.config.token, context.config.otel, context.config.installationId);
75
+ const block = renderBlock(otlpBase, context.bearer, context.config.otel, context.config.installationId);
74
76
  const next = raw.includes(BLOCK_START) ? replaceBlock(raw, block) : appendBlock(raw, block);
75
77
  if (typeof next !== 'string')
76
78
  return { ok: false, changed: false, messages: [next.error(configPath)] };
@@ -85,8 +87,8 @@ export class CodexOtelConfigurator {
85
87
  // The managed block may carry the bearer token, so the file becomes private
86
88
  // — but this file is Codex's, not ours, so the mode it had first is
87
89
  // recorded and uninstall puts it back.
88
- const priorMode = context.config.token ? await currentMode(configPath) : undefined;
89
- await writeFileAtomic(configPath, next, context.config.token ? SECRET_FILE_MODE : undefined);
90
+ const priorMode = context.bearer ? await currentMode(configPath) : undefined;
91
+ await writeFileAtomic(configPath, next, context.bearer ? SECRET_FILE_MODE : undefined);
90
92
  return {
91
93
  ok: true,
92
94
  changed: true,
@@ -138,6 +140,22 @@ export class CodexOtelConfigurator {
138
140
  installState: withoutOtelInstall(context.installState, CODEX_PROVIDER_ID)
139
141
  };
140
142
  }
143
+ /**
144
+ * Swap the bearer in our exporters for the current one.
145
+ *
146
+ * Only the bearer in our own `[otel]` table changes: an MCP server's
147
+ * `Authorization` that Codex parked inside our markers is not ours. No
148
+ * backup: one per rotation would collect copies of every token.
149
+ *
150
+ * @param context - The recorded file, its contents as read and the current bearer.
151
+ * @returns True when the file was rewritten.
152
+ */
153
+ async rewriteBearer(context) {
154
+ const next = withBearer(context.raw, context.bearer);
155
+ if (next === undefined || next === context.raw || tryParseToml(next) === undefined)
156
+ return false;
157
+ return writeIfUnchanged(context.configPath, context.raw, next, SECRET_FILE_MODE);
158
+ }
141
159
  /**
142
160
  * Where the managed block's exporters send. The block is AgentWatch's whole,
143
161
  * so every endpoint in it is.
@@ -243,8 +261,15 @@ function inspectManagedBlock(raw, config) {
243
261
  const otlpBase = otlpBaseUrl(config);
244
262
  if (!otlpBase)
245
263
  return { supported: true, configured: false, detail: 'no backend endpoint configured' };
246
- const actual = extractBlock(raw);
247
- const expected = renderBlock(otlpBase, config.token, config.otel, config.installationId).trim();
264
+ // The bearer's value is not compared: it is the access token, which the hook
265
+ // path rotates. Only whether a header is there, when there is a credential.
266
+ // An install key still in the block once a device exists is stale.
267
+ const block = extractBlock(raw);
268
+ const device = deviceFor(config);
269
+ if (device && config.token && block?.includes(config.token))
270
+ return { supported: true, configured: false, detail: 'AgentWatch [otel] block still holds the install key — run `agentwatch setup`' };
271
+ const actual = block?.replace(RE_BEARER_HEADER, `$1${BEARER_PLACEHOLDER}$3`);
272
+ const expected = renderBlock(otlpBase, hasCredential(config) ? BEARER_PLACEHOLDER : undefined, config.otel, config.installationId).trim();
248
273
  if (actual === expected)
249
274
  return { supported: true, configured: true };
250
275
  return { supported: true, configured: false, detail: 'AgentWatch [otel] block is incomplete or stale — run `agentwatch setup`' };
@@ -258,13 +283,15 @@ function inspectManagedBlock(raw, config) {
258
283
  * @param otlpBase - Backend OTLP base URL.
259
284
  * @param token - Bearer token, when one is configured.
260
285
  * @param signals - The signal selection.
286
+ * @param installationId - This installation's id, when one exists.
261
287
  * @returns The block text, newline-terminated.
262
288
  */
263
289
  function renderBlock(otlpBase, token, signals, installationId) {
264
- // Codex has no header helper, so this map is written once at install and is
265
- // whatever the exporter sends until setup runs again. The installation id is
266
- // fixed for the life of the config, so that suits it; a developer identity
267
- // would not, which is why one is never put here.
290
+ // Codex has no header helper and reads this map once, when a session starts
291
+ // (docs/NATIVE_OTLP_TOKENS.md), so the bearer is the short-lived access token
292
+ // and the hook path rewrites it as it rotates. The installation id is fixed
293
+ // for the life of the config, so that suits it; a developer identity would
294
+ // not, which is why one is never put here.
268
295
  const headers = token
269
296
  ? `, headers = { ${tomlHeaders(token, installationId)} }`
270
297
  : '';
@@ -299,6 +326,29 @@ function tomlHeaders(token, installationId) {
299
326
  }
300
327
  return pairs.join(', ');
301
328
  }
329
+ /**
330
+ * The file with our exporters' bearer set to this one.
331
+ *
332
+ * @param raw - The whole config.toml.
333
+ * @param bearer - The bearer to present.
334
+ * @returns The next contents, or undefined when there is no well-formed block.
335
+ */
336
+ function withBearer(raw, bearer) {
337
+ const span = managedSpan(raw);
338
+ if (!span)
339
+ return undefined;
340
+ // Our table runs from its `[otel]` header to the first foreign table;
341
+ // `managed` re-joins the span without that, so its length up to the end
342
+ // marker is ours in the raw text. A table Codex parked before our header, or
343
+ // a span with no header at all, is never touched.
344
+ const ownedEnd = span.start + span.managed.length - BLOCK_END.length;
345
+ const header = raw.indexOf(`\n[${OTEL_TABLE_KEY}]`, span.start);
346
+ const ownedStart = header + 1;
347
+ if (header === -1 || ownedStart >= ownedEnd)
348
+ return undefined;
349
+ const owned = raw.slice(ownedStart, ownedEnd).replace(RE_BEARER_HEADER, (_match, head, _old, tail) => head + escapeTomlString(bearer) + tail);
350
+ return raw.slice(0, ownedStart) + owned + raw.slice(ownedEnd);
351
+ }
302
352
  /**
303
353
  * Replace, or remove, the marker-delimited block.
304
354
  *
@@ -25,3 +25,8 @@ export declare const RE_TOML_BACKSLASH: RegExp;
25
25
  export declare const RE_TOML_QUOTE: RegExp;
26
26
  /** Start of any TOML table header, used to find where our block stops being ours. */
27
27
  export declare const RE_TOML_TABLE_HEADER: RegExp;
28
+ /**
29
+ * The bearer in our exporters' header maps, value captured. A token rotation
30
+ * changes only this, so drift checks ignore it and the hook rewrites it alone.
31
+ */
32
+ export declare const RE_BEARER_HEADER: RegExp;
@@ -25,3 +25,8 @@ export const RE_TOML_BACKSLASH = /\\/g;
25
25
  export const RE_TOML_QUOTE = /"/g;
26
26
  /** Start of any TOML table header, used to find where our block stops being ours. */
27
27
  export const RE_TOML_TABLE_HEADER = /^\s*\[/;
28
+ /**
29
+ * The bearer in our exporters' header maps, value captured. A token rotation
30
+ * changes only this, so drift checks ignore it and the hook rewrites it alone.
31
+ */
32
+ export const RE_BEARER_HEADER = /("Authorization" = "Bearer )((?:[^"\\]|\\.)*)(")/g;
@@ -28,3 +28,11 @@ export declare const RE_SHELL_CONTROL: RegExp;
28
28
  /** Characters a double quote still escapes inside a quoted argument. */
29
29
  export declare const RE_DOUBLE_QUOTE_ESCAPABLE: RegExp;
30
30
  export declare const RE_WHITESPACE: RegExp;
31
+ /**
32
+ * Stands in for the bearer when a drift check compares an agent's config with
33
+ * what setup would write: the access token rotates hourly, and a rotated token
34
+ * is not drift.
35
+ */
36
+ export declare const BEARER_PLACEHOLDER = "<access token>";
37
+ /** How every literal bearer the edge writes into an agent's config starts. */
38
+ export declare const BEARER_PREFIX = "Bearer ";
@@ -28,3 +28,11 @@ export const RE_SHELL_CONTROL = /[|&;<>\r\n]/;
28
28
  /** Characters a double quote still escapes inside a quoted argument. */
29
29
  export const RE_DOUBLE_QUOTE_ESCAPABLE = /["\\$`]/;
30
30
  export const RE_WHITESPACE = /\s/;
31
+ /**
32
+ * Stands in for the bearer when a drift check compares an agent's config with
33
+ * what setup would write: the access token rotates hourly, and a rotated token
34
+ * is not drift.
35
+ */
36
+ export const BEARER_PLACEHOLDER = '<access token>';
37
+ /** How every literal bearer the edge writes into an agent's config starts. */
38
+ export const BEARER_PREFIX = 'Bearer ';
@@ -44,6 +44,8 @@ export declare const CURSOR_TOOL_KINDS: Readonly<Record<string, ToolKind>>;
44
44
  export declare const CURSOR_READ_TOOL_NAME = "Read";
45
45
  export declare const CURSOR_EDIT_TOOL_NAME = "Edit";
46
46
  export declare const CURSOR_SHELL_TOOL_NAME = "Shell";
47
+ /** Server segment of an MCP key when a Cursor hook names neither a server, a url nor a command. */
48
+ export declare const CURSOR_UNKNOWN_MCP_SERVER = "unknown";
47
49
  /** The dedicated shell hooks, with `command` (and, before the call, `cwd`) at the top level. */
48
50
  export declare const CURSOR_SHELL_EVENTS: ReadonlySet<string>;
49
51
  /** The generic hook that fires before any tool call, the shell's included. */
@@ -81,6 +81,8 @@ export const CURSOR_TOOL_KINDS = {
81
81
  export const CURSOR_READ_TOOL_NAME = 'Read';
82
82
  export const CURSOR_EDIT_TOOL_NAME = 'Edit';
83
83
  export const CURSOR_SHELL_TOOL_NAME = 'Shell';
84
+ /** Server segment of an MCP key when a Cursor hook names neither a server, a url nor a command. */
85
+ export const CURSOR_UNKNOWN_MCP_SERVER = 'unknown';
84
86
  /** The dedicated shell hooks, with `command` (and, before the call, `cwd`) at the top level. */
85
87
  export const CURSOR_SHELL_EVENTS = new Set(['beforeShellExecution', 'afterShellExecution']);
86
88
  /** The generic hook that fires before any tool call, the shell's included. */
@@ -1,9 +1,11 @@
1
+ import fs from 'node:fs';
1
2
  import path from 'node:path';
2
3
  import { asRecord, compact } from '../../core/object.js';
3
4
  import { sha256Hex } from '../../events/event-id.js';
5
+ import { resolvePaths } from '../../storage/paths.js';
4
6
  import { baseEvent, filePathPatch, promptPatch, responsePatch, toolPatch, withPatch } from '../shared/event-builder.js';
5
- import { classifyTool, contentEvidence, parseMcpToolName, shellCallOf, toolCompleteType, toolStartType } from '../shared/tooling.js';
6
- import { ATTACHMENT_FILE_PATH_KEY, CURSOR_DEDICATED_COMPLETION_KINDS, CURSOR_DISPLAY_NAME, CURSOR_EDIT_TOOL_NAME, CURSOR_EVENT_TYPE_MAP, CURSOR_PROVIDER_ID, CURSOR_READ_TOOL_NAME, CURSOR_GENERIC_TOOL_START_EVENT, CURSOR_SHELL_COMMAND_KEY, CURSOR_SHELL_EVENTS, CURSOR_SHELL_WORKDIR_KEY, CURSOR_SHELL_TOOL_NAME, CURSOR_TOOL_KINDS, CURSOR_UNKNOWN_EVENT } from './constants/cursor.constants.js';
7
+ import { classifyTool, contentEvidence, mcpServerFromEndpoint, mcpToolKey, parseMcpToolName, shellCallOf, toolCompleteType, toolStartType } from '../shared/tooling.js';
8
+ import { ATTACHMENT_FILE_PATH_KEY, CURSOR_DEDICATED_COMPLETION_KINDS, CURSOR_DISPLAY_NAME, CURSOR_EDIT_TOOL_NAME, CURSOR_EVENT_TYPE_MAP, CURSOR_PROVIDER_ID, CURSOR_READ_TOOL_NAME, CURSOR_GENERIC_TOOL_START_EVENT, CURSOR_SHELL_COMMAND_KEY, CURSOR_SHELL_EVENTS, CURSOR_SHELL_WORKDIR_KEY, CURSOR_SHELL_TOOL_NAME, CURSOR_TOOL_KINDS, CURSOR_UNKNOWN_EVENT, CURSOR_UNKNOWN_MCP_SERVER } from './constants/cursor.constants.js';
7
9
  import { cursorPayloadSchema } from './schemas/cursor.schema.js';
8
10
  /**
9
11
  * Translate one Cursor hook payload into canonical events.
@@ -233,9 +235,15 @@ function shellPatch(payload, providerEventType, context) {
233
235
  function mcpPatch(payload, providerEventType, context) {
234
236
  const capture = context.config.capture;
235
237
  const parsed = payload.tool_name ? parseMcpToolName(payload.tool_name) : {};
238
+ // An endpoint that names no server still gets a parseable key, so mcpNames:false folds it.
239
+ const toolName = parsed.tool ?? payload.tool_name;
240
+ const endpoint = parsed.server ?? mcpServerFromEndpoint(payload.url, payload.command);
241
+ const server = endpoint ?? rememberedMcpServer(payload, toolName, context) ?? CURSOR_UNKNOWN_MCP_SERVER;
242
+ if (endpoint && toolName)
243
+ rememberMcpServer(payload, toolName, endpoint, context);
236
244
  return {
237
245
  tool: {
238
- name: payload.tool_name,
246
+ name: toolName ? mcpToolKey(server, toolName) : payload.tool_name,
239
247
  status: providerEventType === 'beforeMCPExecution' ? 'started' : 'completed',
240
248
  durationMs: payload.duration
241
249
  },
@@ -249,6 +257,74 @@ function mcpPatch(payload, providerEventType, context) {
249
257
  })
250
258
  };
251
259
  }
260
+ /**
261
+ * Where a conversation's MCP servers are remembered between its hooks.
262
+ *
263
+ * `afterMCPExecution` carries neither url nor command, and only completions
264
+ * become turn records, so the server the before-hook saw has to outlive it.
265
+ *
266
+ * @param payload - Parsed hook payload.
267
+ * @param context - Environment.
268
+ * @returns The state file, or undefined without a conversation id.
269
+ */
270
+ function mcpMemoFile(payload, context) {
271
+ if (!payload.conversation_id)
272
+ return undefined;
273
+ return path.join(resolvePaths(context.env).dataDir, 'cursor-mcp', `${sha256Hex(payload.conversation_id).slice(0, 32)}.json`);
274
+ }
275
+ /**
276
+ * Remembers which server a tool resolved to, for the completion hook.
277
+ *
278
+ * ponytail: one tiny file per conversation, last write wins per tool name, never
279
+ * pruned (the data dir is disposable); two servers exposing the same tool name
280
+ * in one conversation share an entry. Upgrade: key by tool_use_id if Cursor sends it.
281
+ *
282
+ * @param payload - Parsed hook payload.
283
+ * @param tool - Tool name.
284
+ * @param server - Resolved server.
285
+ * @param context - Environment.
286
+ */
287
+ function rememberMcpServer(payload, tool, server, context) {
288
+ const file = mcpMemoFile(payload, context);
289
+ if (!file)
290
+ return;
291
+ try {
292
+ fs.mkdirSync(path.dirname(file), { recursive: true });
293
+ fs.writeFileSync(file, JSON.stringify({ ...readMcpMemo(file), [tool]: server }), { mode: 0o600 });
294
+ }
295
+ catch {
296
+ // Hooks never fail the agent; the completion just keys as unknown.
297
+ }
298
+ }
299
+ /**
300
+ * The server a tool resolved to in this conversation's before-hook.
301
+ *
302
+ * @param payload - Parsed hook payload.
303
+ * @param tool - Tool name.
304
+ * @param context - Environment.
305
+ * @returns The server, or undefined when none was remembered.
306
+ */
307
+ function rememberedMcpServer(payload, tool, context) {
308
+ const file = mcpMemoFile(payload, context);
309
+ if (!file || !tool)
310
+ return undefined;
311
+ const server = readMcpMemo(file)[tool];
312
+ return typeof server === 'string' ? server : undefined;
313
+ }
314
+ /**
315
+ * Reads a conversation's MCP memo.
316
+ *
317
+ * @param file - Memo file.
318
+ * @returns Its contents, empty when missing or unreadable.
319
+ */
320
+ function readMcpMemo(file) {
321
+ try {
322
+ return asRecord(JSON.parse(fs.readFileSync(file, 'utf8'))) ?? {};
323
+ }
324
+ catch {
325
+ return {};
326
+ }
327
+ }
252
328
  /**
253
329
  * File-edit fields for Cursor's dedicated edit hooks.
254
330
  *
@@ -34,3 +34,9 @@ export declare const STANDARD_OTLP_PROTOCOL = "http/json";
34
34
  * that is not a default worth inheriting.
35
35
  */
36
36
  export declare const GEMINI_TELEMETRY_TARGET_LOCAL = "local";
37
+ /**
38
+ * The bearer inside the `OTEL_EXPORTER_OTLP_HEADERS` list, value captured. A
39
+ * token rotation changes only this, so drift checks ignore it and the hook
40
+ * rewrites it alone.
41
+ */
42
+ export declare const RE_BEARER_PAIR: RegExp;
@@ -49,3 +49,9 @@ export const STANDARD_OTLP_PROTOCOL = 'http/json';
49
49
  * that is not a default worth inheriting.
50
50
  */
51
51
  export const GEMINI_TELEMETRY_TARGET_LOCAL = 'local';
52
+ /**
53
+ * The bearer inside the `OTEL_EXPORTER_OTLP_HEADERS` list, value captured. A
54
+ * token rotation changes only this, so drift checks ignore it and the hook
55
+ * rewrites it alone.
56
+ */
57
+ export const RE_BEARER_PAIR = /(Authorization=Bearer )([^,]*)/g;
@@ -1,6 +1,6 @@
1
1
  import type { Env } from '../../core/types/core.types.js';
2
2
  import type { AgentWatchConfig, OtelSignalName } from '../../config/types/config.types.js';
3
- import type { NativeTelemetryConfigurator, NativeTelemetryStatus, SetupContext, SetupOutcome } from '../types/provider.types.js';
3
+ import type { BearerRewriteContext, NativeTelemetryConfigurator, NativeTelemetryStatus, SetupContext, SetupOutcome } from '../types/provider.types.js';
4
4
  /** Configures Gemini CLI's own OTLP export. */
5
5
  export declare class GeminiOtelConfigurator implements NativeTelemetryConfigurator {
6
6
  /**
@@ -47,6 +47,16 @@ export declare class GeminiOtelConfigurator implements NativeTelemetryConfigurat
47
47
  * @returns The outcome.
48
48
  */
49
49
  private configureDisabled;
50
+ /**
51
+ * Swap the bearer in our `OTEL_EXPORTER_OTLP_HEADERS` for the current one.
52
+ *
53
+ * Only when a setup recorded the key as ours, and only the bearer in it
54
+ * changes. No backup: one per rotation would collect copies of every token.
55
+ *
56
+ * @param context - The recorded file, its contents as read, install state and the current bearer.
57
+ * @returns True when the file was rewritten.
58
+ */
59
+ rewriteBearer(context: BearerRewriteContext): Promise<boolean>;
50
60
  /**
51
61
  * Signals Gemini was asked for but will not be given under current consent.
52
62
  *
@@ -1,15 +1,17 @@
1
1
  import { asRecord, omitKeys } from '../../core/object.js';
2
2
  import { enabledSignalNames, otlpBaseUrl, toolContentConsented } from '../../config/config.js';
3
3
  import { INSTALLATION_HEADER } from '../../transport/constants/transport.constants.js';
4
- import { backupFile, currentMode } from '../../storage/atomic-file.js';
4
+ import { backupFile, currentMode, writeIfUnchanged } from '../../storage/atomic-file.js';
5
5
  import { SECRET_FILE_MODE } from '../../storage/constants/storage.constants.js';
6
6
  import { readJsonFile } from '../../storage/json-file.js';
7
- import { HOOK_COMMAND_MARKER } from '../constants/provider.constants.js';
7
+ import { parseJsonLine } from '../../turns/transcript.js';
8
+ import { deviceFor, hasCredential } from '../../credentials/identity.js';
9
+ import { BEARER_PLACEHOLDER, HOOK_COMMAND_MARKER } from '../constants/provider.constants.js';
8
10
  import { writeJsonValidated } from '../shared/hook-config.js';
9
11
  import { withOtelInstall, withoutOtelInstall } from '../shared/install-record.js';
10
12
  import { geminiSettingsPath } from './gemini.detect.js';
11
13
  import { GEMINI_PROVIDER_ID } from './constants/gemini.constants.js';
12
- import { ENV_BLOCK_KEY, GEMINI_ENDPOINT_KEYS, GEMINI_LEGACY_OWNED_KEYS, GEMINI_OTLP_PROTOCOL, GEMINI_TELEMETRY_TARGET_LOCAL, LEGACY_HELPER_KEY, OTEL_EXPORTER_NONE, OTEL_EXPORTER_OTLP, OTLP_HEADERS_KEY, STANDARD_OTLP_PROTOCOL } from './constants/gemini.otel.constants.js';
14
+ import { ENV_BLOCK_KEY, GEMINI_ENDPOINT_KEYS, GEMINI_LEGACY_OWNED_KEYS, GEMINI_OTLP_PROTOCOL, GEMINI_TELEMETRY_TARGET_LOCAL, LEGACY_HELPER_KEY, OTEL_EXPORTER_NONE, OTEL_EXPORTER_OTLP, OTLP_HEADERS_KEY, RE_BEARER_PAIR, STANDARD_OTLP_PROTOCOL } from './constants/gemini.otel.constants.js';
13
15
  /**
14
16
  * Gemini's own prompt-logging switch, forced off.
15
17
  *
@@ -38,10 +40,11 @@ const CONTENT_LOG_OFF = {
38
40
  * which is fail-closed, answered 401 to every batch.
39
41
  *
40
42
  * @param context - Environment, paths and effective config.
43
+ * @param bearer - What to authenticate with; see `SetupContext.bearer`.
41
44
  * @returns The desired variables, or undefined when telemetry is off or no
42
45
  * backend is configured.
43
46
  */
44
- function desiredGeminiOtelEnv(context) {
47
+ function desiredGeminiOtelEnv(context, bearer) {
45
48
  const otlpBase = otlpBaseUrl(context.config);
46
49
  const signals = safeGeminiSignals(context.config);
47
50
  if (!otlpBase || !anySignal(signals))
@@ -58,9 +61,7 @@ function desiredGeminiOtelEnv(context) {
58
61
  OTEL_TRACES_EXPORTER: signals.traces ? OTEL_EXPORTER_OTLP : OTEL_EXPORTER_NONE,
59
62
  OTEL_EXPORTER_OTLP_PROTOCOL: STANDARD_OTLP_PROTOCOL,
60
63
  OTEL_EXPORTER_OTLP_ENDPOINT: otlpBase,
61
- ...(context.config.token
62
- ? { [OTLP_HEADERS_KEY]: otlpHeaders(context.config.token, context.config.installationId) }
63
- : {})
64
+ ...(bearer ? { [OTLP_HEADERS_KEY]: otlpHeaders(bearer, context.config.installationId) } : {})
64
65
  };
65
66
  }
66
67
  /**
@@ -74,7 +75,7 @@ function desiredGeminiOtelEnv(context) {
74
75
  * for Codex: a header builder that reads a config can be handed one with no
75
76
  * token and quietly emit `Bearer ` rather than refusing to be called.
76
77
  *
77
- * @param token - The ingest token; the caller has already checked there is one.
78
+ * @param token - The access token; the caller has already checked there is one.
78
79
  * @param installationId - This installation's id, when one exists.
79
80
  * @returns The header list for the exporter.
80
81
  */
@@ -114,10 +115,19 @@ export class GeminiOtelConfigurator {
114
115
  const ownedKeys = ownedKeysOf(context);
115
116
  if (disabled)
116
117
  return inspectDisabled(settings, envBlock, ownedKeys);
117
- const desired = desiredGeminiOtelEnv(context);
118
+ // The bearer's value is not compared: it is the access token, which the hook
119
+ // path rotates. Only whether a header is there, when there is a credential.
120
+ const device = deviceFor(context.config);
121
+ const desired = desiredGeminiOtelEnv(context, hasCredential(context.config) ? BEARER_PLACEHOLDER : undefined);
118
122
  if (!desired)
119
123
  return { supported: true, configured: false, detail: 'no backend endpoint configured' };
120
- const matches = Object.entries(desired).every(([key, value]) => envBlock[key] === value);
124
+ const headers = envBlock[OTLP_HEADERS_KEY];
125
+ // An install key still in the header list once a device exists is stale.
126
+ if (device && context.config.token && typeof headers === 'string' && headers.includes(context.config.token)) {
127
+ return { supported: true, configured: false, detail: 'telemetry headers still hold the install key — run `agentwatch setup`' };
128
+ }
129
+ const actual = typeof headers === 'string' ? { ...envBlock, [OTLP_HEADERS_KEY]: headers.replace(RE_BEARER_PAIR, `$1${BEARER_PLACEHOLDER}`) } : envBlock;
130
+ const matches = Object.entries(desired).every(([key, value]) => actual[key] === value);
121
131
  // A helper entry left by an older version is dead weight Gemini ignores;
122
132
  // reporting "configured" would hide that setup still has work to do. A
123
133
  // helper belonging to another tool is none of our business.
@@ -125,7 +135,7 @@ export class GeminiOtelConfigurator {
125
135
  return { supported: true, configured: true };
126
136
  if (matches)
127
137
  return { supported: true, configured: false, detail: 'stale otelHeadersHelper entry — run `agentwatch setup`' };
128
- const conflicting = foreignKeys(envBlock, desired, ownedKeys);
138
+ const conflicting = foreignKeys(actual, desired, ownedKeys);
129
139
  if (conflicting.length > 0) {
130
140
  return { supported: true, configured: false, conflict: `existing telemetry env vars: ${conflicting.join(', ')}` };
131
141
  }
@@ -139,7 +149,7 @@ export class GeminiOtelConfigurator {
139
149
  * install state.
140
150
  */
141
151
  async configure(context) {
142
- const desired = desiredGeminiOtelEnv(context);
152
+ const desired = desiredGeminiOtelEnv(context, context.bearer);
143
153
  if (!desired)
144
154
  return this.configureDisabled(context);
145
155
  const settingsPath = geminiSettingsPath(context.env);
@@ -271,6 +281,36 @@ export class GeminiOtelConfigurator {
271
281
  installState: removed.installState
272
282
  };
273
283
  }
284
+ /**
285
+ * Swap the bearer in our `OTEL_EXPORTER_OTLP_HEADERS` for the current one.
286
+ *
287
+ * Only when a setup recorded the key as ours, and only the bearer in it
288
+ * changes. No backup: one per rotation would collect copies of every token.
289
+ *
290
+ * @param context - The recorded file, its contents as read, install state and the current bearer.
291
+ * @returns True when the file was rewritten.
292
+ */
293
+ async rewriteBearer(context) {
294
+ if (!context.installState.agents[GEMINI_PROVIDER_ID]?.otelOwnedKeys.includes(OTLP_HEADERS_KEY))
295
+ return false;
296
+ const settings = parseJsonLine(context.raw);
297
+ const envBlock = asRecord(settings?.[ENV_BLOCK_KEY]);
298
+ const headers = envBlock?.[OTLP_HEADERS_KEY];
299
+ if (!envBlock || typeof headers !== 'string')
300
+ return false;
301
+ const next = headers.replace(RE_BEARER_PAIR, (_match, head) => head + context.bearer);
302
+ if (next === headers)
303
+ return false;
304
+ // In place when the value appears once as written, so the developer's
305
+ // formatting survives every rotation; re-serialized only when it does not.
306
+ const written = JSON.stringify(headers);
307
+ const at = context.raw.indexOf(written);
308
+ const inPlace = at !== -1 && at === context.raw.lastIndexOf(written) ? context.raw.slice(0, at) + JSON.stringify(next) + context.raw.slice(at + written.length) : '';
309
+ const contents = asRecord(parseJsonLine(inPlace)?.[ENV_BLOCK_KEY])?.[OTLP_HEADERS_KEY] === next
310
+ ? inPlace
311
+ : `${JSON.stringify({ ...settings, [ENV_BLOCK_KEY]: { ...envBlock, [OTLP_HEADERS_KEY]: next } }, null, 2)}\n`;
312
+ return writeIfUnchanged(context.configPath, context.raw, contents, SECRET_FILE_MODE);
313
+ }
274
314
  /**
275
315
  * Signals Gemini was asked for but will not be given under current consent.
276
316
  *
@@ -0,0 +1,19 @@
1
+ import type { AgentWatchPaths } from '../../storage/types/storage.types.js';
2
+ /**
3
+ * Put the machine's current access token into every agent config that holds
4
+ * a literal OTLP bearer (Codex, Gemini).
5
+ *
6
+ * They read that header once, when a session starts
7
+ * (docs/NATIVE_OTLP_TOKENS.md), so the hook keeps the file on the live token
8
+ * for the next session. An agent is loaded only when its file holds a bearer
9
+ * that is not this one, so the usual hook pays one small read per agent and no
10
+ * import. Each agent changes nothing but its own bearer.
11
+ *
12
+ * Never throws: a file that cannot be read or written is left as it is, and
13
+ * the next hook tries again.
14
+ *
15
+ * @param paths - Resolved AgentWatch paths, for the install state.
16
+ * @param bearer - The machine's current access token.
17
+ * @returns How many files were rewritten.
18
+ */
19
+ export declare function rewriteNativeBearers(paths: AgentWatchPaths, bearer: string): Promise<number>;
@@ -0,0 +1,46 @@
1
+ import fs from 'node:fs/promises';
2
+ import { debugLog } from '../../core/logger.js';
3
+ import { loadInstallState } from '../../storage/install-state.js';
4
+ import { BEARER_PREFIX } from '../constants/provider.constants.js';
5
+ import { loadProvider } from '../loaders.js';
6
+ /**
7
+ * Put the machine's current access token into every agent config that holds
8
+ * a literal OTLP bearer (Codex, Gemini).
9
+ *
10
+ * They read that header once, when a session starts
11
+ * (docs/NATIVE_OTLP_TOKENS.md), so the hook keeps the file on the live token
12
+ * for the next session. An agent is loaded only when its file holds a bearer
13
+ * that is not this one, so the usual hook pays one small read per agent and no
14
+ * import. Each agent changes nothing but its own bearer.
15
+ *
16
+ * Never throws: a file that cannot be read or written is left as it is, and
17
+ * the next hook tries again.
18
+ *
19
+ * @param paths - Resolved AgentWatch paths, for the install state.
20
+ * @param bearer - The machine's current access token.
21
+ * @returns How many files were rewritten.
22
+ */
23
+ export async function rewriteNativeBearers(paths, bearer) {
24
+ let rewritten = 0;
25
+ try {
26
+ const installState = await loadInstallState(paths);
27
+ for (const [id, agent] of Object.entries(installState.agents)) {
28
+ const configPath = agent.otelConfigPath;
29
+ const raw = configPath ? await fs.readFile(configPath, 'utf8').catch(() => '') : '';
30
+ if (!configPath || !raw.includes(BEARER_PREFIX) || raw.includes(BEARER_PREFIX + bearer))
31
+ continue;
32
+ try {
33
+ const configurator = (await loadProvider(id))?.nativeTelemetry;
34
+ if (await configurator?.rewriteBearer?.({ configPath, installState, bearer, raw }))
35
+ rewritten++;
36
+ }
37
+ catch (error) {
38
+ debugLog(`${id}: rewriting the native exporter bearer failed:`, error);
39
+ }
40
+ }
41
+ }
42
+ catch (error) {
43
+ debugLog('rewriting native exporter bearers failed:', error);
44
+ }
45
+ return rewritten;
46
+ }
@@ -14,6 +14,10 @@ export declare const FILE_EDIT_TOOLS: ReadonlySet<string>;
14
14
  /** Prefix and separator of an MCP tool name. */
15
15
  export declare const MCP_TOOL_PREFIX = "mcp__";
16
16
  export declare const MCP_TOOL_SEPARATOR = "__";
17
+ /** Key a turn's MCP calls fold into under `capture.mcpNames: false`. */
18
+ export declare const MCP_FOLDED_KEY = "mcp";
19
+ /** The bridge's bound on a `tools_used` key. */
20
+ export declare const MAX_TOOL_KEY_LENGTH = 200;
17
21
  /**
18
22
  * Keys a file path may arrive under, in priority order.
19
23
  *
@@ -39,3 +43,5 @@ export declare const SHELL_COMMAND_KEY = "command";
39
43
  * stuffed with them; the agent bounds the prompt before the hook sees it.
40
44
  */
41
45
  export declare const RE_HARNESS_BLOCK: RegExp;
46
+ /** The executable of a command line: a double-quoted, single-quoted or bare first word. */
47
+ export declare const COMMAND_HEAD: RegExp;
@@ -14,6 +14,10 @@ export const FILE_EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookE
14
14
  /** Prefix and separator of an MCP tool name. */
15
15
  export const MCP_TOOL_PREFIX = 'mcp__';
16
16
  export const MCP_TOOL_SEPARATOR = '__';
17
+ /** Key a turn's MCP calls fold into under `capture.mcpNames: false`. */
18
+ export const MCP_FOLDED_KEY = 'mcp';
19
+ /** The bridge's bound on a `tools_used` key. */
20
+ export const MAX_TOOL_KEY_LENGTH = 200;
17
21
  /**
18
22
  * Keys a file path may arrive under, in priority order.
19
23
  *
@@ -39,3 +43,5 @@ export const SHELL_COMMAND_KEY = 'command';
39
43
  * stuffed with them; the agent bounds the prompt before the hook sees it.
40
44
  */
41
45
  export const RE_HARNESS_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
46
+ /** The executable of a command line: a double-quoted, single-quoted or bare first word. */
47
+ export const COMMAND_HEAD = /^\s*(?:"([^"]*)"|'([^']*)'|(\S+))/;
@@ -32,6 +32,34 @@ export declare function toolCompleteType(kind: ToolKind): CanonicalEventType;
32
32
  * @returns The server and tool, or an empty object for a non-MCP name.
33
33
  */
34
34
  export declare function parseMcpToolName(toolName: string): McpToolName;
35
+ /**
36
+ * The `tools_used` key of an MCP call: `mcp__<server>__<tool>`, no arguments.
37
+ *
38
+ * One builder for every provider so the backend can split the key back apart.
39
+ * Scrubbed and cut at the bridge's bound, because a server can come from a
40
+ * URL host or a command and must never carry a credential into a key.
41
+ *
42
+ * @param server - Server's logical name, host or command base name.
43
+ * @param tool - Tool name on that server.
44
+ * @returns The key.
45
+ */
46
+ export declare function mcpToolKey(server: string, tool: string): string;
47
+ /**
48
+ * Fold every `mcp__*` key of a `tools_used` map into `mcp`, keeping the count.
49
+ *
50
+ * @param toolsUsed - Per-tool call counts.
51
+ * @returns The counts with MCP server and tool names withheld.
52
+ */
53
+ export declare function foldMcpNames(toolsUsed: Readonly<Record<string, number>>): Record<string, number>;
54
+ /**
55
+ * Server name of a Cursor MCP hook that carries no `mcp__` name: the host of a
56
+ * remote endpoint, else the base name of a stdio command (first word, quote-aware).
57
+ *
58
+ * @param url - The remote endpoint, if any.
59
+ * @param command - The stdio command line, if any.
60
+ * @returns The server, or undefined when neither yields one.
61
+ */
62
+ export declare function mcpServerFromEndpoint(url: string | undefined, command: string | undefined): string | undefined;
35
63
  /**
36
64
  * Length and hash of text, as evidence for content we may not transmit.
37
65
  *