@agent-watch-ai/edge 0.4.0 → 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 (74) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -3
  3. package/SECURITY.md +1 -1
  4. package/dist/config/config-store.js +1 -1
  5. package/dist/config/repo-config.js +1 -1
  6. package/dist/config/schemas/config.schema.d.ts +93 -857
  7. package/dist/config/schemas/config.schema.js +5 -5
  8. package/dist/credentials/credentials.js +2 -2
  9. package/dist/credentials/schemas/device-api.schema.d.ts +4 -51
  10. package/dist/credentials/schemas/device-state.schema.d.ts +3 -38
  11. package/dist/git/code-state.d.ts +33 -0
  12. package/dist/git/code-state.js +44 -0
  13. package/dist/git/constants/git.constants.d.ts +6 -0
  14. package/dist/git/constants/git.constants.js +6 -0
  15. package/dist/git/index.d.ts +2 -1
  16. package/dist/git/index.js +1 -0
  17. package/dist/git/types/git.types.d.ts +6 -0
  18. package/dist/privacy/command-fingerprint.d.ts +42 -0
  19. package/dist/privacy/command-fingerprint.js +249 -0
  20. package/dist/privacy/constants/command-fingerprint.constants.d.ts +34 -0
  21. package/dist/privacy/constants/command-fingerprint.constants.js +38 -0
  22. package/dist/privacy/index.d.ts +3 -1
  23. package/dist/privacy/index.js +2 -0
  24. package/dist/privacy/product-capture.js +19 -1
  25. package/dist/privacy/types/privacy.types.d.ts +7 -0
  26. package/dist/providers/antigravity/antigravity.adapter.js +3 -0
  27. package/dist/providers/antigravity/schemas/antigravity.schema.d.ts +18 -492
  28. package/dist/providers/claude/claude.adapter.js +12 -1
  29. package/dist/providers/claude/constants/claude.constants.d.ts +6 -0
  30. package/dist/providers/claude/constants/claude.constants.js +6 -0
  31. package/dist/providers/claude/schemas/claude.schema.d.ts +1 -43
  32. package/dist/providers/codex/codex.adapter.js +14 -0
  33. package/dist/providers/codex/schemas/codex.schema.d.ts +1 -41
  34. package/dist/providers/cursor/cursor.adapter.js +5 -2
  35. package/dist/providers/cursor/schemas/cursor.schema.d.ts +5 -85
  36. package/dist/providers/gemini/constants/gemini.constants.d.ts +2 -0
  37. package/dist/providers/gemini/constants/gemini.constants.js +2 -0
  38. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +10 -1
  39. package/dist/providers/gemini/constants/gemini.otel.constants.js +11 -2
  40. package/dist/providers/gemini/gemini.detect.d.ts +11 -0
  41. package/dist/providers/gemini/gemini.detect.js +14 -1
  42. package/dist/providers/gemini/gemini.hooks.d.ts +3 -3
  43. package/dist/providers/gemini/gemini.hooks.js +5 -5
  44. package/dist/providers/gemini/gemini.otel.d.ts +6 -6
  45. package/dist/providers/gemini/gemini.otel.js +392 -121
  46. package/dist/providers/gemini/schemas/gemini.schema.d.ts +1 -49
  47. package/dist/providers/shared/event-builder.d.ts +17 -2
  48. package/dist/providers/shared/event-builder.js +43 -3
  49. package/dist/providers/shared/install-record.d.ts +2 -0
  50. package/dist/providers/shared/install-record.js +3 -2
  51. package/dist/providers/shared/tooling.d.ts +7 -0
  52. package/dist/providers/shared/tooling.js +10 -1
  53. package/dist/providers/shared/types/adapter.types.d.ts +18 -0
  54. package/dist/storage/schemas/storage.schema.d.ts +11 -175
  55. package/dist/storage/schemas/storage.schema.js +7 -1
  56. package/dist/transport/schemas/queue.schema.d.ts +1 -16
  57. package/dist/transport/schemas/queue.schema.js +1 -1
  58. package/dist/turns/constants/turns.constants.d.ts +17 -0
  59. package/dist/turns/constants/turns.constants.js +17 -0
  60. package/dist/turns/index.d.ts +3 -2
  61. package/dist/turns/index.js +1 -0
  62. package/dist/turns/tool-events.d.ts +15 -0
  63. package/dist/turns/tool-events.js +59 -0
  64. package/dist/turns/turn-state.js +2 -2
  65. package/dist/turns/turn-summary.d.ts +1 -1
  66. package/dist/turns/turn-summary.js +1 -0
  67. package/dist/turns/turn-tracker.js +138 -7
  68. package/dist/turns/types/turn-state.types.d.ts +28 -1
  69. package/dist/turns/types/turn-summary.types.d.ts +30 -0
  70. package/dist/turns/types/turn-tracker.types.d.ts +10 -0
  71. package/docs/AUDIT_PROMPT.md +11 -0
  72. package/docs/DATA_HANDLING.md +58 -10
  73. package/docs/ENTERPRISE_DEPLOYMENT.md +2 -1
  74. package/package.json +9 -8
