@agent-watch-ai/edge 0.7.0 → 0.7.1

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 (82) hide show
  1. package/CHANGELOG.md +69 -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/captured-step.js +24 -0
  6. package/dist/capture/constants/capture.constants.d.ts +15 -0
  7. package/dist/capture/constants/capture.constants.js +15 -0
  8. package/dist/capture/launched-runs.d.ts +27 -0
  9. package/dist/capture/launched-runs.js +15 -9
  10. package/dist/capture/python/sitecustomize.py +11 -2
  11. package/dist/capture/venv-loader.d.ts +68 -0
  12. package/dist/capture/venv-loader.js +189 -0
  13. package/dist/cli/constants/cli.constants.d.ts +21 -0
  14. package/dist/cli/constants/cli.constants.js +21 -0
  15. package/dist/cli/doctor-run-capture.d.ts +8 -0
  16. package/dist/cli/doctor-run-capture.js +14 -0
  17. package/dist/cli/doctor.js +6 -2
  18. package/dist/cli/hook-check.d.ts +7 -2
  19. package/dist/cli/hook-check.js +30 -15
  20. package/dist/cli/hook.js +44 -3
  21. package/dist/cli/npm-global.d.ts +24 -0
  22. package/dist/cli/npm-global.js +77 -0
  23. package/dist/cli/npx-install.js +22 -6
  24. package/dist/cli/replay.js +42 -7
  25. package/dist/cli/setup.js +47 -6
  26. package/dist/cli/uninstall.js +34 -1
  27. package/dist/cli/update.js +3 -2
  28. package/dist/config/config-store.d.ts +15 -4
  29. package/dist/config/config-store.js +31 -7
  30. package/dist/config/constants/config.constants.d.ts +8 -1
  31. package/dist/config/constants/config.constants.js +8 -1
  32. package/dist/config/schemas/config.schema.d.ts +2 -2
  33. package/dist/config/schemas/config.schema.js +10 -2
  34. package/dist/credentials/cloud-claim.d.ts +2 -0
  35. package/dist/credentials/cloud-claim.js +21 -2
  36. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  37. package/dist/credentials/constants/credentials.constants.js +8 -0
  38. package/dist/credentials/credential-status.js +1 -1
  39. package/dist/credentials/credentials.d.ts +3 -3
  40. package/dist/credentials/credentials.js +26 -12
  41. package/dist/credentials/identity.d.ts +2 -2
  42. package/dist/credentials/identity.js +2 -2
  43. package/dist/credentials/install-key.d.ts +31 -0
  44. package/dist/credentials/install-key.js +58 -0
  45. package/dist/credentials/migration.d.ts +9 -7
  46. package/dist/credentials/migration.js +58 -18
  47. package/dist/credentials/secret-store.d.ts +12 -0
  48. package/dist/credentials/secret-store.js +18 -1
  49. package/dist/enforcement/enforcement.js +1 -1
  50. package/dist/events/enrich.d.ts +14 -0
  51. package/dist/events/enrich.js +1 -1
  52. package/dist/git/constants/git.constants.d.ts +2 -0
  53. package/dist/git/constants/git.constants.js +9 -0
  54. package/dist/git/repo-snapshot.js +8 -2
  55. package/dist/git/types/snapshot.types.d.ts +4 -0
  56. package/dist/pipeline/hook-pipeline.js +2 -1
  57. package/dist/providers/claude/claude.provider.js +9 -5
  58. package/dist/providers/types/provider.types.d.ts +5 -5
  59. package/dist/replay/checkout-resolver.d.ts +41 -14
  60. package/dist/replay/checkout-resolver.js +134 -30
  61. package/dist/replay/replay-runner.d.ts +3 -1
  62. package/dist/replay/replay-runner.js +74 -22
  63. package/dist/replay/replay-scan.d.ts +2 -1
  64. package/dist/replay/replay-scan.js +14 -2
  65. package/dist/replay/throttle.d.ts +2 -1
  66. package/dist/replay/throttle.js +4 -1
  67. package/dist/replay/transcript-turns.js +29 -3
  68. package/dist/replay/turn-event.d.ts +4 -2
  69. package/dist/replay/turn-event.js +22 -11
  70. package/dist/replay/types/replay.types.d.ts +39 -3
  71. package/dist/replay/worktree-map.d.ts +42 -0
  72. package/dist/replay/worktree-map.js +134 -0
  73. package/dist/snapshot/snapshot-pipeline.js +15 -4
  74. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  75. package/dist/turns/constants/turns.constants.d.ts +16 -0
  76. package/dist/turns/constants/turns.constants.js +16 -0
  77. package/dist/turns/turn-state.d.ts +33 -0
  78. package/dist/turns/turn-state.js +80 -1
  79. package/dist/turns/turn-tracker.js +2 -2
  80. package/docs/DATA_HANDLING.md +8 -6
  81. package/docs/ENTERPRISE_DEPLOYMENT.md +2 -2
  82. package/package.json +1 -1
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.
@@ -211,8 +214,8 @@ async function setup(options, context, cloud) {
211
214
  reportMissingIdentity();
212
215
  return 1;
213
216
  }
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.
217
+ // A root re-run without --token keeps its device, and the key while one is
218
+ // still in the file (an older edge left it beside the device). A sign-in has no key at all.
216
219
  // A deferred re-run keeps a legacy machine's key for the same backend: it keeps sending through the migration window.
