@agent-watch-ai/edge 0.2.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/CHANGELOG.md +558 -0
  2. package/README.md +222 -97
  3. package/SECURITY.md +72 -0
  4. package/dist/billing/session-billing.d.ts +19 -0
  5. package/dist/billing/session-billing.js +52 -0
  6. package/dist/cli/args.d.ts +10 -0
  7. package/dist/cli/args.js +20 -0
  8. package/dist/cli/constants/cli.constants.d.ts +52 -4
  9. package/dist/cli/constants/cli.constants.js +56 -5
  10. package/dist/cli/context.d.ts +33 -2
  11. package/dist/cli/context.js +84 -14
  12. package/dist/cli/doctor.js +321 -33
  13. package/dist/cli/hook-check.d.ts +23 -0
  14. package/dist/cli/hook-check.js +114 -0
  15. package/dist/cli/hook.js +118 -7
  16. package/dist/cli/index.d.ts +3 -1
  17. package/dist/cli/index.js +3 -1
  18. package/dist/cli/misc.d.ts +11 -0
  19. package/dist/cli/misc.js +80 -4
  20. package/dist/cli/npx-install.d.ts +37 -0
  21. package/dist/cli/npx-install.js +79 -0
  22. package/dist/cli/open-browser.d.ts +39 -0
  23. package/dist/cli/open-browser.js +62 -0
  24. package/dist/cli/setup.d.ts +17 -8
  25. package/dist/cli/setup.js +553 -103
  26. package/dist/cli/status.js +82 -13
  27. package/dist/cli/toggle.d.ts +9 -0
  28. package/dist/cli/toggle.js +117 -0
  29. package/dist/cli/types/cli.types.d.ts +43 -3
  30. package/dist/cli/ui.d.ts +7 -0
  31. package/dist/cli/ui.js +10 -1
  32. package/dist/cli/uninstall.js +39 -2
  33. package/dist/cli/update.d.ts +17 -0
  34. package/dist/cli/update.js +76 -0
  35. package/dist/cli.js +110 -12
  36. package/dist/config/config-store.d.ts +57 -0
  37. package/dist/config/config-store.js +250 -12
  38. package/dist/config/config.d.ts +53 -6
  39. package/dist/config/config.js +66 -6
  40. package/dist/config/constants/config.constants.d.ts +116 -6
  41. package/dist/config/constants/config.constants.js +131 -8
  42. package/dist/config/destination.d.ts +24 -0
  43. package/dist/config/destination.js +33 -0
  44. package/dist/config/index.d.ts +7 -4
  45. package/dist/config/index.js +5 -3
  46. package/dist/config/repo-config.d.ts +11 -7
  47. package/dist/config/repo-config.js +64 -15
  48. package/dist/config/root-config.d.ts +72 -0
  49. package/dist/config/root-config.js +170 -0
  50. package/dist/config/schemas/config.schema.d.ts +831 -84
  51. package/dist/config/schemas/config.schema.js +398 -16
  52. package/dist/config/types/config.types.d.ts +15 -1
  53. package/dist/config/types/destination.types.d.ts +8 -0
  54. package/dist/core/async.d.ts +36 -0
  55. package/dist/core/async.js +68 -0
  56. package/dist/core/index.d.ts +1 -1
  57. package/dist/core/index.js +1 -1
  58. package/dist/core/object.d.ts +5 -0
  59. package/dist/core/object.js +9 -4
  60. package/dist/core/pipe.d.ts +0 -13
  61. package/dist/core/pipe.js +1 -9
  62. package/dist/core/types/core.types.d.ts +9 -0
  63. package/dist/core/types/core.types.js +0 -3
  64. package/dist/core/which.d.ts +14 -0
  65. package/dist/core/which.js +43 -3
  66. package/dist/credentials/budget.d.ts +9 -0
  67. package/dist/credentials/budget.js +16 -0
  68. package/dist/credentials/command-runner.d.ts +16 -0
  69. package/dist/credentials/command-runner.js +37 -0
  70. package/dist/credentials/constants/credentials.constants.d.ts +119 -0
  71. package/dist/credentials/constants/credentials.constants.js +120 -0
  72. package/dist/credentials/credential-status.d.ts +14 -0
  73. package/dist/credentials/credential-status.js +38 -0
  74. package/dist/credentials/credentials.d.ts +86 -0
  75. package/dist/credentials/credentials.js +278 -0
  76. package/dist/credentials/device-api.d.ts +73 -0
  77. package/dist/credentials/device-api.js +161 -0
  78. package/dist/credentials/device-state.d.ts +31 -0
  79. package/dist/credentials/device-state.js +51 -0
  80. package/dist/credentials/identity.d.ts +73 -0
  81. package/dist/credentials/identity.js +101 -0
  82. package/dist/credentials/index.d.ts +7 -0
  83. package/dist/credentials/index.js +5 -0
  84. package/dist/credentials/migration.d.ts +46 -0
  85. package/dist/credentials/migration.js +164 -0
  86. package/dist/credentials/schemas/device-api.schema.d.ts +77 -0
  87. package/dist/credentials/schemas/device-api.schema.js +33 -0
  88. package/dist/credentials/schemas/device-state.schema.d.ts +51 -0
  89. package/dist/credentials/schemas/device-state.schema.js +20 -0
  90. package/dist/credentials/secret-store.d.ts +54 -0
  91. package/dist/credentials/secret-store.js +217 -0
  92. package/dist/credentials/sign-in.d.ts +31 -0
  93. package/dist/credentials/sign-in.js +105 -0
  94. package/dist/credentials/token-refresher.d.ts +39 -0
  95. package/dist/credentials/token-refresher.js +185 -0
  96. package/dist/credentials/types/credentials.types.d.ts +206 -0
  97. package/dist/credentials/types/credentials.types.js +1 -0
  98. package/dist/enforcement/constants/enforcement.constants.d.ts +47 -1
  99. package/dist/enforcement/constants/enforcement.constants.js +56 -0
  100. package/dist/enforcement/decision-cache.d.ts +20 -1
  101. package/dist/enforcement/decision-cache.js +65 -2
  102. package/dist/enforcement/decision-client.d.ts +9 -8
  103. package/dist/enforcement/decision-client.js +64 -17
  104. package/dist/enforcement/enforcement.d.ts +23 -2
  105. package/dist/enforcement/enforcement.js +107 -17
  106. package/dist/enforcement/index.d.ts +4 -3
  107. package/dist/enforcement/index.js +3 -2
  108. package/dist/enforcement/types/enforcement.types.d.ts +66 -2
  109. package/dist/enrollment/constants/enrollment.constants.d.ts +2 -6
  110. package/dist/enrollment/constants/enrollment.constants.js +2 -6
  111. package/dist/enrollment/enrollment.d.ts +16 -0
  112. package/dist/enrollment/enrollment.js +54 -0
  113. package/dist/enrollment/index.d.ts +3 -7
  114. package/dist/enrollment/index.js +1 -1
  115. package/dist/enrollment/types/enrollment.types.d.ts +9 -13
  116. package/dist/events/constants/enrich.constants.d.ts +15 -0
  117. package/dist/events/constants/enrich.constants.js +15 -0
  118. package/dist/events/constants/events.constants.d.ts +6 -2
  119. package/dist/events/constants/events.constants.js +5 -1
  120. package/dist/events/enrich.js +92 -10
  121. package/dist/events/event-id.d.ts +0 -8
  122. package/dist/events/event-id.js +0 -10
  123. package/dist/events/index.d.ts +2 -2
  124. package/dist/events/index.js +1 -1
  125. package/dist/events/product-event.d.ts +9 -6
  126. package/dist/events/types/repo-snapshot.types.d.ts +7 -0
  127. package/dist/events/types/session-billing.types.d.ts +16 -0
  128. package/dist/events/types/session-billing.types.js +1 -0
  129. package/dist/feature/constants/feature.constants.d.ts +7 -0
  130. package/dist/feature/constants/feature.constants.js +7 -0
  131. package/dist/feature/index.d.ts +1 -1
  132. package/dist/feature/index.js +1 -1
  133. package/dist/feature/ticket-candidates.d.ts +14 -0
  134. package/dist/feature/ticket-candidates.js +26 -8
  135. package/dist/git/blob-hash.d.ts +21 -0
  136. package/dist/git/blob-hash.js +69 -0
  137. package/dist/git/checkout-root.d.ts +27 -0
  138. package/dist/git/checkout-root.js +75 -0
  139. package/dist/git/constants/git.constants.d.ts +160 -0
  140. package/dist/git/constants/git.constants.js +181 -0
  141. package/dist/git/fingerprint.d.ts +74 -0
  142. package/dist/git/fingerprint.js +219 -0
  143. package/dist/git/gate-checkout.d.ts +44 -0
  144. package/dist/git/gate-checkout.js +201 -0
  145. package/dist/git/git-context.d.ts +45 -0
  146. package/dist/git/git-context.js +61 -3
  147. package/dist/git/index.d.ts +4 -2
  148. package/dist/git/index.js +2 -1
  149. package/dist/git/manifest-repository.d.ts +13 -0
  150. package/dist/git/manifest-repository.js +92 -0
  151. package/dist/git/repo-snapshot.d.ts +29 -3
  152. package/dist/git/repo-snapshot.js +110 -7
  153. package/dist/git/repository-root.d.ts +39 -0
  154. package/dist/git/repository-root.js +131 -0
  155. package/dist/git/types/git.types.d.ts +55 -0
  156. package/dist/git/types/repository-root.types.d.ts +11 -0
  157. package/dist/git/types/repository-root.types.js +1 -0
  158. package/dist/git/types/snapshot.types.d.ts +9 -0
  159. package/dist/pipeline/constants/pipeline.constants.d.ts +10 -0
  160. package/dist/pipeline/constants/pipeline.constants.js +10 -0
  161. package/dist/pipeline/hook-pipeline.js +410 -33
  162. package/dist/pipeline/types/pipeline.types.d.ts +39 -4
  163. package/dist/privacy/constants/privacy.constants.js +15 -1
  164. package/dist/privacy/index.d.ts +1 -0
  165. package/dist/privacy/index.js +1 -0
  166. package/dist/privacy/product-capture.d.ts +12 -0
  167. package/dist/privacy/product-capture.js +75 -0
  168. package/dist/privacy/sanitizer.d.ts +21 -3
  169. package/dist/privacy/sanitizer.js +52 -8
  170. package/dist/process/ancestors.d.ts +39 -0
  171. package/dist/process/ancestors.js +121 -0
  172. package/dist/process/constants/process.constants.d.ts +34 -0
  173. package/dist/process/constants/process.constants.js +34 -0
  174. package/dist/process/index.d.ts +7 -0
  175. package/dist/process/index.js +2 -0
  176. package/dist/process/types/process.types.d.ts +23 -0
  177. package/dist/process/types/process.types.js +1 -0
  178. package/dist/providers/antigravity/antigravity.adapter.d.ts +12 -1
  179. package/dist/providers/antigravity/antigravity.adapter.js +21 -3
  180. package/dist/providers/antigravity/antigravity.detect.d.ts +0 -9
  181. package/dist/providers/antigravity/antigravity.detect.js +1 -1
  182. package/dist/providers/antigravity/antigravity.provider.js +3 -2
  183. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +2 -0
  184. package/dist/providers/antigravity/constants/antigravity.constants.js +2 -0
  185. package/dist/providers/claude/claude.adapter.d.ts +11 -1
  186. package/dist/providers/claude/claude.adapter.js +26 -5
  187. package/dist/providers/claude/claude.otel.d.ts +32 -18
  188. package/dist/providers/claude/claude.otel.js +81 -6
  189. package/dist/providers/claude/claude.provider.js +5 -2
  190. package/dist/providers/claude/constants/claude.constants.d.ts +2 -0
  191. package/dist/providers/claude/constants/claude.constants.js +2 -0
  192. package/dist/providers/claude/constants/claude.otel.constants.d.ts +4 -0
  193. package/dist/providers/claude/constants/claude.otel.constants.js +8 -0
  194. package/dist/providers/codex/codex.adapter.d.ts +15 -1
  195. package/dist/providers/codex/codex.adapter.js +29 -5
  196. package/dist/providers/codex/codex.otel.d.ts +36 -3
  197. package/dist/providers/codex/codex.otel.js +199 -32
  198. package/dist/providers/codex/codex.provider.js +5 -2
  199. package/dist/providers/codex/constants/codex.constants.d.ts +2 -0
  200. package/dist/providers/codex/constants/codex.constants.js +16 -0
  201. package/dist/providers/codex/constants/codex.otel.constants.d.ts +10 -0
  202. package/dist/providers/codex/constants/codex.otel.constants.js +10 -0
  203. package/dist/providers/constants/provider.constants.d.ts +8 -3
  204. package/dist/providers/constants/provider.constants.js +8 -3
  205. package/dist/providers/cursor/constants/cursor.constants.d.ts +9 -0
  206. package/dist/providers/cursor/constants/cursor.constants.js +9 -0
  207. package/dist/providers/cursor/cursor.adapter.d.ts +33 -1
  208. package/dist/providers/cursor/cursor.adapter.js +129 -4
  209. package/dist/providers/cursor/cursor.detect.d.ts +0 -7
  210. package/dist/providers/cursor/cursor.detect.js +1 -1
  211. package/dist/providers/cursor/cursor.provider.js +5 -2
  212. package/dist/providers/gemini/constants/gemini.constants.d.ts +9 -0
  213. package/dist/providers/gemini/constants/gemini.constants.js +9 -0
  214. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +9 -1
  215. package/dist/providers/gemini/constants/gemini.otel.constants.js +9 -0
  216. package/dist/providers/gemini/gemini.adapter.d.ts +14 -1
  217. package/dist/providers/gemini/gemini.adapter.js +25 -5
  218. package/dist/providers/gemini/gemini.detect.d.ts +0 -7
  219. package/dist/providers/gemini/gemini.detect.js +1 -1
  220. package/dist/providers/gemini/gemini.otel.d.ts +30 -21
  221. package/dist/providers/gemini/gemini.otel.js +166 -22
  222. package/dist/providers/gemini/gemini.provider.js +2 -1
  223. package/dist/providers/index.d.ts +1 -1
  224. package/dist/providers/index.js +1 -1
  225. package/dist/providers/loaders.d.ts +10 -0
  226. package/dist/providers/loaders.js +40 -0
  227. package/dist/providers/provider.d.ts +11 -0
  228. package/dist/providers/provider.js +1 -1
  229. package/dist/providers/registry.d.ts +11 -8
  230. package/dist/providers/registry.js +11 -15
  231. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  232. package/dist/providers/shared/bearer-rewrite.js +46 -0
  233. package/dist/providers/shared/constants/hook-refusal.constants.d.ts +7 -0
  234. package/dist/providers/shared/constants/hook-refusal.constants.js +7 -0
  235. package/dist/providers/shared/constants/shell-directories.constants.d.ts +30 -0
  236. package/dist/providers/shared/constants/shell-directories.constants.js +39 -0
  237. package/dist/providers/shared/constants/tooling.constants.d.ts +24 -2
  238. package/dist/providers/shared/constants/tooling.constants.js +25 -3
  239. package/dist/providers/shared/event-builder.d.ts +12 -14
  240. package/dist/providers/shared/event-builder.js +20 -14
  241. package/dist/providers/shared/exporter-allowlist.d.ts +20 -0
  242. package/dist/providers/shared/exporter-allowlist.js +49 -0
  243. package/dist/providers/shared/hook-config.d.ts +2 -21
  244. package/dist/providers/shared/hook-config.js +5 -4
  245. package/dist/providers/shared/hook-refusal.d.ts +12 -0
  246. package/dist/providers/shared/hook-refusal.js +17 -1
  247. package/dist/providers/shared/install-record.d.ts +12 -2
  248. package/dist/providers/shared/install-record.js +5 -2
  249. package/dist/providers/shared/shell-directories.d.ts +24 -0
  250. package/dist/providers/shared/shell-directories.js +90 -0
  251. package/dist/providers/shared/tooling.d.ts +40 -1
  252. package/dist/providers/shared/tooling.js +70 -1
  253. package/dist/providers/shared/types/adapter.types.d.ts +1 -2
  254. package/dist/providers/types/provider.types.d.ts +81 -1
  255. package/dist/snapshot/constants/snapshot.constants.d.ts +32 -0
  256. package/dist/snapshot/constants/snapshot.constants.js +33 -0
  257. package/dist/snapshot/snapshot-event.js +52 -11
  258. package/dist/snapshot/snapshot-pipeline.js +1 -1
  259. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  260. package/dist/storage/atomic-file.d.ts +21 -0
  261. package/dist/storage/atomic-file.js +20 -1
  262. package/dist/storage/constants/storage.constants.d.ts +19 -0
  263. package/dist/storage/constants/storage.constants.js +19 -0
  264. package/dist/storage/disabled.d.ts +13 -0
  265. package/dist/storage/disabled.js +24 -0
  266. package/dist/storage/index.d.ts +2 -0
  267. package/dist/storage/index.js +2 -0
  268. package/dist/storage/paths.js +3 -2
  269. package/dist/storage/schemas/storage.schema.d.ts +72 -0
  270. package/dist/storage/schemas/storage.schema.js +6 -0
  271. package/dist/storage/sweep-marker.d.ts +19 -0
  272. package/dist/storage/sweep-marker.js +55 -0
  273. package/dist/storage/types/storage.types.d.ts +2 -0
  274. package/dist/storage/uninstalled.d.ts +58 -0
  275. package/dist/storage/uninstalled.js +107 -0
  276. package/dist/transport/auth-block.d.ts +66 -0
  277. package/dist/transport/auth-block.js +129 -0
  278. package/dist/transport/constants/transport.constants.d.ts +82 -3
  279. package/dist/transport/constants/transport.constants.js +83 -4
  280. package/dist/transport/cooldown.js +8 -1
  281. package/dist/transport/delivery.d.ts +14 -6
  282. package/dist/transport/delivery.js +80 -55
  283. package/dist/transport/http-transport.d.ts +1 -0
  284. package/dist/transport/http-transport.js +52 -10
  285. package/dist/transport/index.d.ts +6 -3
  286. package/dist/transport/index.js +3 -0
  287. package/dist/transport/queue-partition.d.ts +91 -0
  288. package/dist/transport/queue-partition.js +143 -0
  289. package/dist/transport/queue.d.ts +99 -20
  290. package/dist/transport/queue.js +210 -69
  291. package/dist/transport/response-body.d.ts +25 -0
  292. package/dist/transport/response-body.js +64 -0
  293. package/dist/transport/send.d.ts +11 -0
  294. package/dist/transport/send.js +17 -0
  295. package/dist/transport/types/delivery-flow.types.d.ts +19 -0
  296. package/dist/transport/types/delivery-flow.types.js +1 -0
  297. package/dist/transport/types/transport.types.d.ts +45 -0
  298. package/dist/turns/claude-transcript.d.ts +19 -1
  299. package/dist/turns/claude-transcript.js +46 -1
  300. package/dist/turns/codex-originator.d.ts +11 -0
  301. package/dist/turns/codex-originator.js +31 -0
  302. package/dist/turns/codex-transcript.d.ts +30 -0
  303. package/dist/turns/codex-transcript.js +88 -0
  304. package/dist/turns/constants/turns.constants.d.ts +141 -5
  305. package/dist/turns/constants/turns.constants.js +155 -5
  306. package/dist/turns/file-identity.d.ts +27 -0
  307. package/dist/turns/file-identity.js +48 -0
  308. package/dist/turns/gemini-transcript.d.ts +30 -0
  309. package/dist/turns/gemini-transcript.js +96 -0
  310. package/dist/turns/index.d.ts +3 -3
  311. package/dist/turns/index.js +1 -1
  312. package/dist/turns/inherited-checkout.d.ts +54 -0
  313. package/dist/turns/inherited-checkout.js +155 -0
  314. package/dist/turns/native-session-titles.d.ts +26 -0
  315. package/dist/turns/native-session-titles.js +102 -0
  316. package/dist/turns/transcript.d.ts +3 -2
  317. package/dist/turns/transcript.js +5 -1
  318. package/dist/turns/turn-state.d.ts +224 -3
  319. package/dist/turns/turn-state.js +456 -21
  320. package/dist/turns/turn-summary.d.ts +1 -14
  321. package/dist/turns/turn-summary.js +87 -51
  322. package/dist/turns/turn-tracker.d.ts +21 -2
  323. package/dist/turns/turn-tracker.js +379 -56
  324. package/dist/turns/types/transcript.types.d.ts +5 -0
  325. package/dist/turns/types/turn-state.types.d.ts +116 -5
  326. package/dist/turns/types/turn-summary.types.d.ts +64 -14
  327. package/dist/turns/types/turn-tracker.types.d.ts +27 -1
  328. package/dist/turns/work-checkout.d.ts +67 -0
  329. package/dist/turns/work-checkout.js +700 -0
  330. package/dist/untraced/constants/untraced.constants.d.ts +31 -0
  331. package/dist/untraced/constants/untraced.constants.js +63 -0
  332. package/dist/untraced/untraced.d.ts +35 -0
  333. package/dist/untraced/untraced.js +105 -0
  334. package/dist/update/constants/update.constants.d.ts +18 -0
  335. package/dist/update/constants/update.constants.js +20 -0
  336. package/dist/update/update-check.d.ts +52 -0
  337. package/dist/update/update-check.js +113 -0
  338. package/docs/AUDIT_PROMPT.md +129 -0
  339. package/docs/DATA_HANDLING.md +655 -0
  340. package/docs/ENTERPRISE_DEPLOYMENT.md +194 -0
  341. package/docs/PERFORMANCE.md +81 -0
  342. package/package.json +14 -4
  343. package/dist/enrollment/enrollment-provider.d.ts +0 -5
  344. package/dist/enrollment/manual-enrollment.d.ts +0 -32
  345. package/dist/enrollment/manual-enrollment.js +0 -72
  346. package/example/README.md +0 -43
  347. package/example/server.mjs +0 -240
  348. /package/dist/{enrollment/enrollment-provider.js → config/types/destination.types.js} +0 -0
