@agent-watch-ai/edge 0.3.1 → 0.5.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 (123) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +10 -6
  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 +2 -2
  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/repo-config.js +1 -1
  17. package/dist/config/schemas/config.schema.d.ts +113 -767
  18. package/dist/config/schemas/config.schema.js +17 -8
  19. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  20. package/dist/credentials/constants/credentials.constants.js +9 -1
  21. package/dist/credentials/credential-status.js +8 -4
  22. package/dist/credentials/credentials.d.ts +16 -2
  23. package/dist/credentials/credentials.js +30 -5
  24. package/dist/credentials/device-api.d.ts +10 -1
  25. package/dist/credentials/device-api.js +12 -1
  26. package/dist/credentials/identity.d.ts +12 -1
  27. package/dist/credentials/identity.js +12 -1
  28. package/dist/credentials/migration.d.ts +1 -1
  29. package/dist/credentials/migration.js +1 -1
  30. package/dist/credentials/schemas/device-api.schema.d.ts +4 -51
  31. package/dist/credentials/schemas/device-state.schema.d.ts +3 -38
  32. package/dist/credentials/sign-in.d.ts +14 -1
  33. package/dist/credentials/sign-in.js +24 -5
  34. package/dist/credentials/types/credentials.types.d.ts +12 -1
  35. package/dist/enforcement/decision-client.js +2 -1
  36. package/dist/enforcement/enforcement.js +7 -5
  37. package/dist/enforcement/types/enforcement.types.d.ts +2 -2
  38. package/dist/git/code-state.d.ts +33 -0
  39. package/dist/git/code-state.js +44 -0
  40. package/dist/git/constants/git.constants.d.ts +6 -0
  41. package/dist/git/constants/git.constants.js +6 -0
  42. package/dist/git/index.d.ts +2 -1
  43. package/dist/git/index.js +1 -0
  44. package/dist/git/types/git.types.d.ts +6 -0
  45. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  46. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  47. package/dist/pipeline/hook-pipeline.js +56 -7
  48. package/dist/privacy/command-fingerprint.d.ts +42 -0
  49. package/dist/privacy/command-fingerprint.js +249 -0
  50. package/dist/privacy/constants/command-fingerprint.constants.d.ts +34 -0
  51. package/dist/privacy/constants/command-fingerprint.constants.js +38 -0
  52. package/dist/privacy/index.d.ts +3 -1
  53. package/dist/privacy/index.js +2 -0
  54. package/dist/privacy/product-capture.js +20 -0
  55. package/dist/privacy/types/privacy.types.d.ts +7 -0
  56. package/dist/providers/antigravity/antigravity.adapter.js +3 -0
  57. package/dist/providers/antigravity/schemas/antigravity.schema.d.ts +18 -492
  58. package/dist/providers/claude/claude.adapter.js +12 -1
  59. package/dist/providers/claude/constants/claude.constants.d.ts +6 -0
  60. package/dist/providers/claude/constants/claude.constants.js +6 -0
  61. package/dist/providers/claude/schemas/claude.schema.d.ts +1 -43
  62. package/dist/providers/codex/codex.adapter.js +14 -0
  63. package/dist/providers/codex/codex.otel.d.ts +12 -1
  64. package/dist/providers/codex/codex.otel.js +61 -11
  65. package/dist/providers/codex/constants/codex.otel.constants.d.ts +5 -0
  66. package/dist/providers/codex/constants/codex.otel.constants.js +5 -0
  67. package/dist/providers/codex/schemas/codex.schema.d.ts +1 -41
  68. package/dist/providers/constants/provider.constants.d.ts +8 -0
  69. package/dist/providers/constants/provider.constants.js +8 -0
  70. package/dist/providers/cursor/constants/cursor.constants.d.ts +2 -0
  71. package/dist/providers/cursor/constants/cursor.constants.js +2 -0
  72. package/dist/providers/cursor/cursor.adapter.js +84 -5
  73. package/dist/providers/cursor/schemas/cursor.schema.d.ts +5 -85
  74. package/dist/providers/gemini/constants/gemini.constants.d.ts +2 -0
  75. package/dist/providers/gemini/constants/gemini.constants.js +2 -0
  76. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +16 -1
  77. package/dist/providers/gemini/constants/gemini.otel.constants.js +16 -1
  78. package/dist/providers/gemini/gemini.detect.d.ts +11 -0
  79. package/dist/providers/gemini/gemini.detect.js +14 -1
  80. package/dist/providers/gemini/gemini.hooks.d.ts +3 -3
  81. package/dist/providers/gemini/gemini.hooks.js +5 -5
  82. package/dist/providers/gemini/gemini.otel.d.ts +14 -4
  83. package/dist/providers/gemini/gemini.otel.js +418 -107
  84. package/dist/providers/gemini/schemas/gemini.schema.d.ts +1 -49
  85. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  86. package/dist/providers/shared/bearer-rewrite.js +46 -0
  87. package/dist/providers/shared/constants/tooling.constants.d.ts +6 -0
  88. package/dist/providers/shared/constants/tooling.constants.js +6 -0
  89. package/dist/providers/shared/event-builder.d.ts +17 -2
  90. package/dist/providers/shared/event-builder.js +43 -3
  91. package/dist/providers/shared/install-record.d.ts +2 -0
  92. package/dist/providers/shared/install-record.js +3 -2
  93. package/dist/providers/shared/tooling.d.ts +35 -0
  94. package/dist/providers/shared/tooling.js +61 -1
  95. package/dist/providers/shared/types/adapter.types.d.ts +18 -0
  96. package/dist/providers/types/provider.types.d.ts +24 -0
  97. package/dist/storage/atomic-file.d.ts +14 -0
  98. package/dist/storage/atomic-file.js +19 -0
  99. package/dist/storage/constants/storage.constants.d.ts +2 -0
  100. package/dist/storage/constants/storage.constants.js +2 -0
  101. package/dist/storage/schemas/storage.schema.d.ts +11 -175
  102. package/dist/storage/schemas/storage.schema.js +7 -1
  103. package/dist/transport/schemas/queue.schema.d.ts +1 -16
  104. package/dist/transport/schemas/queue.schema.js +1 -1
  105. package/dist/turns/constants/turns.constants.d.ts +17 -0
  106. package/dist/turns/constants/turns.constants.js +17 -0
  107. package/dist/turns/index.d.ts +3 -2
  108. package/dist/turns/index.js +1 -0
  109. package/dist/turns/tool-events.d.ts +15 -0
  110. package/dist/turns/tool-events.js +59 -0
  111. package/dist/turns/turn-state.js +2 -2
  112. package/dist/turns/turn-summary.d.ts +1 -1
  113. package/dist/turns/turn-summary.js +1 -0
  114. package/dist/turns/turn-tracker.js +138 -7
  115. package/dist/turns/types/turn-state.types.d.ts +28 -1
  116. package/dist/turns/types/turn-summary.types.d.ts +30 -0
  117. package/dist/turns/types/turn-tracker.types.d.ts +10 -0
  118. package/dist/turns/work-checkout.d.ts +5 -3
  119. package/dist/turns/work-checkout.js +46 -12
  120. package/docs/AUDIT_PROMPT.md +11 -0
  121. package/docs/DATA_HANDLING.md +69 -14
  122. package/docs/ENTERPRISE_DEPLOYMENT.md +21 -5
  123. package/package.json +9 -8
