@agent-watch-ai/edge 0.2.5 → 0.3.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 (346) hide show
  1. package/CHANGELOG.md +512 -0
  2. package/README.md +217 -96
  3. package/SECURITY.md +69 -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 +50 -4
  9. package/dist/cli/constants/cli.constants.js +54 -5
  10. package/dist/cli/context.d.ts +33 -2
  11. package/dist/cli/context.js +84 -14
  12. package/dist/cli/doctor.js +309 -32
  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 +439 -98
  26. package/dist/cli/status.js +82 -13
  27. package/dist/cli/toggle.d.ts +9 -0
  28. package/dist/cli/toggle.js +113 -0
  29. package/dist/cli/types/cli.types.d.ts +37 -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 +100 -13
  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 +113 -6
  41. package/dist/config/constants/config.constants.js +126 -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 +721 -84
  51. package/dist/config/schemas/config.schema.js +388 -15
  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 +111 -0
  71. package/dist/credentials/constants/credentials.constants.js +112 -0
  72. package/dist/credentials/credential-status.d.ts +14 -0
  73. package/dist/credentials/credential-status.js +34 -0
  74. package/dist/credentials/credentials.d.ts +72 -0
  75. package/dist/credentials/credentials.js +253 -0
  76. package/dist/credentials/device-api.d.ts +64 -0
  77. package/dist/credentials/device-api.js +150 -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 +62 -0
  81. package/dist/credentials/identity.js +90 -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 +18 -0
  93. package/dist/credentials/sign-in.js +86 -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 +195 -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 +62 -16
  104. package/dist/enforcement/enforcement.d.ts +23 -2
  105. package/dist/enforcement/enforcement.js +103 -15
  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 +64 -0
  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 +7 -0
  160. package/dist/pipeline/constants/pipeline.constants.js +7 -0
  161. package/dist/pipeline/hook-pipeline.js +360 -32
  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 +73 -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 +24 -2
  197. package/dist/providers/codex/codex.otel.js +147 -30
  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 +5 -0
  202. package/dist/providers/codex/constants/codex.otel.constants.js +5 -0
  203. package/dist/providers/constants/provider.constants.d.ts +0 -3
  204. package/dist/providers/constants/provider.constants.js +0 -3
  205. package/dist/providers/cursor/constants/cursor.constants.d.ts +7 -0
  206. package/dist/providers/cursor/constants/cursor.constants.js +7 -0
  207. package/dist/providers/cursor/cursor.adapter.d.ts +33 -1
  208. package/dist/providers/cursor/cursor.adapter.js +52 -3
  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 +3 -1
  215. package/dist/providers/gemini/constants/gemini.otel.constants.js +3 -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 +19 -20
  221. package/dist/providers/gemini/gemini.otel.js +121 -17
  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/constants/hook-refusal.constants.d.ts +7 -0
  232. package/dist/providers/shared/constants/hook-refusal.constants.js +7 -0
  233. package/dist/providers/shared/constants/shell-directories.constants.d.ts +30 -0
  234. package/dist/providers/shared/constants/shell-directories.constants.js +39 -0
  235. package/dist/providers/shared/constants/tooling.constants.d.ts +18 -2
  236. package/dist/providers/shared/constants/tooling.constants.js +19 -3
  237. package/dist/providers/shared/event-builder.d.ts +12 -14
  238. package/dist/providers/shared/event-builder.js +20 -14
  239. package/dist/providers/shared/exporter-allowlist.d.ts +20 -0
  240. package/dist/providers/shared/exporter-allowlist.js +49 -0
  241. package/dist/providers/shared/hook-config.d.ts +2 -21
  242. package/dist/providers/shared/hook-config.js +5 -4
  243. package/dist/providers/shared/hook-refusal.d.ts +12 -0
  244. package/dist/providers/shared/hook-refusal.js +17 -1
  245. package/dist/providers/shared/install-record.d.ts +12 -2
  246. package/dist/providers/shared/install-record.js +5 -2
  247. package/dist/providers/shared/shell-directories.d.ts +24 -0
  248. package/dist/providers/shared/shell-directories.js +90 -0
  249. package/dist/providers/shared/tooling.d.ts +12 -1
  250. package/dist/providers/shared/tooling.js +18 -0
  251. package/dist/providers/shared/types/adapter.types.d.ts +1 -2
  252. package/dist/providers/types/provider.types.d.ts +57 -1
  253. package/dist/snapshot/constants/snapshot.constants.d.ts +32 -0
  254. package/dist/snapshot/constants/snapshot.constants.js +33 -0
  255. package/dist/snapshot/snapshot-event.js +52 -11
  256. package/dist/snapshot/snapshot-pipeline.js +1 -1
  257. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  258. package/dist/storage/atomic-file.d.ts +7 -0
  259. package/dist/storage/atomic-file.js +1 -1
  260. package/dist/storage/constants/storage.constants.d.ts +17 -0
  261. package/dist/storage/constants/storage.constants.js +17 -0
  262. package/dist/storage/disabled.d.ts +13 -0
  263. package/dist/storage/disabled.js +24 -0
  264. package/dist/storage/index.d.ts +2 -0
  265. package/dist/storage/index.js +2 -0
  266. package/dist/storage/paths.js +3 -2
  267. package/dist/storage/schemas/storage.schema.d.ts +72 -0
  268. package/dist/storage/schemas/storage.schema.js +6 -0
  269. package/dist/storage/sweep-marker.d.ts +19 -0
  270. package/dist/storage/sweep-marker.js +55 -0
  271. package/dist/storage/types/storage.types.d.ts +2 -0
  272. package/dist/storage/uninstalled.d.ts +58 -0
  273. package/dist/storage/uninstalled.js +107 -0
  274. package/dist/transport/auth-block.d.ts +66 -0
  275. package/dist/transport/auth-block.js +129 -0
  276. package/dist/transport/constants/transport.constants.d.ts +82 -3
  277. package/dist/transport/constants/transport.constants.js +83 -4
  278. package/dist/transport/cooldown.js +8 -1
  279. package/dist/transport/delivery.d.ts +14 -6
  280. package/dist/transport/delivery.js +80 -55
  281. package/dist/transport/http-transport.d.ts +1 -0
  282. package/dist/transport/http-transport.js +52 -10
  283. package/dist/transport/index.d.ts +6 -3
  284. package/dist/transport/index.js +3 -0
  285. package/dist/transport/queue-partition.d.ts +91 -0
  286. package/dist/transport/queue-partition.js +143 -0
  287. package/dist/transport/queue.d.ts +99 -20
  288. package/dist/transport/queue.js +210 -69
  289. package/dist/transport/response-body.d.ts +25 -0
  290. package/dist/transport/response-body.js +64 -0
  291. package/dist/transport/send.d.ts +11 -0
  292. package/dist/transport/send.js +17 -0
  293. package/dist/transport/types/delivery-flow.types.d.ts +19 -0
  294. package/dist/transport/types/delivery-flow.types.js +1 -0
  295. package/dist/transport/types/transport.types.d.ts +45 -0
  296. package/dist/turns/claude-transcript.d.ts +19 -1
  297. package/dist/turns/claude-transcript.js +46 -1
  298. package/dist/turns/codex-originator.d.ts +11 -0
  299. package/dist/turns/codex-originator.js +31 -0
  300. package/dist/turns/codex-transcript.d.ts +30 -0
  301. package/dist/turns/codex-transcript.js +88 -0
  302. package/dist/turns/constants/turns.constants.d.ts +141 -5
  303. package/dist/turns/constants/turns.constants.js +155 -5
  304. package/dist/turns/file-identity.d.ts +27 -0
  305. package/dist/turns/file-identity.js +48 -0
  306. package/dist/turns/gemini-transcript.d.ts +30 -0
  307. package/dist/turns/gemini-transcript.js +96 -0
  308. package/dist/turns/index.d.ts +3 -3
  309. package/dist/turns/index.js +1 -1
  310. package/dist/turns/inherited-checkout.d.ts +54 -0
  311. package/dist/turns/inherited-checkout.js +155 -0
  312. package/dist/turns/native-session-titles.d.ts +26 -0
  313. package/dist/turns/native-session-titles.js +102 -0
  314. package/dist/turns/transcript.d.ts +3 -2
  315. package/dist/turns/transcript.js +5 -1
  316. package/dist/turns/turn-state.d.ts +224 -3
  317. package/dist/turns/turn-state.js +456 -21
  318. package/dist/turns/turn-summary.d.ts +1 -14
  319. package/dist/turns/turn-summary.js +87 -51
  320. package/dist/turns/turn-tracker.d.ts +21 -2
  321. package/dist/turns/turn-tracker.js +379 -56
  322. package/dist/turns/types/transcript.types.d.ts +5 -0
  323. package/dist/turns/types/turn-state.types.d.ts +116 -5
  324. package/dist/turns/types/turn-summary.types.d.ts +64 -14
  325. package/dist/turns/types/turn-tracker.types.d.ts +27 -1
  326. package/dist/turns/work-checkout.d.ts +65 -0
  327. package/dist/turns/work-checkout.js +666 -0
  328. package/dist/untraced/constants/untraced.constants.d.ts +31 -0
  329. package/dist/untraced/constants/untraced.constants.js +63 -0
  330. package/dist/untraced/untraced.d.ts +35 -0
  331. package/dist/untraced/untraced.js +105 -0
  332. package/dist/update/constants/update.constants.d.ts +18 -0
  333. package/dist/update/constants/update.constants.js +20 -0
  334. package/dist/update/update-check.d.ts +52 -0
  335. package/dist/update/update-check.js +113 -0
  336. package/docs/AUDIT_PROMPT.md +129 -0
  337. package/docs/DATA_HANDLING.md +648 -0
  338. package/docs/ENTERPRISE_DEPLOYMENT.md +179 -0
  339. package/docs/PERFORMANCE.md +81 -0
  340. package/package.json +14 -4
  341. package/dist/enrollment/enrollment-provider.d.ts +0 -5
  342. package/dist/enrollment/manual-enrollment.d.ts +0 -32
  343. package/dist/enrollment/manual-enrollment.js +0 -72
  344. package/example/README.md +0 -43
  345. package/example/server.mjs +0 -240
  346. /package/dist/{enrollment/enrollment-provider.js → config/types/destination.types.js} +0 -0