217
220
  const token = signedIn ? undefined : (enrolled.token ?? (heldDevice ? existingRoot?.token : undefined) ?? (deferred && (baseConfig.endpoint ?? DEFAULT_ENDPOINT) === enrolled.endpoint ? baseConfig.token : undefined));
218
221
  // The same key again (an MDM re-push, a re-run) keeps its device; a new key
@@ -424,6 +427,8 @@ async function readPipedStdin() {
424
427
  async function signIn(options, context, target) {
425
428
  const ctx = { env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn };
426
429
  if (target.cloud) {
430
+ // Said before the claim leaves, so a VM that claims at the wrong backend shows where in its log.
431
+ println(`agentwatch setup --cloud: claiming a cloud device at ${target.endpoint}`);
427
432
  const claimed = await enrollWithCloudClaim(ctx, { endpoint: target.endpoint, identity: target.cloud, installationId: target.installationId, name: os.hostname() });
428
433
  if (!('error' in claimed))
429
434
  println(`${symbols.ok} claimed a cloud device; device credential kept in ${storeLabel(claimed.device.store)}`);
@@ -741,19 +746,55 @@ async function exchangeInstallKey(context, identity, replaced, scope) {
741
746
  const ctx = { env: context.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, ...(scope === undefined ? {} : { scope }) };
742
747
  if (replaced)
743
748
  await forgetDeviceIfUnused(ctx, replaced);
744
- if (!identity.token)
749
+ if (!identity.token) {
750
+ await reenrollFromStoredKey(ctx, identity);
745
751
  return;
752
+ }
746
753
  const device = await migrateInstallKey(ctx, identity, { ignoreBackoff: true });
747
754
  if (!device) {
748
755
  println(`${symbols.warn} install key not yet exchanged for a device credential; it stays in the config and the next run retries`);
749
756
  return;
750
757
  }
758
+ const { config } = await loadConfig(context.paths);
759
+ if ([config, ...Object.values(config.roots ?? {})].some((entry) => entry.token === identity.token && entry.device?.id === device.id)) {
760
+ println(`${symbols.warn} the install key is still in ${context.paths.configFile}; re-run setup to move it to ${storeLabel(device.store)}`);
761
+ }
751
762
  if (device.store === 'file') {
752
763
  println(`${symbols.warn} device credential stored in ${storeLabel(device.store)}: ${path.join(context.paths.configDir, CREDENTIALS_DIR_NAME)}`);
753
764
  return;
754
765
  }
755
766
  println(`${symbols.ok} install key exchanged for a device credential, kept in ${storeLabel(device.store)}`);
756
767
  }
768
+ /**
769
+ * Enroll a refused device again with the install key kept in its store, as a
770
+ * setup with the key in the config would. A device with no refusal, or one
771
+ * signed in through the browser (no key), is left as it is, silently.
772
+ *
773
+ * @param ctx - Credential context for this run.
774
+ * @param identity - The effective config this run configured.
775
+ */
776
+ async function reenrollFromStoredKey(ctx, identity) {
777
+ if (!deviceFor(identity) || !(await readDeviceState(identityPaths(ctx.paths, identityOf(identity)).deviceStateFile)).refusal)
778
+ return;
779
+ if (await migrateInstallKey(ctx, identity, { ignoreBackoff: true })) {
780
+ println(`${symbols.ok} device enrolled again with the install key kept in its store`);
781
+ return;
782
+ }
783
+ println(`${symbols.warn} the device credential is refused and could not be enrolled again; pass --token <install key> or sign in again`);
784
+ }
785
+ /**
786
+ * Whether two identities share a queue partition: a key and the device it was
787
+ * exchanged for (the key moved to the store) are one identity.
788
+ *
789
+ * @param a - One identity.
790
+ * @param b - The other.
791
+ * @returns True when they name the same partition.
792
+ */
793
+ function sameIdentity(a, b) {
794
+ if (a === undefined || b === undefined)
795
+ return a === b;
796
+ return identityFingerprint(a) === identityFingerprint(b);
797
+ }
757
798
  /**
758
799
  * Say what happens to a backlog queued for the previous backend or token.
759
800
  *
@@ -771,7 +812,7 @@ async function reportStrandedBacklog(context, previousConfig, config, owner) {
771
812
  const configuredUrl = eventsUrl(config);
772
813
  if (!previousUrl || !configuredUrl)
773
814
  return;
774
- if (previousUrl === configuredUrl && identityOf(previousConfig) === identityOf(config))
815
+ if (previousUrl === configuredUrl && sameIdentity(identityOf(previousConfig), identityOf(config)))
775
816
  return;
776
817
  const queue = openIdentityDelivery({ ...context, identityConfig: previousConfig }).queue;
777
818
  const stranded = await queue.pendingFor(previousUrl);
@@ -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));
@@ -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
  }
@@ -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
@@ -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
@@ -64,7 +64,7 @@ export declare const otelSchema: z.ZodObject<{
64
64
  */
65
65
  export declare const enforcementSchema: z.ZodObject<{
66
66
  enabled: z.ZodDefault<z.ZodBoolean>;
67
- timeoutMs: z.ZodDefault<z.ZodNumber>;
67
+ timeoutMs: z.ZodPipe<z.ZodDefault<z.ZodNumber>, z.ZodTransform<number, number>>;
68
68
  cacheTtlMs: z.ZodDefault<z.ZodNumber>;
69
69
  }, z.core.$strip>;
70
70
  /** Which records the edge itself emits. */
@@ -258,7 +258,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
258
258
  }, z.core.$strip>>;
259
259
  enforcement: z.ZodPrefault<z.ZodObject<{
260
260
  enabled: z.ZodDefault<z.ZodBoolean>;
261
- timeoutMs: z.ZodDefault<z.ZodNumber>;
261
+ timeoutMs: z.ZodPipe<z.ZodDefault<z.ZodNumber>, z.ZodTransform<number, number>>;
262
262
  cacheTtlMs: z.ZodDefault<z.ZodNumber>;
263
263
  }, z.core.$strip>>;
264
264
  }, z.core.$loose>, z.ZodTransform<{
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { asRecord } from '../../core/object.js';
3
3
  import { CREDENTIAL_STORE_KINDS, DEVICE_SOURCE_BATCH_CODE, RE_DEVICE_ID } from '../../credentials/constants/credentials.constants.js';
4
- import { AGENT_WATCH_HOSTS, CUSTOM_ENDPOINT_MESSAGE, CUSTOM_ENDPOINTS_KEY, DELIVERABLE_URL_MESSAGE, DEVICE_URL_FIELDS, ROOTS_KEY, ROOT_URL_FIELDS, URL_FIELDS, LOOPBACK_HOSTS, DEFAULT_DRAIN_BATCH_SIZE, DEFAULT_ENFORCEMENT_CACHE_TTL_MS, DEFAULT_ENFORCEMENT_TIMEOUT_MS, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_EVENT_AGE_DAYS, DEFAULT_MAX_QUEUE_EVENTS, DEFAULT_SEND_TIMEOUT_MS } from '../constants/config.constants.js';
4
+ import { AGENT_WATCH_HOSTS, CUSTOM_ENDPOINT_MESSAGE, CUSTOM_ENDPOINTS_KEY, DELIVERABLE_URL_MESSAGE, DEVICE_URL_FIELDS, ROOTS_KEY, ROOT_URL_FIELDS, URL_FIELDS, LOOPBACK_HOSTS, DEFAULT_DRAIN_BATCH_SIZE, DEFAULT_ENFORCEMENT_CACHE_TTL_MS, DEFAULT_ENFORCEMENT_TIMEOUT_MS, LEGACY_ENFORCEMENT_TIMEOUT_MS, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_EVENT_AGE_DAYS, DEFAULT_MAX_QUEUE_EVENTS, DEFAULT_SEND_TIMEOUT_MS } from '../constants/config.constants.js';
5
5
  /**
6
6
  * The content flags, off.
7
7
  *
@@ -93,7 +93,15 @@ export const enforcementSchema = z
93
93
  .object({
94
94
  enabled: z.boolean().default(true),
95
95
  /** Hard ceiling for the check; it sits between enter and the agent's first call. */
96
- timeoutMs: z.number().int().positive().default(DEFAULT_ENFORCEMENT_TIMEOUT_MS),
96
+ // ponytail: a stored 300 is read as the old default and lifted. A developer who
97
+ // chose exactly 300 by hand gets 500 too; a config migration step would tell
98
+ // them apart if that ever matters.
99
+ timeoutMs: z
100
+ .number()
101
+ .int()
102
+ .positive()
103
+ .default(DEFAULT_ENFORCEMENT_TIMEOUT_MS)
104
+ .transform((ms) => (ms === LEGACY_ENFORCEMENT_TIMEOUT_MS ? DEFAULT_ENFORCEMENT_TIMEOUT_MS : ms)),
97
105
  /** Mirrors the platform's own cache TTL for the same decision. */
98
106
  cacheTtlMs: z.number().int().positive().default(DEFAULT_ENFORCEMENT_CACHE_TTL_MS)
99
107
  })
