@agent-watch-ai/edge 0.6.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 (309) hide show
  1. package/CHANGELOG.md +288 -9
  2. package/README.md +307 -5
  3. package/dist/billing/billing-mode.d.ts +37 -5
  4. package/dist/billing/billing-mode.js +28 -19
  5. package/dist/billing/constants/billing.constants.d.ts +0 -2
  6. package/dist/billing/constants/billing.constants.js +0 -2
  7. package/dist/billing/index.d.ts +2 -1
  8. package/dist/billing/index.js +1 -1
  9. package/dist/billing/session-billing.d.ts +7 -3
  10. package/dist/billing/session-billing.js +34 -13
  11. package/dist/billing/types/billing.types.d.ts +7 -0
  12. package/dist/capture/capture-env.d.ts +147 -0
  13. package/dist/capture/capture-env.js +301 -0
  14. package/dist/capture/captured-step.d.ts +88 -0
  15. package/dist/capture/captured-step.js +503 -0
  16. package/dist/capture/constants/capture.constants.d.ts +85 -0
  17. package/dist/capture/constants/capture.constants.js +87 -0
  18. package/dist/capture/launched-runs.d.ts +43 -0
  19. package/dist/capture/launched-runs.js +157 -0
  20. package/dist/capture/node.cjs +697 -0
  21. package/dist/capture/node.d.cts +32 -0
  22. package/dist/capture/python/sitecustomize.py +832 -0
  23. package/dist/capture/schemas/capture.schema.d.ts +35 -0
  24. package/dist/capture/schemas/capture.schema.js +31 -0
  25. package/dist/capture/types/capture.types.d.ts +20 -0
  26. package/dist/capture/venv-loader.d.ts +68 -0
  27. package/dist/capture/venv-loader.js +189 -0
  28. package/dist/cli/constants/cli.constants.d.ts +23 -6
  29. package/dist/cli/constants/cli.constants.js +24 -7
  30. package/dist/cli/context.d.ts +19 -22
  31. package/dist/cli/context.js +23 -54
  32. package/dist/cli/doctor-run-capture.d.ts +21 -0
  33. package/dist/cli/doctor-run-capture.js +33 -0
  34. package/dist/cli/doctor.js +21 -68
  35. package/dist/cli/hook-check.d.ts +7 -2
  36. package/dist/cli/hook-check.js +30 -15
  37. package/dist/cli/hook.d.ts +14 -0
  38. package/dist/cli/hook.js +82 -1
  39. package/dist/cli/index.d.ts +1 -1
  40. package/dist/cli/index.js +1 -1
  41. package/dist/cli/misc.js +10 -2
  42. package/dist/cli/npm-global.d.ts +24 -0
  43. package/dist/cli/npm-global.js +77 -0
  44. package/dist/cli/npx-install.js +22 -6
  45. package/dist/cli/replay.d.ts +33 -0
  46. package/dist/cli/replay.js +228 -0
  47. package/dist/cli/setup.d.ts +10 -2
  48. package/dist/cli/setup.js +200 -31
  49. package/dist/cli/status.js +45 -5
  50. package/dist/cli/toggle.js +10 -0
  51. package/dist/cli/types/cli.types.d.ts +15 -1
  52. package/dist/cli/uninstall.js +42 -23
  53. package/dist/cli/update.js +3 -2
  54. package/dist/cli.js +104 -17
  55. package/dist/config/config-store.d.ts +15 -4
  56. package/dist/config/config-store.js +31 -7
  57. package/dist/config/config.d.ts +0 -2
  58. package/dist/config/config.js +0 -1
  59. package/dist/config/constants/config.constants.d.ts +8 -1
  60. package/dist/config/constants/config.constants.js +10 -1
  61. package/dist/config/events-transport.d.ts +15 -0
  62. package/dist/config/events-transport.js +29 -0
  63. package/dist/config/index.d.ts +2 -1
  64. package/dist/config/index.js +1 -0
  65. package/dist/config/root-config.d.ts +12 -0
  66. package/dist/config/root-config.js +24 -0
  67. package/dist/config/schemas/config.schema.d.ts +15 -2
  68. package/dist/config/schemas/config.schema.js +52 -8
  69. package/dist/config/types/config.types.d.ts +7 -0
  70. package/dist/core/index.d.ts +1 -1
  71. package/dist/core/index.js +1 -1
  72. package/dist/core/version.d.ts +9 -0
  73. package/dist/core/version.js +14 -0
  74. package/dist/core/which.d.ts +11 -0
  75. package/dist/core/which.js +18 -0
  76. package/dist/credentials/cloud-claim.d.ts +34 -0
  77. package/dist/credentials/cloud-claim.js +61 -0
  78. package/dist/credentials/constants/credentials.constants.d.ts +16 -1
  79. package/dist/credentials/constants/credentials.constants.js +17 -2
  80. package/dist/credentials/credential-status.js +1 -1
  81. package/dist/credentials/credentials.d.ts +3 -3
  82. package/dist/credentials/credentials.js +26 -12
  83. package/dist/credentials/device-api.d.ts +15 -1
  84. package/dist/credentials/device-api.js +12 -1
  85. package/dist/credentials/identity.d.ts +2 -2
  86. package/dist/credentials/identity.js +2 -2
  87. package/dist/credentials/install-key.d.ts +31 -0
  88. package/dist/credentials/install-key.js +58 -0
  89. package/dist/credentials/migration.d.ts +9 -7
  90. package/dist/credentials/migration.js +58 -18
  91. package/dist/credentials/secret-store.d.ts +12 -0
  92. package/dist/credentials/secret-store.js +18 -1
  93. package/dist/credentials/sign-in.d.ts +27 -0
  94. package/dist/credentials/sign-in.js +31 -1
  95. package/dist/credentials/token-refresher.d.ts +5 -1
  96. package/dist/credentials/token-refresher.js +10 -2
  97. package/dist/enforcement/enforcement.js +1 -1
  98. package/dist/events/constants/events.constants.d.ts +5 -2
  99. package/dist/events/constants/events.constants.js +4 -1
  100. package/dist/events/enrich.d.ts +14 -0
  101. package/dist/events/enrich.js +1 -1
  102. package/dist/events/index.d.ts +1 -0
  103. package/dist/events/product-event.d.ts +6 -3
  104. package/dist/events/types/events.types.d.ts +6 -0
  105. package/dist/events/types/replay-progress.types.d.ts +26 -0
  106. package/dist/events/types/replay-progress.types.js +1 -0
  107. package/dist/events/types/repo-tree.types.d.ts +2 -1
  108. package/dist/feature/ticket-candidates.d.ts +1 -1
  109. package/dist/git/checkout-root.d.ts +15 -0
  110. package/dist/git/checkout-root.js +18 -0
  111. package/dist/git/code-state.d.ts +2 -16
  112. package/dist/git/code-state.js +11 -12
  113. package/dist/git/constants/git.constants.d.ts +33 -11
  114. package/dist/git/constants/git.constants.js +45 -12
  115. package/dist/git/fingerprint.d.ts +3 -6
  116. package/dist/git/fingerprint.js +5 -8
  117. package/dist/git/git-context.js +5 -1
  118. package/dist/git/index.d.ts +1 -2
  119. package/dist/git/index.js +1 -1
  120. package/dist/git/repo-snapshot.d.ts +13 -4
  121. package/dist/git/repo-snapshot.js +53 -9
  122. package/dist/git/types/snapshot.types.d.ts +6 -0
  123. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  124. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  125. package/dist/pipeline/hook-pipeline.js +82 -57
  126. package/dist/privacy/product-capture.js +2 -0
  127. package/dist/providers/antigravity/antigravity.capture.d.ts +2 -0
  128. package/dist/providers/antigravity/antigravity.capture.js +5 -0
  129. package/dist/providers/antigravity/antigravity.detect.js +8 -22
  130. package/dist/providers/antigravity/antigravity.provider.js +10 -3
  131. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +1 -0
  132. package/dist/providers/antigravity/constants/antigravity.constants.js +1 -0
  133. package/dist/providers/claude/claude.adapter.js +9 -6
  134. package/dist/providers/claude/claude.detect.js +2 -17
  135. package/dist/providers/claude/claude.otel.d.ts +21 -3
  136. package/dist/providers/claude/claude.otel.js +216 -61
  137. package/dist/providers/claude/claude.provider.js +21 -1
  138. package/dist/providers/claude/claude.version.d.ts +9 -0
  139. package/dist/providers/claude/claude.version.js +28 -0
  140. package/dist/providers/claude/constants/claude.constants.d.ts +27 -0
  141. package/dist/providers/claude/constants/claude.constants.js +27 -0
  142. package/dist/providers/claude/constants/claude.otel.constants.d.ts +27 -0
  143. package/dist/providers/claude/constants/claude.otel.constants.js +45 -5
  144. package/dist/providers/claude/types/claude.types.d.ts +13 -0
  145. package/dist/providers/codex/codex.capture.d.ts +76 -0
  146. package/dist/providers/codex/codex.capture.js +454 -0
  147. package/dist/providers/codex/codex.detect.js +2 -4
  148. package/dist/providers/codex/codex.otel.d.ts +38 -2
  149. package/dist/providers/codex/codex.otel.js +50 -6
  150. package/dist/providers/codex/codex.provider.js +8 -0
  151. package/dist/providers/codex/codex.surface.d.ts +9 -0
  152. package/dist/{turns/codex-originator.js → providers/codex/codex.surface.js} +17 -3
  153. package/dist/providers/codex/codex.titles.d.ts +14 -0
  154. package/dist/providers/codex/codex.titles.js +35 -0
  155. package/dist/providers/codex/constants/codex.constants.d.ts +4 -0
  156. package/dist/providers/codex/constants/codex.constants.js +4 -0
  157. package/dist/providers/cursor/constants/cursor.constants.d.ts +17 -4
  158. package/dist/providers/cursor/constants/cursor.constants.js +25 -5
  159. package/dist/providers/cursor/cursor-mcp-memo.d.ts +34 -0
  160. package/dist/providers/cursor/cursor-mcp-memo.js +94 -0
  161. package/dist/providers/cursor/cursor.adapter.js +20 -82
  162. package/dist/providers/cursor/cursor.capture.d.ts +1 -0
  163. package/dist/providers/cursor/cursor.capture.js +4 -0
  164. package/dist/providers/cursor/cursor.detect.d.ts +5 -1
  165. package/dist/providers/cursor/cursor.detect.js +11 -26
  166. package/dist/providers/cursor/cursor.hooks.js +2 -2
  167. package/dist/providers/cursor/cursor.provider.js +16 -7
  168. package/dist/providers/cursor/cursor.titles.d.ts +14 -0
  169. package/dist/providers/cursor/cursor.titles.js +20 -0
  170. package/dist/providers/cursor/schemas/cursor.schema.d.ts +3 -3
  171. package/dist/providers/cursor/schemas/cursor.schema.js +5 -3
  172. package/dist/providers/gemini/constants/gemini.constants.d.ts +16 -0
  173. package/dist/providers/gemini/constants/gemini.constants.js +17 -0
  174. package/dist/providers/gemini/gemini.capture.d.ts +81 -0
  175. package/dist/providers/gemini/gemini.capture.js +210 -0
  176. package/dist/providers/gemini/gemini.detect.js +57 -24
  177. package/dist/providers/gemini/gemini.otel.d.ts +38 -2
  178. package/dist/providers/gemini/gemini.otel.js +56 -125
  179. package/dist/providers/gemini/gemini.provider.js +5 -0
  180. package/dist/providers/index.d.ts +1 -0
  181. package/dist/providers/index.js +1 -0
  182. package/dist/providers/provider.d.ts +8 -0
  183. package/dist/providers/provider.js +9 -0
  184. package/dist/providers/registry.d.ts +14 -0
  185. package/dist/providers/registry.js +14 -0
  186. package/dist/providers/shared/constants/hook-config.constants.d.ts +2 -0
  187. package/dist/providers/shared/constants/hook-config.constants.js +2 -0
  188. package/dist/providers/shared/constants/terminal-capture.constants.d.ts +6 -0
  189. package/dist/providers/shared/constants/terminal-capture.constants.js +6 -0
  190. package/dist/providers/shared/editor-paths.d.ts +8 -0
  191. package/dist/providers/shared/editor-paths.js +18 -0
  192. package/dist/providers/shared/hook-config.d.ts +5 -0
  193. package/dist/providers/shared/hook-config.js +39 -1
  194. package/dist/providers/shared/hooks-marker.d.ts +14 -0
  195. package/dist/providers/shared/hooks-marker.js +23 -0
  196. package/dist/providers/shared/install-record.d.ts +29 -0
  197. package/dist/providers/shared/install-record.js +52 -0
  198. package/dist/providers/shared/session-title-store.d.ts +23 -0
  199. package/dist/providers/shared/session-title-store.js +50 -0
  200. package/dist/providers/shared/terminal-capture.d.ts +41 -0
  201. package/dist/providers/shared/terminal-capture.js +109 -0
  202. package/dist/providers/shared/tooling.d.ts +21 -0
  203. package/dist/providers/shared/tooling.js +36 -1
  204. package/dist/providers/types/provider.types.d.ts +57 -4
  205. package/dist/replay/checkout-resolver.d.ts +56 -0
  206. package/dist/replay/checkout-resolver.js +173 -0
  207. package/dist/replay/codex-turns.d.ts +24 -0
  208. package/dist/replay/codex-turns.js +221 -0
  209. package/dist/replay/constants/replay.constants.d.ts +99 -0
  210. package/dist/replay/constants/replay.constants.js +102 -0
  211. package/dist/replay/describe.d.ts +10 -0
  212. package/dist/replay/describe.js +31 -0
  213. package/dist/replay/gemini-turns.d.ts +36 -0
  214. package/dist/replay/gemini-turns.js +192 -0
  215. package/dist/replay/machine.d.ts +34 -0
  216. package/dist/replay/machine.js +68 -0
  217. package/dist/replay/progress-event.d.ts +21 -0
  218. package/dist/replay/progress-event.js +45 -0
  219. package/dist/replay/replay-runner.d.ts +60 -0
  220. package/dist/replay/replay-runner.js +581 -0
  221. package/dist/replay/replay-scan.d.ts +84 -0
  222. package/dist/replay/replay-scan.js +182 -0
  223. package/dist/replay/replay-state.d.ts +108 -0
  224. package/dist/replay/replay-state.js +199 -0
  225. package/dist/replay/resume.d.ts +18 -0
  226. package/dist/replay/resume.js +34 -0
  227. package/dist/replay/start.d.ts +23 -0
  228. package/dist/replay/start.js +39 -0
  229. package/dist/replay/throttle.d.ts +36 -0
  230. package/dist/replay/throttle.js +44 -0
  231. package/dist/replay/transcript-turns.d.ts +35 -0
  232. package/dist/replay/transcript-turns.js +241 -0
  233. package/dist/replay/turn-event.d.ts +40 -0
  234. package/dist/replay/turn-event.js +127 -0
  235. package/dist/replay/types/replay.types.d.ts +198 -0
  236. package/dist/replay/types/replay.types.js +1 -0
  237. package/dist/replay/window.d.ts +28 -0
  238. package/dist/replay/window.js +41 -0
  239. package/dist/replay/worktree-map.d.ts +42 -0
  240. package/dist/replay/worktree-map.js +134 -0
  241. package/dist/snapshot/branch-selection.d.ts +40 -23
  242. package/dist/snapshot/branch-selection.js +71 -41
  243. package/dist/snapshot/constants/snapshot-stages.constants.d.ts +3 -1
  244. package/dist/snapshot/constants/snapshot-stages.constants.js +3 -1
  245. package/dist/snapshot/constants/snapshot.constants.d.ts +34 -7
  246. package/dist/snapshot/constants/snapshot.constants.js +34 -7
  247. package/dist/snapshot/index.d.ts +2 -2
  248. package/dist/snapshot/index.js +1 -1
  249. package/dist/snapshot/snapshot-pipeline.js +100 -26
  250. package/dist/snapshot/snapshot-state.js +6 -2
  251. package/dist/snapshot/tree-pipeline.d.ts +1 -1
  252. package/dist/snapshot/tree-pipeline.js +34 -15
  253. package/dist/snapshot/types/snapshot.types.d.ts +22 -3
  254. package/dist/storage/schemas/storage.schema.d.ts +2 -0
  255. package/dist/storage/schemas/storage.schema.js +6 -0
  256. package/dist/transport/delivery-stats.d.ts +13 -1
  257. package/dist/transport/delivery-stats.js +18 -2
  258. package/dist/transport/delivery.d.ts +4 -3
  259. package/dist/transport/delivery.js +21 -7
  260. package/dist/transport/identity-delivery.d.ts +20 -0
  261. package/dist/transport/identity-delivery.js +41 -0
  262. package/dist/transport/index.d.ts +2 -0
  263. package/dist/transport/index.js +1 -0
  264. package/dist/transport/types/delivery-flow.types.d.ts +7 -0
  265. package/dist/turns/claude-transcript.js +4 -12
  266. package/dist/turns/codex-transcript.d.ts +9 -0
  267. package/dist/turns/codex-transcript.js +27 -19
  268. package/dist/turns/constants/turns.constants.d.ts +29 -12
  269. package/dist/turns/constants/turns.constants.js +31 -19
  270. package/dist/turns/gemini-transcript.d.ts +19 -1
  271. package/dist/turns/gemini-transcript.js +29 -18
  272. package/dist/turns/index.d.ts +3 -4
  273. package/dist/turns/index.js +2 -3
  274. package/dist/turns/run-state.d.ts +71 -0
  275. package/dist/turns/run-state.js +114 -0
  276. package/dist/turns/tool-events.d.ts +11 -1
  277. package/dist/turns/tool-events.js +32 -9
  278. package/dist/turns/transcript.d.ts +15 -14
  279. package/dist/turns/transcript.js +23 -4
  280. package/dist/turns/turn-state.d.ts +82 -7
  281. package/dist/turns/turn-state.js +157 -10
  282. package/dist/turns/turn-summary.js +7 -2
  283. package/dist/turns/turn-tracker.d.ts +9 -16
  284. package/dist/turns/turn-tracker.js +163 -87
  285. package/dist/turns/types/transcript.types.d.ts +11 -1
  286. package/dist/turns/types/turn-provider.types.d.ts +33 -0
  287. package/dist/turns/types/turn-provider.types.js +1 -0
  288. package/dist/turns/types/turn-state.types.d.ts +9 -0
  289. package/dist/turns/types/turn-summary.types.d.ts +17 -1
  290. package/dist/turns/types/turn-tracker.types.d.ts +3 -1
  291. package/dist/turns/work-checkout.js +1 -2
  292. package/docs/AUDIT_PROMPT.md +10 -0
  293. package/docs/DATA_HANDLING.md +201 -13
  294. package/docs/ENTERPRISE_DEPLOYMENT.md +3 -3
  295. package/docs/PERFORMANCE.md +10 -0
  296. package/package.json +3 -2
  297. package/dist/events/canonical-event.d.ts +0 -10
  298. package/dist/events/canonical-event.js +0 -9
  299. package/dist/git/repository-root.d.ts +0 -39
  300. package/dist/git/repository-root.js +0 -131
  301. package/dist/git/types/repository-root.types.d.ts +0 -11
  302. package/dist/transport/transport.d.ts +0 -6
  303. package/dist/turns/codex-originator.d.ts +0 -11
  304. package/dist/turns/cursor-transcript.d.ts +0 -21
  305. package/dist/turns/cursor-transcript.js +0 -66
  306. package/dist/turns/native-session-titles.d.ts +0 -26
  307. package/dist/turns/native-session-titles.js +0 -102
  308. /package/dist/{git/types/repository-root.types.js → billing/types/billing.types.js} +0 -0
  309. /package/dist/{transport/transport.js → capture/types/capture.types.js} +0 -0