package/dist/cli/setup.js CHANGED
@@ -1,36 +1,73 @@
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 { defaultConfig, enabledSignalNames, eventsUrl, parseOtelSignals, sharesOtlpCollector } from '../config/config.js';
5
+ import { ensureInstallationId, storedRetiredCapture, updateConfig, withStoredDevices } from '../config/config-store.js';
6
+ import { CONFIG_LOCK_WAIT_MS, CONTENT_CAPTURE_KEYS, ROOT_URL_FIELDS, URL_FIELDS } from '../config/constants/config.constants.js';
7
+ import { deliverableOrigin, needsTrust } from '../config/schemas/config.schema.js';
8
+ import { applyRootOverride, canonicalRoot } from '../config/root-config.js';
9
+ import { transitionDestination } from '../config/destination.js';
10
+ import { asRecord, compact } from '../core/object.js';
11
+ import { CREDENTIALS_DIR_NAME } from '../credentials/constants/credentials.constants.js';
12
+ import { forgetDeviceIfUnused, revokeDeviceIfUnused } from '../credentials/credentials.js';
13
+ import { deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
14
+ import { abandonDevice, migrateInstallKey } from '../credentials/migration.js';
15
+ import { signInDevice } from '../credentials/sign-in.js';
16
+ import { identityPaths } from '../transport/queue-partition.js';
17
+ import { clearUninstalled, configScopes, uninstallScope } from '../storage/uninstalled.js';
18
+ import { storeLabel } from '../credentials/secret-store.js';
19
+ import { collectGitContext, developerDisplayName, developerIdentity } from '../git/git-context.js';
20
+ import { resolveEnrollment } from '../enrollment/enrollment.js';
7
21
  import { providers } from '../providers/registry.js';
22
+ import { removeRefusedExporters } from '../providers/shared/exporter-allowlist.js';
8
23
  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';
24
+ import { readJsonFile } from '../storage/json-file.js';
25
+ import { MACHINE_SCOPE, TOKEN_VAR } from '../storage/constants/storage.constants.js';
26
+ import { signInOpener } from './open-browser.js';
27
+ import { buildCliContext, buildHookCommand, openIdentityQueue } from './context.js';
28
+ import { DEVELOPER_IDENTITY_REMEDIES, NO_CONFIG_WRITTEN, NO_DEVELOPER_IDENTITY, SETUP_EXCHANGE_TIMEOUT_MS } from './constants/cli.constants.js';
29
+ import { bold, customEndpointOverride, dim, printErrln, println, symbols } from './ui.js';
12
30
  /**
13
31
  * `agentwatch setup` — configure the backend, then register hooks and native
14
32
  * telemetry in every detected agent.
15
33
  *
16
34
  * 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.
35
+ * been: a `--otel` typo, an unparseable existing config, a refused endpoint or
36
+ * a missing token fails the run before the first file is touched. No endpoint
37
+ * at all means the production Agent Watch backend.
19
38
  *
20
- * @param options - Environment, flags and the interactive prompt.
39
+ * @param options - Environment and flags.
21
40
  * @returns 0 when every step succeeded, else 1.
22
41
  */
23
42
  export async function runSetup(options) {
24
43
  const context = await buildCliContext(options.env);
25
44
  println(bold('AgentWatch Setup'));
26
45
  println();
46
+ if (context.disabled) {
47
+ println('AgentWatch is disabled. Run agentwatch on before setup; setup does not override the off switch.');
48
+ return 1;
49
+ }
27
50
  if (context.configState === 'invalid') {
28
51
  println(`${symbols.fail} existing config at ${context.paths.configFile} is invalid: ${context.configError}`);
29
52
  println(' fix or delete it, then re-run setup');
30
53
  return 1;
31
54
  }
32
- // A fresh install starts from the real defaults (full capture), not the
33
- // fail-safe metadata-only fallback the hook runtime uses.
55
+ // Named, not fatal. `saveConfig` carries a refused URL over from the raw file
56
+ // rather than writing the parsed `null` back, so this run cannot erase the
57
+ // line the developer wrote or the warning that reports it — and refusing the
58
+ // run instead left the machine with no CLI repair path at all, including
59
+ // `agentwatch setup --endpoint https://…`, which supplies a replacement for
60
+ // the very field it would have been refused over. One tenant's typo also
61
+ // stopped every other tenant's install, which is the blast radius this
62
+ // release removed from `loadConfig`.
63
+ if (context.configWarnings.length > 0) {
64
+ println(`${symbols.warn} existing config at ${context.paths.configFile} holds a URL the edge will not send to:`);
65
+ for (const warning of context.configWarnings)
66
+ println(` ${warning}`);
67
+ println(' it is kept as written; nothing is sent there until it is fixed');
68
+ }
69
+ // A fresh install starts from the schema defaults: metadata on, content off.
70
+ // Turning content capture on is a separate, deliberate edit to the config.
34
71
  const baseConfig = context.configState === 'missing' ? defaultConfig() : context.config;
35
72
  const otel = resolveOtel(baseConfig, options.otel);
36
73
  if (!otel) {
@@ -44,37 +81,303 @@ export async function runSetup(options) {
44
81
  println('No supported agents found. Install Claude Code or Codex and re-run `agentwatch setup`.');
45
82
  return 1;
46
83
  }
47
- const ask = interactivePrompt(options);
48
- const enrolled = await enroll(options, baseConfig, ask);
84
+ const resolved = await resolveRoot(options, baseConfig);
85
+ if ('error' in resolved) {
86
+ println(`${symbols.fail} ${resolved.error}`);
87
+ return 1;
88
+ }
89
+ const rootPath = resolved.root;
90
+ // Re-running a root keeps its chosen backend. Only a missing base inherits;
91
+ // a refused one requires repair, and the machine token is never inherited.
92
+ const existingRoot = rootPath === undefined ? undefined : baseConfig.roots?.[rootPath];
93
+ const inherited = rootPath === undefined ? baseConfig : { endpoint: existingRoot?.endpoint === undefined ? baseConfig.endpoint : existingRoot.endpoint };
94
+ const heldDevice = rootPath === undefined ? baseConfig.device : existingRoot?.device;
95
+ const enrolled = enroll(options, inherited, baseConfig.customEndpoints);
49
96
  if ('error' in enrolled) {
50
97
  println(`${symbols.fail} ${enrolled.error}`);
51
98
  return 1;
52
99
  }
53
- const developerEmail = await resolveDeveloperEmail(options, baseConfig, ask);
100
+ if (rootPath !== undefined && !enrolled.token && !enrolled.signIn && !heldDevice) {
101
+ println(`${symbols.fail} a project root needs its own token: pass --token or $${TOKEN_VAR}, the machine token is not inherited`);
102
+ return 1;
103
+ }
104
+ // Without a prompt, a missing token would otherwise write an install that
105
+ // authenticates against nothing while reporting success.
106
+ if (!enrolled.token && !enrolled.signIn && !heldDevice) {
107
+ println(`${symbols.fail} no token: pass --token or $${TOKEN_VAR}`);
108
+ return 1;
109
+ }
110
+ const installationId = baseConfig.installationId ?? crypto.randomUUID();
111
+ const developerEmail = await resolveDeveloperEmail(options, baseConfig);
54
112
  if (!developerEmail) {
55
113
  reportMissingIdentity();
56
114
  return 1;
57
115
  }
58
- const config = ensureInstallationId({
59
- ...baseConfig,
116
+ // Absent is a real answer and must stay absent: writing an empty name would
117
+ // hand the platform a value to store, and the backend coalesces — it keeps the
118
+ // name it already has only for as long as nobody sends a worse one.
119
+ const developerName = await resolveDeveloperName(options, baseConfig);
120
+ // After every check that can refuse the run, so a developer never signs in
121
+ // for a setup that was going to fail anyway.
122
+ const signedIn = enrolled.signIn ? await signIn(options, context, { ...enrolled.signIn, endpoint: enrolled.endpoint, installationId }) : undefined;
123
+ if (signedIn && 'error' in signedIn) {
124
+ println(`${symbols.fail} ${signedIn.error}`);
125
+ return 1;
126
+ }
127
+ // A root re-run without --token keeps the key its device was exchanged for:
128
+ // the key stays beside the device until AWT-357. A sign-in has no key at all.
129
+ const token = signedIn ? undefined : (enrolled.token ?? (heldDevice ? existingRoot?.token : undefined));
130
+ // The same key again (an MDM re-push, a re-run) keeps its device; a new key
131
+ // starts a new enrollment, and the old device would otherwise stand beside
132
+ // it as a second identity.
133
+ const device = signedIn?.device ?? deviceFor({ token, device: heldDevice });
134
+ const displaced = device && device === heldDevice ? undefined : heldDevice;
135
+ const identity = {
60
136
  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}`);
137
+ token,
138
+ device,
139
+ // A sign-in's device belongs to whoever approved it, not to this checkout's git email.
140
+ developerEmail: signedIn?.developerEmail ?? developerEmail,
141
+ ...(developerName ? { developerName } : {})
142
+ };
143
+ const stored = rootPath === undefined ? baseConfig : baseConfig.roots?.[rootPath];
144
+ const previous = rootPath === undefined ? baseConfig.endpoint : previousEndpoint(stored, baseConfig);
145
+ const transition = transitionDestination(stored ?? {}, previous, enrolled.endpoint);
146
+ const updated = { ...stored, ...identity, ...transition.routes };
147
+ const withIdentity = rootPath === undefined
148
+ ? { ...baseConfig, ...updated }
149
+ : { ...baseConfig, roots: { ...baseConfig.roots, [rootPath]: compact(updated) } };
150
+ for (const field of transition.cleared) {
151
+ println(`${symbols.warn} cleared ${field} (${stored?.[field]}) for ${rootPath ?? 'machine'}; backend is now ${identity.endpoint}; reconfigure this route if it is still required`);
152
+ }
153
+ const customEndpoints = nextTrustedOrigins(baseConfig.customEndpoints, previous, enrolled.endpoint, options.allowCustomEndpoint === true, withIdentity);
154
+ const config = ensureInstallationId({ ...withIdentity, ...(signedIn ? { installationId } : {}), customEndpoints, otel, emit: { ...baseConfig.emit, llmCalls: true } });
155
+ await reportContentDowngrade(context, config);
156
+ // Under the config lock and onto the file as it is now: a hook may have
157
+ // exchanged this key while setup was running.
158
+ const written = await updateConfig(context.paths, (loaded) => withStoredDevices(config, loaded.config), { waitMs: CONFIG_LOCK_WAIT_MS, now: options.env.now }).catch(() => 'busy');
159
+ if (written === 'busy') {
160
+ // Whatever stopped the write, nothing names the new device: revoke it here.
161
+ if (signedIn)
162
+ await abandonSignIn(options, context, signedIn);
163
+ println(`${symbols.fail} could not write ${context.paths.configFile} (another agentwatch process may be writing it); re-run setup`);
164
+ return 1;
165
+ }
166
+ const beforeIdentity = rootPath === undefined ? baseConfig : applyRootOverride(baseConfig, rootPath).config;
167
+ const afterIdentity = rootPath === undefined ? config : applyRootOverride(config, rootPath).config;
168
+ if (stored && hasCredential(beforeIdentity)) {
169
+ await reportStrandedBacklog(context, beforeIdentity, afterIdentity, rootPath ?? 'machine');
170
+ }
171
+ if (rootPath !== undefined)
172
+ println(`${symbols.ok} project root: ${rootPath}`);
173
+ println(`${symbols.ok} backend: ${identity.endpoint}`);
174
+ if (customEndpoints.length > 0)
175
+ println(`${symbols.warn} ${customEndpointOverride(customEndpoints)}`);
176
+ if (rootPath !== undefined && !sharesOtlpCollector(config, applyRootOverride(config, rootPath).config)) {
177
+ println(`${symbols.warn} native OTLP cannot use this root's bearer with the machine-wide collector; only hook-path events use the root identity`);
178
+ }
179
+ println(`${symbols.ok} developer: ${developerLabel(developerEmail, signedIn)}`);
180
+ if (developerName)
181
+ println(`${symbols.ok} name: ${developerName}`);
70
182
  println(`${symbols.ok} otel signals: ${enabledSignalNames(otel).join(', ') || 'none'}`);
71
183
  println(dim(` config: ${context.paths.configFile}`));
72
184
  println();
185
+ // After the agents, so the Codex and Gemini files this run writes carry the
186
+ // install key, which keeps working through the migration window (AWT-357
187
+ // moves them to short-lived tokens).
73
188
  const failures = await installAgents(options, context, config, detected);
189
+ // Setup is the one way back after an uninstall, for the entry it ran for
190
+ // only: a root's setup leaves the machine uninstalled, and the reverse.
191
+ const scope = uninstallScope(rootPath);
192
+ const stillUninstalled = await clearUninstalled(context.paths, scope, configScopes(config.roots));
193
+ // A sign-in's displaced device is switched off on the platform, not only forgotten here:
194
+ // its only local secret goes with it, so nothing could revoke it later.
195
+ if (signedIn && displaced)
196
+ await revokeDeviceIfUnused({ env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn }, displaced);
197
+ await exchangeInstallKey(context, afterIdentity, signedIn ? undefined : displaced, rootPath === undefined ? undefined : scope);
198
+ // A root with its own credential keeps queueing until its own setup, and
199
+ // `status` only shows it from inside that root.
200
+ if (rootPath === undefined) {
201
+ for (const root of stillUninstalled.filter((marked) => marked !== MACHINE_SCOPE)) {
202
+ println(`${symbols.warn} root ${root} is still uninstalled; run \`agentwatch setup --root ${root}\` to bring it back`);
203
+ }
204
+ }
74
205
  println(failures === 0 ? `${symbols.ok} setup complete` : `${symbols.warn} setup finished with ${failures} skipped step(s) — see above`);
206
+ println(dim(' restart any agent session already running: it keeps the hooks it started with'));
207
+ if (detected.some(({ provider }) => provider.id === 'codex'))
208
+ println(dim(' Codex: approve the hooks with /hooks; until you do, no hook runs'));
75
209
  println(dim(' run `agentwatch status` anytime, `agentwatch doctor` to diagnose'));
76
210
  return failures === 0 ? 0 : 1;
77
211
  }
212
+ /**
213
+ * Revoke and forget a device whose config write failed: nothing names it, so
214
+ * uninstall could never find it and a re-run would enroll a second one.
215
+ *
216
+ * @param options - Setup options, for the environment and test seams.
217
+ * @param context - Resolved CLI context.
218
+ * @param signedIn - The device just enrolled and its secret.
219
+ * @param signedIn.device - The device that no config names.
220
+ * @param signedIn.deviceSecret - Its secret, in hand so no keychain read is needed.
221
+ */
222
+ async function abandonSignIn(options, context, signedIn) {
223
+ const ctx = { env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn };
224
+ await abandonDevice(ctx, signedIn.device, signedIn.deviceSecret, identityPaths(context.paths, identityOf({ device: signedIn.device })).accessTokenFile);
225
+ }
226
+ /**
227
+ * Who setup says the developer is. After a sign-in that is the approver. A
228
+ * gateway older than AWT-555 does not name it, so the line shows the email this
229
+ * machine stores and sends, and says the platform credits the approver.
230
+ *
231
+ * @param developerEmail - The flag, config or git email.
232
+ * @param signedIn - This run's sign-in, if any.
233
+ * @returns The text after `developer:`.
234
+ */
235
+ function developerLabel(developerEmail, signedIn) {
236
+ if (!signedIn)
237
+ return developerEmail;
238
+ return signedIn.developerEmail ? `${signedIn.developerEmail} (signed in)` : `${developerEmail} (stored on this machine; the platform credits the account that approved the sign-in)`;
239
+ }
240
+ /**
241
+ * Enroll through the browser and say where the credential went.
242
+ *
243
+ * @param options - Setup options, for the environment and test seams.
244
+ * @param context - Resolved CLI context.
245
+ * @param target - Backend, organization and the installation the credential binds to.
246
+ * @param target.endpoint - The backend to sign in with.
247
+ * @param target.organizationId - The organization's public id.
248
+ * @param target.installationId - The installation the credential is bound to.
249
+ * @returns The device, or the message to show.
250
+ */
251
+ async function signIn(options, context, target) {
252
+ const ctx = { env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn };
253
+ const open = signInOpener(options, Boolean(process.stdout.isTTY));
254
+ const result = await signInDevice(ctx, { ...target, name: os.hostname(), print: println, open, sleep: options.sleep });
255
+ if ('error' in result)
256
+ return result;
257
+ println(`${symbols.ok} signed in; device credential kept in ${storeLabel(result.device.store)}`);
258
+ return result;
259
+ }
260
+ /**
261
+ * The origins this machine trusts after this run.
262
+ *
263
+ * The flag adds exactly the origin this run named, and only when the allowlist
264
+ * would refuse it: never another refused URL already in the file, and nothing
265
+ * for an Agent Watch host or loopback. The origin this entry was sending to
266
+ * before goes when nothing in the new config sends there any more, so moving a
267
+ * machine back to an Agent Watch host leaves no stale trust behind. Every other
268
+ * trusted origin stays, so a `--root` run cannot strand the machine's backend.
269
+ *
270
+ * @param current - The machine's trusted origins before this run.
271
+ * @param previous - The endpoint the entry being set up used before.
272
+ * @param endpoint - The endpoint this run enrolled.
273
+ * @param allow - `--allow-custom-endpoint` was passed.
274
+ * @param next - The config this run is about to write.
275
+ * @returns The trusted origins to write.
276
+ */
277
+ function nextTrustedOrigins(current, previous, endpoint, allow, next) {
278
+ const stale = typeof previous === 'string' ? deliverableOrigin(previous) : undefined;
279
+ const referenced = referencedOrigins(next);
280
+ const kept = current.filter((origin) => origin !== stale || referenced.has(origin));
281
+ const added = allow && needsTrust(endpoint) ? deliverableOrigin(endpoint) : undefined;
282
+ return added === undefined || kept.includes(added) ? kept : [...kept, added];
283
+ }
284
+ /**
285
+ * The origin of every backend URL a config sends to, machine and roots.
286
+ *
287
+ * @param config - The config.
288
+ * @returns The origins.
289
+ */
290
+ function referencedOrigins(config) {
291
+ const values = URL_FIELDS.map((field) => config[field]);
292
+ for (const root of Object.values(config.roots ?? {})) {
293
+ values.push(...ROOT_URL_FIELDS.map((field) => root[field]));
294
+ }
295
+ return new Set(values.map((value) => (typeof value === 'string' ? deliverableOrigin(value) : undefined)).filter((origin) => origin !== undefined));
296
+ }
297
+ /**
298
+ * The destination the entry was sending to before this run.
299
+ *
300
+ * An entry that names no `endpoint` of its own was sending to the machine's, so
301
+ * a run that changes nothing must not read as a reroute. A *refused* one is not
302
+ * converted: this file's own rule is that a refusal is never the same
303
+ * destination as the machine's, and `??` would have said the opposite —
304
+ * carrying the previous engagement's live ingest onto a new token, which is the
305
+ * misroute the carry list exists to stop.
306
+ *
307
+ * @param stored - The entry as it stands, absent for a root being created.
308
+ * @param baseConfig - Config this run starts from.
309
+ * @returns The previous destination, or undefined when there is no entry.
310
+ */
311
+ function previousEndpoint(stored, baseConfig) {
312
+ if (stored === undefined)
313
+ return undefined;
314
+ return stored.endpoint === undefined ? baseConfig.endpoint : stored.endpoint;
315
+ }
316
+ /**
317
+ * The project root this run files an identity under, when `--root` was given.
318
+ *
319
+ * A root is a second identity on top of the machine's own, never a substitute
320
+ * for it: agents export native OTLP to one machine-wide endpoint with one
321
+ * bearer, so without a machine identity every hook outside the root would send
322
+ * unauthenticated and the native ledger would belong to nobody. `--otel` is
323
+ * refused for the same reason — the signal selection reconfigures every agent
324
+ * on the machine, which is not one tenant's decision to make.
325
+ *
326
+ * The path is the real one so it matches the cwd an agent reports, and it has
327
+ * to exist: a typo here would file a tenant under a directory nothing ever runs
328
+ * in.
329
+ *
330
+ * @param options - Flags and environment.
331
+ * @param baseConfig - Config the run starts from.
332
+ * @returns The existing matching key or a new canonical root, or the refusal.
333
+ */
334
+ async function resolveRoot(options, baseConfig) {
335
+ if (options.root === undefined)
336
+ return {};
337
+ if (!hasCredential(baseConfig))
338
+ return { error: 'set up the machine identity first (agentwatch setup without --root); a project root is an addition to it' };
339
+ if (options.otel !== undefined)
340
+ return { error: 'native OTLP signals are machine-wide; run setup without --root to change them' };
341
+ try {
342
+ const root = await fs.realpath(path.resolve(options.env.cwd, options.root));
343
+ const existing = Object.keys(baseConfig.roots ?? {}).filter((key) => path.isAbsolute(key) && canonicalRoot(key) === root);
344
+ if (existing.length > 1)
345
+ return { error: `multiple configured root keys resolve to ${root}; consolidate them before setup` };
346
+ return { root: existing[0] ?? root };
347
+ }
348
+ catch {
349
+ return { error: `project root does not exist: ${options.root}` };
350
+ }
351
+ }
352
+ /**
353
+ * Name the content flags this machine has set but cannot use.
354
+ *
355
+ * Retired `prompts` / `responses` flags come first: they collected nothing since
356
+ * this release, and the save that follows removes them, so this is said once.
357
+ *
358
+ * The consent gate runs on load, so a file whose tool flags say `true` without
359
+ * the global marker is metadata-only in memory while still reading as opted-in
360
+ * on disk. Those flags survive the write, so that warning is not about losing
361
+ * them — it is the answer to "I set `promptText: true`, why is nothing arriving".
362
+ *
363
+ * @param context - Resolved paths and the gated config setup started from.
364
+ * @param config - The config about to be saved.
365
+ */
366
+ async function reportContentDowngrade(context, config) {
367
+ const retired = await storedRetiredCapture(context.paths);
368
+ if (retired.length > 0) {
369
+ println(`${symbols.warn} removing capture ${retired.join(', ')} from the config: they collect nothing (prompt text is capture.promptText, response text is never collected)`);
370
+ }
371
+ if (config.contentCaptureConsent)
372
+ return;
373
+ const read = await readJsonFile(context.paths.configFile);
374
+ const stored = read.state === 'ok' ? asRecord(asRecord(read.value)?.['capture']) : undefined;
375
+ const inert = CONTENT_CAPTURE_KEYS.filter((key) => stored?.[key] === true && config.capture[key] === false);
376
+ if (inert.length === 0)
377
+ return;
378
+ println(`${symbols.warn} content capture ${inert.join(', ')} is set but inert: global contentCaptureConsent is not true`);
379
+ println(dim(' the flags are kept as written; add contentCaptureConsent to ~/.agentwatch/config.json to make them take effect'));
380
+ }
78
381
  /**
79
382
  * The OTLP signal selection for this run.
80
383
  *
@@ -120,24 +423,73 @@ async function reportDetection(options) {
120
423
  /**
121
424
  * Acquire the backend endpoint and token.
122
425
  *
123
- * @param options - Flags and the interactive prompt.
124
- * @param baseConfig - Config the run starts from.
125
- * @param ask - The prompt, when the run is interactive.
426
+ * An origin this machine already trusts needs no flag, so an MDM policy can
427
+ * re-run the same line; any other origin outside the allowlist needs the flag
428
+ * on this run, so a forged setup line cannot ride on trust granted to another
429
+ * backend.
430
+ *
431
+ * @param options - Flags.
432
+ * @param inherited - What this run may fall back to when a flag is absent.
433
+ * @param trusted - The origins this machine already trusts.
126
434
  * @returns The enrollment result, or the message to show.
127
435
  */
128
- async function enroll(options, baseConfig, ask) {
436
+ function enroll(options, inherited, trusted) {
437
+ // A *refused* stored endpoint (`null`, a URL the edge will not talk to) is
438
+ // never replaced by the default: the token beside it belongs to that backend,
439
+ // and defaulting would hand it to ours.
440
+ if (options.setupUrl === undefined && options.endpoint === undefined && inherited.endpoint === null) {
441
+ return { error: 'the configured endpoint is refused; nothing was written. Re-run setup with --endpoint <url>' };
442
+ }
129
443
  try {
130
- return await new ManualEnrollmentProvider().enroll({
444
+ return resolveEnrollment({
131
445
  setupUrl: options.setupUrl,
132
- endpoint: options.endpoint ?? baseConfig.endpoint,
133
- token: options.token ?? baseConfig.token,
134
- ask
446
+ allowCustomEndpoint: options.allowCustomEndpoint === true,
447
+ trustedOrigins: trusted,
448
+ // An enrollment URL names its own backend: only an explicit flag may clash with it.
449
+ endpoint: options.setupUrl ? options.endpoint : (options.endpoint ?? inherited.endpoint ?? undefined),
450
+ // Flag, then environment, then what is already stored. An MDM policy runs
451
+ // with no terminal and has to get the token in somehow; `--token` puts it
452
+ // on a command line, where `ps` can read it for the life of the process.
453
+ //
454
+ // `||`, not `??`: an exported-but-empty variable is a variable nobody set,
455
+ // and enrollment treats a defined token as final — so `??` would write an
456
+ // empty token and leave an install that authenticates
457
+ // against nothing while reporting success.
458
+ //
459
+ // Trimmed here, at the one boundary every non-interactive token crosses.
460
+ // A partition is keyed by the token's hash and a bearer is the token
461
+ // verbatim, so `tok\n` is a different exclusive identity from `tok` and a
462
+ // malformed `Authorization` header — and a trailing newline is what a
463
+ // mounted secret file, `read`, and most `.env` loaders hand over.
464
+ // `|| undefined` after it, so whitespace-only stops
465
+ // being a token here rather than at some later `if`.
466
+ token: (options.token || options.env.vars[TOKEN_VAR] || (options.setupUrl ? undefined : inherited.token))?.trim() || undefined
135
467
  });
136
468
  }
137
469
  catch (error) {
138
470
  return { error: error.message };
139
471
  }
140
472
  }
473
+ /**
474
+ * What to call this developer: the flag, then the config, then `git config
475
+ * user.name`.
476
+ *
477
+ * An install whose developer cannot be named is still a working install — the
478
+ * platform falls back to the address.
479
+ *
480
+ * @param options - Setup options, including the flag and injected git runner.
481
+ * @param baseConfig - Config the run starts from.
482
+ * @returns The name, or undefined when nothing knows one.
483
+ */
484
+ export async function resolveDeveloperName(options, baseConfig) {
485
+ const flag = options.developerName?.trim();
486
+ if (flag)
487
+ return flag;
488
+ return developerDisplayName(baseConfig.developerName, options.env.cwd, {
489
+ home: options.env.home,
490
+ run: options.gitRun
491
+ });
492
+ }
141
493
  /**
142
494
  * The developer identity this install will be attributed to.
143
495
  *
@@ -146,24 +498,15 @@ async function enroll(options, baseConfig, ask) {
146
498
  * the gate will later ask the platform about. The flag is the only override,
147
499
  * for a machine whose git identity is someone else's.
148
500
  *
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
501
  * @param options - Flags, environment and the git runner override.
153
502
  * @param baseConfig - Config the run starts from.
154
- * @param ask - The prompt, when the run is interactive.
155
503
  * @returns The identity, or undefined when nothing names the developer.
156
504
  */
157
- export async function resolveDeveloperEmail(options, baseConfig, ask) {
505
+ export async function resolveDeveloperEmail(options, baseConfig) {
158
506
  const flag = options.developerEmail?.trim();
159
507
  if (flag)
160
508
  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;
509
+ return developerIdentity(baseConfig.developerEmail, options.env.cwd, { home: options.env.home, run: options.gitRun });
167
510
  }
168
511
  /**
169
512
  * Refuse the install, naming both ways to fix it.
@@ -179,36 +522,60 @@ function reportMissingIdentity() {
179
522
  printErrln(` ${NO_CONFIG_WRITTEN}`);
180
523
  }
181
524
  /**
182
- * Offer to re-route a backlog queued for a previous backend.
525
+ * Trade the install key this run configured for a device credential, now.
183
526
  *
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.
527
+ * Setup is where someone is watching, so the outcome is said here rather than
528
+ * found later in `status`: which store took the secret, or that the exchange
529
+ * did not happen and the next run retries. A device this run replaced with a
530
+ * new key has its secret removed, so the keychain does not collect orphans,
531
+ * unless another entry (the machine or a root) still names it.
532
+ *
533
+ * @param context - Resolved CLI context.
534
+ * @param identity - The effective config this run configured.
535
+ * @param replaced - The device credential a new install key displaced.
536
+ * @param scope - The root this run configured, absent for the machine.
537
+ */
538
+ async function exchangeInstallKey(context, identity, replaced, scope) {
539
+ const ctx = { env: context.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, ...(scope === undefined ? {} : { scope }) };
540
+ if (replaced)
541
+ await forgetDeviceIfUnused(ctx, replaced);
542
+ if (!identity.token)
543
+ return;
544
+ const device = await migrateInstallKey(ctx, identity, { ignoreBackoff: true });
545
+ if (!device) {
546
+ println(`${symbols.warn} install key not yet exchanged for a device credential; it stays in the config and the next run retries`);
547
+ return;
548
+ }
549
+ if (device.store === 'file') {
550
+ println(`${symbols.warn} device credential stored in ${storeLabel(device.store)}: ${path.join(context.paths.configDir, CREDENTIALS_DIR_NAME)}`);
551
+ return;
552
+ }
553
+ println(`${symbols.ok} install key exchanged for a device credential, kept in ${storeLabel(device.store)}`);
554
+ }
555
+ /**
556
+ * Say what happens to a backlog queued for the previous backend or token.
557
+ *
558
+ * It stays where it is and expires: moving captured content to a different
559
+ * backend or tenant is a routing decision setup does not make for anyone, and
560
+ * setup never prompts.
188
561
  *
189
562
  * @param context - Resolved CLI context.
190
563
  * @param previousConfig - Config before this run.
191
564
  * @param config - Config this run just wrote.
192
- * @param ask - The prompt, when the run is interactive.
565
+ * @param owner - Machine or selected root whose records are stranded.
193
566
  */
194
- async function offerBacklogRetarget(context, previousConfig, config, ask) {
567
+ async function reportStrandedBacklog(context, previousConfig, config, owner) {
195
568
  const previousUrl = eventsUrl(previousConfig);
196
569
  const configuredUrl = eventsUrl(config);
197
- if (!previousUrl || !configuredUrl || previousUrl === configuredUrl)
570
+ if (!previousUrl || !configuredUrl)
571
+ return;
572
+ if (previousUrl === configuredUrl && identityOf(previousConfig) === identityOf(config))
198
573
  return;
199
- const queue = buildQueue({ ...context, config });
574
+ const queue = openIdentityQueue({ ...context, identityConfig: previousConfig });
200
575
  const stranded = await queue.pendingFor(previousUrl);
201
576
  if (stranded === 0)
202
577
  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`);
578
+ println(`${symbols.warn} keeping ${stranded} offline event(s) captured under ${owner} under the previous identity; they expire after ${config.delivery.maxEventAgeDays} day(s)`);
212
579
  }
213
580
  /**
214
581
  * Register hooks and native telemetry in every detected agent.
@@ -240,6 +607,13 @@ async function installAgents(options, context, config, detected) {
240
607
  if (!hooks.ok)
241
608
  failures++;
242
609
  if (provider.nativeTelemetry && (await provider.nativeTelemetry.supported(options.env))) {
610
+ // First, so an exporter left pointing at a host this config refuses is
611
+ // gone even when there is no allowed route to write in its place.
612
+ const swept = await removeRefusedExporters({ ...setupContext, installState }, [provider]);
613
+ installState = swept.installState;
614
+ for (const refused of swept.refused)
615
+ println(`${refused.removed ? symbols.warn : symbols.fail} ${refused.message}`);
616
+ failures += swept.refused.filter((refused) => !refused.removed).length;
243
617
  const otel = await provider.nativeTelemetry.configure({ ...setupContext, installState });
244
618
  installState = printOutcome(otel, installState);
245
619
  if (!otel.ok)
@@ -263,36 +637,3 @@ function printOutcome(outcome, current) {
263
637
  }
264
638
  return outcome.installState ?? current;
265
639
  }
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
- }