package/dist/cli/setup.js CHANGED
@@ -1,36 +1,74 @@
1
- import process from 'node:process';
2
- import readline from 'node:readline/promises';
3
- import { defaultConfig, enabledSignalNames, eventsUrl, parseOtelSignals } from '../config/config.js';
4
- import { ensureInstallationId, saveConfig } from '../config/config-store.js';
5
- import { collectGitContext, developerIdentity } from '../git/git-context.js';
6
- import { ManualEnrollmentProvider } from '../enrollment/manual-enrollment.js';
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { text } from 'node:stream/consumers';
5
+ import { defaultConfig, enabledSignalNames, eventsUrl, parseOtelSignals, sharesOtlpCollector } from '../config/config.js';
6
+ import { ensureInstallationId, loadConfig, storedRetiredCapture, updateConfig, withStoredDevices } from '../config/config-store.js';
7
+ import { CONFIG_LOCK_WAIT_MS, CONTENT_CAPTURE_KEYS, DEFAULT_ENDPOINT, ROOT_URL_FIELDS, URL_FIELDS } from '../config/constants/config.constants.js';
8
+ import { deliverableOrigin, needsTrust } from '../config/schemas/config.schema.js';
9
+ import { applyRootOverride, canonicalRoot } from '../config/root-config.js';
10
+ import { transitionDestination } from '../config/destination.js';
11
+ import { asRecord, compact } from '../core/object.js';
12
+ import { CREDENTIALS_DIR_NAME, DEVICE_SOURCE_BATCH_CODE } from '../credentials/constants/credentials.constants.js';
13
+ import { forgetDeviceIfUnused, nativeExporterBearer, revokeDeviceIfUnused } from '../credentials/credentials.js';
14
+ import { awaitingSignIn, credentialId, deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
15
+ import { abandonDevice, migrateInstallKey } from '../credentials/migration.js';
16
+ import { enrollWithCode, signInDevice } from '../credentials/sign-in.js';
17
+ import { identityPaths } from '../transport/queue-partition.js';
18
+ import { clearUninstalled, configScopes, uninstallScope } from '../storage/uninstalled.js';
19
+ import { storeLabel } from '../credentials/secret-store.js';
20
+ import { collectGitContext, developerDisplayName, developerIdentity } from '../git/git-context.js';
21
+ import { resolveEnrollment } from '../enrollment/enrollment.js';
7
22
  import { providers } from '../providers/registry.js';
23
+ import { removeRefusedExporters } from '../providers/shared/exporter-allowlist.js';
8
24
  import { saveInstallState } from '../storage/install-state.js';
9
- import { buildCliContext, buildHookCommand, buildQueue } from './context.js';
10
- import { DEVELOPER_EMAIL_PROMPT, DEVELOPER_IDENTITY_REMEDIES, NO_CONFIG_WRITTEN, NO_DEVELOPER_IDENTITY } from './constants/cli.constants.js';
11
- import { bold, dim, printErrln, println, symbols } from './ui.js';
25
+ import { readJsonFile } from '../storage/json-file.js';
26
+ import { ENROLLMENT_CODE_VAR, MACHINE_SCOPE, TOKEN_VAR } from '../storage/constants/storage.constants.js';
27
+ import { signInOpener } from './open-browser.js';
28
+ import { buildCliContext, buildHookCommand, openIdentityQueue } from './context.js';
29
+ import { DEVELOPER_IDENTITY_REMEDIES, ENROLLMENT_CODE_STDIN, NO_CONFIG_WRITTEN, NO_DEVELOPER_IDENTITY, SETUP_EXCHANGE_TIMEOUT_MS } from './constants/cli.constants.js';
30
+ import { bold, customEndpointOverride, dim, printErrln, println, symbols } from './ui.js';
12
31
  /**
13
32
  * `agentwatch setup` — configure the backend, then register hooks and native
14
33
  * telemetry in every detected agent.
15
34
  *
16
35
  * Ordered so nothing is written until everything that can be validated has
17
- * been: a `--otel` typo, an unparseable existing config or a missing endpoint
18
- * fails the run before the first file is touched.
36
+ * been: a `--otel` typo, an unparseable existing config, a refused endpoint or
37
+ * a missing token fails the run before the first file is touched. No endpoint
38
+ * at all means the production Agent Watch backend.
19
39
  *
20
- * @param options - Environment, flags and the interactive prompt.
40
+ * @param options - Environment and flags.
21
41
  * @returns 0 when every step succeeded, else 1.
22
42
  */
23
43
  export async function runSetup(options) {
24
44
  const context = await buildCliContext(options.env);
25
45
  println(bold('AgentWatch Setup'));
26
46
  println();
47
+ if (context.disabled) {
48
+ println('AgentWatch is disabled. Run agentwatch on before setup; setup does not override the off switch.');
49
+ return 1;
50
+ }
27
51
  if (context.configState === 'invalid') {
28
52
  println(`${symbols.fail} existing config at ${context.paths.configFile} is invalid: ${context.configError}`);
29
53
  println(' fix or delete it, then re-run setup');
30
54
  return 1;
31
55
  }
32
- // A fresh install starts from the real defaults (full capture), not the
33
- // fail-safe metadata-only fallback the hook runtime uses.
56
+ // Named, not fatal. `saveConfig` carries a refused URL over from the raw file
57
+ // rather than writing the parsed `null` back, so this run cannot erase the
58
+ // line the developer wrote or the warning that reports it — and refusing the
59
+ // run instead left the machine with no CLI repair path at all, including
60
+ // `agentwatch setup --endpoint https://…`, which supplies a replacement for
61
+ // the very field it would have been refused over. One tenant's typo also
62
+ // stopped every other tenant's install, which is the blast radius this
63
+ // release removed from `loadConfig`.
64
+ if (context.configWarnings.length > 0) {
65
+ println(`${symbols.warn} existing config at ${context.paths.configFile} holds a URL the edge will not send to:`);
66
+ for (const warning of context.configWarnings)
67
+ println(` ${warning}`);
68
+ println(' it is kept as written; nothing is sent there until it is fixed');
69
+ }
70
+ // A fresh install starts from the schema defaults: metadata on, content off.
71
+ // Turning content capture on is a separate, deliberate edit to the config.
34
72
  const baseConfig = context.configState === 'missing' ? defaultConfig() : context.config;
35
73
  const otel = resolveOtel(baseConfig, options.otel);
36
74
  if (!otel) {
@@ -44,37 +82,391 @@ export async function runSetup(options) {
44
82
  println('No supported agents found. Install Claude Code or Codex and re-run `agentwatch setup`.');
45
83
  return 1;
46
84
  }
47
- const ask = interactivePrompt(options);
48
- const enrolled = await enroll(options, baseConfig, ask);
85
+ const resolved = await resolveRoot(options, baseConfig);
86
+ if ('error' in resolved) {
87
+ println(`${symbols.fail} ${resolved.error}`);
88
+ return 1;
89
+ }
90
+ const rootPath = resolved.root;
91
+ // Re-running a root keeps its chosen backend. Only a missing base inherits;
92
+ // a refused one requires repair, and the machine token is never inherited.
93
+ const existingRoot = rootPath === undefined ? undefined : baseConfig.roots?.[rootPath];
94
+ const inherited = rootPath === undefined ? baseConfig : { endpoint: existingRoot?.endpoint === undefined ? baseConfig.endpoint : existingRoot.endpoint };
95
+ const heldDevice = rootPath === undefined ? baseConfig.device : existingRoot?.device;
96
+ if (options.deferSignIn === true && (options.setupUrl === undefined || rootPath !== undefined)) {
97
+ println(`${symbols.fail} --defer-sign-in takes the organization enrollment URL and configures the machine, not a project root; nothing was written`);
98
+ return 1;
99
+ }
100
+ const enrolled = enroll({ ...options, setupUrl: options.setupUrl ?? pendingSignInUrl(options, baseConfig, rootPath) }, inherited, baseConfig.customEndpoints);
49
101
  if ('error' in enrolled) {
50
102
  println(`${symbols.fail} ${enrolled.error}`);
51
103
  return 1;
52
104
  }
53
- const developerEmail = await resolveDeveloperEmail(options, baseConfig, ask);
54
- if (!developerEmail) {
105
+ const code = await readEnrollmentCode(options, enrolled.signIn !== undefined);
106
+ if ('error' in code) {
107
+ println(`${symbols.fail} ${code.error}`);
108
+ return 1;
109
+ }
110
+ // The same code still exported on a re-run (an MDM re-push) is spent: keep the device it enrolled.
111
+ const heldHere = heldDevice !== undefined && heldDevice.endpoint === enrolled.endpoint;
112
+ const spent = code.code !== undefined && heldHere && heldDevice.codeId === credentialId(code.code);
113
+ const redeem = spent ? undefined : code.code;
114
+ // A code enrolls a machine with no device for this backend now, so there is no sign-in
115
+ // left to defer. A device already held for it stays, as on any deferred re-run.
116
+ const deferred = options.deferSignIn === true && (code.code === undefined || heldHere);
117
+ if (options.deferSignIn === true && !deferred)
118
+ println(`${symbols.warn} an enrollment code is redeemed now; --defer-sign-in is ignored`);
119
+ if (deferred && redeem !== undefined)
120
+ println(`${symbols.warn} this machine already holds a device; the enrollment code was not redeemed (uninstall first to enroll with it)`);
121
+ if (rootPath !== undefined && !enrolled.token && !enrolled.signIn && !heldDevice) {
122
+ println(`${symbols.fail} a project root needs its own token: pass --token or $${TOKEN_VAR}, the machine token is not inherited`);
123
+ return 1;
124
+ }
125
+ // Without a prompt, a missing token would otherwise write an install that
126
+ // authenticates against nothing while reporting success.
127
+ if (!enrolled.token && !enrolled.signIn && !heldDevice) {
128
+ println(`${symbols.fail} no token: pass --token or $${TOKEN_VAR}`);
129
+ return 1;
130
+ }
131
+ const installationId = baseConfig.installationId ?? crypto.randomUUID();
132
+ const developerEmail = await resolveDeveloperEmail(options, baseConfig);
133
+ // A sign-in or a code names the developer itself (checked once it has), and a deferred install names nobody yet.
134
+ if (!developerEmail && !enrolled.signIn) {
135
+ reportMissingIdentity();
136
+ return 1;
137
+ }
138
+ // Absent is a real answer and must stay absent: writing an empty name would
139
+ // hand the platform a value to store, and the backend coalesces — it keeps the
140
+ // name it already has only for as long as nobody sends a worse one.
141
+ const developerName = await resolveDeveloperName(options, baseConfig);
142
+ if (spent)
143
+ println(`${symbols.ok} already enrolled with this enrollment code; it was not redeemed again`);
144
+ // After every check that can refuse the run, so a developer never signs in
145
+ // for a setup that was going to fail anyway. A spent code signs nobody in.
146
+ // Deferred: no sign-in here. A device its developer already enrolled is kept below.
147
+ const signedIn = enrolled.signIn && !deferred && !spent ? await signIn(options, context, { ...enrolled.signIn, endpoint: enrolled.endpoint, installationId, code: redeem }) : undefined;
148
+ if (signedIn && 'error' in signedIn) {
149
+ println(`${symbols.fail} ${signedIn.error}`);
150
+ return 1;
151
+ }
152
+ // A gateway older than AWT-555 names no approver: still nobody to attribute to.
153
+ // A code names its developer on the platform, and a deferred install names nobody yet.
154
+ if (!signedIn?.developerEmail && !developerEmail && !code.code && !deferred) {
155
+ if (signedIn)
156
+ await abandonSignIn(options, context, signedIn);
55
157
  reportMissingIdentity();
56
158
  return 1;
57
159
  }
58
- const config = ensureInstallationId({
59
- ...baseConfig,
160
+ // A root re-run without --token keeps the key its device was exchanged for:
161
+ // the key stays beside the device to enroll again. A sign-in has no key at all.
162
+ // A deferred re-run keeps a legacy machine's key for the same backend: it keeps sending through the migration window.
163
+ const token = signedIn ? undefined : (enrolled.token ?? (heldDevice ? existingRoot?.token : undefined) ?? (deferred && (baseConfig.endpoint ?? DEFAULT_ENDPOINT) === enrolled.endpoint ? baseConfig.token : undefined));
164
+ // The same key again (an MDM re-push, a re-run) keeps its device; a new key
165
+ // starts a new enrollment, and the old device would otherwise stand beside
166
+ // it as a second identity.
167
+ const device = signedIn?.device ?? deviceFor({ token, device: heldDevice });
168
+ const displaced = device && device === heldDevice ? undefined : heldDevice;
169
+ const identity = {
60
170
  endpoint: enrolled.endpoint,
61
- token: enrolled.token,
62
- developerEmail,
63
- otel,
64
- emit: { ...baseConfig.emit, llmCalls: true }
65
- });
66
- await saveConfig(context.paths, config);
67
- await offerBacklogRetarget(context, baseConfig, config, ask);
68
- println(`${symbols.ok} backend: ${config.endpoint}`);
69
- println(`${symbols.ok} developer: ${developerEmail}`);
171
+ token,
172
+ device,
173
+ // A sign-in's device belongs to whoever approved it, not to this checkout's git email.
174
+ developerEmail: signedIn?.developerEmail ?? developerEmail,
175
+ ...(developerName ? { developerName } : {})
176
+ };
177
+ const stored = rootPath === undefined ? baseConfig : baseConfig.roots?.[rootPath];
178
+ const previous = rootPath === undefined ? baseConfig.endpoint : previousEndpoint(stored, baseConfig);
179
+ const transition = transitionDestination(stored ?? {}, previous, enrolled.endpoint);
180
+ const updated = { ...stored, ...identity, ...transition.routes };
181
+ const withIdentity = rootPath === undefined
182
+ ? { ...baseConfig, ...updated }
183
+ : { ...baseConfig, roots: { ...baseConfig.roots, [rootPath]: compact(updated) } };
184
+ for (const field of transition.cleared) {
185
+ println(`${symbols.warn} cleared ${field} (${stored?.[field]}) for ${rootPath ?? 'machine'}; backend is now ${identity.endpoint}; reconfigure this route if it is still required`);
186
+ }
187
+ const customEndpoints = nextTrustedOrigins(baseConfig.customEndpoints, previous, enrolled.endpoint, options.allowCustomEndpoint === true, withIdentity);
188
+ // Set by an enrollment URL and cleared by any other machine setup, so it never outlives the backend it belongs to.
189
+ const organization = rootPath === undefined ? { organizationId: enrolled.signIn?.organizationId } : {};
190
+ const config = ensureInstallationId({ ...withIdentity, ...organization, ...(signedIn ? { installationId } : {}), customEndpoints, otel, emit: { ...baseConfig.emit, llmCalls: true } });
191
+ await reportContentDowngrade(context, config);
192
+ // Under the config lock and onto the file as it is now: a hook may have
193
+ // exchanged this key while setup was running.
194
+ const written = await updateConfig(context.paths, (loaded) => withStoredDevices(config, loaded.config), { waitMs: CONFIG_LOCK_WAIT_MS, now: options.env.now }).catch(() => 'busy');
195
+ if (written === 'busy') {
196
+ // Whatever stopped the write, nothing names the new device: revoke it here.
197
+ if (signedIn)
198
+ await abandonSignIn(options, context, signedIn);
199
+ println(`${symbols.fail} could not write ${context.paths.configFile} (another agentwatch process may be writing it); re-run setup`);
200
+ return 1;
201
+ }
202
+ const beforeIdentity = rootPath === undefined ? baseConfig : applyRootOverride(baseConfig, rootPath).config;
203
+ const afterIdentity = rootPath === undefined ? config : applyRootOverride(config, rootPath).config;
204
+ if (stored && hasCredential(beforeIdentity)) {
205
+ await reportStrandedBacklog(context, beforeIdentity, afterIdentity, rootPath ?? 'machine');
206
+ }
207
+ if (rootPath !== undefined)
208
+ println(`${symbols.ok} project root: ${rootPath}`);
209
+ println(`${symbols.ok} backend: ${identity.endpoint}`);
210
+ if (customEndpoints.length > 0)
211
+ println(`${symbols.warn} ${customEndpointOverride(customEndpoints)}`);
212
+ if (rootPath !== undefined && !sharesOtlpCollector(config, applyRootOverride(config, rootPath).config)) {
213
+ println(`${symbols.warn} native OTLP cannot use this root's bearer with the machine-wide collector; only hook-path events use the root identity`);
214
+ }
215
+ if (!deferred || developerEmail)
216
+ println(`${symbols.ok} developer: ${developerLabel(developerEmail, signedIn)}`);
217
+ if (developerName)
218
+ println(`${symbols.ok} name: ${developerName}`);
70
219
  println(`${symbols.ok} otel signals: ${enabledSignalNames(otel).join(', ') || 'none'}`);
71
220
  println(dim(` config: ${context.paths.configFile}`));
72
221
  println();
73
- const failures = await installAgents(options, context, config, detected);
222
+ // Setup is the one way back after an uninstall, for the entry it ran for
223
+ // only: a root's setup leaves the machine uninstalled, and the reverse.
224
+ const scope = uninstallScope(rootPath);
225
+ const stillUninstalled = await clearUninstalled(context.paths, scope, configScopes(config.roots));
226
+ // A sign-in's displaced device is switched off on the platform, not only forgotten here:
227
+ // its only local secret goes with it, so nothing could revoke it later.
228
+ if (signedIn && displaced)
229
+ await revokeDeviceIfUnused({ env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn }, displaced);
230
+ await exchangeInstallKey(context, afterIdentity, signedIn ? undefined : displaced, rootPath === undefined ? undefined : scope);
231
+ // After the exchange, so the Codex and Gemini files carry the machine's
232
+ // access token, or the install key while it has no device (AWT-357). From
233
+ // the file: the exchange filed the device there.
234
+ const bearer = await nativeExporterBearer({ env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn }, (await loadConfig(context.paths)).config);
235
+ const failures = await installAgents(options, context, config, detected, bearer);
236
+ // A root with its own credential keeps queueing until its own setup, and
237
+ // `status` only shows it from inside that root.
238
+ if (rootPath === undefined) {
239
+ for (const root of stillUninstalled.filter((marked) => marked !== MACHINE_SCOPE)) {
240
+ println(`${symbols.warn} root ${root} is still uninstalled; run \`agentwatch setup --root ${root}\` to bring it back`);
241
+ }
242
+ }
243
+ if (awaitingSignIn(config))
244
+ println(`${symbols.warn} not signed in: the developer runs \`agentwatch setup\` as themselves to finish; nothing is sent until then`);
74
245
  println(failures === 0 ? `${symbols.ok} setup complete` : `${symbols.warn} setup finished with ${failures} skipped step(s) — see above`);
246
+ println(dim(' restart any agent session already running: it keeps the hooks it started with'));
247
+ if (detected.some(({ provider }) => provider.id === 'codex'))
248
+ println(dim(' Codex: approve the hooks with /hooks; until you do, no hook runs'));
75
249
  println(dim(' run `agentwatch status` anytime, `agentwatch doctor` to diagnose'));
76
250
  return failures === 0 ? 0 : 1;
77
251
  }
252
+ /**
253
+ * Revoke and forget a device whose config write failed: nothing names it, so
254
+ * uninstall could never find it and a re-run would enroll a second one.
255
+ *
256
+ * @param options - Setup options, for the environment and test seams.
257
+ * @param context - Resolved CLI context.
258
+ * @param signedIn - The device just enrolled and its secret.
259
+ * @param signedIn.device - The device that no config names.
260
+ * @param signedIn.deviceSecret - Its secret, in hand so no keychain read is needed.
261
+ */
262
+ async function abandonSignIn(options, context, signedIn) {
263
+ const ctx = { env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn };
264
+ await abandonDevice(ctx, signedIn.device, signedIn.deviceSecret, identityPaths(context.paths, identityOf({ device: signedIn.device })).accessTokenFile);
265
+ }
266
+ /**
267
+ * Who setup says the developer is. After a sign-in that is the approver. A
268
+ * gateway older than AWT-555 does not name it, so the line shows the email this
269
+ * machine stores and sends, and says the platform credits the approver. A code
270
+ * names its developer on the platform, so it may enroll with no email here.
271
+ *
272
+ * @param developerEmail - The flag, config or git email, if any.
273
+ * @param signedIn - This run's sign-in, if any.
274
+ * @returns The text after `developer:`.
275
+ */
276
+ function developerLabel(developerEmail, signedIn) {
277
+ const shown = signedIn?.developerEmail ?? developerEmail;
278
+ if (!shown)
279
+ return 'the identity the enrollment code names (no email on this machine)';
280
+ if (!signedIn)
281
+ return shown;
282
+ if (signedIn.device.source === DEVICE_SOURCE_BATCH_CODE)
283
+ return `${shown} (stored on this machine; the platform credits the identity the enrollment code names)`;
284
+ return signedIn.developerEmail ? `${shown} (signed in)` : `${shown} (stored on this machine; the platform credits the account that approved the sign-in)`;
285
+ }
286
+ /**
287
+ * The admin-issued enrollment code for this run: from `$AGENTWATCH_ENROLLMENT_CODE`,
288
+ * or stdin with `--enrollment-code -`. Never from argv, where `ps` can read it
289
+ * for the life of the process (SPEC R4). Only an enrollment URL redeems one, so
290
+ * a variable left exported after enrolling does not stop a later setup.
291
+ *
292
+ * @param options - Setup options: the flag, the environment and the stdin seam.
293
+ * @param withUrl - This run was given an enrollment URL.
294
+ * @returns The code, none, or why the run is refused.
295
+ */
296
+ async function readEnrollmentCode(options, withUrl) {
297
+ const flag = options.enrollmentCode;
298
+ if (flag !== undefined && flag !== ENROLLMENT_CODE_STDIN) {
299
+ return { error: `an enrollment code goes in $${ENROLLMENT_CODE_VAR} or on stdin with --enrollment-code -, never on the command line, where other users can read it; nothing was written. If that was a code, ask your admin for a new one` };
300
+ }
301
+ if (flag !== undefined && !withUrl)
302
+ return { error: 'an enrollment code is redeemed with the enrollment URL: agentwatch setup <backend>?organization=<id>; nothing was written' };
303
+ if (!withUrl)
304
+ return {};
305
+ // `||`, as for the token: an exported-but-empty variable is one nobody set.
306
+ if (flag === undefined)
307
+ return { code: options.env.vars[ENROLLMENT_CODE_VAR]?.trim() || undefined };
308
+ const piped = (await (options.readStdin ?? readPipedStdin)()).trim();
309
+ return piped ? { code: piped } : { error: 'no enrollment code on stdin (pipe it in, a terminal is not read); nothing was written' };
310
+ }
311
+ /**
312
+ * Stdin for `--enrollment-code -`, only when it is a pipe: a terminal would wait
313
+ * for an end of input nobody knows to type.
314
+ *
315
+ * @returns The piped text, or empty for a terminal or a failed read.
316
+ */
317
+ async function readPipedStdin() {
318
+ // A broken pipe reads as no code, refused like an empty one.
319
+ return process.stdin.isTTY ? '' : text(process.stdin).catch(() => '');
320
+ }
321
+ /**
322
+ * Enroll with the admin-issued code when there is one, else through the
323
+ * browser, and say where the credential went.
324
+ *
325
+ * @param options - Setup options, for the environment and test seams.
326
+ * @param context - Resolved CLI context.
327
+ * @param target - Backend, organization, the installation the credential binds to, and the code.
328
+ * @param target.endpoint - The backend to sign in with.
329
+ * @param target.organizationId - The organization's public id.
330
+ * @param target.installationId - The installation the credential is bound to.
331
+ * @param target.code - The admin-issued code; the browser sign-in runs without one.
332
+ * @returns The device, or the message to show.
333
+ */
334
+ async function signIn(options, context, target) {
335
+ const ctx = { env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn };
336
+ if (target.code) {
337
+ const redeemed = await enrollWithCode(ctx, { endpoint: target.endpoint, code: target.code, installationId: target.installationId, name: os.hostname() });
338
+ if (!('error' in redeemed))
339
+ println(`${symbols.ok} enrolled with an admin-issued code; device credential kept in ${storeLabel(redeemed.device.store)}`);
340
+ return redeemed;
341
+ }
342
+ const open = signInOpener(options, Boolean(process.stdout.isTTY));
343
+ const result = await signInDevice(ctx, { ...target, name: os.hostname(), print: println, open, sleep: options.sleep });
344
+ if ('error' in result)
345
+ return result;
346
+ println(`${symbols.ok} signed in; device credential kept in ${storeLabel(result.device.store)}`);
347
+ return result;
348
+ }
349
+ /**
350
+ * The origins this machine trusts after this run.
351
+ *
352
+ * The flag adds exactly the origin this run named, and only when the allowlist
353
+ * would refuse it: never another refused URL already in the file, and nothing
354
+ * for an Agent Watch host or loopback. The origin this entry was sending to
355
+ * before goes when nothing in the new config sends there any more, so moving a
356
+ * machine back to an Agent Watch host leaves no stale trust behind. Every other
357
+ * trusted origin stays, so a `--root` run cannot strand the machine's backend.
358
+ *
359
+ * @param current - The machine's trusted origins before this run.
360
+ * @param previous - The endpoint the entry being set up used before.
361
+ * @param endpoint - The endpoint this run enrolled.
362
+ * @param allow - `--allow-custom-endpoint` was passed.
363
+ * @param next - The config this run is about to write.
364
+ * @returns The trusted origins to write.
365
+ */
366
+ function nextTrustedOrigins(current, previous, endpoint, allow, next) {
367
+ const stale = typeof previous === 'string' ? deliverableOrigin(previous) : undefined;
368
+ const referenced = referencedOrigins(next);
369
+ const kept = current.filter((origin) => origin !== stale || referenced.has(origin));
370
+ const added = allow && needsTrust(endpoint) ? deliverableOrigin(endpoint) : undefined;
371
+ return added === undefined || kept.includes(added) ? kept : [...kept, added];
372
+ }
373
+ /**
374
+ * The origin of every backend URL a config sends to, machine and roots.
375
+ *
376
+ * @param config - The config.
377
+ * @returns The origins.
378
+ */
379
+ function referencedOrigins(config) {
380
+ const values = URL_FIELDS.map((field) => config[field]);
381
+ for (const root of Object.values(config.roots ?? {})) {
382
+ values.push(...ROOT_URL_FIELDS.map((field) => root[field]));
383
+ }
384
+ return new Set(values.map((value) => (typeof value === 'string' ? deliverableOrigin(value) : undefined)).filter((origin) => origin !== undefined));
385
+ }
386
+ /**
387
+ * The destination the entry was sending to before this run.
388
+ *
389
+ * An entry that names no `endpoint` of its own was sending to the machine's, so
390
+ * a run that changes nothing must not read as a reroute. A *refused* one is not
391
+ * converted: this file's own rule is that a refusal is never the same
392
+ * destination as the machine's, and `??` would have said the opposite —
393
+ * carrying the previous engagement's live ingest onto a new token, which is the
394
+ * misroute the carry list exists to stop.
395
+ *
396
+ * @param stored - The entry as it stands, absent for a root being created.
397
+ * @param baseConfig - Config this run starts from.
398
+ * @returns The previous destination, or undefined when there is no entry.
399
+ */
400
+ function previousEndpoint(stored, baseConfig) {
401
+ if (stored === undefined)
402
+ return undefined;
403
+ return stored.endpoint === undefined ? baseConfig.endpoint : stored.endpoint;
404
+ }
405
+ /**
406
+ * The project root this run files an identity under, when `--root` was given.
407
+ *
408
+ * A root is a second identity on top of the machine's own, never a substitute
409
+ * for it: agents export native OTLP to one machine-wide endpoint with one
410
+ * bearer, so without a machine identity every hook outside the root would send
411
+ * unauthenticated and the native ledger would belong to nobody. `--otel` is
412
+ * refused for the same reason — the signal selection reconfigures every agent
413
+ * on the machine, which is not one tenant's decision to make.
414
+ *
415
+ * The path is the real one so it matches the cwd an agent reports, and it has
416
+ * to exist: a typo here would file a tenant under a directory nothing ever runs
417
+ * in.
418
+ *
419
+ * @param options - Flags and environment.
420
+ * @param baseConfig - Config the run starts from.
421
+ * @returns The existing matching key or a new canonical root, or the refusal.
422
+ */
423
+ async function resolveRoot(options, baseConfig) {
424
+ if (options.root === undefined)
425
+ return {};
426
+ if (!hasCredential(baseConfig))
427
+ return { error: 'set up the machine identity first (agentwatch setup without --root); a project root is an addition to it' };
428
+ if (options.otel !== undefined)
429
+ return { error: 'native OTLP signals are machine-wide; run setup without --root to change them' };
430
+ try {
431
+ const root = await fs.realpath(path.resolve(options.env.cwd, options.root));
432
+ const existing = Object.keys(baseConfig.roots ?? {}).filter((key) => path.isAbsolute(key) && canonicalRoot(key) === root);
433
+ if (existing.length > 1)
434
+ return { error: `multiple configured root keys resolve to ${root}; consolidate them before setup` };
435
+ return { root: existing[0] ?? root };
436
+ }
437
+ catch {
438
+ return { error: `project root does not exist: ${options.root}` };
439
+ }
440
+ }
441
+ /**
442
+ * Name the content flags this machine has set but cannot use.
443
+ *
444
+ * Retired `prompts` / `responses` flags come first: they collected nothing since
445
+ * this release, and the save that follows removes them, so this is said once.
446
+ *
447
+ * The consent gate runs on load, so a file whose tool flags say `true` without
448
+ * the global marker is metadata-only in memory while still reading as opted-in
449
+ * on disk. Those flags survive the write, so that warning is not about losing
450
+ * them — it is the answer to "I set `promptText: true`, why is nothing arriving".
451
+ *
452
+ * @param context - Resolved paths and the gated config setup started from.
453
+ * @param config - The config about to be saved.
454
+ */
455
+ async function reportContentDowngrade(context, config) {
456
+ const retired = await storedRetiredCapture(context.paths);
457
+ if (retired.length > 0) {
458
+ println(`${symbols.warn} removing capture ${retired.join(', ')} from the config: they collect nothing (prompt text is capture.promptText, response text is never collected)`);
459
+ }
460
+ if (config.contentCaptureConsent)
461
+ return;
462
+ const read = await readJsonFile(context.paths.configFile);
463
+ const stored = read.state === 'ok' ? asRecord(asRecord(read.value)?.['capture']) : undefined;
464
+ const inert = CONTENT_CAPTURE_KEYS.filter((key) => stored?.[key] === true && config.capture[key] === false);
465
+ if (inert.length === 0)
466
+ return;
467
+ println(`${symbols.warn} content capture ${inert.join(', ')} is set but inert: global contentCaptureConsent is not true`);
468
+ println(dim(' the flags are kept as written; add contentCaptureConsent to ~/.agentwatch/config.json to make them take effect'));
469
+ }
78
470
  /**
79
471
  * The OTLP signal selection for this run.
80
472
  *
@@ -118,26 +510,92 @@ async function reportDetection(options) {
118
510
  return results.filter(({ detection }) => detection.detected);
119
511
  }
120
512
  /**
121
- * Acquire the backend endpoint and token.
513
+ * The enrollment URL a plain `agentwatch setup` resumes: the organization an
514
+ * MDM install was configured for, while it still holds no credential. Only
515
+ * when the run names no other backend or key, so those keep their meaning.
122
516
  *
123
- * @param options - Flags and the interactive prompt.
517
+ * @param options - Flags and environment.
124
518
  * @param baseConfig - Config the run starts from.
125
- * @param ask - The prompt, when the run is interactive.
519
+ * @param rootPath - The root this run is for, absent for the machine.
520
+ * @returns The URL to sign in with, or undefined.
521
+ */
522
+ function pendingSignInUrl(options, baseConfig, rootPath) {
523
+ if (rootPath !== undefined || options.endpoint || options.token || options.env.vars[TOKEN_VAR]?.trim())
524
+ return undefined;
525
+ if (!awaitingSignIn(baseConfig) || typeof baseConfig.endpoint !== 'string')
526
+ return undefined;
527
+ return `${baseConfig.endpoint}?organization=${baseConfig.organizationId}`;
528
+ }
529
+ /**
530
+ * Acquire the backend endpoint and token.
531
+ *
532
+ * An origin this machine already trusts needs no flag, so an MDM policy can
533
+ * re-run the same line; any other origin outside the allowlist needs the flag
534
+ * on this run, so a forged setup line cannot ride on trust granted to another
535
+ * backend.
536
+ *
537
+ * @param options - Flags.
538
+ * @param inherited - What this run may fall back to when a flag is absent.
539
+ * @param trusted - The origins this machine already trusts.
126
540
  * @returns The enrollment result, or the message to show.
127
541
  */
128
- async function enroll(options, baseConfig, ask) {
542
+ function enroll(options, inherited, trusted) {
543
+ // A *refused* stored endpoint (`null`, a URL the edge will not talk to) is
544
+ // never replaced by the default: the token beside it belongs to that backend,
545
+ // and defaulting would hand it to ours.
546
+ if (options.setupUrl === undefined && options.endpoint === undefined && inherited.endpoint === null) {
547
+ return { error: 'the configured endpoint is refused; nothing was written. Re-run setup with --endpoint <url>' };
548
+ }
129
549
  try {
130
- return await new ManualEnrollmentProvider().enroll({
550
+ return resolveEnrollment({
131
551
  setupUrl: options.setupUrl,
132
- endpoint: options.endpoint ?? baseConfig.endpoint,
133
- token: options.token ?? baseConfig.token,
134
- ask
552
+ allowCustomEndpoint: options.allowCustomEndpoint === true,
553
+ trustedOrigins: trusted,
554
+ // An enrollment URL names its own backend: only an explicit flag may clash with it.
555
+ endpoint: options.setupUrl ? options.endpoint : (options.endpoint ?? inherited.endpoint ?? undefined),
556
+ // Flag, then environment, then what is already stored. An MDM policy runs
557
+ // with no terminal and has to get the token in somehow; `--token` puts it
558
+ // on a command line, where `ps` can read it for the life of the process.
559
+ //
560
+ // `||`, not `??`: an exported-but-empty variable is a variable nobody set,
561
+ // and enrollment treats a defined token as final — so `??` would write an
562
+ // empty token and leave an install that authenticates
563
+ // against nothing while reporting success.
564
+ //
565
+ // Trimmed here, at the one boundary every non-interactive token crosses.
566
+ // A partition is keyed by the token's hash and a bearer is the token
567
+ // verbatim, so `tok\n` is a different exclusive identity from `tok` and a
568
+ // malformed `Authorization` header — and a trailing newline is what a
569
+ // mounted secret file, `read`, and most `.env` loaders hand over.
570
+ // `|| undefined` after it, so whitespace-only stops
571
+ // being a token here rather than at some later `if`.
572
+ token: (options.token || options.env.vars[TOKEN_VAR] || (options.setupUrl ? undefined : inherited.token))?.trim() || undefined
135
573
  });
136
574
  }
137
575
  catch (error) {
138
576
  return { error: error.message };
139
577
  }
140
578
  }
579
+ /**
580
+ * What to call this developer: the flag, then the config, then `git config
581
+ * user.name`.
582
+ *
583
+ * An install whose developer cannot be named is still a working install — the
584
+ * platform falls back to the address.
585
+ *
586
+ * @param options - Setup options, including the flag and injected git runner.
587
+ * @param baseConfig - Config the run starts from.
588
+ * @returns The name, or undefined when nothing knows one.
589
+ */
590
+ export async function resolveDeveloperName(options, baseConfig) {
591
+ const flag = options.developerName?.trim();
592
+ if (flag)
593
+ return flag;
594
+ return developerDisplayName(baseConfig.developerName, options.env.cwd, {
595
+ home: options.env.home,
596
+ run: options.gitRun
597
+ });
598
+ }
141
599
  /**
142
600
  * The developer identity this install will be attributed to.
143
601
  *
@@ -146,24 +604,15 @@ async function enroll(options, baseConfig, ask) {
146
604
  * the gate will later ask the platform about. The flag is the only override,
147
605
  * for a machine whose git identity is someone else's.
148
606
  *
149
- * Nothing is asked when the identity is already known: the prompt exists for
150
- * the machine that has no answer, not to re-confirm one we already trust.
151
- *
152
607
  * @param options - Flags, environment and the git runner override.
153
608
  * @param baseConfig - Config the run starts from.
154
- * @param ask - The prompt, when the run is interactive.
155
609
  * @returns The identity, or undefined when nothing names the developer.
156
610
  */
157
- export async function resolveDeveloperEmail(options, baseConfig, ask) {
611
+ export async function resolveDeveloperEmail(options, baseConfig) {
158
612
  const flag = options.developerEmail?.trim();
159
613
  if (flag)
160
614
  return flag;
161
- const detected = await developerIdentity(baseConfig.developerEmail, options.env.cwd, { home: options.env.home, run: options.gitRun });
162
- if (detected)
163
- return detected;
164
- if (!ask)
165
- return undefined;
166
- return (await ask(DEVELOPER_EMAIL_PROMPT)).trim() || undefined;
615
+ return developerIdentity(baseConfig.developerEmail, options.env.cwd, { home: options.env.home, run: options.gitRun });
167
616
  }
168
617
  /**
169
618
  * Refuse the install, naming both ways to fix it.
@@ -179,36 +628,60 @@ function reportMissingIdentity() {
179
628
  printErrln(` ${NO_CONFIG_WRITTEN}`);
180
629
  }
181
630
  /**
182
- * Offer to re-route a backlog queued for a previous backend.
631
+ * Trade the install key this run configured for a device credential, now.
632
+ *
633
+ * Setup is where someone is watching, so the outcome is said here rather than
634
+ * found later in `status`: which store took the secret, or that the exchange
635
+ * did not happen and the next run retries. A device this run replaced with a
636
+ * new key has its secret removed, so the keychain does not collect orphans,
637
+ * unless another entry (the machine or a root) still names it.
638
+ *
639
+ * @param context - Resolved CLI context.
640
+ * @param identity - The effective config this run configured.
641
+ * @param replaced - The device credential a new install key displaced.
642
+ * @param scope - The root this run configured, absent for the machine.
643
+ */
644
+ async function exchangeInstallKey(context, identity, replaced, scope) {
645
+ const ctx = { env: context.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, ...(scope === undefined ? {} : { scope }) };
646
+ if (replaced)
647
+ await forgetDeviceIfUnused(ctx, replaced);
648
+ if (!identity.token)
649
+ return;
650
+ const device = await migrateInstallKey(ctx, identity, { ignoreBackoff: true });
651
+ if (!device) {
652
+ println(`${symbols.warn} install key not yet exchanged for a device credential; it stays in the config and the next run retries`);
653
+ return;
654
+ }
655
+ if (device.store === 'file') {
656
+ println(`${symbols.warn} device credential stored in ${storeLabel(device.store)}: ${path.join(context.paths.configDir, CREDENTIALS_DIR_NAME)}`);
657
+ return;
658
+ }
659
+ println(`${symbols.ok} install key exchanged for a device credential, kept in ${storeLabel(device.store)}`);
660
+ }
661
+ /**
662
+ * Say what happens to a backlog queued for the previous backend or token.
183
663
  *
184
- * Backlog queued for the previous backend must not silently expire pinned to a
185
- * URL nothing will ever drain — but moving captured content to a *different*
186
- * backend is a routing decision only the user can make, because the previous URL
187
- * may belong to another organization. So: ask, never assume.
664
+ * It stays where it is and expires: moving captured content to a different
665
+ * backend or tenant is a routing decision setup does not make for anyone, and
666
+ * setup never prompts.
188
667
  *
189
668
  * @param context - Resolved CLI context.
190
669
  * @param previousConfig - Config before this run.
191
670
  * @param config - Config this run just wrote.
192
- * @param ask - The prompt, when the run is interactive.
671
+ * @param owner - Machine or selected root whose records are stranded.
193
672
  */
194
- async function offerBacklogRetarget(context, previousConfig, config, ask) {
673
+ async function reportStrandedBacklog(context, previousConfig, config, owner) {
195
674
  const previousUrl = eventsUrl(previousConfig);
196
675
  const configuredUrl = eventsUrl(config);
197
- if (!previousUrl || !configuredUrl || previousUrl === configuredUrl)
676
+ if (!previousUrl || !configuredUrl)
198
677
  return;
199
- const queue = buildQueue({ ...context, config });
678
+ if (previousUrl === configuredUrl && identityOf(previousConfig) === identityOf(config))
679
+ return;
680
+ const queue = openIdentityQueue({ ...context, identityConfig: previousConfig });
200
681
  const stranded = await queue.pendingFor(previousUrl);
201
682
  if (stranded === 0)
202
683
  return;
203
- const answer = ask
204
- ? (await ask(`${stranded} offline event(s) are queued for the previous backend (${previousUrl}). Deliver them to the new backend? [y/N]: `)).trim().toLowerCase()
205
- : '';
206
- if (answer !== 'y' && answer !== 'yes') {
207
- println(`${symbols.warn} keeping ${stranded} offline event(s) pinned to the previous backend; they expire after ${config.delivery.maxEventAgeDays} day(s)`);
208
- return;
209
- }
210
- const retargeted = await queue.retarget(configuredUrl, previousUrl);
211
- println(retargeted ? `${symbols.ok} offline backlog re-routed to the new backend` : `${symbols.warn} queue busy; backlog not re-routed — re-run setup to retry`);
684
+ println(`${symbols.warn} keeping ${stranded} offline event(s) captured under ${owner} under the previous identity; they expire after ${config.delivery.maxEventAgeDays} day(s)`);
212
685
  }
213
686
  /**
214
687
  * Register hooks and native telemetry in every detected agent.
@@ -221,9 +694,10 @@ async function offerBacklogRetarget(context, previousConfig, config, ask) {
221
694
  * @param context - Resolved CLI context.
222
695
  * @param config - The configuration just written.
223
696
  * @param detected - Agents to install into.
697
+ * @param bearer - What native exporters authenticate with; see `SetupContext.bearer`.
224
698
  * @returns How many steps were skipped or failed.
225
699
  */
226
- async function installAgents(options, context, config, detected) {
700
+ async function installAgents(options, context, config, detected, bearer) {
227
701
  let installState = context.installState;
228
702
  let failures = 0;
229
703
  for (const { provider } of detected) {
@@ -233,13 +707,22 @@ async function installAgents(options, context, config, detected) {
233
707
  paths: context.paths,
234
708
  config,
235
709
  hookCommand: (options.hookCommandFor ?? ((id) => buildHookCommand(options.env, id)))(provider.id),
236
- installState
710
+ installState,
711
+ ...(bearer ? { bearer } : {})
237
712
  };
238
713
  const hooks = await provider.installHooks(setupContext);
239
714
  installState = printOutcome(hooks, installState);
240
715
  if (!hooks.ok)
241
716
  failures++;
242
- if (provider.nativeTelemetry && (await provider.nativeTelemetry.supported(options.env))) {
717
+ // No exporter before a sign-in: it would send with no credential at all.
718
+ if (provider.nativeTelemetry && !awaitingSignIn(config) && (await provider.nativeTelemetry.supported(options.env))) {
719
+ // First, so an exporter left pointing at a host this config refuses is
720
+ // gone even when there is no allowed route to write in its place.
721
+ const swept = await removeRefusedExporters({ ...setupContext, installState }, [provider]);
722
+ installState = swept.installState;
723
+ for (const refused of swept.refused)
724
+ println(`${refused.removed ? symbols.warn : symbols.fail} ${refused.message}`);
725
+ failures += swept.refused.filter((refused) => !refused.removed).length;
243
726
  const otel = await provider.nativeTelemetry.configure({ ...setupContext, installState });
244
727
  installState = printOutcome(otel, installState);
245
728
  if (!otel.ok)
@@ -263,36 +746,3 @@ function printOutcome(outcome, current) {
263
746
  }
264
747
  return outcome.installState ?? current;
265
748
  }
266
- /**
267
- * The prompt this run may use, if any.
268
- *
269
- * `--yes` wins over an injected prompt as well as over the terminal: the
270
- * command a developer copies out of the product carries it, and that command
271
- * has to run to completion on a machine where nobody is typing.
272
- *
273
- * @param options - Flags and the injected prompt.
274
- * @returns The prompt, or undefined when the run must not block on input.
275
- */
276
- function interactivePrompt(options) {
277
- if (options.yes)
278
- return undefined;
279
- return options.ask ?? defaultAsk();
280
- }
281
- /**
282
- * The terminal prompt, when there is a terminal.
283
- *
284
- * @returns The prompt, or undefined when stdin is not a TTY.
285
- */
286
- function defaultAsk() {
287
- if (!process.stdin.isTTY)
288
- return undefined;
289
- return async (question) => {
290
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
291
- try {
292
- return await rl.question(question);
293
- }
294
- finally {
295
- rl.close();
296
- }
297
- };
298
- }