@@ -6,6 +6,8 @@ export interface CloudIdentity {
6
6
  readonly key: string;
7
7
  /** The signed-in Claude account's email; never git's (in a cloud VM that is `noreply@anthropic.com`). */
8
8
  readonly email: string;
9
+ /** The gateway the block exports usage to (the origin of its `<gateway>/v1/otlp` endpoint), when it names one. */
10
+ readonly gateway?: string;
9
11
  }
10
12
  /**
11
13
  * What the managed settings and the Claude account give this VM to claim with,
@@ -1,6 +1,8 @@
1
1
  import { createPrivateKey, randomBytes, sign } from 'node:crypto';
2
2
  import { claudeAccountEmail } from '../billing/billing-mode.js';
3
- import { AGENTWATCH_CLOUD_KEY, AGENTWATCH_CLOUD_ORGANIZATION } from './constants/credentials.constants.js';
3
+ import { OTLP_BASE_PATH, RE_TRAILING_SLASHES } from '../config/constants/config.constants.js';
4
+ import { compact } from '../core/object.js';
5
+ import { AGENTWATCH_CLOUD_KEY, AGENTWATCH_CLOUD_ORGANIZATION, OTEL_ENDPOINT_VAR } from './constants/credentials.constants.js';
4
6
  /**
5
7
  * What the managed settings and the Claude account give this VM to claim with,
6
8
  * or the one line that says why it cannot.
@@ -16,7 +18,24 @@ export async function cloudIdentity(env) {
16
18
  const email = await claudeAccountEmail(env.home).catch(() => undefined);
17
19
  if (!email)
18
20
  return { skip: 'no Claude account email in ~/.claude.json; Agent Watch not installed' };
19
- return { organizationId, key, email };
21
+ return compact({ organizationId, key, email, gateway: blockGateway(env.vars[OTEL_ENDPOINT_VAR]) });
22
+ }
23
+ /**
24
+ * The gateway a managed block exports usage to: Settings renders its OTLP
25
+ * endpoint as `<gateway>/v1/otlp`, a gateway under a path prefix included.
26
+ * Anything else (a developer's own collector) names no Agent Watch backend.
27
+ *
28
+ * @param endpoint - The block's `OTEL_EXPORTER_OTLP_ENDPOINT`.
29
+ * @returns The gateway, or undefined.
30
+ */
31
+ function blockGateway(endpoint) {
32
+ if (endpoint === undefined || !URL.canParse(endpoint))
33
+ return undefined;
34
+ const url = new URL(endpoint);
35
+ const pathname = url.pathname.replace(RE_TRAILING_SLASHES, '');
36
+ if (!pathname.endsWith(OTLP_BASE_PATH) || url.search || url.hash)
37
+ return undefined;
38
+ return `${url.origin}${pathname.slice(0, -OTLP_BASE_PATH.length)}`;
20
39
  }