@@ -1,17 +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, writeIfUnchanged } 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 { parseJsonLine } from '../../turns/transcript.js';
8
10
  import { deviceFor, hasCredential } from '../../credentials/identity.js';
9
11
  import { BEARER_PLACEHOLDER, HOOK_COMMAND_MARKER } from '../constants/provider.constants.js';
10
12
  import { writeJsonValidated } from '../shared/hook-config.js';
11
13
  import { withOtelInstall, withoutOtelInstall } from '../shared/install-record.js';
12
- import { geminiSettingsPath } from './gemini.detect.js';
13
- import { GEMINI_PROVIDER_ID } from './constants/gemini.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';
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';
15
17
  /**
16
18
  * Gemini's own prompt-logging switch, forced off.
17
19
  *
@@ -85,7 +87,37 @@ function otlpHeaders(token, installationId) {
85
87
  pairs.push(`${INSTALLATION_HEADER}=${installationId}`);
86
88
  return pairs.join(',');
87
89
  }
88
- /** 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. */
89
121
  export class GeminiOtelConfigurator {
90
122
  /**
91
123
  * Whether this agent can export native telemetry at all.
@@ -103,46 +135,49 @@ export class GeminiOtelConfigurator {
103
135
  * @returns The status, naming any foreign configuration in the way.
104
136
  */
105
137
  async inspect(context) {
106
- const disabled = !anySignal(safeGeminiSignals(context.config));
107
- const read = await readJsonFile(geminiSettingsPath(context.env));
108
- const settings = read.state === 'ok' ? asRecord(read.value) : undefined;
109
- if (!settings) {
110
- if (disabled && read.state === 'missing')
111
- return { supported: true, configured: true, detail: 'disabled in config (otel)' };
112
- 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`' };
113
140
  }
114
- 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 ?? '');
115
145
  const ownedKeys = ownedKeysOf(context);
116
- if (disabled)
117
- return inspectDisabled(settings, envBlock, ownedKeys);
146
+ if (!anySignal(safeGeminiSignals(context.config)))
147
+ return inspectDisabled(envFile, ownedKeys, anySignal(context.config.otel));
118
148
  // The bearer's value is not compared: it is the access token, which the hook
119
149
  // path rotates. Only whether a header is there, when there is a credential.
120
150
  const device = deviceFor(context.config);
121
151
  const desired = desiredGeminiOtelEnv(context, hasCredential(context.config) ? BEARER_PLACEHOLDER : undefined);
122
152
  if (!desired)
123
153
  return { supported: true, configured: false, detail: 'no backend endpoint configured' };
124
- const headers = envBlock[OTLP_HEADERS_KEY];
154
+ if (raw === undefined)
155
+ return { supported: true, configured: false, detail: 'no .env file' };
156
+ const headers = envFile[OTLP_HEADERS_KEY];
125
157
  // 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)) {
158
+ if (device && context.config.token && headers?.includes(context.config.token)) {
127
159
  return { supported: true, configured: false, detail: 'telemetry headers still hold the install key — run `agentwatch setup`' };
128
160
  }
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);
131
- // A helper entry left by an older version is dead weight Gemini ignores;
132
- // reporting "configured" would hide that setup still has work to do. A
133
- // helper belonging to another tool is none of our business.
134
- if (matches && !hasOurLegacyHelper(settings))
135
- return { supported: true, configured: true };
136
- if (matches)
137
- return { supported: true, configured: false, detail: 'stale otelHeadersHelper entry — run `agentwatch setup`' };
138
- const conflicting = foreignKeys(actual, desired, ownedKeys);
139
- if (conflicting.length > 0) {
140
- return { supported: true, configured: false, conflict: `existing telemetry env vars: ${conflicting.join(', ')}` };
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 };
141
168
  }
142
- 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 };
143
178
  }
144
179
  /**
145
- * Write the telemetry configuration into Gemini CLI's settings.
180
+ * Write the telemetry configuration into Gemini CLI's `.env`.
146
181
  *
147
182
  * @param context - Environment, paths, config and install state.
148
183
  * @returns Whether the file changed, what to tell the user, and the next
@@ -152,51 +187,59 @@ export class GeminiOtelConfigurator {
152
187
  const desired = desiredGeminiOtelEnv(context, context.bearer);
153
188
  if (!desired)
154
189
  return this.configureDisabled(context);
155
- const settingsPath = geminiSettingsPath(context.env);
156
- const read = await readJsonFile(settingsPath);
157
- if (read.state === 'invalid') {
158
- return { ok: false, changed: false, messages: [`refusing to modify unparseable ${settingsPath} (${read.error})`] };
159
- }
160
- if (read.state === 'ok' && !asRecord(read.value)) {
161
- return { ok: false, changed: false, messages: [`refusing to modify ${settingsPath}: top level is not an object`] };
162
- }
163
- const settings = (read.state === 'ok' ? asRecord(read.value) : undefined) ?? {};
164
- 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 ?? '';
165
195
  const ownedKeys = ownedKeysOf(context);
166
- 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);
167
200
  if (conflicting.length > 0) {
168
201
  return {
169
202
  ok: false,
170
203
  changed: false,
171
- 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)`]
172
205
  };
173
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
+ }));
174
219
  // Keys we own that this configuration no longer wants (a signal turned off