@@ -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. */
@@ -80,6 +80,16 @@ export declare const emitSchema: z.ZodObject<{
80
80
  * @returns True when the edge may send there.
81
81
  */
82
82
  export declare function isAllowedHost(value: string, trusted: ReadonlySet<string>): boolean;
83
+ /**
84
+ * Whether a URL is one AgentWatch itself sends to: an Agent Watch host or an
85
+ * origin this machine trusts. Unlike `isAllowedHost`, loopback alone does not
86
+ * count, because a collector on localhost is as likely the developer's own.
87
+ *
88
+ * @param value - The URL as written.
89
+ * @param trusted - Origins this machine trusts (`customEndpoints`).
90
+ * @returns True when the URL points at Agent Watch.
91
+ */
92
+ export declare function isAgentWatchEndpoint(value: string, trusted: ReadonlySet<string>): boolean;
83
93
  /**
84
94
  * The origin of a URL the edge could deliver to, for recording trust in it.
85
95
  *
@@ -215,6 +225,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
215
225
  developerEmail: z.ZodOptional<z.ZodString>;
216
226
  developerName: z.ZodOptional<z.ZodString>;
217
227
  }, z.core.$strip>>>;
228
+ ignoredRoots: z.ZodDefault<z.ZodArray<z.ZodString>>;
218
229
  contentCaptureConsent: z.ZodDefault<z.ZodBoolean>;
219
230
  customEndpoints: z.ZodDefault<z.ZodCatch<z.ZodArray<z.ZodString>>>;
220
231
  allowlistVersion: z.ZodOptional<z.ZodNumber>;
@@ -247,7 +258,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
247
258
  }, z.core.$strip>>;
248
259
  enforcement: z.ZodPrefault<z.ZodObject<{
249
260
  enabled: z.ZodDefault<z.ZodBoolean>;
250
- timeoutMs: z.ZodDefault<z.ZodNumber>;
261
+ timeoutMs: z.ZodPipe<z.ZodDefault<z.ZodNumber>, z.ZodTransform<number, number>>;
251
262
  cacheTtlMs: z.ZodDefault<z.ZodNumber>;
252
263
  }, z.core.$strip>>;
253
264
  }, z.core.$loose>, z.ZodTransform<{
@@ -261,6 +272,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
261
272
  mcpNames: boolean;
262
273
  };
263
274
  schemaVersion: 1;
275
+ ignoredRoots: string[];
264
276
  contentCaptureConsent: boolean;
265
277
  customEndpoints: string[];
266
278
  untracedNotices: boolean;
@@ -322,6 +334,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
322
334
  }, {
323
335
  [x: string]: unknown;
324
336
  schemaVersion: 1;
337
+ ignoredRoots: string[];
325
338
  contentCaptureConsent: boolean;
326
339
  customEndpoints: string[];
327
340
  untracedNotices: boolean;
@@ -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
  })
@@ -139,17 +147,14 @@ function judgeUrl(value, trusted) {
139
147
  if (!url)
140
148
  return { kind: 'undeliverable' };
141
149
  const origin = originOf(url);
142
- // Without the trailing dot: `host.` is the same DNS name as `host`.
143
- const host = url.hostname.endsWith('.') ? url.hostname.slice(0, -1) : url.hostname;
150
+ const host = bareHost(url);
144
151
  const loopback = LOOPBACK_HOSTS.has(host);
145
152
  if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
146
153
  return { kind: 'undeliverable', ...(url.protocol === 'http:' ? { origin } : {}) };
147
154
  }
148
155
  if (loopback || trusted.has(origin))
149
156
  return { kind: 'allowed', origin };
150
- // A port other than the default needs trust: a different port on the right
151
- // name is a different service.
152
- if (url.protocol === 'https:' && url.port === '' && AGENT_WATCH_HOSTS.has(host))
157
+ if (isAgentWatchHost(url))
153
158
  return { kind: 'allowed', origin };
154
159
  return { kind: 'untrusted', origin };
155
160
  }
@@ -162,7 +167,7 @@ function judgeUrl(value, trusted) {
162
167
  * @returns The origin.
163
168
  */
164
169
  function originOf(url) {
165
- const host = url.hostname.endsWith('.') ? url.hostname.slice(0, -1) : url.hostname;
170
+ const host = bareHost(url);
166
171
  return `${url.protocol}//${host}${url.port ? `:${url.port}` : ''}`;
167
172
  }
168
173
  /**
@@ -175,6 +180,40 @@ function originOf(url) {
175
180
  export function isAllowedHost(value, trusted) {
176
181
  return judgeUrl(value, trusted).kind === 'allowed';
177
182
  }
183
+ /**
184
+ * Whether a URL is one AgentWatch itself sends to: an Agent Watch host or an
185
+ * origin this machine trusts. Unlike `isAllowedHost`, loopback alone does not
186
+ * count, because a collector on localhost is as likely the developer's own.
187
+ *
188
+ * @param value - The URL as written.
189
+ * @param trusted - Origins this machine trusts (`customEndpoints`).
190
+ * @returns True when the URL points at Agent Watch.
191
+ */
192
+ export function isAgentWatchEndpoint(value, trusted) {
193
+ const url = parseUrl(value);
194
+ if (!url || judgeUrl(value, trusted).kind !== 'allowed')
195
+ return false;
196
+ return trusted.has(originOf(url)) || isAgentWatchHost(url);
197
+ }
198
+ /**
199
+ * Whether a parsed URL is an Agent Watch host on the default https port: a
200
+ * different port on the right name is a different service.
201
+ *
202
+ * @param url - A parsed URL.
203
+ * @returns True for an Agent Watch host.
204
+ */
205
+ function isAgentWatchHost(url) {
206
+ return url.protocol === 'https:' && url.port === '' && AGENT_WATCH_HOSTS.has(bareHost(url));
207
+ }
208
+ /**
209
+ * A URL's host without the trailing dot: `host.` is the same DNS name as `host`.
210
+ *
211
+ * @param url - A parsed URL.
212
+ * @returns The host.
213
+ */
214
+ function bareHost(url) {
215
+ return url.hostname.endsWith('.') ? url.hostname.slice(0, -1) : url.hostname;
216
+ }
178
217
  /**
179
218
  * The origin of a URL the edge could deliver to, for recording trust in it.
180
219
  *
@@ -452,6 +491,11 @@ export const configSchema = z
452
491
  * wins, so a nested checkout can override the workspace above it.
453
492
  */
454
493
  roots: z.record(z.string(), rootOverrideSchema).optional(),
494
+ /**
495
+ * Absolute directories whose hooks answer the agent and capture nothing; `<dir>/**` covers the subtree.
496
+ * No `.catch`: a malformed list invalidates the file loudly instead of quietly capturing where the developer opted out.
497
+ */
498
+ ignoredRoots: z.array(z.string()).default([]),
455
499
  contentCaptureConsent: z.boolean().default(false),
456
500
  /**
457
501
  * Origins this machine sends to outside the Agent Watch hosts. Written by
@@ -45,3 +45,10 @@ export interface EffectiveConfig extends MergedConfig {
45
45
  /** Project root whose identity was applied, when one matched. */
46
46
  readonly rootPath?: string;
47
47
  }
