@agent-watch-ai/edge 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +4 -1
  3. package/dist/billing/session-billing.d.ts +5 -2
  4. package/dist/billing/session-billing.js +27 -6
  5. package/dist/capture/capture-env.d.ts +3 -3
  6. package/dist/capture/capture-env.js +5 -5
  7. package/dist/capture/captured-step.js +24 -0
  8. package/dist/capture/constants/capture.constants.d.ts +15 -0
  9. package/dist/capture/constants/capture.constants.js +15 -0
  10. package/dist/capture/launched-runs.d.ts +27 -0
  11. package/dist/capture/launched-runs.js +15 -9
  12. package/dist/capture/python/sitecustomize.py +11 -2
  13. package/dist/capture/venv-loader.d.ts +68 -0
  14. package/dist/capture/venv-loader.js +189 -0
  15. package/dist/cli/constants/cli.constants.d.ts +21 -0
  16. package/dist/cli/constants/cli.constants.js +22 -1
  17. package/dist/cli/doctor-run-capture.d.ts +8 -0
  18. package/dist/cli/doctor-run-capture.js +14 -0
  19. package/dist/cli/doctor.js +6 -2
  20. package/dist/cli/hook-check.d.ts +7 -2
  21. package/dist/cli/hook-check.js +30 -15
  22. package/dist/cli/hook.js +44 -3
  23. package/dist/cli/npm-global.d.ts +24 -0
  24. package/dist/cli/npm-global.js +77 -0
  25. package/dist/cli/npx-install.js +22 -6
  26. package/dist/cli/replay.js +42 -7
  27. package/dist/cli/setup.js +71 -7
  28. package/dist/cli/types/cli.types.d.ts +2 -0
  29. package/dist/cli/uninstall.js +34 -1
  30. package/dist/cli/update.js +3 -2
  31. package/dist/cli.js +4 -1
  32. package/dist/config/config-store.d.ts +15 -4
  33. package/dist/config/config-store.js +31 -7
  34. package/dist/config/config.d.ts +8 -0
  35. package/dist/config/config.js +10 -0
  36. package/dist/config/constants/config.constants.d.ts +13 -1
  37. package/dist/config/constants/config.constants.js +13 -1
  38. package/dist/config/repo-config.js +7 -2
  39. package/dist/config/schemas/config.schema.d.ts +6 -2
  40. package/dist/config/schemas/config.schema.js +17 -3
  41. package/dist/credentials/cloud-claim.d.ts +2 -0
  42. package/dist/credentials/cloud-claim.js +21 -2
  43. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  44. package/dist/credentials/constants/credentials.constants.js +8 -0
  45. package/dist/credentials/credential-status.js +1 -1
  46. package/dist/credentials/credentials.d.ts +3 -3
  47. package/dist/credentials/credentials.js +26 -12
  48. package/dist/credentials/identity.d.ts +2 -2
  49. package/dist/credentials/identity.js +2 -2
  50. package/dist/credentials/install-key.d.ts +31 -0
  51. package/dist/credentials/install-key.js +58 -0
  52. package/dist/credentials/migration.d.ts +9 -7
  53. package/dist/credentials/migration.js +58 -18
  54. package/dist/credentials/secret-store.d.ts +12 -0
  55. package/dist/credentials/secret-store.js +18 -1
  56. package/dist/enforcement/enforcement.js +1 -1
  57. package/dist/events/enrich.d.ts +14 -0
  58. package/dist/events/enrich.js +1 -1
  59. package/dist/git/constants/git.constants.d.ts +2 -0
  60. package/dist/git/constants/git.constants.js +9 -0
  61. package/dist/git/repo-snapshot.js +8 -2
  62. package/dist/git/types/snapshot.types.d.ts +4 -0
  63. package/dist/pipeline/hook-pipeline.js +5 -2
  64. package/dist/providers/antigravity/antigravity.adapter.d.ts +14 -0
  65. package/dist/providers/antigravity/antigravity.adapter.js +86 -18
  66. package/dist/providers/antigravity/antigravity.provider.js +7 -4
  67. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +10 -0
  68. package/dist/providers/antigravity/constants/antigravity.constants.js +10 -0
  69. package/dist/providers/antigravity/schemas/antigravity.schema.js +7 -13
  70. package/dist/providers/claude/claude.otel.d.ts +33 -1
  71. package/dist/providers/claude/claude.otel.js +81 -12
  72. package/dist/providers/claude/claude.provider.js +12 -6
  73. package/dist/providers/codex/codex.capture.d.ts +1 -1
  74. package/dist/providers/codex/codex.capture.js +3 -3
  75. package/dist/providers/codex/codex.otel.js +2 -2
  76. package/dist/providers/codex/codex.provider.js +2 -1
  77. package/dist/providers/gemini/gemini.capture.js +2 -2
  78. package/dist/providers/gemini/gemini.otel.js +2 -2
  79. package/dist/providers/gemini/gemini.provider.js +2 -1
  80. package/dist/providers/shared/terminal-capture.js +3 -3
  81. package/dist/providers/types/provider.types.d.ts +5 -5
  82. package/dist/replay/checkout-resolver.d.ts +41 -14
  83. package/dist/replay/checkout-resolver.js +134 -30
  84. package/dist/replay/replay-runner.d.ts +3 -1
  85. package/dist/replay/replay-runner.js +74 -22
  86. package/dist/replay/replay-scan.d.ts +2 -1
  87. package/dist/replay/replay-scan.js +14 -2
  88. package/dist/replay/throttle.d.ts +2 -1
  89. package/dist/replay/throttle.js +4 -1
  90. package/dist/replay/transcript-turns.js +29 -3
  91. package/dist/replay/turn-event.d.ts +4 -2
  92. package/dist/replay/turn-event.js +22 -11
  93. package/dist/replay/types/replay.types.d.ts +39 -3
  94. package/dist/replay/worktree-map.d.ts +42 -0
  95. package/dist/replay/worktree-map.js +134 -0
  96. package/dist/snapshot/snapshot-pipeline.js +15 -4
  97. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  98. package/dist/turns/antigravity-transcript.d.ts +40 -0
  99. package/dist/turns/antigravity-transcript.js +102 -0
  100. package/dist/turns/claude-transcript.d.ts +35 -1
  101. package/dist/turns/claude-transcript.js +185 -2
  102. package/dist/turns/codex-transcript.d.ts +22 -1
  103. package/dist/turns/codex-transcript.js +161 -2
  104. package/dist/turns/constants/turns.constants.d.ts +67 -0
  105. package/dist/turns/constants/turns.constants.js +67 -0
  106. package/dist/turns/gemini-transcript.d.ts +17 -1
  107. package/dist/turns/gemini-transcript.js +36 -2
  108. package/dist/turns/transcript.d.ts +31 -1
  109. package/dist/turns/transcript.js +74 -0
  110. package/dist/turns/turn-state.d.ts +51 -1
  111. package/dist/turns/turn-state.js +124 -10
  112. package/dist/turns/turn-tracker.js +156 -18
  113. package/dist/turns/types/transcript.types.d.ts +25 -0
  114. package/dist/turns/types/turn-provider.types.d.ts +18 -1
  115. package/dist/turns/types/turn-state.types.d.ts +10 -0
  116. package/docs/DATA_HANDLING.md +11 -6
  117. package/docs/ENTERPRISE_DEPLOYMENT.md +2 -2
  118. package/package.json +1 -1