175
- // since the last run) would otherwise linger.
176
- const stale = new Set(ownedKeys.filter((key) => key !== LEGACY_HELPER_KEY && desired[key] === undefined));
177
- const withEnv = { ...settings, [ENV_BLOCK_KEY]: { ...omitKeys(envBlock, stale), ...desired } };
178
- // Gemini never read this; leaving it behind only confuses the next reader.
179
- const nextSettings = hasOurLegacyHelper(withEnv) ? omitKeys(withEnv, new Set([LEGACY_HELPER_KEY])) : withEnv;
180
- const changed = JSON.stringify(nextSettings) !== JSON.stringify(settings);
181
- // Only when the block actually carries the bearer. This file is Gemini's,
182
- // not ours, and `writeFileAtomic` preserves the target's mode by design —
183
- // so tightening it unconditionally changed another tool's permissions on a
184
- // 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.
185
227
  const carriesCredential = desired[OTLP_HEADERS_KEY] !== undefined;
186
- const priorMode = carriesCredential ? await currentMode(settingsPath) : undefined;
228
+ const priorMode = carriesCredential ? await currentMode(envPath) : undefined;
187
229
  if (changed) {
188
- await backupFile(settingsPath, context.paths.backupsDir, context.env.now());
189
- 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);
190
232
  }