48
+ /** Ceilings for one transport; both in milliseconds, so they are named, never positional. */
49
+ export interface TransportLimits {
50
+ /** Ceiling for one request; defaults to the config's `delivery.timeoutMs`. */
51
+ readonly timeoutMs?: number;
52
+ /** Ceiling for the whole send; the hook passes what is left of its budget. */
53
+ readonly budgetMs?: number;
54
+ }
@@ -6,7 +6,7 @@ export type { Env, FlowObserver, FlowResult, FlowTrace, Step, StepOutcome, Unkno
6
6
  export { realEnv } from './env.js';
7
7
  export { debugEnabled, debugLog, setVerbose, warnLog } from './logger.js';
8
8
  export { meetsMinVersion, parseVersion } from './version.js';
9
- export { findExecutable } from './which.js';
9
+ export { findExecutable, findFirstExecutable } from './which.js';
10
10
  export { asArray, asRecord, compact, firstNumber, firstString, firstStringOf, isRecord, omitKeys } from './object.js';
11
11
  export { add, finiteOrZero, sumPresent } from './number.js';
12
12
  export { pollUntil, sleep } from './async.js';
@@ -1,7 +1,7 @@
1
1
  export { realEnv } from './env.js';
2
2
  export { debugEnabled, debugLog, setVerbose, warnLog } from './logger.js';
3
3
  export { meetsMinVersion, parseVersion } from './version.js';
4
- export { findExecutable } from './which.js';
4
+ export { findExecutable, findFirstExecutable } from './which.js';
5
5
  export { asArray, asRecord, compact, firstNumber, firstString, firstStringOf, isRecord, omitKeys } from './object.js';
6
6
  export { add, finiteOrZero, sumPresent } from './number.js';
7
7
  export { pollUntil, sleep } from './async.js';
@@ -17,3 +17,12 @@ export declare function parseVersion(output: string): string | undefined;
17
17
  * @returns True when version >= min.
18
18
  */
19
19
  export declare function meetsMinVersion(version: string, min: string): boolean;
20
+ /**
21
+ * Run a `--version`-style command, treating any failure as no answer.
22
+ *
23
+ * @param command - Executable.
24
+ * @param args - Its arguments.
25
+ * @param timeoutMs - Kill budget.
26
+ * @returns Its stdout, or undefined.
27
+ */
28
+ export declare function execVersion(command: string, args: readonly string[], timeoutMs: number): Promise<string | undefined>;
@@ -1,3 +1,4 @@
1
+ import { execFile } from 'node:child_process';
1
2
  import { RE_SEMVER } from './constants/core.constants.js';
2
3
  /**
3
4
  * First dotted version (x.y.z) found in CLI output.
@@ -33,3 +34,16 @@ export function meetsMinVersion(version, min) {
33
34
  }
34
35
  return true;
35
36
  }
37
+ /**
38
+ * Run a `--version`-style command, treating any failure as no answer.
39
+ *
40
+ * @param command - Executable.
41
+ * @param args - Its arguments.
42
+ * @param timeoutMs - Kill budget.
43
+ * @returns Its stdout, or undefined.
44
+ */
45
+ export function execVersion(command, args, timeoutMs) {
46
+ return new Promise((resolve) => {
47
+ execFile(command, [...args], { timeout: timeoutMs }, (error, stdout) => resolve(error ? undefined : stdout));
48
+ });
49
+ }
@@ -11,6 +11,17 @@ import type { Env } from './types/core.types.js';
11
11
  * @returns Absolute path of the first match, or undefined when not found.
12
12
  */
13
13
  export declare function findExecutable(env: Env, name: string): string | undefined;
14
+ /**
15
+ * The first of several executable names found on PATH.
16
+ *
17
+ * For an agent that ships under more than one name (editor and CLI, old and
18
+ * new): the names are tried in order, so the preferred one wins.
19
+ *
20
+ * @param env - Environment supplying PATH and the platform.
21
+ * @param names - Executable names without extension, most preferred first.
22
+ * @returns Absolute path of the first match, or undefined when none is found.
23
+ */
24
+ export declare function findFirstExecutable(env: Env, names: readonly string[]): string | undefined;
14
25
  /**
15
26
  * Locate a tool the OS ships, in the OS's own directories only.
16
27
  *
@@ -15,6 +15,24 @@ import { POSIX_EXECUTABLE_MASK, WINDOWS_EXECUTABLE_EXTENSIONS } from './constant
15
15
  export function findExecutable(env, name) {
16
16
  return findIn((env.vars['PATH'] ?? '').split(path.delimiter).filter(Boolean), env.platform, name);
17
17
  }
18
+ /**
19
+ * The first of several executable names found on PATH.
20
+ *
21
+ * For an agent that ships under more than one name (editor and CLI, old and
22
+ * new): the names are tried in order, so the preferred one wins.
23
+ *
24
+ * @param env - Environment supplying PATH and the platform.
25
+ * @param names - Executable names without extension, most preferred first.
26
+ * @returns Absolute path of the first match, or undefined when none is found.
27
+ */
28
+ export function findFirstExecutable(env, names) {
29
+ for (const name of names) {
30
+ const found = findExecutable(env, name);
31
+ if (found)
32
+ return found;
33
+ }
34
+ return undefined;
35
+ }
18
36
  /**
19
37
  * Locate a tool the OS ships, in the OS's own directories only.
20
38
  *
@@ -0,0 +1,34 @@
1
+ import type { Env } from '../core/types/core.types.js';
2
+ /** What a Claude Code cloud VM claims a device with: the managed settings and the session's Claude account. */
3
+ export interface CloudIdentity {
4
+ readonly organizationId: string;
5
+ /** Base64url PKCS8 DER Ed25519 private key. Never printed, logged or written. */
6
+ readonly key: string;
7
+ /** The signed-in Claude account's email; never git's (in a cloud VM that is `noreply@anthropic.com`). */
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;
11
+ }
12
+ /**
13
+ * What the managed settings and the Claude account give this VM to claim with,
14
+ * or the one line that says why it cannot.
15
+ *
16
+ * @param env - Environment and home of this VM.
17
+ * @returns The identity, or the reason to install nothing.
18
+ */
19
+ export declare function cloudIdentity(env: Env): Promise<CloudIdentity | {
20
+ readonly skip: string;
21
+ }>;
22
+ /**
23
+ * The claim text and its Ed25519 signature over the text's exact UTF-8 bytes
24
+ * (the Contract: the gateway verifies the bytes before it parses them, so no
25
+ * one canonicalizes JSON). A fresh nonce every call: the gateway spends each once.
26
+ *
27
+ * @param identity - Organization, key and email.
28
+ * @param now - The time the claim is issued at; the gateway allows ±5 minutes.
29
+ * @returns The claim and signature, or undefined when the key is no Ed25519 private key.
30
+ */
31
+ export declare function signCloudClaim(identity: CloudIdentity, now: Date): {
32
+ readonly claim: string;
33
+ readonly signature: string;
34
+ } | undefined;
@@ -0,0 +1,61 @@
1
+ import { createPrivateKey, randomBytes, sign } from 'node:crypto';
2
+ import { claudeAccountEmail } from '../billing/billing-mode.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';
6
+ /**
7
+ * What the managed settings and the Claude account give this VM to claim with,
8
+ * or the one line that says why it cannot.
9
+ *
10
+ * @param env - Environment and home of this VM.
11
+ * @returns The identity, or the reason to install nothing.
12
+ */
13
+ export async function cloudIdentity(env) {
14
+ const organizationId = env.vars[AGENTWATCH_CLOUD_ORGANIZATION]?.trim();
15
+ const key = env.vars[AGENTWATCH_CLOUD_KEY]?.trim();
16
+ if (!organizationId || !key)
17
+ return { skip: `no ${AGENTWATCH_CLOUD_ORGANIZATION} or ${AGENTWATCH_CLOUD_KEY} in the managed settings; Agent Watch not installed` };
18
+ const email = await claudeAccountEmail(env.home).catch(() => undefined);
19
+ if (!email)
20
+ return { skip: 'no Claude account email in ~/.claude.json; Agent Watch not installed' };
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)}`;
39
+ }
40
+ /**
41
+ * The claim text and its Ed25519 signature over the text's exact UTF-8 bytes
42
+ * (the Contract: the gateway verifies the bytes before it parses them, so no
43
+ * one canonicalizes JSON). A fresh nonce every call: the gateway spends each once.
44
+ *
45
+ * @param identity - Organization, key and email.
46
+ * @param now - The time the claim is issued at; the gateway allows ±5 minutes.
47
+ * @returns The claim and signature, or undefined when the key is no Ed25519 private key.
48
+ */
49
+ export function signCloudClaim(identity, now) {
50
+ const claim = JSON.stringify({ v: 1, organizationId: identity.organizationId, email: identity.email, issuedAt: now.toISOString(), nonce: randomBytes(16).toString('base64url') });
51
+ try {
52
+ const key = createPrivateKey({ key: Buffer.from(identity.key, 'base64url'), format: 'der', type: 'pkcs8' });
53
+ if (key.asymmetricKeyType !== 'ed25519')
54
+ return undefined;
55
+ return { claim, signature: sign(null, Buffer.from(claim, 'utf8'), key).toString('base64url') };
56
+ }
57
+ catch {
58
+ // Never the error: it may quote the key.
59
+ return undefined;
60
+ }
61
+ }
@@ -55,6 +55,15 @@ export declare const ENROLLMENT_SESSION_PATH = "/v1/devices/enrollment-sessions"
55
55
  export declare const ENROLLMENT_SESSION_TOKEN_PATH = "/v1/devices/enrollment-sessions/token";
56
56
  /** AWT-275 unattended enrollment: an admin-issued, single-use code in the body. */
57
57
  export declare const ENROLL_CODE_PATH = "/v1/devices/enroll-code";
58
+ /** Cloud claim: a Claude Code cloud VM trades a claim signed with its organization's cloud session key for a device. Public; the signature is the credential. */
59
+ export declare const CLOUD_CLAIM_PATH = "/v1/devices/cloud-claim";
60
+ /** Set to `true` by Claude Code in a cloud session; the only place `setup --cloud` claims a device. */
61
+ export declare const CLAUDE_CODE_REMOTE_VAR = "CLAUDE_CODE_REMOTE";
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
+ export declare const AGENTWATCH_CLOUD_ORGANIZATION = "AGENTWATCH_CLOUD_ORGANIZATION";
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";
58
67
  /** Recorded on a device enrolled with an admin-issued code, so `status` can say so (core `DeviceCredentialSource.BatchCode`). */
59
68
  export declare const DEVICE_SOURCE_BATCH_CODE = "batch-code";
60
69
  /** The RFC 8628 answers of a poll that are not failures: keep waiting. */
@@ -81,7 +90,7 @@ export declare const REFUSAL_SECRET_EXPIRED = "device_secret_expired";
81
90
  * backend cooldown.
82
91
  */
83
92
  export declare const DEVICE_REFUSALS: ReadonlySet<string>;
84
- /** Every reason the edge acts on, from any route. */
93
+ /** Every reason the edge acts on, from any route. `installation_mismatch` is read so a plain-401 refresh never fires on it. */
85
94
  export declare const KNOWN_REFUSALS: ReadonlySet<string>;
86
95
  /**
87
96
  * The share of the hook's delivery budget credential work may spend: a
@@ -117,3 +126,9 @@ export declare const ENROLL_RETRY_MS = 3600000;
117
126
  export declare const RE_PLAIN_EMAIL: RegExp;
118
127
  /** What an MDM install that has not signed in yet tells its developer, wherever it speaks. */
119
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";
@@ -56,6 +56,15 @@ export const ENROLLMENT_SESSION_PATH = '/v1/devices/enrollment-sessions';
56
56
  export const ENROLLMENT_SESSION_TOKEN_PATH = '/v1/devices/enrollment-sessions/token';
57
57
  /** AWT-275 unattended enrollment: an admin-issued, single-use code in the body. */
58
58
  export const ENROLL_CODE_PATH = '/v1/devices/enroll-code';
59
+ /** Cloud claim: a Claude Code cloud VM trades a claim signed with its organization's cloud session key for a device. Public; the signature is the credential. */
60
+ export const CLOUD_CLAIM_PATH = '/v1/devices/cloud-claim';
61
+ /** Set to `true` by Claude Code in a cloud session; the only place `setup --cloud` claims a device. */
62
+ export const CLAUDE_CODE_REMOTE_VAR = 'CLAUDE_CODE_REMOTE';
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
+ export const AGENTWATCH_CLOUD_ORGANIZATION = 'AGENTWATCH_CLOUD_ORGANIZATION';
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';
59
68
  /** Recorded on a device enrolled with an admin-issued code, so `status` can say so (core `DeviceCredentialSource.BatchCode`). */
60
69
  export const DEVICE_SOURCE_BATCH_CODE = 'batch-code';
61
70
  /** The RFC 8628 answers of a poll that are not failures: keep waiting. */
@@ -82,8 +91,8 @@ export const REFUSAL_SECRET_EXPIRED = 'device_secret_expired';
82
91
  * backend cooldown.
83
92
  */
84
93
  export const DEVICE_REFUSALS = new Set([REFUSAL_DEVICE_REVOKED, 'device_unknown', REFUSAL_SECRET_EXPIRED]);
85
- /** Every reason the edge acts on, from any route. */
86
- export const KNOWN_REFUSALS = new Set([REFUSAL_TOKEN_EXPIRED, REFUSAL_INSTALL_KEY_RETIRED, REFUSAL_ENROLLMENT_CODE_INVALID, ...DEVICE_REFUSALS]);
94
+ /** Every reason the edge acts on, from any route. `installation_mismatch` is read so a plain-401 refresh never fires on it. */
95
+ export const KNOWN_REFUSALS = new Set([REFUSAL_TOKEN_EXPIRED, REFUSAL_INSTALL_KEY_RETIRED, REFUSAL_ENROLLMENT_CODE_INVALID, 'installation_mismatch', ...DEVICE_REFUSALS]);
87
96
  /**
88
97
  * The share of the hook's delivery budget credential work may spend: a
89
98
  * keychain read, a refresh or an exchange together. The send gets the rest, so
@@ -118,3 +127,9 @@ export const ENROLL_RETRY_MS = 3_600_000;
118
127
  export const RE_PLAIN_EMAIL = /^[^\s@\p{Cc}\p{Cf}]{1,64}@[^\s@\p{Cc}\p{Cf}]{1,189}$/u;
119
128
  /** What an MDM install that has not signed in yet tells its developer, wherever it speaks. */
120
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
  }
@@ -1,4 +1,4 @@
1
- import type { DeviceApiResult, EnrollInput, IssuedDeviceCredential, PollSessionInput, RedeemCodeInput, RefreshedAccessToken, RefreshInput, RevokeInput, StartedEnrollmentSession, StartSessionInput } from './types/credentials.types.js';
1
+ import type { DeviceApiResult, DeviceRouteInput, EnrollInput, IssuedDeviceCredential, PollSessionInput, RedeemCodeInput, RefreshedAccessToken, RefreshInput, RevokeInput, StartedEnrollmentSession, StartSessionInput } from './types/credentials.types.js';
2
2
  /**
3
3
  * Trade the install key for a device credential of this machine's own.
4
4
  *
@@ -19,6 +19,20 @@ export declare function enrollDevice(input: EnrollInput): Promise<DeviceApiResul
19
19
  * @returns The credential, or why not (`enrollment_code_invalid` for any code it cannot redeem).
20
20
  */
21
21
  export declare function redeemEnrollmentCode(input: RedeemCodeInput): Promise<DeviceApiResult<IssuedDeviceCredential>>;
22
+ /**
23
+ * Trade a claim signed with the organization's cloud session key for a device
24
+ * of this Claude Code cloud VM's own. Public on the gateway: the signature is
25
+ * the credential. Every refusal is `401 cloud_claim_refused`.
26
+ *
27
+ * @param input - Gateway base URL, the claim text and its signature, installation, machine label, timeout.
28
+ * @returns The credential, or why not.
29
+ */
30
+ export declare function claimCloudDevice(input: DeviceRouteInput & {
31
+ readonly claim: string;
32
+ readonly signature: string;
33
+ readonly installationId: string;
34
+ readonly name: string;
35
+ }): Promise<DeviceApiResult<IssuedDeviceCredential>>;
22
36
  /**
23
37
  * Open a browser sign-in session. Public on the gateway: the organization's id
24
38
  * is all it takes, and no install key travels on this path.
@@ -2,7 +2,7 @@ import { joinUrl } from '../config/config.js';
2
2
  import { asRecord } from '../core/object.js';
3
3
  import { AUTHORIZATION_HEADER, CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE, USER_AGENT, USER_AGENT_HEADER } from '../transport/constants/transport.constants.js';
4
4
  import { discardResponseBody, readCappedJson } from '../transport/response-body.js';
5
- import { ENROLL_CODE_PATH, ENROLL_PATH, ENROLLMENT_SESSION_PATH, ENROLLMENT_SESSION_TOKEN_PATH, KNOWN_REFUSALS, REVOKE_PATH, TOKEN_PATH } from './constants/credentials.constants.js';
5
+ import { CLOUD_CLAIM_PATH, ENROLL_CODE_PATH, ENROLL_PATH, ENROLLMENT_SESSION_PATH, ENROLLMENT_SESSION_TOKEN_PATH, KNOWN_REFUSALS, REVOKE_PATH, TOKEN_PATH } from './constants/credentials.constants.js';
6
6
  import { issuedDeviceCredentialSchema, pollErrorSchema, refreshedAccessTokenSchema, startedEnrollmentSessionSchema } from './schemas/device-api.schema.js';
7
7
  /**
8
8
  * Trade the install key for a device credential of this machine's own.
@@ -28,6 +28,17 @@ export async function enrollDevice(input) {
28
28
  export async function redeemEnrollmentCode(input) {
29
29
  return post(input, ENROLL_CODE_PATH, { code: input.code, installationId: input.installationId, name: input.name }, issuedDeviceCredentialSchema);
30
30
  }
31
+ /**
32
+ * Trade a claim signed with the organization's cloud session key for a device
33
+ * of this Claude Code cloud VM's own. Public on the gateway: the signature is
34
+ * the credential. Every refusal is `401 cloud_claim_refused`.
35
+ *
36
+ * @param input - Gateway base URL, the claim text and its signature, installation, machine label, timeout.
37
+ * @returns The credential, or why not.
38
+ */
39
+ export async function claimCloudDevice(input) {
40
+ return post(input, CLOUD_CLAIM_PATH, { claim: input.claim, signature: input.signature, installationId: input.installationId, name: input.name }, issuedDeviceCredentialSchema);
41
+ }
31
42
  /**
32
43
  * Open a browser sign-in session. Public on the gateway: the organization's id
33
44
  * is all it takes, and no install key travels on this path.