21
40
  /**
22
41
  * The claim text and its Ed25519 signature over the text's exact UTF-8 bytes
@@ -62,6 +62,8 @@ export declare const CLAUDE_CODE_REMOTE_VAR = "CLAUDE_CODE_REMOTE";
62
62
  /** The managed-settings env names Settings renders (core `AGENTWATCH_CLOUD_ORGANIZATION`, `AGENTWATCH_CLOUD_KEY`): the organization's id and its base64url PKCS8 DER Ed25519 private key. */
63
63
  export declare const AGENTWATCH_CLOUD_ORGANIZATION = "AGENTWATCH_CLOUD_ORGANIZATION";
64
64
  export declare const AGENTWATCH_CLOUD_KEY = "AGENTWATCH_CLOUD_KEY";
65
+ /** The OTLP endpoint the managed block sets, `<gateway>/v1/otlp`: the block's only word on its backend. */
66
+ export declare const OTEL_ENDPOINT_VAR = "OTEL_EXPORTER_OTLP_ENDPOINT";
65
67
  /** Recorded on a device enrolled with an admin-issued code, so `status` can say so (core `DeviceCredentialSource.BatchCode`). */
66
68
  export declare const DEVICE_SOURCE_BATCH_CODE = "batch-code";
67
69
  /** The RFC 8628 answers of a poll that are not failures: keep waiting. */