191
233
  return {
192
234
  ok: true,
193
- changed,
194
- messages: changed
235
+ changed: changed || legacy.changed,
236
+ messages: changed || legacy.changed
195
237
  ? [`native OpenTelemetry configured (signals: ${enabledSignalNames(safeGeminiSignals(context.config)).join(', ')})`, 'restart running Gemini CLI sessions to pick it up']
196
238
  : ['native OpenTelemetry already up to date'],
197
- installState: withOtelInstall(context.installState, GEMINI_PROVIDER_ID, {
198
- configPath: settingsPath,
199
- 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,
200
243
  configuredAt: context.env.now(),
201
244
  ...(changed && priorMode !== undefined && priorMode !== SECRET_FILE_MODE ? { priorMode } : {})
202
245
  })
@@ -206,35 +249,39 @@ export class GeminiOtelConfigurator {
206
249
  * Remove the telemetry configuration AgentWatch wrote.
207
250
  *
208
251
  * @param context - Environment, paths, config and install state.
209
- * @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
210
253
  * install state.
211
254
  */
212
255
  async uninstall(context) {
213
- const settingsPath = geminiSettingsPath(context.env);
214
- const read = await readJsonFile(settingsPath);
215
- if (read.state === 'missing')
216
- return { ok: true, changed: false, messages: ['no Gemini settings file'] };
217
- if (read.state === 'invalid') {
218
- return { ok: false, changed: false, messages: [`refusing to modify unparseable ${settingsPath} (${read.error})`] };
219
- }
220
- const settings = asRecord(read.value);
221
- if (!settings) {
222
- return { ok: false, changed: false, messages: [`refusing to modify ${settingsPath}: top level is not an object`] };
223
- }
224
- const removable = new Set((context.installState.agents[GEMINI_PROVIDER_ID]?.otelOwnedKeys ?? GEMINI_LEGACY_OWNED_KEYS).filter((key) => key !== LEGACY_HELPER_KEY));
225
- const nextSettings = strippedSettings(settings, removable);
226
- 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;
227
271
  if (changed) {
228
- await backupFile(settingsPath, context.paths.backupsDir, context.env.now());
229
- // The mode the file had before AgentWatch tightened it, when it was
230
- // tightened. `writeJsonValidated` with no mode would otherwise keep our
231
- // 0600 on a file that no longer holds a token.
232
- 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 }));
233
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 };
234
281
  return {
235
282
  ok: true,
236
- changed,
237
- 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'],
238
285
  installState: withoutOtelInstall(context.installState, GEMINI_PROVIDER_ID)
239
286
  };
240
287
  }
@@ -245,15 +292,17 @@ export class GeminiOtelConfigurator {
245
292
  * @returns The owned endpoints.
246
293
  */
247
294
  async exporterEndpoints(context) {
248
- const read = await readJsonFile(geminiSettingsPath(context.env));
249
- const envBlock = asRecord(read.state === 'ok' ? asRecord(read.value)?.[ENV_BLOCK_KEY] : undefined);
250
295
  // No record owns nothing: unlike an explicit `uninstall`, the sweep runs
251
296
  // unasked, and Gemini installed after setup holds only the developer's keys.
252
- 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)) ?? '');
253
302
  const endpoints = [];
254
303
  for (const key of GEMINI_ENDPOINT_KEYS) {
255
- const value = envBlock?.[key];
256
- if (owned.has(key) && typeof value === 'string')
304
+ const value = envFile[key];
305
+ if (owned.has(key) && value !== undefined)
257
306
  endpoints.push(value);
258
307
  }
259
308
  return endpoints;
@@ -282,10 +331,10 @@ export class GeminiOtelConfigurator {
282
331
  };
283
332
  }