@@ -1,7 +1,9 @@
1
1
  import { spawnSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
2
3
  import { createRequire } from 'node:module';
3
4
  import path from 'node:path';
4
5
  import { NPX_CACHE_SEGMENT, NPX_HANDOFF_VAR } from './constants/cli.constants.js';
6
+ import { npmGlobalRoot } from './npm-global.js';
5
7
  import { printErrln, symbols } from './ui.js';
6
8
  /**
7
9
  * Whether this process runs from npx's download cache, and has not already
@@ -58,18 +60,24 @@ export function installGloballyAndHandOff(setupArgs) {
58
60
  printErrln(`${symbols.fail} could not install ${spec} globally; ${manual}`);
59
61
  return 1;
60
62
  }
61
- const prefix = spawnSync('npm', ['prefix', '-g'], { encoding: 'utf8', shell }).stdout?.trim();
62
- const root = spawnSync('npm', ['root', '-g'], { encoding: 'utf8', shell }).stdout?.trim();
63
- if (!prefix || !root || !path.isAbsolute(prefix) || !path.isAbsolute(root)) {
63
+ const root = npmGlobalRoot(process.env, shell);
64
+ if (!root) {
64
65
  printErrln(`${symbols.fail} could not find npm's global folder; ${manual}`);
65
66
  return 1;
66
67
  }
67
- // Windows puts the global shims in the prefix itself; everything else in prefix/bin.
68
- const globalBin = shell ? prefix : path.join(prefix, 'bin');
69
- const env = { ...process.env, PATH: handoffPath(process.env['PATH'] ?? '', globalBin), [NPX_HANDOFF_VAR]: '1' };
70
68
  // The installed entry point under node, never a shim through a shell: the
71
69
  // arguments carry the token, and cmd.exe would interpret them.
72
70
  const cli = path.join(root, pkg.name, 'dist', 'cli.js');
71
+ // The prefix npx was run with may belong to another npm than the one on PATH
72
+ // that just installed: hand off only to the version installed here.
73
+ if (!existsSync(cli) || installedVersion(path.join(root, pkg.name)) !== pkg.version) {
74
+ printErrln(`${symbols.fail} installed ${spec} but did not find it in ${root}; ${manual}`);
75
+ return 1;
76
+ }
77
+ // npm's global root is <prefix>/node_modules on Windows, with the shims in the
78
+ // prefix itself; elsewhere <prefix>/lib/node_modules, with the shims in <prefix>/bin.
79
+ const globalBin = shell ? path.dirname(root) : path.join(root, '..', '..', 'bin');
80
+ const env = { ...process.env, PATH: handoffPath(process.env['PATH'] ?? '', globalBin), [NPX_HANDOFF_VAR]: '1' };
73
81
  const setup = spawnSync(process.execPath, [cli, ...setupArgs], { stdio: 'inherit', env });
74
82
  if (setup.error || setup.status === null) {
75
83
  printErrln(`${symbols.fail} installed ${spec} but could not start it; ${manual}`);
@@ -77,3 +85,11 @@ export function installGloballyAndHandOff(setupArgs) {
77
85
  }
78
86
  return setup.status;
79
87
  }
88
+ function installedVersion(dir) {
89
+ try {
90
+ return JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8')).version;
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ }
@@ -1,3 +1,4 @@
1
+ import fs from 'node:fs/promises';
1
2
  import path from 'node:path';
2
3
  import process from 'node:process';
3
4
  import { sleep } from '../core/async.js';
@@ -9,6 +10,7 @@ import { isIgnoredRoot, selectRoot } from '../config/root-config.js';
9
10
  import { loadEffectiveConfig } from '../config/repo-config.js';
10
11
  import { developerDisplayName, developerIdentity } from '../git/git-context.js';
11
12
  import { createCheckoutResolver } from '../replay/checkout-resolver.js';
13
+ import { learnWorktrees } from '../replay/worktree-map.js';
12
14
  import { REPLAY_BATTERY_CHECK_MS, REPLAY_SEND_TIMEOUT_MS } from '../replay/constants/replay.constants.js';
13
15
  import { hookAgeMs, readLoad, readOnBattery } from '../replay/machine.js';
14
16
  import { claimAutomaticReplay, replayStateFile } from '../replay/replay-state.js';
@@ -36,10 +38,16 @@ import { bold, dim, println, symbols } from './ui.js';
36
38
  */
37
39
  export async function runReplayCommand(options) {
38
40
  const days = parseReplayDays(options.days);
41
+ // Setup's automatic replay inherits the shell's environment; an operator window is never meant for it.
42
+ const window = options.claimAutomatic === true ? undefined : operatorWindow(options.env.vars);
39
43
  if (days === undefined) {
40
44
  println(`${symbols.fail} invalid --replay-days "${options.days}" (expected a whole number of days, 1 to 366)`);
41
45
  return 1;
42
46
  }
47
+ if (typeof window === 'string') {
48
+ println(`${symbols.fail} ${window}`);
49
+ return 1;
50
+ }
43
51
  if (options.machine === true && options.root !== undefined) {
44
52
  println(`${symbols.fail} choose either --machine or --root, not both`);
45
53
  return 1;
@@ -67,14 +75,15 @@ export async function runReplayCommand(options) {
67
75
  if (options.stop)
68
76
  return report(await stopReplay(ports), replayCommand);
69
77
  if (options.dryRun)
70
- return runDry(ports, days);
78
+ return runDry(ports, days, window);
71
79
  if (options.claimAutomatic === true && !(await claimAutomaticReplay(context.paths.configDir, context.paths.dataDir))) {
72
80
  println(`${symbols.off} automatic historical replay was already attempted on this machine`);
73
81
  return 0;
74
82
  }
83
+ const period = window ? `${window.start.toISOString()} to ${window.end.toISOString()}` : `the last ${days} days`;
75
84
  if (!options.resume)
76
- println(`Replaying the last ${days} days of Claude Code, Codex and Gemini CLI sessions. ${dim(`Ctrl-C stops it; \`${replayCommand} --resume\` carries on.`)}`);
77
- return report(await runReplay(ports, { days, resume: options.resume, dryRun: false, skipIfExisting: options.skipIfExisting }), replayCommand);
85
+ println(`Replaying ${period} of Claude Code, Codex and Gemini CLI sessions. ${dim(`Ctrl-C stops it; \`${replayCommand} --resume\` carries on.`)}`);
86
+ return report(await runReplay(ports, { days, window, resume: options.resume, dryRun: false, skipIfExisting: options.skipIfExisting }), replayCommand);
78
87
  }
79
88
  /**
80
89
  * Count what a replay would send, and what that cost this machine.
@@ -83,9 +92,9 @@ export async function runReplayCommand(options) {
83
92
  * @param days - The window.
84
93
  * @returns 0.
85
94
  */
86
- async function runDry(ports, days) {
95
+ async function runDry(ports, days, window) {
87
96
  const started = performance.now();
88
- const result = await runReplay(ports, { days, resume: false, dryRun: true, skipIfExisting: false });
97
+ const result = await runReplay(ports, { days, window, resume: false, dryRun: true, skipIfExisting: false });
89
98
  const wallMs = performance.now() - started;
90
99
  const usage = process.resourceUsage();
91
100
  println(bold('Replay dry run — nothing was sent or written'));
@@ -99,6 +108,19 @@ async function runDry(ports, days) {
99
108
  println(`wall ${(wallMs / 1000).toFixed(1)} s, cpu ${((usage.userCPUTime + usage.systemCPUTime) / 1e6).toFixed(1)} s, peak memory ${(usage.maxRSS / 1024).toFixed(0)} MB`);
100
109
  return 0;
101
110
  }
111
+ function operatorWindow(vars) {
112
+ const from = vars.AGENTWATCH_OPERATOR_REPLAY_FROM;
113
+ const until = vars.AGENTWATCH_OPERATOR_REPLAY_UNTIL;
114
+ if (from === undefined && until === undefined)
115
+ return undefined;
116
+ if (from === undefined || until === undefined)
117
+ return 'operator replay needs both window bounds';
118
+ const start = new Date(from);
119
+ const end = new Date(until);
120
+ if (!Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime()) || start >= end)
121
+ return 'operator replay window is invalid';
122
+ return { start, end };
123
+ }
102
124
  function report(result, replayCommand) {
103
125
  println(`${result.outcome === 'skipped' ? symbols.off : symbols.ok} ${result.message.replace('agentwatch replay', replayCommand)}`);
104
126
  return 0;
@@ -128,6 +150,8 @@ async function buildPorts(context, dryRun) {
128
150
  const paths = identityPaths(context.paths, token);
129
151
  const opened = openIdentityDelivery(context);
130
152
  let battery;
153
+ const worktrees = new Map();
154
+ const checkout = createCheckoutResolver(worktrees);
131
155
  return {
132
156
  env,
133
157
  paths: context.paths,
@@ -144,7 +168,9 @@ async function buildPorts(context, dryRun) {
144
168
  authBlock: opened.authBlock,
145
169
  cooldown: opened.cooldown,
146
170
  inScope: (cwd) => !isIgnoredRoot(context.config.ignoredRoots, cwd) && selectRoot(context.config.roots, cwd)?.path === context.identityRoot,
147
- checkout: createCheckoutResolver(),
171
+ checkout,
172
+ learnWorktrees: (learned) => learnWorktrees(worktrees, learned),
173
+ localCheckouts: async () => childCheckouts(context.identityRoot, checkout),
148
174
  captureFor: cachedCaptureFor(async (cwd) => (await loadEffectiveConfig(context.paths, cwd)).config.capture),
149
175
  machine: async () => {
150
176
  const nowMs = env.now().getTime();
@@ -157,6 +183,15 @@ async function buildPorts(context, dryRun) {
157
183
  log: (line) => println(dim(line))
158
184
  };
159
185
  }
186
+ async function childCheckouts(root, checkout) {
187
+ if (!root)
188
+ return [];
189
+ const entries = await fs.readdir(root, { withFileTypes: true }).catch(() => []);
190
+ const found = await Promise.all(entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')).map((entry) => checkout(path.join(root, entry.name))));
191
+ // ponytail: rooted replay scans direct children only. That covers the workspace layout without
192
+ // walking node_modules; a future repository index can replace this if nested repos become common.
193
+ return [...new Map(found.filter((item) => item !== undefined).map((item) => [item.root, item])).values()];
194
+ }
160
195
  /**
161
196
  * The agents whose transcripts a replay reads, each where its provider looks for them, with its billing mode.
162
197
  *
@@ -168,7 +203,7 @@ async function replaySources(context) {
168
203
  const firstInstalledAt = context.installState.agents[GEMINI_PROVIDER_ID]?.hooksFirstInstalledAt;
169
204
  const firstInstalledMs = firstInstalledAt === undefined ? undefined : Date.parse(firstInstalledAt);
170
205
  const sources = [
171
- claudeSource(claudeProjectsDir(env.home)),
206
+ claudeSource(claudeProjectsDir(env.home), env.home),
172
207
  codexSource(codexHome(env)),
173
208
  geminiSource(path.dirname(geminiSettingsPath(env)), Number.isNaN(firstInstalledMs) ? undefined : firstInstalledMs)
174
209
  ];
package/dist/cli/setup.js CHANGED
@@ -12,8 +12,9 @@ import { asRecord, compact } from '../core/object.js';
12
12
  import { cloudIdentity } from '../credentials/cloud-claim.js';
13
13
  import { CLAUDE_CODE_REMOTE_VAR, CREDENTIALS_DIR_NAME, DEVICE_SOURCE_BATCH_CODE } from '../credentials/constants/credentials.constants.js';
14
14
  import { forgetDeviceIfUnused, nativeExporterBearer, revokeDeviceIfUnused } from '../credentials/credentials.js';
15
- import { awaitingSignIn, credentialId, deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
15
+ import { awaitingSignIn, credentialId, deviceFor, hasCredential, identityFingerprint, identityOf } from '../credentials/identity.js';
16
16
  import { abandonDevice, migrateInstallKey } from '../credentials/migration.js';
17
+ import { readDeviceState } from '../credentials/device-state.js';
17
18
  import { enrollWithCloudClaim, enrollWithCode, signInDevice } from '../credentials/sign-in.js';
18
19
  import { identityPaths } from '../transport/queue-partition.js';
19
20
  import { clearUninstalled, configScopes, uninstallScope } from '../storage/uninstalled.js';
@@ -70,7 +71,9 @@ export async function runSetup(options) {
70
71
  }
71
72
  // The flag path of resolveDeveloperEmail: git (noreply@anthropic.com here) is never asked.
72
73
  // A fresh VM has no earlier sessions to replay.
73
- await setup({ ...options, developerEmail: identity.email, noReplay: true }, context, identity);
74
+ // The block names its backend only in its OTLP endpoint: claim there, not at
75
+ // the production default, unless --endpoint says otherwise.
76
+ await setup({ ...options, endpoint: options.endpoint ?? identity.gateway, developerEmail: identity.email, noReplay: true }, context, identity);
74
77
  }
75
78
  catch {
76
79
  // Never the error: it can come from a device route.
@@ -120,6 +123,11 @@ async function setup(options, context, cloud) {
120
123
  println(`${symbols.fail} invalid --otel value "${options.otel}" (expected "all", "none" or a comma list of logs,traces,metrics)`);
121
124
  return 1;
122
125
  }
126
+ const runs = resolveCaptureRuns(baseConfig, options.captureRuns);
127
+ if (runs === undefined) {
128
+ println(`${symbols.fail} invalid --capture-runs value "${options.captureRuns}" (expected "on" or "off")`);
129
+ return 1;
130
+ }
123
131
  const replayDays = parseReplayDays(options.replayDays);
124
132
  if (replayDays === undefined) {
125
133
  println(`${symbols.fail} invalid --replay-days "${options.replayDays}" (expected a whole number of days, 1 to 366)`);
@@ -211,8 +219,8 @@ async function setup(options, context, cloud) {
211
219
  reportMissingIdentity();
212
220
  return 1;
213
221
  }
214
- // A root re-run without --token keeps the key its device was exchanged for:
215
- // the key stays beside the device to enroll again. A sign-in has no key at all.
222
+ // A root re-run without --token keeps its device, and the key while one is
223
+ // still in the file (an older edge left it beside the device). A sign-in has no key at all.
216
224
  // A deferred re-run keeps a legacy machine's key for the same backend: it keeps sending through the migration window.
217
225
  const token = signedIn ? undefined : (enrolled.token ?? (heldDevice ? existingRoot?.token : undefined) ?? (deferred && (baseConfig.endpoint ?? DEFAULT_ENDPOINT) === enrolled.endpoint ? baseConfig.token : undefined));
218
226
  // The same key again (an MDM re-push, a re-run) keeps its device; a new key
@@ -242,7 +250,7 @@ async function setup(options, context, cloud) {
242
250
  const customEndpoints = nextTrustedOrigins(baseConfig.customEndpoints, previous, enrolled.endpoint, options.allowCustomEndpoint === true, withIdentity);
243
251
  // Set by an enrollment URL and cleared by any other machine setup, so it never outlives the backend it belongs to.
244
252
  const organization = rootPath === undefined ? { organizationId: enrolled.signIn?.organizationId } : {};
245
- const config = ensureInstallationId({ ...withIdentity, ...organization, ...(signedIn ? { installationId } : {}), customEndpoints, otel, emit: { ...baseConfig.emit, llmCalls: true } });
253
+ const config = ensureInstallationId({ ...withIdentity, ...organization, ...(signedIn ? { installationId } : {}), customEndpoints, otel, capture: { ...baseConfig.capture, runs }, emit: { ...baseConfig.emit, llmCalls: true } });
246
254
  await reportContentDowngrade(context, config);
247
255
  // Under the config lock and onto the file as it is now: a hook may have
248
256
  // exchanged this key while setup was running.
@@ -272,6 +280,7 @@ async function setup(options, context, cloud) {
272
280
  if (developerName)
273
281
  println(`${symbols.ok} name: ${developerName}`);
274
282
  println(`${symbols.ok} otel signals: ${enabledSignalNames(otel).join(', ') || 'none'}`);
283
+ println(`${symbols.ok} run capture: ${runs ? 'on' : 'off'}`);
275
284
  println(dim(` config: ${context.paths.configFile}`));
276
285
  println();
277
286
  // Setup is the one way back after an uninstall, for the entry it ran for
@@ -424,6 +433,8 @@ async function readPipedStdin() {
424
433
  async function signIn(options, context, target) {
425
434
  const ctx = { env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn };
426
435
  if (target.cloud) {
436
+ // Said before the claim leaves, so a VM that claims at the wrong backend shows where in its log.
437
+ println(`agentwatch setup --cloud: claiming a cloud device at ${target.endpoint}`);
427
438
  const claimed = await enrollWithCloudClaim(ctx, { endpoint: target.endpoint, identity: target.cloud, installationId: target.installationId, name: os.hostname() });
428
439
  if (!('error' in claimed))
429
440
  println(`${symbols.ok} claimed a cloud device; device credential kept in ${storeLabel(claimed.device.store)}`);
@@ -523,6 +534,8 @@ async function resolveRoot(options, baseConfig) {
523
534
  return { error: 'set up the machine identity first (agentwatch setup without --root); a project root is an addition to it' };
524
535
  if (options.otel !== undefined)
525
536
  return { error: 'native OTLP signals are machine-wide; run setup without --root to change them' };
537
+ if (options.captureRuns !== undefined)
538
+ return { error: 'run capture is machine-wide; run setup without --root to change it' };
526
539
  try {
527
540
  const root = await fs.realpath(path.resolve(options.env.cwd, options.root));
528
541
  const existing = Object.keys(baseConfig.roots ?? {}).filter((key) => path.isAbsolute(key) && canonicalRoot(key) === root);
@@ -578,6 +591,21 @@ function resolveOtel(baseConfig, flag) {
578
591
  return baseConfig.otel;
579
592
  return parseOtelSignals(flag);
580
593
  }
594
+ /**
595
+ * The run capture switch for this run, validated with the other flags.
596
+ *
597
+ * @param baseConfig - Config the run starts from.
598
+ * @param flag - Raw `--capture-runs` value, when given.
599
+ * @returns On or off, or undefined when the flag is invalid.
600
+ */
601
+ function resolveCaptureRuns(baseConfig, flag) {
602
+ if (flag === undefined)
603
+ return baseConfig.capture.runs;
604
+ const value = flag.trim().toLowerCase();
605
+ if (value === 'on' || value === 'off')
606
+ return value === 'on';
607
+ return undefined;
608
+ }
581
609
  /**
582
610
  * Print the repository context. Informational; never fails the run.
583
611
  *
@@ -741,19 +769,55 @@ async function exchangeInstallKey(context, identity, replaced, scope) {
741
769
  const ctx = { env: context.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, ...(scope === undefined ? {} : { scope }) };
742
770
  if (replaced)
743
771
  await forgetDeviceIfUnused(ctx, replaced);
744
- if (!identity.token)
772
+ if (!identity.token) {
773
+ await reenrollFromStoredKey(ctx, identity);
745
774
  return;
775
+ }
746
776
  const device = await migrateInstallKey(ctx, identity, { ignoreBackoff: true });
747
777
  if (!device) {
748
778
  println(`${symbols.warn} install key not yet exchanged for a device credential; it stays in the config and the next run retries`);
749
779
  return;
750
780
  }
781
+ const { config } = await loadConfig(context.paths);
782
+ if ([config, ...Object.values(config.roots ?? {})].some((entry) => entry.token === identity.token && entry.device?.id === device.id)) {
783
+ println(`${symbols.warn} the install key is still in ${context.paths.configFile}; re-run setup to move it to ${storeLabel(device.store)}`);
784
+ }
751
785
  if (device.store === 'file') {
752
786
  println(`${symbols.warn} device credential stored in ${storeLabel(device.store)}: ${path.join(context.paths.configDir, CREDENTIALS_DIR_NAME)}`);
753
787
  return;
754
788
  }
755
789
  println(`${symbols.ok} install key exchanged for a device credential, kept in ${storeLabel(device.store)}`);
756
790
  }
791
+ /**
792
+ * Enroll a refused device again with the install key kept in its store, as a
793
+ * setup with the key in the config would. A device with no refusal, or one
794
+ * signed in through the browser (no key), is left as it is, silently.
795
+ *
796
+ * @param ctx - Credential context for this run.
797
+ * @param identity - The effective config this run configured.
798
+ */
799
+ async function reenrollFromStoredKey(ctx, identity) {
800
+ if (!deviceFor(identity) || !(await readDeviceState(identityPaths(ctx.paths, identityOf(identity)).deviceStateFile)).refusal)
801
+ return;
802
+ if (await migrateInstallKey(ctx, identity, { ignoreBackoff: true })) {
803
+ println(`${symbols.ok} device enrolled again with the install key kept in its store`);
804
+ return;
805
+ }
806
+ println(`${symbols.warn} the device credential is refused and could not be enrolled again; pass --token <install key> or sign in again`);
807
+ }
808
+ /**
809
+ * Whether two identities share a queue partition: a key and the device it was
810
+ * exchanged for (the key moved to the store) are one identity.
811
+ *
812
+ * @param a - One identity.
813
+ * @param b - The other.
814
+ * @returns True when they name the same partition.
815
+ */
816
+ function sameIdentity(a, b) {
817
+ if (a === undefined || b === undefined)
818
+ return a === b;
819
+ return identityFingerprint(a) === identityFingerprint(b);
820
+ }
757
821
  /**
758
822
  * Say what happens to a backlog queued for the previous backend or token.
759
823
  *
@@ -771,7 +835,7 @@ async function reportStrandedBacklog(context, previousConfig, config, owner) {
771
835
  const configuredUrl = eventsUrl(config);
772
836
  if (!previousUrl || !configuredUrl)
773
837
  return;
774
- if (previousUrl === configuredUrl && identityOf(previousConfig) === identityOf(config))
838
+ if (previousUrl === configuredUrl && sameIdentity(identityOf(previousConfig), identityOf(config)))
775
839
  return;
776
840
  const queue = openIdentityDelivery({ ...context, identityConfig: previousConfig }).queue;
777
841
  const stranded = await queue.pendingFor(previousUrl);
@@ -75,6 +75,8 @@ export interface SetupOptions {
75
75
  readonly root?: string;
76
76
  /** OTLP signal selection: "all", "none" or a comma list of logs,traces,metrics. */
77
77
  readonly otel?: string;
78
+ /** Run capture (`capture.runs`): "on" or "off". */
79
+ readonly captureRuns?: string;
78
80
  /** The agents `--agent` selected; every registered agent when absent. */
79
81
  readonly agents?: readonly AgentProvider[];
80
82
  readonly hookCommandFor?: (providerId: string) => string;
@@ -1,7 +1,10 @@
1
1
  import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { VENV_LOADER_FILE, VENV_RECORDS_DIR } from '../capture/constants/capture.constants.js';
2
4
  import { providers } from '../providers/registry.js';
3
5
  import { saveInstallState } from '../storage/install-state.js';
4
6
  import { uninstalledFile } from '../storage/uninstalled.js';
7
+ import { removeVenvLoaders } from '../capture/venv-loader.js';
5
8
  import { forgetDeviceCredentials } from '../credentials/credentials.js';
6
9
  import { buildCliContext, buildHookCommand } from './context.js';
7
10
  import { SETUP_EXCHANGE_TIMEOUT_MS } from './constants/cli.constants.js';
@@ -49,6 +52,19 @@ export async function runUninstall(options) {
49
52
  println();
50
53
  }
51
54
  await saveInstallState(context.paths, installState);
55
+ // The loaders `python -I` runs come in through: harmless once the hooks are gone, but not ours to leave.
56
+ let loadersLeft = 0;
57
+ if (wholeInstall) {
58
+ const loaders = await removeVenvLoaders(context.paths.dataDir);
59
+ loadersLeft = loaders.left.length;
60
+ for (const folder of loaders.removed) {
61
+ println(`${symbols.ok} run capture loader removed from ${folder}`);
62
+ }
63
+ for (const folder of loaders.left) {
64
+ println(`${symbols.fail} could not remove ${path.join(folder, VENV_LOADER_FILE)}; delete it by hand`);
65
+ failures++;
66
+ }
67
+ }
52
68
  // The whole install, not one agent: the device is switched off on the
53
69
  // platform and its secret goes with it, so a reinstall enrolls again rather
54
70
  // than finding a credential nobody chose to keep. The network never fails
@@ -67,9 +83,11 @@ export async function runUninstall(options) {
67
83
  }
68
84
  }
69
85
  if (options.purge) {
70
- await fs.rm(context.paths.dataDir, { recursive: true, force: true });
86
+ await purgeDataDir(context.paths.dataDir, loadersLeft > 0);
71
87
  await fs.rm(context.paths.configDir, { recursive: true, force: true });
72
88
  println(`${symbols.ok} local configuration and queued data removed`);
89
+ if (loadersLeft > 0)
90
+ println(`run capture records kept in ${path.join(context.paths.dataDir, VENV_RECORDS_DIR)}, so a re-run can remove those loaders`);
73
91
  }
74
92
  if (!options.purge) {
75
93
  println(`local config kept at ${context.paths.configFile} (use --purge to remove)`);
@@ -104,3 +122,18 @@ function revocationLine(revocation) {
104
122
  const where = revocation.removed ? 'removed from this machine but still active on the platform' : 'still active on the platform and still on this machine';
105
123
  return `${symbols.warn} device credential ${where} (${revocation.reason}); an admin can revoke this machine in Settings → Install${leftover}`;
106
124
  }
125
+ /**
126
+ * Remove the data dir, all of it or all but the venv loader records: those are how a
127
+ * re-run finds the loaders this one could not remove.
128
+ *
129
+ * @param dataDir - The data dir.
130
+ * @param keepRecords - Whether a loader was left behind.
131
+ */
132
+ async function purgeDataDir(dataDir, keepRecords) {
133
+ if (!keepRecords) {
134
+ await fs.rm(dataDir, { recursive: true, force: true });
135
+ return;
136
+ }
137
+ const names = await fs.readdir(dataDir).catch(() => []);
138
+ await Promise.all(names.filter((name) => name !== VENV_RECORDS_DIR).map((name) => fs.rm(path.join(dataDir, name), { recursive: true, force: true })));
139
+ }
@@ -5,6 +5,7 @@ import process from 'node:process';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { resolvePaths } from '../storage/paths.js';
7
7
  import { installedPackage, isNewer, refreshLatest } from '../update/update-check.js';
8
+ import { npmGlobalRoot } from './npm-global.js';
8
9
  import { printErrln, println, symbols } from './ui.js';
9
10
  /**
10
11
  * `agentwatch update [--check]` — install the latest release from npm.
@@ -64,8 +65,8 @@ export async function runUpdate(env, checkOnly) {
64
65
  * @returns The real path, or undefined when npm has none or cannot say.
65
66
  */
66
67
  function npmGlobalCopy(name, shell) {
67
- const globalRoot = spawnSync('npm', ['root', '-g'], { encoding: 'utf8', shell }).stdout?.trim();
68
- if (!globalRoot || !path.isAbsolute(globalRoot))
68
+ const globalRoot = npmGlobalRoot(process.env, shell);
69
+ if (!globalRoot)
69
70
  return undefined;
70
71
  try {
71
72
  return realpathSync(path.join(globalRoot, name));
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { providerIds } from './providers/loaders.js';
11
11
  const HELP = `agentwatch — telemetry edge for AI coding agents
12
12
 
13
13
  Usage:
14
- agentwatch setup [enrollment-url] [--endpoint <url>] [--allow-custom-endpoint] [--no-browser] [--enrollment-code -] [--token <token>] [--developer-email <email>] [--developer-name <name>] [--root <path>] [--otel <signals>] [--replay-days <n>] [--no-replay] [--agent <id>]
14
+ agentwatch setup [enrollment-url] [--endpoint <url>] [--allow-custom-endpoint] [--no-browser] [--enrollment-code -] [--token <token>] [--developer-email <email>] [--developer-name <name>] [--root <path>] [--otel <signals>] [--capture-runs on|off] [--replay-days <n>] [--no-replay] [--agent <id>]
15
15
  agentwatch setup --cloud (a Claude Code cloud session's managed SessionStart hook)
16
16
  agentwatch status
17
17
  agentwatch replay [--machine | --root <path>] [--replay-days <n>] [--resume | --stop] [--dry-run]
@@ -52,6 +52,8 @@ Flags:
52
52
  --otel <signals> native OTLP signals agents export to the backend: comma list of
53
53
  logs,traces,metrics, or "all"/"none" (default: logs — the
54
54
  per-request usage/cost ledger the backend turns into llm.call)
55
+ --capture-runs on|off count the provider calls of scripts an agent starts (default: on).
56
+ Apart from --otel: --otel none leaves it on
55
57
  --defer-sign-in with an enrollment URL, for an MDM run: save the organization and
56
58
  install the hooks with no credential. Nothing is sent until the
57
59
  developer runs \`agentwatch setup\` and signs in as themselves.
@@ -167,6 +169,7 @@ async function main() {
167
169
  developerName: stringFlag(parsed, 'developer-name'),
168
170
  root: stringFlag(parsed, 'root'),
169
171
  otel: stringFlag(parsed, 'otel'),
172
+ captureRuns: stringFlag(parsed, 'capture-runs'),
170
173
  agents: selected.agents,
171
174
  deferSignIn: boolFlag(parsed, 'defer-sign-in'),
172
175
  replayDays: stringFlag(parsed, 'replay-days'),
@@ -42,10 +42,9 @@ export declare function updateConfig(paths: AgentWatchPaths, change: (current: C
42
42
  readonly now?: () => Date;
43
43
  }): Promise<'saved' | 'unchanged' | 'busy'>;
44
44
  /**
45
- * Record the device an install key was exchanged for, beside that key,
46
- * wherever the file holds it: the machine entry and every root sharing it.
47
- *
48
- * The key stays, to enroll again when the device secret expires.
45
+ * Record the device an install key was exchanged for wherever the file holds
46
+ * that key, or a device of the same id whose key already left the file (an
47
+ * expired secret enrolled again): the machine entry and every root sharing it.
49
48
  *
50
49
  * @param paths - Resolved AgentWatch paths.
51
50
  * @param installKey - The key that was exchanged.
@@ -54,6 +53,18 @@ export declare function updateConfig(paths: AgentWatchPaths, change: (current: C
54
53
  * @returns What {@link updateConfig} did.
55
54
  */
56
55
  export declare function attachDevice(paths: AgentWatchPaths, installKey: string, device: DeviceCredentialRef, waitMs: number): Promise<'saved' | 'unchanged' | 'busy'>;
56
+ /**
57
+ * Take an install key out of every entry that already names the device it was
58
+ * exchanged for. The caller has put the key in that device's secret store
59
+ * first, so it is still there to enroll again when the secret expires.
60
+ *
61
+ * @param paths - Resolved AgentWatch paths.
62
+ * @param installKey - The key to remove.
63
+ * @param deviceId - The device it was exchanged for.
64
+ * @param waitMs - How long to wait for the config lock.
65
+ * @returns What {@link updateConfig} did.
66
+ */
67
+ export declare function detachInstallKey(paths: AgentWatchPaths, installKey: string, deviceId: string, waitMs: number): Promise<'saved' | 'unchanged' | 'busy'>;
57
68
  /**
58
69
  * A config about to be written, with the devices the file on disk already
59
70
  * holds for its install keys laid back in.
@@ -121,10 +121,9 @@ export async function updateConfig(paths, change, options = {}) {
121
121
  }
122
122
  }
123
123
  /**
124
- * Record the device an install key was exchanged for, beside that key,
125
- * wherever the file holds it: the machine entry and every root sharing it.
126
- *
127
- * The key stays, to enroll again when the device secret expires.
124
+ * Record the device an install key was exchanged for wherever the file holds
125
+ * that key, or a device of the same id whose key already left the file (an
126
+ * expired secret enrolled again): the machine entry and every root sharing it.
128
127
  *
129
128
  * @param paths - Resolved AgentWatch paths.
130
129
  * @param installKey - The key that was exchanged.
@@ -133,12 +132,37 @@ export async function updateConfig(paths, change, options = {}) {
133
132
  * @returns What {@link updateConfig} did.
134
133
  */
135
134
  export async function attachDevice(paths, installKey, device, waitMs) {
135
+ const holdsKey = (entry) => entry.token === installKey || (entry.token === undefined && entry.device?.id === device.id);
136
+ return updateEntries(paths, (entry) => (holdsKey(entry) ? { ...entry, device } : entry), waitMs);
137
+ }
138
+ /**
139
+ * Take an install key out of every entry that already names the device it was
140
+ * exchanged for. The caller has put the key in that device's secret store
141
+ * first, so it is still there to enroll again when the secret expires.
142
+ *
143
+ * @param paths - Resolved AgentWatch paths.
144
+ * @param installKey - The key to remove.
145
+ * @param deviceId - The device it was exchanged for.
146
+ * @param waitMs - How long to wait for the config lock.
147
+ * @returns What {@link updateConfig} did.
148
+ */
149
+ export async function detachInstallKey(paths, installKey, deviceId, waitMs) {
150
+ return updateEntries(paths, (entry) => (entry.token === installKey && entry.device?.id === deviceId ? { ...entry, token: undefined } : entry), waitMs);
151
+ }
152
+ /**
153
+ * Apply one change to the machine entry and to every root, under the config lock.
154
+ *
155
+ * @param paths - Resolved AgentWatch paths.
156
+ * @param change - What to do to one entry's credential fields.
157
+ * @param waitMs - How long to wait for the config lock.
158
+ * @returns What {@link updateConfig} did.
159
+ */
160
+ async function updateEntries(paths, change, waitMs) {
136
161
  return updateConfig(paths, (loaded) => {
137
162
  if (loaded.state !== 'ok')
138
163
  return undefined;
139
- const attach = (entry) => (entry.token === installKey ? { ...entry, device } : entry);
140
- const roots = loaded.config.roots ? Object.fromEntries(Object.entries(loaded.config.roots).map(([key, root]) => [key, attach(root)])) : undefined;
141
- const next = { ...attach(loaded.config), ...(roots ? { roots } : {}) };
164
+ const roots = loaded.config.roots ? Object.fromEntries(Object.entries(loaded.config.roots).map(([key, root]) => [key, change(root)])) : undefined;
165
+ const next = { ...change(loaded.config), ...(roots ? { roots } : {}) };
142
166
  return JSON.stringify(next) === JSON.stringify(loaded.config) ? undefined : next;
143
167
  }, { waitMs });
144
168
  }
@@ -12,6 +12,14 @@ export declare function defaultConfig(): AgentWatchConfig;
12
12
  * @returns True when at least one signal is on.
13
13
  */
14
14
  export declare function otelEnabled(config: AgentWatchConfig): boolean;
15
+ /**
16
+ * Whether setup writes run capture into each agent's environment. Apart from
17
+ * `otelEnabled` on purpose: captured calls go out as events, not OTLP.
18
+ *
19
+ * @param config - Effective configuration.
20
+ * @returns True when `capture.runs` is on.
21
+ */
22
+ export declare function runCaptureEnabled(config: AgentWatchConfig): boolean;
15
23
  /**
16
24
  * Names of the enabled OTLP signals, for setup and status messages.
17
25
  *
@@ -17,6 +17,16 @@ export function defaultConfig() {
17
17
  export function otelEnabled(config) {
18
18
  return config.otel.logs || config.otel.traces || config.otel.metrics;
19
19
  }
20
+ /**
21
+ * Whether setup writes run capture into each agent's environment. Apart from
22
+ * `otelEnabled` on purpose: captured calls go out as events, not OTLP.
23
+ *
24
+ * @param config - Effective configuration.
25
+ * @returns True when `capture.runs` is on.
26
+ */
27
+ export function runCaptureEnabled(config) {
28
+ return config.capture.runs;
29
+ }
20
30
  /**
21
31
  * Names of the enabled OTLP signals, for setup and status messages.
22
32
  *
@@ -14,7 +14,14 @@ export declare const DEFAULT_MAX_EVENT_AGE_DAYS = 7;
14
14
  * `cache_ttl_ms` and the ceiling on any advice it does give, so it is the one
15
15
  * number on the path no platform change can shorten.
16
16
  */
17
- export declare const DEFAULT_ENFORCEMENT_TIMEOUT_MS = 300;
17
+ export declare const DEFAULT_ENFORCEMENT_TIMEOUT_MS = 500;
18
+ /**
19
+ * The default before 500, still written into every config saved by an earlier
20
+ * version: setup saves the parsed config, defaults included. 300 ms is about the
21
+ * whole round trip from outside the US (~190 ms to reach the gateway, ~105 ms
22
+ * inside it), so roughly half the asks failed open (2026-11-14).
23
+ */
24
+ export declare const LEGACY_ENFORCEMENT_TIMEOUT_MS = 300;
18
25
  export declare const DEFAULT_ENFORCEMENT_CACHE_TTL_MS = 5000;
19
26
  /**
20
27
  * The window the product promises between a cap being crossed and the next
@@ -128,6 +135,11 @@ export declare const GLOBAL_ONLY_BLOCKS: readonly ["delivery", "otel", "enforcem
128
135
  * to silence usage telemetry for everyone who clones the repository.
129
136
  */
130
137
  export declare const GLOBAL_ONLY_EMIT_KEYS: ReadonlySet<string>;
138
+ /**
139
+ * Capture flags a repo file may not set. Run capture is written into each agent's
140
+ * machine-wide environment by setup, so a repository has no say in it.
141
+ */
142
+ export declare const GLOBAL_ONLY_CAPTURE_KEYS: ReadonlySet<string>;
131
143
  /**
132
144
  * The capture flags that carry raw content off the machine: the developer's
133
145
  * prompt text, tool arguments and tool results, and the session's title. Response text is not here
@@ -14,7 +14,14 @@ export const DEFAULT_MAX_EVENT_AGE_DAYS = 7;
14
14
  * `cache_ttl_ms` and the ceiling on any advice it does give, so it is the one
15
15
  * number on the path no platform change can shorten.
16
16
  */
17
- export const DEFAULT_ENFORCEMENT_TIMEOUT_MS = 300;
17
+ export const DEFAULT_ENFORCEMENT_TIMEOUT_MS = 500;
18
+ /**
19
+ * The default before 500, still written into every config saved by an earlier
20
+ * version: setup saves the parsed config, defaults included. 300 ms is about the
21
+ * whole round trip from outside the US (~190 ms to reach the gateway, ~105 ms
22
+ * inside it), so roughly half the asks failed open (2026-11-14).
23
+ */
24
+ export const LEGACY_ENFORCEMENT_TIMEOUT_MS = 300;
18
25
  export const DEFAULT_ENFORCEMENT_CACHE_TTL_MS = 5_000;
19
26
  /**
20
27
  * The window the product promises between a cap being crossed and the next
@@ -151,6 +158,11 @@ export const GLOBAL_ONLY_BLOCKS = ['delivery', 'otel', 'enforcement'];
151
158
  * to silence usage telemetry for everyone who clones the repository.
152
159
  */
153
160
  export const GLOBAL_ONLY_EMIT_KEYS = new Set(['llmCalls', 'turnSummaries']);
161
+ /**
162
+ * Capture flags a repo file may not set. Run capture is written into each agent's
163
+ * machine-wide environment by setup, so a repository has no say in it.
164
+ */
165
+ export const GLOBAL_ONLY_CAPTURE_KEYS = new Set(['runs']);
154
166
  /**
155
167
  * The capture flags that carry raw content off the machine: the developer's
156
168
  * prompt text, tool arguments and tool results, and the session's title. Response text is not here