@@ -124,3 +126,9 @@ export declare const ENROLL_RETRY_MS = 3600000;
124
126
  export declare const RE_PLAIN_EMAIL: RegExp;
125
127
  /** What an MDM install that has not signed in yet tells its developer, wherever it speaks. */
126
128
  export declare const NOT_SIGNED_IN = "AgentWatch is set up for your organization but not signed in: run `agentwatch setup` to sign in. Nothing is recorded until then";
129
+ /**
130
+ * Appended to a device id to name the account (or file) its install key is
131
+ * kept under, in the same store as the device secret: the key enrolls the
132
+ * device again when the secret expires, and is never left in the config.
133
+ */
134
+ export declare const INSTALL_KEY_ACCOUNT_SUFFIX = ".install-key";
@@ -63,6 +63,8 @@ export const CLAUDE_CODE_REMOTE_VAR = 'CLAUDE_CODE_REMOTE';
63
63
  /** The managed-settings env names Settings renders (core `AGENTWATCH_CLOUD_ORGANIZATION`, `AGENTWATCH_CLOUD_KEY`): the organization's id and its base64url PKCS8 DER Ed25519 private key. */
64
64
  export const AGENTWATCH_CLOUD_ORGANIZATION = 'AGENTWATCH_CLOUD_ORGANIZATION';
65
65
  export const AGENTWATCH_CLOUD_KEY = 'AGENTWATCH_CLOUD_KEY';
66
+ /** The OTLP endpoint the managed block sets, `<gateway>/v1/otlp`: the block's only word on its backend. */
67
+ export const OTEL_ENDPOINT_VAR = 'OTEL_EXPORTER_OTLP_ENDPOINT';
66
68
  /** Recorded on a device enrolled with an admin-issued code, so `status` can say so (core `DeviceCredentialSource.BatchCode`). */
67
69
  export const DEVICE_SOURCE_BATCH_CODE = 'batch-code';