@@ -1,15 +1,19 @@
1
+ import { existsSync } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
1
4
  import { asRecord, omitKeys } from '../../core/object.js';
2
5
  import { enabledSignalNames, otlpBaseUrl, toolContentConsented } from '../../config/config.js';
3
6
  import { INSTALLATION_HEADER } from '../../transport/constants/transport.constants.js';
4
- import { backupFile, currentMode } from '../../storage/atomic-file.js';
7
+ import { backupFile, currentMode, writeFileAtomic, writeIfUnchanged } from '../../storage/atomic-file.js';
5
8
  import { SECRET_FILE_MODE } from '../../storage/constants/storage.constants.js';
6
9
  import { readJsonFile } from '../../storage/json-file.js';
7
- import { HOOK_COMMAND_MARKER } from '../constants/provider.constants.js';
10
+ import { deviceFor, hasCredential } from '../../credentials/identity.js';
11
+ import { BEARER_PLACEHOLDER, HOOK_COMMAND_MARKER } from '../constants/provider.constants.js';
8
12
  import { writeJsonValidated } from '../shared/hook-config.js';
9
13
  import { withOtelInstall, withoutOtelInstall } from '../shared/install-record.js';
10
- import { geminiSettingsPath } from './gemini.detect.js';
11
- 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 { geminiEnvPath, geminiSettingsPath } from './gemini.detect.js';
15
+ import { GEMINI_ENV_FILE, GEMINI_HOME_DIR, GEMINI_PROVIDER_ID } from './constants/gemini.constants.js';
16
+ 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, RE_ENV_LINE, RE_QUOTED_VALUE, STANDARD_OTLP_PROTOCOL, TELEMETRY_BLOCK_KEY } from './constants/gemini.otel.constants.js';
13
17
  /**
14
18
  * Gemini's own prompt-logging switch, forced off.
15
19
  *
@@ -38,10 +42,11 @@ const CONTENT_LOG_OFF = {
38
42
  * which is fail-closed, answered 401 to every batch.
39
43
  *
40
44
  * @param context - Environment, paths and effective config.
45
+ * @param bearer - What to authenticate with; see `SetupContext.bearer`.
41
46
  * @returns The desired variables, or undefined when telemetry is off or no
42
47
  * backend is configured.
43
48
  */