284
333
  /**
285
- * Swap the bearer in our `OTEL_EXPORTER_OTLP_HEADERS` for the current one.
334
+ * Swap the bearer in our `OTEL_EXPORTER_OTLP_HEADERS` line for the current one.
286
335
  *
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.
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.
289
338
  *
290
339
  * @param context - The recorded file, its contents as read, install state and the current bearer.
291
340
  * @returns True when the file was rewritten.
@@ -293,23 +342,21 @@ export class GeminiOtelConfigurator {
293
342
  async rewriteBearer(context) {
294
343
  if (!context.installState.agents[GEMINI_PROVIDER_ID]?.otelOwnedKeys.includes(OTLP_HEADERS_KEY))
295
344
  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')
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)
300
355
  return false;
301
- const next = headers.replace(RE_BEARER_PAIR, (_match, head) => head + context.bearer);
302
- if (next === headers)
356
+ const next = lines[at].replace(RE_BEARER_PAIR, (_match, head) => head + context.bearer);
357
+ if (next === lines[at])
303
358
  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);
359
+ return writeIfUnchanged(context.configPath, context.raw, [...lines.slice(0, at), next, ...lines.slice(at + 1)].join('\n'), SECRET_FILE_MODE);
313
360
  }
314
361
  /**
315
362
  * Signals Gemini was asked for but will not be given under current consent.
@@ -330,12 +377,18 @@ export class GeminiOtelConfigurator {
330
377
  * Gemini logs always carry function arguments, so they need tool-content
331
378
  * consent. Detailed traces can carry prompts unbounded and unscrubbed, outside
332
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.
333
384
  * @param config - Global, consent-gated configuration.
334
385
  * @returns The signals safe to materialize in Gemini settings.
335
386
  */
336
387
  function safeGeminiSignals(config) {
388
+ if (!toolContentConsented(config))
389
+ return { logs: false, traces: false, metrics: false };
337
390
  return {
338
- logs: config.otel.logs && toolContentConsented(config),
391
+ logs: config.otel.logs,
339
392
  traces: false,
340
393
  metrics: config.otel.metrics
341
394
  };
@@ -349,26 +402,45 @@ function anySignal(signals) {
349
402
  return signals.logs || signals.traces || signals.metrics;
350
403
  }
351
404
  /**
352
- * Settings keys a previous AgentWatch setup recorded as its own.
405
+ * `.env` keys a previous AgentWatch setup recorded as its own.
353
406
  *
354
- * @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.
355
411
  * @returns The recorded keys.
356
412
  */
357
413
  function ownedKeysOf(context) {
358
- 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;
359
427
  }
360
428
  /**
361
429
  * Status when telemetry is deliberately off.
362
430
  *
363
- * @param settings - The whole settings object.
364
- * @param envBlock - Its env block.
431
+ * @param envFile - The `.env` as a key map.
365
432
  * @param ownedKeys - Keys a previous setup recorded.
433
+ * @param requested - Whether config asked for a signal, so consent is what holds it back.
366
434
  * @returns Configured, unless our own leftovers are still in place.
367
435
  */
368
- function inspectDisabled(settings, envBlock, ownedKeys) {
369
- const leftover = ownedKeys.some((key) => (key === LEGACY_HELPER_KEY ? settings[key] !== undefined : envBlock[key] !== undefined)) || hasOurLegacyHelper(settings);
370
- if (!leftover)
371
- 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
+ }
372
444
  return {
373
445
  supported: true,
374
446
  configured: false,
@@ -378,14 +450,14 @@ function inspectDisabled(settings, envBlock, ownedKeys) {
378
450
  /**
379
451
  * Desired keys already set to a value we did not write.
380
452
  *
381
- * @param envBlock - Current env block.
453
+ * @param envFile - Current `.env` values, and settings.json telemetry fields by owned key.
382
454
  * @param desired - What we want to write.
383
455
  * @param ownedKeys - Keys a previous setup recorded as ours.
384
456
  * @returns The conflicting key names.
385
457
  */
386
- function foreignKeys(envBlock, desired, ownedKeys) {
387
- const owned = new Set([...ownedKeys, ...Object.keys(CONTENT_LOG_OFF)]);
388
- 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));
389
461
  }
390
462
  /**
391
463
  * Settings with our telemetry keys and legacy helper removed.
@@ -416,3 +488,202 @@ function hasOurLegacyHelper(settings) {
416
488
  const value = settings[LEGACY_HELPER_KEY];
417
489
  return typeof value === 'string' && value.includes(HOOK_COMMAND_MARKER);
418
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
+ }