68
70
  /** The RFC 8628 answers of a poll that are not failures: keep waiting. */
@@ -125,3 +127,9 @@ export const ENROLL_RETRY_MS = 3_600_000;
125
127
  export const RE_PLAIN_EMAIL = /^[^\s@\p{Cc}\p{Cf}]{1,64}@[^\s@\p{Cc}\p{Cf}]{1,189}$/u;
126
128
  /** What an MDM install that has not signed in yet tells its developer, wherever it speaks. */
127
129
  export const NOT_SIGNED_IN = 'AgentWatch is set up for your organization but not signed in: run `agentwatch setup` to sign in. Nothing is recorded until then';
130
+ /**
131
+ * Appended to a device id to name the account (or file) its install key is
132
+ * kept under, in the same store as the device secret: the key enrolls the
133
+ * device again when the secret expires, and is never left in the config.
134
+ */
135
+ export const INSTALL_KEY_ACCOUNT_SUFFIX = '.install-key';
@@ -27,7 +27,7 @@ export async function describeCredential(paths, config, scope) {
27
27
  return { level: 'warn', detail: 'none configured' };
28
28
  const { refusal } = await readDeviceState(identityPaths(paths, identityOf(config)).deviceStateFile);
29
29
  if (refusal) {
30
- return { level: 'fail', detail: `device credential refused by the backend (${refusal.reason}) since ${refusal.since}; events are queued — enroll again with \`agentwatch setup --token <install key>\`` };
30
+ return { level: 'fail', detail: `device credential refused by the backend (${refusal.reason}) since ${refusal.since}; events are queued — enroll again with \`agentwatch setup\` (\`--token <install key>\` if the key is not kept on this machine)` };
31
31
  }
32
32
  // SPEC R4: an admin-assigned identity is marked as such wherever it shows.
33
33
  const how = device.source === DEVICE_SOURCE_BATCH_CODE ? ', enrolled with an admin-issued code' : '';
@@ -4,8 +4,8 @@ import type { CredentialContext, DeviceCredentialRef, DeviceForgetResult } from
4
4
  * The bearer to send for this config, doing the network work it needs.
5
5
  *
6
6
  * A config whose device is listed sends that device's access token, refreshed
7
- * when due, and never its install key (which stays in the config to enroll
8
- * again after the secret expires). An install key with no device yet is offered for exchange
7
+ * when due, and never its install key (kept in the device's secret store to
8
+ * enroll again after the secret expires). An install key with no device yet is offered for exchange
9
9
  * first and presented itself only while that fails. A device the gateway
10
10
  * refused is enrolled again when `migrateInstallKey` allows it, and its install
11
11
  * key is never sent in its place. Undefined means "nothing to send with": the
@@ -35,7 +35,7 @@ export declare function cachedBearer(ctx: CredentialContext, config: AgentWatchC
35
35
  /**
36
36
  * The bearer an agent's own config file may hold (Codex, Gemini, AWT-357):
37
37
  * the device access token, refreshed when due. Never the device secret. The
38
- * install key while there is no access token: no device yet (its exchange
38
+ * install key (from the config or its device's store) while there is no access token: no device yet (its exchange
39
39
  * is failing), or a device whose refresh is in cooldown or offline. Writing
40
40
  * no header would get every export refused, and the hook only swaps an
41
41
  * existing bearer. The hook replaces the key once a device token exists. For
@@ -13,14 +13,15 @@ import { readDeviceState } from './device-state.js';
13
13
  import { ENROLL_LOCK_PREFIX } from './constants/credentials.constants.js';
14
14
  import { credentialId, deviceFor, deviceRefs, identityOf } from './identity.js';
15
15
  import { secretLocation, secretStoreFor } from './secret-store.js';
16
+ import { forgetInstallKey, storedInstallKey } from './install-key.js';
16
17
  import { migrateInstallKey } from './migration.js';
17
18
  import { cachedAccessToken, currentAccessToken } from './token-refresher.js';
18
19
  /**
19
20
  * The bearer to send for this config, doing the network work it needs.
20
21
  *
21
22
  * A config whose device is listed sends that device's access token, refreshed
22
- * when due, and never its install key (which stays in the config to enroll
23
- * again after the secret expires). An install key with no device yet is offered for exchange
23
+ * when due, and never its install key (kept in the device's secret store to
24
+ * enroll again after the secret expires). An install key with no device yet is offered for exchange
24
25
  * first and presented itself only while that fails. A device the gateway
25
26
  * refused is enrolled again when `migrateInstallKey` allows it, and its install
26
27
  * key is never sent in its place. Undefined means "nothing to send with": the
@@ -41,7 +42,7 @@ export async function resolveBearer(ctx, config) {
41
42
  return undefined;
42
43
  if (deviceFor(config)) {
43
44
  const token = await currentAccessToken(ctx, config);
44
- if (token || !config.token || !(await readDeviceState(identityPaths(ctx.paths, config.token).deviceStateFile)).refusal)
45
+ if (token || !(await readDeviceState(identityPaths(ctx.paths, identityOf(config)).deviceStateFile)).refusal)
45
46
  return token;
46
47
  const renewed = await migrateInstallKey(ctx, config);
47
48
  return renewed ? await currentAccessToken(ctx, { ...config, device: renewed }) : undefined;
@@ -82,7 +83,7 @@ export async function cachedBearer(ctx, config) {
82
83
  /**
83
84
  * The bearer an agent's own config file may hold (Codex, Gemini, AWT-357):
84
85
  * the device access token, refreshed when due. Never the device secret. The
85
- * install key while there is no access token: no device yet (its exchange
86
+ * install key (from the config or its device's store) while there is no access token: no device yet (its exchange
86
87
  * is failing), or a device whose refresh is in cooldown or offline. Writing
87
88
  * no header would get every export refused, and the hook only swaps an
88
89
  * existing bearer. The hook replaces the key once a device token exists. For
@@ -96,7 +97,10 @@ export async function nativeExporterBearer(ctx, config) {
96
97
  try {
97
98
  if (await isUninstalled(ctx.paths))
98
99
  return undefined;
99
- return (deviceFor(config) ? await currentAccessToken(ctx, config) : undefined) ?? config.token;
100
+ const device = deviceFor(config);
101
+ if (!device)
102
+ return config.token;
103
+ return (await currentAccessToken(ctx, config)) ?? config.token ?? (await storedInstallKey(ctx, device));
100
104
  }
101
105
  catch (error) {
102
106
  debugLog('credentials: resolving the native exporter bearer failed:', error);
@@ -158,8 +162,10 @@ export async function revokeDeviceIfUnused(ctx, device) {
158
162
  */
159
163
  export async function forgetDeviceCredentials(ctx) {
160
164
  const before = await loadConfig(ctx.paths);
161
- const keys = [...new Set([before.config.token, ...Object.values(before.config.roots ?? {}).map((root) => root.token)].filter((key) => Boolean(key)))];
162
- const releases = await holdEnrollLocks(ctx, keys.map(credentialId).sort());
165
+ const keys = [before.config.token, ...Object.values(before.config.roots ?? {}).map((root) => root.token)].filter((key) => Boolean(key));
166
+ // A device whose key moved to its store enrolls again under its own id.
167
+ const ids = new Set([...keys.map(credentialId), ...deviceRefs(before.config).map((ref) => ref.id)]);
168
+ const releases = await holdEnrollLocks(ctx, [...ids].sort());
163
169
  let held = new Map();
164
170
  let invalid = false;
165
171
  let marked;
@@ -190,12 +196,12 @@ export async function forgetDeviceCredentials(ctx) {
190
196
  return { marked, config: 'ok', revocations };
191
197
  }
192
198
  /**
193
- * Each install key's enroll lock, waiting a while for one a hook holds. A lock
199
+ * Each enroll lock, waiting a while for one a hook holds. A lock
194
200
  * still taken after the wait is skipped: the exchange looks at the marker again
195
201
  * before it attaches anything, so the lock narrows the race, it does not close it.
196
202
  *
197
203
  * @param ctx - Paths and clock.
198
- * @param ids - The keys' device ids, sorted.
204
+ * @param ids - The device ids of every install key and device the config names, sorted.
199
205
  * @returns The releases of the locks taken.
200
206
  */
201
207
  async function holdEnrollLocks(ctx, ids) {
@@ -267,12 +273,20 @@ async function revokeHeld(ctx, device) {
267
273
  return { reason: result.status === undefined ? 'the platform could not be reached' : `the platform answered ${result.status}` };
268
274
  }
269
275
  /**
270
- * Delete one device's secret and cached access token.
276
+ * Delete one device's secret, the install key kept beside it, and its cached access token.
271
277
  *
272
278
  * @param ctx - Paths, environment, timeout and keychain runner.
273
279
  * @param device - The device.
274
280
  */
275
281
  async function forgetSecret(ctx, device) {
276
- await secretStoreFor(device.store, ctx).remove(device.id);
277
- await fs.rm(identityPaths(ctx.paths, identityOf({ device })).accessTokenFile, { force: true });
282
+ // Each part is tried whatever happened to the others: a secret the store would
283
+ // not let go of must not keep the install key on the machine too.
284
+ const results = await Promise.allSettled([
285
+ secretStoreFor(device.store, ctx).remove(device.id),
286
+ forgetInstallKey(ctx, device),
287
+ fs.rm(identityPaths(ctx.paths, identityOf({ device })).accessTokenFile, { force: true })
288
+ ]);
289
+ const failed = results.find((result) => result.status === 'rejected');
290
+ if (failed)
291
+ throw failed.reason;
278
292
  }
@@ -49,8 +49,8 @@ export declare function identityFingerprint(identity: string): string;
49
49
  /**
50
50
  * The device credential that stands for this config's identity, if any.
51
51
  *
52
- * The install key stays beside its device in the config through the migration
53
- * window, to enroll again when the secret expires. A device whose
52
+ * A key and a device side by side are one identity until the exchange moves
53
+ * the key to the store (or an older edge left it there). A device whose
54
54
  * id is not that key's is a leftover from an earlier key and stands for
55
55
  * nothing.
56
56
  *
@@ -63,8 +63,8 @@ export function identityFingerprint(identity) {
63
63
  /**
64
64
  * The device credential that stands for this config's identity, if any.
65
65
  *
66
- * The install key stays beside its device in the config through the migration
67
- * window, to enroll again when the secret expires. A device whose
66
+ * A key and a device side by side are one identity until the exchange moves
67
+ * the key to the store (or an older edge left it there). A device whose
68
68
  * id is not that key's is a leftover from an earlier key and stands for
69
69
  * nothing.
70
70
  *
@@ -0,0 +1,31 @@
1
+ import type { CredentialContext, DeviceCredentialRef } from './types/credentials.types.js';
2
+ /**
3
+ * Move an install key from the config into its device's secret store.
4
+ *
5
+ * The key is needed again only when the device secret expires, so it lives
6
+ * where the secret does, not in plain text in `config.json`. The config entry
7
+ * keeps it until the store has proven it holds the key, so a failed write never
8
+ * loses it. Never throws.
9
+ *
10
+ * @param ctx - Paths, environment, timeout and keychain runner.
11
+ * @param installKey - The key that was exchanged.
12
+ * @param device - The device it was exchanged for.
13
+ * @param waitMs - How long to wait for the config lock.
14
+ * @returns True when the store holds the key and the config was updated.
15
+ */
16
+ export declare function retireInstallKey(ctx: CredentialContext, installKey: string, device: DeviceCredentialRef, waitMs: number): Promise<boolean>;
17
+ /**
18
+ * The install key a device was exchanged for, from its secret store.
19
+ *
20
+ * @param ctx - Paths, environment, timeout and keychain runner.
21
+ * @param device - The device.
22
+ * @returns The key, or undefined (a sign-in device has none).
23
+ */
24
+ export declare function storedInstallKey(ctx: CredentialContext, device: DeviceCredentialRef): Promise<string | undefined>;
25
+ /**
26
+ * Remove the install key kept for a device, if any.
27
+ *
28
+ * @param ctx - Paths, environment, timeout and keychain runner.
29
+ * @param device - The device being forgotten.
30
+ */
31
+ export declare function forgetInstallKey(ctx: CredentialContext, device: DeviceCredentialRef): Promise<void>;