44
- function desiredGeminiOtelEnv(context) {
49
+ function desiredGeminiOtelEnv(context, bearer) {
45
50
  const otlpBase = otlpBaseUrl(context.config);
46
51
  const signals = safeGeminiSignals(context.config);
47
52
  if (!otlpBase || !anySignal(signals))
@@ -58,9 +63,7 @@ function desiredGeminiOtelEnv(context) {
58
63
  OTEL_TRACES_EXPORTER: signals.traces ? OTEL_EXPORTER_OTLP : OTEL_EXPORTER_NONE,
59
64
  OTEL_EXPORTER_OTLP_PROTOCOL: STANDARD_OTLP_PROTOCOL,
60
65
  OTEL_EXPORTER_OTLP_ENDPOINT: otlpBase,
61
- ...(context.config.token
62
- ? { [OTLP_HEADERS_KEY]: otlpHeaders(context.config.token, context.config.installationId) }
63
- : {})
66
+ ...(bearer ? { [OTLP_HEADERS_KEY]: otlpHeaders(bearer, context.config.installationId) } : {})
64
67
  };
65
68
  }
66
69
  /**
@@ -74,7 +77,7 @@ function desiredGeminiOtelEnv(context) {
74
77
  * for Codex: a header builder that reads a config can be handed one with no
75
78
  * token and quietly emit `Bearer ` rather than refusing to be called.
76
79
  *
77
- * @param token - The ingest token; the caller has already checked there is one.
80
+ * @param token - The access token; the caller has already checked there is one.
78
81
  * @param installationId - This installation's id, when one exists.
79
82
  * @returns The header list for the exporter.
80
83
  */
@@ -84,7 +87,37 @@ function otlpHeaders(token, installationId) {
84
87
  pairs.push(`${INSTALLATION_HEADER}=${installationId}`);
85
88
  return pairs.join(',');
86
89
  }
87
- /** Configures Gemini CLI's own OTLP export. */
90
+ /**
91
+ * The same switch, target, endpoint and prompt-logging-off in Gemini's native
92
+ * settings.json `telemetry` block, keyed `telemetry.<field>`.
93
+ *
94
+ * Gemini reads only the first `.env` it finds walking up from the folder, so a
95
+ * project `.env` hides ours. These settings still apply there; the bearer does
96
+ * not, as the block has no header field. `logPrompts` is set because Gemini's
97
+ * default is true.
98
+ *
99
+ * @param desired - The `.env` variables being written.
100
+ * @returns The fields to set, by owned key.
101
+ */
102
+ function desiredTelemetryFields(desired) {
103
+ return {
104
+ [`${TELEMETRY_BLOCK_KEY}.enabled`]: true,
105
+ [`${TELEMETRY_BLOCK_KEY}.target`]: GEMINI_TELEMETRY_TARGET_LOCAL,
106
+ [`${TELEMETRY_BLOCK_KEY}.otlpEndpoint`]: desired.GEMINI_TELEMETRY_OTLP_ENDPOINT,
107
+ [`${TELEMETRY_BLOCK_KEY}.otlpProtocol`]: GEMINI_OTLP_PROTOCOL,
108
+ [`${TELEMETRY_BLOCK_KEY}.logPrompts`]: false
109
+ };
110
+ }
111
+ /**
112
+ * The settings.json field an owned key names.
113
+ *
114
+ * @param key - An owned key.
115
+ * @returns The `telemetry` field, or undefined for a `.env` key.
116
+ */
117
+ function telemetryField(key) {
118
+ return key.startsWith(`${TELEMETRY_BLOCK_KEY}.`) ? key.slice(TELEMETRY_BLOCK_KEY.length + 1) : undefined;
119
+ }
120
+ /** Configures Gemini CLI's own OTLP export, through `~/.gemini/.env` and settings.json. */
88
121
  export class GeminiOtelConfigurator {
89
122
  /**
90
123
  * Whether this agent can export native telemetry at all.
@@ -102,91 +135,111 @@ export class GeminiOtelConfigurator {
102
135
  * @returns The status, naming any foreign configuration in the way.
103
136
  */
104
137
  async inspect(context) {
105
- const disabled = !anySignal(safeGeminiSignals(context.config));
106
- const read = await readJsonFile(geminiSettingsPath(context.env));
107
- const settings = read.state === 'ok' ? asRecord(read.value) : undefined;
108
- if (!settings) {
109
- if (disabled && read.state === 'missing')
110
- return { supported: true, configured: true, detail: 'disabled in config (otel)' };
111
- return { supported: true, configured: false, detail: read.state === 'invalid' ? 'settings unparseable' : 'no settings file' };
138
+ if (legacyRecorded(context)) {
139
+ return { supported: true, configured: false, detail: 'telemetry still in settings.json, which Gemini does not read — run `agentwatch setup`' };
112
140
  }
113
- const envBlock = asRecord(settings[ENV_BLOCK_KEY]) ?? {};
141
+ const raw = await readEnvFile(geminiEnvPath(context.env));
142
+ if (raw === null)
143
+ return { supported: true, configured: false, detail: '.env unreadable' };
144
+ const envFile = parseEnv(raw ?? '');
114
145
  const ownedKeys = ownedKeysOf(context);
115
- if (disabled)
116
- return inspectDisabled(settings, envBlock, ownedKeys);
117
- const desired = desiredGeminiOtelEnv(context);
146
+ if (!anySignal(safeGeminiSignals(context.config)))
147
+ return inspectDisabled(envFile, ownedKeys, anySignal(context.config.otel));
148
+ // The bearer's value is not compared: it is the access token, which the hook
149
+ // path rotates. Only whether a header is there, when there is a credential.
150
+ const device = deviceFor(context.config);
151
+ const desired = desiredGeminiOtelEnv(context, hasCredential(context.config) ? BEARER_PLACEHOLDER : undefined);
118
152
  if (!desired)
119
153
  return { supported: true, configured: false, detail: 'no backend endpoint configured' };
120
- const matches = Object.entries(desired).every(([key, value]) => envBlock[key] === value);
121
- // A helper entry left by an older version is dead weight Gemini ignores;
122
- // reporting "configured" would hide that setup still has work to do. A
123
- // helper belonging to another tool is none of our business.
124
- if (matches && !hasOurLegacyHelper(settings))
125
- return { supported: true, configured: true };
126
- if (matches)
127
- return { supported: true, configured: false, detail: 'stale otelHeadersHelper entry — run `agentwatch setup`' };
128
- const conflicting = foreignKeys(envBlock, desired, ownedKeys);
129
- if (conflicting.length > 0) {
130
- return { supported: true, configured: false, conflict: `existing telemetry env vars: ${conflicting.join(', ')}` };
154
+ if (raw === undefined)
155
+ return { supported: true, configured: false, detail: 'no .env file' };
156
+ const headers = envFile[OTLP_HEADERS_KEY];
157
+ // An install key still in the header list once a device exists is stale.
158
+ if (device && context.config.token && headers?.includes(context.config.token)) {
159
+ return { supported: true, configured: false, detail: 'telemetry headers still hold the install key — run `agentwatch setup`' };
160
+ }
161
+ const actual = headers === undefined ? envFile : { ...envFile, [OTLP_HEADERS_KEY]: headers.replace(RE_BEARER_PAIR, `$1${BEARER_PLACEHOLDER}`) };
162
+ if (!Object.entries(desired).every(([key, value]) => actual[key] === value)) {
163
+ const conflicting = foreignKeys(actual, desired, ownedKeys);
164
+ if (conflicting.length > 0) {
165
+ return { supported: true, configured: false, conflict: `existing telemetry env vars: ${conflicting.join(', ')}` };
166
+ }
167
+ return { supported: true, configured: false };
131
168
  }
132
- return { supported: true, configured: false };
169
+ const block = await settingsTelemetry(context.env);
170
+ if (!Object.entries(desiredTelemetryFields(desired)).every(([key, value]) => block[telemetryField(key)] === value)) {
171
+ return { supported: true, configured: false, detail: 'settings.json telemetry block missing or changed — run `agentwatch setup`' };
172
+ }
173
+ const shadow = shadowingEnvFile(context.env.cwd, geminiEnvPath(context.env));
174
+ if (shadow) {
175
+ return { supported: true, configured: false, conflict: `Gemini loads ${shadow} in this folder, not ${geminiEnvPath(context.env)}, so it exports without the AgentWatch token` };
176
+ }
177
+ return { supported: true, configured: true };
133
178
  }
134
179
  /**
135
- * Write the telemetry configuration into Gemini CLI's settings.
180
+ * Write the telemetry configuration into Gemini CLI's `.env`.
136
181
  *
137
182
  * @param context - Environment, paths, config and install state.
138
183
  * @returns Whether the file changed, what to tell the user, and the next
139
184
  * install state.
140
185
  */
141
186
  async configure(context) {
142
- const desired = desiredGeminiOtelEnv(context);
187
+ const desired = desiredGeminiOtelEnv(context, context.bearer);
143
188
  if (!desired)
144
189
  return this.configureDisabled(context);
145
- const settingsPath = geminiSettingsPath(context.env);
146
- const read = await readJsonFile(settingsPath);
147
- if (read.state === 'invalid') {
148
- return { ok: false, changed: false, messages: [`refusing to modify unparseable ${settingsPath} (${read.error})`] };
149
- }
150
- if (read.state === 'ok' && !asRecord(read.value)) {
151
- return { ok: false, changed: false, messages: [`refusing to modify ${settingsPath}: top level is not an object`] };
152
- }
153
- const settings = (read.state === 'ok' ? asRecord(read.value) : undefined) ?? {};
154
- const envBlock = asRecord(settings[ENV_BLOCK_KEY]) ?? {};
190
+ const envPath = geminiEnvPath(context.env);
191
+ const read = await readEnvFile(envPath);
192
+ if (read === null)
193
+ return unreadable(envPath);
194
+ const raw = read ?? '';
155
195
  const ownedKeys = ownedKeysOf(context);
156
- const conflicting = foreignKeys(envBlock, desired, ownedKeys);
196
+ const fields = desiredTelemetryFields(desired);
197
+ const block = await settingsTelemetry(context.env);
198
+ const current = { ...parseEnv(raw), ...Object.fromEntries(Object.keys(fields).map((key) => [key, block[telemetryField(key)]])) };
199
+ const conflicting = foreignKeys(current, { ...desired, ...fields }, ownedKeys);
157
200
  if (conflicting.length > 0) {
158
201
  return {
159
202
  ok: false,
160
203
  changed: false,
161
- messages: [`skipping native OpenTelemetry: ${conflicting.join(', ')} already set in ${settingsPath} (not AgentWatch-owned)`]
204
+ messages: [`skipping native OpenTelemetry: ${conflicting.join(', ')} already set in ${envPath} or settings.json (not AgentWatch-owned)`]
162
205
  };
163
206
  }
207
+ const legacy = await updateSettings(context, false, fields);
208
+ if (!legacy.ok)
209
+ return legacy;
210
+ // What each key held before we first set it, so uninstall gives it back. A
211
+ // key already ours keeps what was recorded when it was taken.
212
+ const owned = new Set(ownedKeys);
213
+ const previous = priorValuesOf(context);
214
+ const before = { ...envLinesByKey(raw), ...legacy.prior };
215
+ const priorValues = Object.fromEntries([...Object.keys(desired), ...Object.keys(fields)].flatMap((key) => {
216
+ const prior = owned.has(key) ? previous[key] : before[key];
217
+ return prior === undefined ? [] : [[key, prior]];
218
+ }));
164
219
  // Keys we own that this configuration no longer wants (a signal turned off
165
- // since the last run) would otherwise linger.
166
- const stale = new Set(ownedKeys.filter((key) => key !== LEGACY_HELPER_KEY && desired[key] === undefined));
167
- const withEnv = { ...settings, [ENV_BLOCK_KEY]: { ...omitKeys(envBlock, stale), ...desired } };
168
- // Gemini never read this; leaving it behind only confuses the next reader.
169
- const nextSettings = hasOurLegacyHelper(withEnv) ? omitKeys(withEnv, new Set([LEGACY_HELPER_KEY])) : withEnv;
170
- const changed = JSON.stringify(nextSettings) !== JSON.stringify(settings);
171
- // Only when the block actually carries the bearer. This file is Gemini's,
172
- // not ours, and `writeFileAtomic` preserves the target's mode by design —
173
- // so tightening it unconditionally changed another tool's permissions on a
174
- // shared workstation for no reason, and could never be undone.
220
+ // since the last run) would otherwise linger; the developer's own go back.
221
+ const staleKeys = ownedKeys.filter((key) => desired[key] === undefined && !Object.hasOwn(fields, key));
222
+ const lines = Object.fromEntries(Object.entries(desired).map(([key, value]) => [key, `${key}=${value}`]));
223
+ const next = rewriteEnv(raw, { ...lines, ...restoredLines(previous, staleKeys) }, new Set(staleKeys));
224
+ const changed = next !== raw;
225
+ // Only when the file actually carries the bearer: without one there is
226
+ // nothing to protect, and the developer's own file keeps its mode.
175
227
  const carriesCredential = desired[OTLP_HEADERS_KEY] !== undefined;
176
- const priorMode = carriesCredential ? await currentMode(settingsPath) : undefined;
228
+ const priorMode = carriesCredential ? await currentMode(envPath) : undefined;
177
229
  if (changed) {
178
- await backupFile(settingsPath, context.paths.backupsDir, context.env.now());
179
- await writeJsonValidated(settingsPath, nextSettings, carriesCredential ? SECRET_FILE_MODE : undefined);
230
+ await backupFile(envPath, context.paths.backupsDir, context.env.now());
231
+ await writeFileAtomic(envPath, next, carriesCredential ? SECRET_FILE_MODE : undefined);
180
232
  }
181
233
  return {
182
234
  ok: true,
183
- changed,
184
- messages: changed
235
+ changed: changed || legacy.changed,
236
+ messages: changed || legacy.changed
185
237
  ? [`native OpenTelemetry configured (signals: ${enabledSignalNames(safeGeminiSignals(context.config)).join(', ')})`, 'restart running Gemini CLI sessions to pick it up']
186
238
  : ['native OpenTelemetry already up to date'],
187
- installState: withOtelInstall(context.installState, GEMINI_PROVIDER_ID, {
188
- configPath: settingsPath,
189
- ownedKeys: Object.keys(desired),
239
+ installState: withOtelInstall(legacy.installState ?? context.installState, GEMINI_PROVIDER_ID, {
240
+ configPath: envPath,
241
+ ownedKeys: [...Object.keys(desired), ...Object.keys(fields)],
242
+ priorValues,
190
243
  configuredAt: context.env.now(),
191
244
  ...(changed && priorMode !== undefined && priorMode !== SECRET_FILE_MODE ? { priorMode } : {})
192
245
  })
@@ -196,35 +249,39 @@ export class GeminiOtelConfigurator {
196
249
  * Remove the telemetry configuration AgentWatch wrote.
197
250
  *
198
251
  * @param context - Environment, paths, config and install state.
199
- * @returns Whether the file changed, what to tell the user, and the next
252
+ * @returns Whether a file changed, what to tell the user, and the next
200
253
  * install state.
201
254
  */
202
255
  async uninstall(context) {
203
- const settingsPath = geminiSettingsPath(context.env);
204
- const read = await readJsonFile(settingsPath);
205
- if (read.state === 'missing')
206
- return { ok: true, changed: false, messages: ['no Gemini settings file'] };
207
- if (read.state === 'invalid') {
208
- return { ok: false, changed: false, messages: [`refusing to modify unparseable ${settingsPath} (${read.error})`] };
209
- }
210
- const settings = asRecord(read.value);
211
- if (!settings) {
212
- return { ok: false, changed: false, messages: [`refusing to modify ${settingsPath}: top level is not an object`] };
213
- }
214
- const removable = new Set((context.installState.agents[GEMINI_PROVIDER_ID]?.otelOwnedKeys ?? GEMINI_LEGACY_OWNED_KEYS).filter((key) => key !== LEGACY_HELPER_KEY));
215
- const nextSettings = strippedSettings(settings, removable);
216
- const changed = JSON.stringify(nextSettings) !== JSON.stringify(settings);
256
+ const owned = ownedKeysOf(context);
257
+ const priors = priorValuesOf(context);
258
+ const record = context.installState.agents[GEMINI_PROVIDER_ID];
259
+ // The file setup wrote, even when HOME or GEMINI_HOME differ now.
260
+ const envPath = owned.length > 0 && record?.otelConfigPath ? record.otelConfigPath : geminiEnvPath(context.env);
261
+ const raw = await readEnvFile(envPath);
262
+ if (raw === null)
263
+ return unreadable(envPath);
264
+ // No record at all (none written yet, or the state file was unreadable):
265
+ // the names AgentWatch writes count as ours, but only in a file whose
266
+ // header line carries our installation header, so `off` still removes the
267
+ // bearer and a developer's own collector lines stay.
268
+ const removable = owned.length > 0 || !parseEnv(raw ?? '')[OTLP_HEADERS_KEY]?.includes(INSTALLATION_HEADER) ? owned : GEMINI_LEGACY_OWNED_KEYS;
269
+ const next = raw === undefined ? '' : rewriteEnv(raw, restoredLines(priors, removable), new Set(removable));
270
+ const changed = raw !== undefined && next !== raw;
217
271
  if (changed) {
218
- await backupFile(settingsPath, context.paths.backupsDir, context.env.now());
219
- // The mode the file had before AgentWatch tightened it, when it was
220
- // tightened. `writeJsonValidated` with no mode would otherwise keep our
221
- // 0600 on a file that no longer holds a token.
222
- await writeJsonValidated(settingsPath, nextSettings, context.installState.agents[GEMINI_PROVIDER_ID]?.otelPriorMode);
272
+ await backupFile(envPath, context.paths.backupsDir, context.env.now());
273
+ await (next.trim() ? writeFileAtomic(envPath, next, record?.otelPriorMode) : fs.rm(envPath, { force: true }));
223
274
  }
275
+ // After the .env, so a settings.json Gemini parses but we cannot never
276
+ // keeps the bearer in place. Our fields go back to what they held, or go.
277
+ const fields = Object.fromEntries(owned.filter((key) => telemetryField(key)).map((key) => [key, parsePrior(priors[key])]));
278
+ const legacy = await updateSettings(context, true, fields);
279
+ if (!legacy.ok)
280
+ return { ...legacy, changed: changed || legacy.changed };
224
281
  return {
225
282
  ok: true,
226
- changed,
227
- messages: changed ? ['native OpenTelemetry configuration removed'] : ['no AgentWatch OpenTelemetry configuration found'],
283
+ changed: changed || legacy.changed,
284
+ messages: changed || legacy.changed ? ['native OpenTelemetry configuration removed'] : ['no AgentWatch OpenTelemetry configuration found'],
228
285
  installState: withoutOtelInstall(context.installState, GEMINI_PROVIDER_ID)
229
286
  };
230
287
  }
@@ -235,15 +292,17 @@ export class GeminiOtelConfigurator {
235
292
  * @returns The owned endpoints.
236
293
  */
237
294
  async exporterEndpoints(context) {
238
- const read = await readJsonFile(geminiSettingsPath(context.env));
239
- const envBlock = asRecord(read.state === 'ok' ? asRecord(read.value)?.[ENV_BLOCK_KEY] : undefined);
240
295
  // No record owns nothing: unlike an explicit `uninstall`, the sweep runs
241
296
  // unasked, and Gemini installed after setup holds only the developer's keys.
242
- const owned = new Set(context.installState.agents[GEMINI_PROVIDER_ID]?.otelOwnedKeys ?? []);
297
+ // Then the file, which may hold their API key, is not even read.
298
+ const owned = new Set(ownedKeysOf(context));
299
+ if (owned.size === 0)
300
+ return [];
301
+ const envFile = parseEnv(await readEnvFile(geminiEnvPath(context.env)) ?? '');
243
302
  const endpoints = [];
244
303
  for (const key of GEMINI_ENDPOINT_KEYS) {
245
- const value = envBlock?.[key];
246
- if (owned.has(key) && typeof value === 'string')
304
+ const value = envFile[key];
305
+ if (owned.has(key) && value !== undefined)
247
306
  endpoints.push(value);
248
307
  }
249
308
  return endpoints;
@@ -271,6 +330,34 @@ export class GeminiOtelConfigurator {
271
330
  installState: removed.installState
272
331
  };
273
332
  }
333
+ /**
334
+ * Swap the bearer in our `OTEL_EXPORTER_OTLP_HEADERS` line for the current one.
335
+ *
336
+ * Only when a setup recorded the key as ours, and only the bearer in that
337
+ * line changes. No backup: one per rotation would collect copies of every token.
338
+ *
339
+ * @param context - The recorded file, its contents as read, install state and the current bearer.
340
+ * @returns True when the file was rewritten.
341
+ */
342
+ async rewriteBearer(context) {
343
+ if (!context.installState.agents[GEMINI_PROVIDER_ID]?.otelOwnedKeys.includes(OTLP_HEADERS_KEY))
344
+ return false;
345
+ const lines = context.raw.split('\n');
346
+ // The last line wins, as in Gemini's loader. Our entry in a settings.json
347
+ // an older version wrote (it carries our installation header) is matched
348
+ // too, so the token left there still rotates until setup moves it.
349
+ let at = -1;
350
+ for (const [index, line] of lines.entries()) {
351
+ if (RE_ENV_LINE.exec(line)?.[1] === OTLP_HEADERS_KEY || (line.includes(`"${OTLP_HEADERS_KEY}"`) && line.includes(INSTALLATION_HEADER)))
352
+ at = index;
353
+ }
354
+ if (at === -1)
355
+ return false;
356
+ const next = lines[at].replace(RE_BEARER_PAIR, (_match, head) => head + context.bearer);
357
+ if (next === lines[at])
358
+ return false;
359
+ return writeIfUnchanged(context.configPath, context.raw, [...lines.slice(0, at), next, ...lines.slice(at + 1)].join('\n'), SECRET_FILE_MODE);
360
+ }
274
361
  /**
275
362
  * Signals Gemini was asked for but will not be given under current consent.
276
363
  *
@@ -290,12 +377,18 @@ export class GeminiOtelConfigurator {
290
377
  * Gemini logs always carry function arguments, so they need tool-content
291
378
  * consent. Detailed traces can carry prompts unbounded and unscrubbed, outside
292
379
  * the summary's `promptText` path, so no configuration makes them safe.
380
+ *
381
+ * Gemini 0.64 ignores `OTEL_LOGS_EXPORTER=none` and `OTEL_TRACES_EXPORTER=none`:
382
+ * once its export is on, logs and traces leave with the metrics. So without
383
+ * tool-content consent nothing is exported, metrics included.
293
384
  * @param config - Global, consent-gated configuration.
294
385
  * @returns The signals safe to materialize in Gemini settings.
295
386
  */
296
387
  function safeGeminiSignals(config) {
388
+ if (!toolContentConsented(config))
389
+ return { logs: false, traces: false, metrics: false };
297
390
  return {
298
- logs: config.otel.logs && toolContentConsented(config),
391
+ logs: config.otel.logs,
299
392
  traces: false,
300
393
  metrics: config.otel.metrics
301
394
  };
@@ -309,26 +402,45 @@ function anySignal(signals) {
309
402
  return signals.logs || signals.traces || signals.metrics;
310
403
  }
311
404
  /**
312
- * Settings keys a previous AgentWatch setup recorded as its own.
405
+ * `.env` keys a previous AgentWatch setup recorded as its own.
313
406
  *
314
- * @param context - Install state carrier.
407
+ * Keys recorded for the old settings.json location say nothing about a
408
+ * `.env`, whose same-named lines are the developer's.
409
+ *
410
+ * @param context - Environment and install state.
315
411
  * @returns The recorded keys.
316
412
  */
317
413
  function ownedKeysOf(context) {
318
- return context.installState.agents[GEMINI_PROVIDER_ID]?.otelOwnedKeys ?? [];
414
+ const record = context.installState.agents[GEMINI_PROVIDER_ID];
415
+ return record && path.basename(record.otelConfigPath ?? '') === GEMINI_ENV_FILE ? record.otelOwnedKeys : [];
416
+ }
417
+ /**
418
+ * Whether the install state records telemetry in settings.json, where versions
419
+ * before AWT-580 wrote it and Gemini never applied it.
420
+ *
421
+ * @param context - Environment and install state.
422
+ * @returns True when such a record holds keys.
423
+ */
424
+ function legacyRecorded(context) {
425
+ const record = context.installState.agents[GEMINI_PROVIDER_ID];
426
+ return record !== undefined && record.otelOwnedKeys.length > 0 && path.basename(record.otelConfigPath ?? '') !== GEMINI_ENV_FILE;
319
427
  }
320
428
  /**
321
429
  * Status when telemetry is deliberately off.
322
430
  *
323
- * @param settings - The whole settings object.
324
- * @param envBlock - Its env block.
431
+ * @param envFile - The `.env` as a key map.
325
432
  * @param ownedKeys - Keys a previous setup recorded.
433
+ * @param requested - Whether config asked for a signal, so consent is what holds it back.
326
434
  * @returns Configured, unless our own leftovers are still in place.
327
435
  */
328
- function inspectDisabled(settings, envBlock, ownedKeys) {
329
- const leftover = ownedKeys.some((key) => (key === LEGACY_HELPER_KEY ? settings[key] !== undefined : envBlock[key] !== undefined)) || hasOurLegacyHelper(settings);
330
- if (!leftover)
331
- return { supported: true, configured: true, detail: 'disabled by config or content consent' };
436
+ function inspectDisabled(envFile, ownedKeys, requested) {
437
+ if (!ownedKeys.some((key) => envFile[key] !== undefined)) {
438
+ return {
439
+ supported: true,
440
+ configured: true,
441
+ detail: requested ? 'export off until tool-content consent, as Gemini sends logs and traces with any signal; no llm.call ledger from this agent' : 'disabled by config'
442
+ };
443
+ }
332
444
  return {
333
445
  supported: true,
334
446
  configured: false,
@@ -338,14 +450,14 @@ function inspectDisabled(settings, envBlock, ownedKeys) {
338
450
  /**
339
451
  * Desired keys already set to a value we did not write.
340
452
  *
341
- * @param envBlock - Current env block.
453
+ * @param envFile - Current `.env` values, and settings.json telemetry fields by owned key.
342
454
  * @param desired - What we want to write.
343
455
  * @param ownedKeys - Keys a previous setup recorded as ours.
344
456
  * @returns The conflicting key names.
345
457
  */
346
- function foreignKeys(envBlock, desired, ownedKeys) {
347
- const owned = new Set([...ownedKeys, ...Object.keys(CONTENT_LOG_OFF)]);
348
- return Object.keys(desired).filter((key) => envBlock[key] !== undefined && envBlock[key] !== desired[key] && !owned.has(key));
458
+ function foreignKeys(envFile, desired, ownedKeys) {
459
+ const owned = new Set([...ownedKeys, ...Object.keys(CONTENT_LOG_OFF), `${TELEMETRY_BLOCK_KEY}.logPrompts`]);
460
+ return Object.keys(desired).filter((key) => envFile[key] !== undefined && envFile[key] !== desired[key] && !owned.has(key));
349
461
  }
350
462
  /**
351
463
  * Settings with our telemetry keys and legacy helper removed.
@@ -376,3 +488,202 @@ function hasOurLegacyHelper(settings) {
376
488
  const value = settings[LEGACY_HELPER_KEY];
377
489
  return typeof value === 'string' && value.includes(HOOK_COMMAND_MARKER);
378
490
  }
491
+ /**
492
+ * Bring settings.json in line: our keys out of the `env` block older versions
493
+ * wrote, and our `telemetry` fields set or, when undefined, removed.
494
+ *
495
+ * @param context - Environment, paths and install state.
496
+ * @param fallback - Whether, with no record at all, the names older versions
497
+ * wrote count as ours (explicit uninstall only, as before).
498
+ * @param fields - Telemetry fields by owned key: a value to set, undefined to remove.
499
+ * @returns The outcome, with the JSON each named field held before; its
500
+ * install state drops the settings.json record.
501
+ */
502
+ async function updateSettings(context, fallback, fields) {
503
+ const settingsPath = geminiSettingsPath(context.env);
504
+ const record = context.installState.agents[GEMINI_PROVIDER_ID];
505
+ const recorded = legacyRecorded(context);
506
+ const unrecordedKeys = fallback && !record ? GEMINI_LEGACY_OWNED_KEYS : [];
507
+ const keys = recorded && record ? record.otelOwnedKeys : unrecordedKeys;
508
+ const installState = recorded ? withoutOtelInstall(context.installState, GEMINI_PROVIDER_ID) : context.installState;
509
+ const read = await readJsonFile(settingsPath);
510
+ const settings = read.state === 'ok' ? asRecord(read.value) : undefined;
511
+ const touchesFields = Object.keys(fields).length > 0;
512
+ if (!settings && read.state !== 'missing' && (keys.length > 0 || touchesFields)) {
513
+ return { ok: false, changed: false, messages: [`refusing to modify unreadable ${settingsPath}`], prior: {} };
514
+ }
515
+ const current = settings ?? {};
516
+ const block = asRecord(current[TELEMETRY_BLOCK_KEY]) ?? {};
517
+ const prior = Object.fromEntries(Object.keys(fields).flatMap((key) => (block[telemetryField(key)] === undefined ? [] : [[key, JSON.stringify(block[telemetryField(key)])]])));
518
+ const stripped = keys.length > 0 || hasOurLegacyHelper(current) ? strippedSettings(current, new Set(keys)) : current;
519
+ const nextSettings = touchesFields ? withTelemetryFields(stripped, fields) : stripped;
520
+ const changed = JSON.stringify(nextSettings) !== JSON.stringify(current);
521
+ if (changed) {
522
+ await backupFile(settingsPath, context.paths.backupsDir, context.env.now());
523
+ // The mode the file had before an older version tightened it for the token.
524
+ await writeJsonValidated(settingsPath, nextSettings, recorded ? record?.otelPriorMode : undefined);
525
+ }
526
+ return { ok: true, changed, messages: [], installState, prior };
527
+ }
528
+ /**
529
+ * Settings with telemetry fields set or removed; other fields stay.
530
+ *
531
+ * @param settings - The whole settings object.
532
+ * @param fields - Values by owned key; undefined removes the field.
533
+ * @returns The next settings object, without an emptied block.
534
+ */
535
+ function withTelemetryFields(settings, fields) {
536
+ const merged = { ...asRecord(settings[TELEMETRY_BLOCK_KEY]), ...Object.fromEntries(Object.entries(fields).map(([key, value]) => [telemetryField(key), value])) };
537
+ const block = Object.fromEntries(Object.entries(merged).filter(([, value]) => value !== undefined));
538
+ return Object.keys(block).length > 0 ? { ...settings, [TELEMETRY_BLOCK_KEY]: block } : omitKeys(settings, new Set([TELEMETRY_BLOCK_KEY]));
539
+ }
540
+ /**
541
+ * The settings.json `telemetry` block as Gemini reads it.
542
+ *
543
+ * @param env - Environment supplying HOME and GEMINI_HOME.
544
+ * @returns The block; empty when there is none.
545
+ */
546
+ async function settingsTelemetry(env) {
547
+ const read = await readJsonFile(geminiSettingsPath(env));
548
+ return asRecord(asRecord(read.state === 'ok' ? read.value : undefined)?.[TELEMETRY_BLOCK_KEY]) ?? {};
549
+ }
550
+ /**
551
+ * A `.env` Gemini would load from this folder in place of ours.
552
+ *
553
+ * Mirrors Gemini's lookup for a trusted folder: walking up, `<dir>/.gemini/.env`
554
+ * then `<dir>/.env`, the first found wins. (In an untrusted folder Gemini skips
555
+ * ours anyway.)
556
+ *
557
+ * @param cwd - The folder Gemini starts in.
558
+ * @param ours - Our `.env`.
559
+ * @returns The shadowing file, or undefined when ours is the one loaded.
560
+ */
561
+ function shadowingEnvFile(cwd, ours) {
562
+ for (let dir = path.resolve(cwd);; dir = path.dirname(dir)) {
563
+ const found = [path.join(dir, GEMINI_HOME_DIR, GEMINI_ENV_FILE), path.join(dir, GEMINI_ENV_FILE)].find((file) => existsSync(file));
564
+ if (found)
565
+ return found === ours ? undefined : found;
566
+ if (path.dirname(dir) === dir)
567
+ return undefined;
568
+ }
569
+ }
570
+ /**
571
+ * What owned keys held before a setup first set them.
572
+ *
573
+ * @param context - Install state.
574
+ * @returns Prior text by key; `.env` keys hold their whole line.
575
+ */
576
+ function priorValuesOf(context) {
577
+ return context.installState.agents[GEMINI_PROVIDER_ID]?.otelPriorValues ?? {};
578
+ }
579
+ /**
580
+ * A recorded settings.json value.
581
+ *
582
+ * @param prior - Its JSON text, if one was recorded.
583
+ * @returns The value; undefined (remove the field) when absent or unparseable.
584
+ */
585
+ function parsePrior(prior) {
586
+ try {
587
+ return prior === undefined ? undefined : JSON.parse(prior);
588
+ }
589
+ catch {
590
+ return undefined;
591
+ }
592
+ }
593
+ /**
594
+ * The developer's own `.env` lines to put back for these keys.
595
+ *
596
+ * @param priors - Prior text by key.
597
+ * @param keys - Keys being given up.
598
+ * @returns Lines by key, for those that had one.
599
+ */
600
+ function restoredLines(priors, keys) {
601
+ return Object.fromEntries(keys.flatMap((key) => (telemetryField(key) === undefined && priors[key] !== undefined ? [[key, priors[key]]] : [])));
602
+ }
603
+ /**
604
+ * The `.env` text.
605
+ *
606
+ * @param filePath - The file.
607
+ * @returns Its contents, undefined when there is none, or null when it cannot
608
+ * be read (so it is never replaced by a file holding only our lines).
609
+ */
610
+ async function readEnvFile(filePath) {
611
+ try {
612
+ return await fs.readFile(filePath, 'utf8');
613
+ }
614
+ catch (error) {
615
+ return error.code === 'ENOENT' ? undefined : null;
616
+ }
617
+ }
618
+ /**
619
+ * The refusal for a `.env` that exists but cannot be read.
620
+ *
621
+ * @param envPath - The file.
622
+ * @returns The outcome.
623
+ */
624
+ function unreadable(envPath) {
625
+ return { ok: false, changed: false, messages: [`refusing to modify unreadable ${envPath}`] };
626
+ }
627
+ /**
628
+ * The `KEY=value` lines of a dotenv file, the last one winning as in Gemini's
629
+ * loader. Quotes around a value are dropped.
630
+ *
631
+ * @param raw - File contents.
632
+ * @returns Values by key.
633
+ */
634
+ function parseEnv(raw) {
635
+ const entries = [];
636
+ for (const line of raw.split('\n')) {
637
+ const match = RE_ENV_LINE.exec(line);
638
+ if (match)
639
+ entries.push([match[1], match[2].replace(RE_QUOTED_VALUE, '$2')]);
640
+ }
641
+ return Object.fromEntries(entries);
642
+ }
643
+ /**
644
+ * The last `KEY=value` line for each key, as written.
645
+ *
646
+ * @param raw - File contents.
647
+ * @returns Lines by key.
648
+ */
649
+ function envLinesByKey(raw) {
650
+ const lines = {};
651
+ for (const line of raw.split('\n')) {
652
+ const key = RE_ENV_LINE.exec(line)?.[1];
653
+ if (key !== undefined)
654
+ lines[key] = line;
655
+ }
656
+ return lines;
657
+ }
658
+ /**
659
+ * The `.env` text with `set` written and `drop` removed; every other line,
660
+ * comments included, stays as it was.
661
+ *
662
+ * @param raw - Current contents.
663
+ * @param set - Whole lines by key: replacing that key's line where it stands,
664
+ * appended otherwise.
665
+ * @param drop - Keys to remove.
666
+ * @returns The next contents; `raw` itself when nothing changes.
667
+ */
668
+ function rewriteEnv(raw, set, drop) {
669
+ const body = raw.endsWith('\n') ? raw.slice(0, -1) : raw;
670
+ const lines = [];
671
+ const written = new Set();
672
+ for (const line of body === '' ? [] : body.split('\n')) {
673
+ const key = RE_ENV_LINE.exec(line)?.[1];
674
+ const setting = key !== undefined && Object.hasOwn(set, key);
675
+ if (key === undefined || (!setting && !drop.has(key))) {
676
+ lines.push(line);
677
+ continue;
678
+ }
679
+ if (setting && !written.has(key))
680
+ lines.push(set[key]);
681
+ written.add(key);
682
+ }
683
+ for (const [key, line] of Object.entries(set)) {
684
+ if (!written.has(key))
685
+ lines.push(line);
686
+ }
687
+ const next = lines.length === 0 ? '' : `${lines.join('\n')}\n`;
688
+ return next.trimEnd() === raw.trimEnd() ? raw : next;
689
+ }