@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
@@ -1,31 +1,52 @@
1
1
  import path from 'node:path';
2
+ import { performance } from 'node:perf_hooks';
2
3
  import { asRecord } from '../core/object.js';
4
+ import { applyProductCapture } from '../privacy/product-capture.js';
3
5
  import { debugLog } from '../core/logger.js';
4
6
  import { next, runFlow, step, stop } from '../core/pipe.js';
5
7
  import { loadEffectiveConfig } from '../config/repo-config.js';
8
+ import { CREDENTIAL_BUDGET_SHARE, NOT_SIGNED_IN } from '../credentials/constants/credentials.constants.js';
9
+ import { cachedBearer, resolveBearer } from '../credentials/credentials.js';
10
+ import { awaitingSignIn, deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
11
+ import { cachedAccessToken } from '../credentials/token-refresher.js';
12
+ import { credentialScope, inheritedRootConfig, selectRoot, servesMultipleIdentities } from '../config/root-config.js';
6
13
  import { DECISION_BLOCK } from '../enforcement/constants/enforcement.constants.js';
7
- import { resolveEnforcement } from '../enforcement/enforcement.js';
14
+ import { enforcementWouldAsk, resolveEnforcement } from '../enforcement/enforcement.js';
15
+ import { sessionBillingFact } from '../billing/session-billing.js';
8
16
  import { enrichEvents } from '../events/enrich.js';
17
+ import { readGateCheckout } from '../git/gate-checkout.js';
18
+ import { checkoutRootOf } from '../git/checkout-root.js';
19
+ import { normalizeRemote } from '../git/remote-sanitize.js';
9
20
  import { developerIdentity, runGit } from '../git/git-context.js';
21
+ import { rewriteNativeBearers } from '../providers/shared/bearer-rewrite.js';
22
+ import { isUninstalled } from '../storage/uninstalled.js';
23
+ import { shellDirectories } from '../providers/shared/shell-directories.js';
10
24
  import { runSnapshotPipeline } from '../snapshot/snapshot-pipeline.js';
11
25
  import { SnapshotStateStore } from '../snapshot/snapshot-state.js';
12
26
  import { SNAPSHOT_BUDGET_MS } from '../snapshot/constants/snapshot.constants.js';
27
+ import { BackendAuthBlock } from '../transport/auth-block.js';
13
28
  import { BackendCooldown } from '../transport/cooldown.js';
14
29
  import { DeliveryStats } from '../transport/delivery-stats.js';
15
30
  import { deliverEvents } from '../transport/delivery.js';
16
31
  import { HttpTransport } from '../transport/http-transport.js';
17
32
  import { EventQueue } from '../transport/queue.js';
18
- import { COOLDOWN_FILE_NAME, DELIVERY_STATS_FILE_NAME } from '../transport/constants/transport.constants.js';
33
+ import { identityPaths, settleLegacyQueue } from '../transport/queue-partition.js';
19
34
  import { eventsUrl } from '../config/config.js';
20
- import { trackTurn } from '../turns/turn-tracker.js';
21
- import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, STAGE_ENRICH, STAGE_PARSE_EVENTS, STAGE_RESOLVE_CONTEXT, STAGE_SNAPSHOT, STAGE_TRACK_TURN, STOP_DRY_RUN, STOP_NO_EVENTS, STOP_NO_SNAPSHOT } from './constants/pipeline.constants.js';
35
+ import { untracedNotice as untracedNoticeText } from '../untraced/constants/untraced.constants.js';
36
+ import { isRunCommand, manifestVerdict, rootHash } from '../untraced/untraced.js';
37
+ import { installedPackage, startUpdateCheck, updateNotice } from '../update/update-check.js';
38
+ import { TurnStateStore } from '../turns/turn-state.js';
39
+ import { MAX_TURN_CHECKOUTS, SHELL_REREAD_TYPES, TOOL_START_TYPES } from '../turns/constants/turns.constants.js';
40
+ import { resolveSurface, trackTurnOutcome } from '../turns/turn-tracker.js';
41
+ import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, STAGE_ENRICH, MAX_WORKSPACE_ROOTS, STAGE_NOMINATE, STAGE_PARSE_EVENTS, STAGE_RESOLVE_CONTEXT, STAGE_REWRITE_BEARERS, STAGE_SNAPSHOT, STAGE_TRACK_TURN, STAGE_UNTRACED, STAGE_UPDATE, QUIET_SESSION_SOURCES, STOP_DRY_RUN, STAGE_AWAIT_SIGN_IN, STOP_NO_EVENTS, STOP_NOT_SIGNED_IN, STOP_NO_SNAPSHOT } from './constants/pipeline.constants.js';
22
42
  /**
23
43
  * The hook flow, as the list of stages it is.
24
44
  *
25
45
  * Read top to bottom, this is the whole contract of the hook path: work out
26
46
  * where we are and what the effective config says, turn the payload into
27
47
  * canonical events, ask whether this turn may start at all, attach development
28
- * context, assemble the turn, deliver, and — when a turn has just closed — tell
48
+ * context, assemble the turn, deliver, keep the Codex and Gemini files on the
49
+ * live access token, and — when a turn has just closed — tell
29
50
  * the platform what this repository's recent branches look like.
30
51
  * Every stage takes the whole state and returns the next one, so adding or
31
52
  * reordering a step is a change to this array rather than to a call graph.
@@ -33,10 +54,15 @@ import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, S
33
54
  const HOOK_STAGES = [
34
55
  step(STAGE_RESOLVE_CONTEXT, resolveContext),
35
56
  step(STAGE_PARSE_EVENTS, parseEvents),
57
+ step(STAGE_AWAIT_SIGN_IN, awaitSignIn),
58
+ step(STAGE_NOMINATE, nominate),
59
+ step(STAGE_UNTRACED, untracedNotice),
60
+ step(STAGE_UPDATE, updateNoticeStage),
36
61
  step(STAGE_ENFORCE, enforce),
37
62
  step(STAGE_ENRICH, enrich),
38
63
  step(STAGE_TRACK_TURN, trackTurnStage),
39
64
  step(STAGE_DELIVER, deliver),
65
+ step(STAGE_REWRITE_BEARERS, rewriteBearers),
40
66
  step(STAGE_SNAPSHOT, snapshot)
41
67
  ];
42
68
  /**
@@ -53,7 +79,7 @@ export function runHookPipeline(input) {
53
79
  const initial = {
54
80
  ...input,
55
81
  cwd: resolvePayloadCwd(input),
56
- config: input.globalConfig,
82
+ config: input.globalConfig.config,
57
83
  events: [],
58
84
  outbound: []
59
85
  };
@@ -73,8 +99,8 @@ export function runHookPipeline(input) {
73
99
  * @returns The state with its effective config resolved.
74
100
  */
75
101
  async function resolveContext(state) {
76
- const effective = await loadEffectiveConfig(state.paths, state.cwd);
77
- return next({ ...state, config: effective.config });
102
+ const effective = await loadEffectiveConfig(state.paths, state.cwd, state.globalConfig);
103
+ return next({ ...state, config: effective.config, credentialScope: credentialScope(selectRoot(state.globalConfig.config.roots, state.cwd)) });
78
104
  }
79
105
  /**
80
106
  * Turn the payload into canonical events.
@@ -88,6 +114,147 @@ async function parseEvents(state) {
88
114
  return stop(state, STOP_NO_EVENTS);
89
115
  return next({ ...state, events });
90
116
  }
117
+ /**
118
+ * Name the checkouts a shell call is about to work in.
119
+ *
120
+ * The only place the edge reads a shell command. It is read in memory for
121
+ * directory names, each name becomes the real root of the checkout it lies in,
122
+ * and only those roots go on: the command and every directory in it go out of
123
+ * scope here, and nothing — not the state, an event, a record or a log line —
124
+ * holds either. A failure logs a fixed sentence, never its error, which could
125
+ * quote a path.
126
+ *
127
+ * A working directory the agent names for the call (Codex `workdir`, Cursor's
128
+ * shell `cwd`) is nominated as it stands, and the command's relative paths are
129
+ * read against it. The folders an agent has open (Cursor's workspace roots) are
130
+ * candidates too, but weak ones: they say where the agent sits, not what the
131
+ * call named.
132
+ *
133
+ * Only on a tool-start hook, or a tool call's completion, failed or not (a shell
134
+ * command may have created the worktree it named; `shellCall` answers only for
135
+ * a shell), and only while git capture is on: which checkout a
136
+ * turn worked in is git metadata, and a developer who turned that off said no.
137
+ * Open folders are read on a tool start only.
138
+ *
139
+ * @param state - Current flow state.
140
+ * @returns The state, with the named checkouts' roots.
141
+ */
142
+ async function nominate(state) {
143
+ const start = state.events.some((event) => TOOL_START_TYPES.has(event.event.type));
144
+ if (!state.config.capture.git || (!start && !state.events.some((event) => SHELL_REREAD_TYPES.has(event.event.type))))
145
+ return next(state);
146
+ try {
147
+ const call = state.provider.shellCall?.(state.payload);
148
+ // Untrusted: only an absolute directory is taken, never one resolved against a guess.
149
+ const workdir = typeof call?.workdir === 'string' && path.isAbsolute(call.workdir) ? call.workdir : undefined;
150
+ const named = [
151
+ ...(workdir ? [workdir] : []),
152
+ ...(typeof call?.command === 'string' && call.command ? shellDirectories(call.command, workdir ?? state.cwd, state.env.home) : [])
153
+ ];
154
+ // ponytail: the first few open checkouts only, so weak candidates never fill a
155
+ // turn's checkout slots before a call names one; a wider window loses the rest.
156
+ // The folders looked at are bounded too, since the list is untrusted.
157
+ const open = [...new Set((start ? (state.provider.workspaceRoots?.(state.payload) ?? []) : []).filter((root) => typeof root === 'string' && path.isAbsolute(root)))].slice(0, MAX_TURN_CHECKOUTS);
158
+ const [nominations, openRoots] = await Promise.all([checkoutRoots(named), checkoutRoots(open)]);
159
+ return next({ ...state, nominations, workspaceRoots: openRoots.slice(0, MAX_WORKSPACE_ROOTS) });
160
+ }
161
+ catch {
162
+ debugLog('shell nomination failed; this call names no checkout');
163
+ return next(state);
164
+ }
165
+ }
166
+ /**
167
+ * Stop here on an MDM install whose developer has not signed in: nothing is
168
+ * enriched, tracked, sent or queued, because nothing is anyone's yet. A session
169
+ * start says how to finish, the one place the developer is sure to see it.
170
+ *
171
+ * @param state - Current flow state.
172
+ * @returns The state unchanged, or a stop carrying the sign-in notice.
173
+ */
174
+ async function awaitSignIn(state) {
175
+ if (!awaitingSignIn(state.config))
176
+ return next(state);
177
+ return stop(isLoudSessionStart(state) && !state.dryRun ? { ...state, notice: NOT_SIGNED_IN } : state, STOP_NOT_SIGNED_IN);
178
+ }
179
+ /**
180
+ * Whether this payload is a developer starting or resuming work, the moment a
181
+ * notice is worth showing; not a `/clear` or `/compact` mid-session.
182
+ *
183
+ * @param state - Current flow state.
184
+ * @returns True for a session start that is not a quiet one.
185
+ */
186
+ function isLoudSessionStart(state) {
187
+ return state.events.some((event) => event.event.type === 'session.started') && !QUIET_SESSION_SOURCES.has(String(asRecord(state.payload)?.['source']));
188
+ }
189
+ /**
190
+ * Tell the developer, as a session starts or resumes, that npm has a newer release.
191
+ *
192
+ * Not on Claude Code's `clear` or `compact` starts: those happen mid-session,
193
+ * and the line would come back after every compaction.
194
+ *
195
+ * Reads a local cache only; a stale one starts a detached registry check whose
196
+ * answer shows on the next session. Every failure means no notice.
197
+ *
198
+ * @param state - Current flow state.
199
+ * @returns The state, carrying the notice when one is due.
200
+ */
201
+ async function updateNoticeStage(state) {
202
+ if (state.dryRun || state.notice !== undefined || !state.config.updateNotices || !state.provider.getNoticeResponse)
203
+ return next(state);
204
+ if (!isLoudSessionStart(state))
205
+ return next(state);
206
+ const notice = await updateNotice(state.paths.dataDir, state.env.now(), installedPackage().version, () => startUpdateCheck(state.env));
207
+ return next(notice === undefined ? state : { ...state, notice });
208
+ }
209
+ /**
210
+ * Tell the developer, once per repository per session, that a run called an
211
+ * LLM with no tracing (AWT-310).
212
+ *
213
+ * Decided on this machine from the dependency manifests alone: it adds no
214
+ * event, field or request, and every failure — an unreadable manifest, a store
215
+ * that cannot be written — means no notice, never a failed hook. The command is
216
+ * read in memory for the one question "is this a run?" and goes no further.
217
+ *
218
+ * @param state - Current flow state.
219
+ * @returns The state, carrying the notice when this run earns one.
220
+ */
221
+ async function untracedNotice(state) {
222
+ if (state.dryRun || !state.config.untracedNotices || !state.provider.getNoticeResponse)
223
+ return next(state);
224
+ const sessionId = state.events.find((event) => event.event.type === 'shell.completed')?.session.id;
225
+ if (!sessionId)
226
+ return next(state);
227
+ try {
228
+ const call = state.provider.shellCall?.(state.payload);
229
+ if (typeof call?.command !== 'string' || !isRunCommand(call.command))
230
+ return next(state);
231
+ const workdir = typeof call.workdir === 'string' && path.isAbsolute(call.workdir) ? call.workdir : state.cwd;
232
+ // The checkouts the command names, then the one the agent sits in: the run may be in either.
233
+ const here = await checkoutRootOf(workdir);
234
+ const roots = [...new Set([...(state.nominations ?? []), ...(here ? [here] : [])])];
235
+ for (const root of roots) {
236
+ const verdict = await manifestVerdict(root, state.paths.dataDir);
237
+ if (verdict.providers.length === 0 || verdict.traced)
238
+ continue;
239
+ if (await new TurnStateStore(state.paths.turnsDir).takeNotice(sessionId, rootHash(root)))
240
+ return next({ ...state, notice: untracedNoticeText(verdict.providers) });
241
+ }
242
+ }
243
+ catch {
244
+ debugLog('untraced: check failed; no notice');
245
+ }
246
+ return next(state);
247
+ }
248
+ /**
249
+ * The distinct checkout roots a list of paths lies in, `stat`s only.
250
+ *
251
+ * @param paths - Absolute paths.
252
+ * @returns Canonical roots, in first-seen order.
253
+ */
254
+ async function checkoutRoots(paths) {
255
+ const roots = await Promise.all(paths.map(checkoutRootOf));
256
+ return [...new Set(roots.filter((root) => root !== undefined))];
257
+ }
91
258
  /**
92
259
  * Ask the platform whether this turn may start.
93
260
  *
@@ -104,30 +271,142 @@ async function parseEvents(state) {
104
271
  * @returns The state, carrying the refusal when there is one.
105
272
  */
106
273
  async function enforce(state) {
107
- if (state.dryRun || !state.provider.getBlockResponse || !isTurnGate(state))
274
+ if (state.dryRun || !state.provider.getBlockResponse)
108
275
  return next(state);
276
+ const prompt = turnGateEvent(state);
277
+ if (!prompt)
278
+ return next(state);
279
+ // Nothing below is paid for on a machine that would not ask. Working out which
280
+ // checkout this is costs a walk of the working copy and, once per checkout, a
281
+ // git process — small, and still the wrong thing to spend on a developer whose
282
+ // organization set no cap.
283
+ if (!enforcementWouldAsk(state.config))
284
+ return next(state);
285
+ // Together, not in turn. Each can cost its own git timeout, and taken in order
286
+ // a slow machine pays both before the agent's first token. Resolving the
287
+ // identity first would save a checkout lookup only on a machine that has no
288
+ // identity at all — a rare and stable condition — at the price of doubling the
289
+ // worst case for everyone else. The session's model joins them for the same
290
+ // reason: it is one small file, and it is still a file.
291
+ const [developerId, checkout, model] = await Promise.all([
292
+ developerIdentity(state.config.developerEmail, state.cwd, { home: state.env.home }),
293
+ gateCheckout(state, prompt),
294
+ statedModel(state, prompt)
295
+ ]);
296
+ // Cached only: a refresh or an exchange may cost a network round trip, and
297
+ // this sits between enter and the agent's first token. Delivery refreshes.
298
+ const bearer = await cachedBearer(credentialContext(state, state.config.enforcement.timeoutMs), state.config);
109
299
  const decision = await resolveEnforcement({
110
300
  config: state.config,
111
301
  paths: state.paths,
112
- developerId: await developerIdentity(state.config.developerEmail, state.cwd, { home: state.env.home }),
302
+ developerId,
303
+ checkout,
304
+ model,
305
+ ...(bearer ? { bearer } : {}),
113
306
  now: state.env.now
114
307
  });
115
308
  if (decision.decision !== DECISION_BLOCK)
116
- return next(state);
309
+ return next({ ...state, failOpenReason: decision.failOpenReason });
117
310
  return next({ ...state, blockMessage: decision.message });
118
311
  }
119
312
  /**
120
- * Whether this payload is the moment before the turn's first LLM call.
313
+ * The event that makes this payload the moment before the turn's first LLM
314
+ * call, if it is one.
121
315
  *
122
316
  * @param state - Current flow state.
123
- * @returns True when the provider reported a submitted prompt.
317
+ * @returns The submitted prompt, or undefined when this hook is not a gate.
124
318
  */
125
- function isTurnGate(state) {
319
+ function turnGateEvent(state) {
126
320
  for (const event of state.events) {
127
321
  if (event.event.type === PROMPT_SUBMITTED_TYPE)
128
- return true;
322
+ return event;
323
+ }
324
+ return undefined;
325
+ }
326
+ /**
327
+ * The checkout to state on the gate request.
328
+ *
329
+ * From a session's second turn on, the checkout its last turn changed, wherever
330
+ * the agent sits now: a spinoff parked in the docs repository that edits a
331
+ * feature worktree is working on that feature. The turn tracker wrote down the
332
+ * checkout's root and repository, so this costs one small file and the same
333
+ * `.git` walk as today, and the branch is still read from `HEAD` on disk, so a
334
+ * switch since that turn is seen. No git process: the repository is the one
335
+ * remembered.
336
+ *
337
+ * Only a checkout the asking tenant's root governs: the config (and so the token)
338
+ * asking here comes from the folder the agent sits in, and another tenant's
339
+ * repository must never travel on it. With no roots there is one tenant, and the
340
+ * tracker only remembered a checkout beneath the session's start folder.
341
+ *
342
+ * Anything missing, unreadable, gone or on a detached HEAD answers exactly what
343
+ * today's lookup of the agent's own folder answers.
344
+ *
345
+ * @param state - Current flow state.
346
+ * @param prompt - The prompt event being gated.
347
+ * @returns The checkout, or undefined when none is known.
348
+ */
349
+ async function gateCheckout(state, prompt) {
350
+ const base = { checkoutsDir: state.paths.checkoutsDir, now: state.env.now };
351
+ const work = await lastWorkCheckout(state, prompt.session.id);
352
+ const carried = work && await readGateCheckout({ ...base, cwd: work.root, repository: work.repository });
353
+ return carried ?? readGateCheckout({ ...base, cwd: state.cwd });
354
+ }
355
+ /**
356
+ * The session's last changed checkout, when the asking tenant may name it.
357
+ *
358
+ * @param state - Current flow state.
359
+ * @param sessionId - Provider session id, if the prompt has one.
360
+ * @returns The remembered checkout, or undefined.
361
+ */
362
+ async function lastWorkCheckout(state, sessionId) {
363
+ if (!sessionId)
364
+ return undefined;
365
+ try {
366
+ const work = await new TurnStateStore(state.paths.turnsDir).readWorkCheckout(sessionId);
367
+ const roots = state.globalConfig.config.roots;
368
+ // Only a value already in the canonical, credential-free form git capture
369
+ // produces: a checkout with no remote is remembered by its folder name, which
370
+ // names no repository (today's gate states nothing for it either), and a
371
+ // damaged or hand-edited file must never put anything else on the request.
372
+ if (!work || normalizeRemote(`https://${work.repository}`) !== work.repository)
373
+ return undefined;
374
+ return selectRoot(roots, work.root)?.path === selectRoot(roots, state.cwd)?.path ? work : undefined;
375
+ }
376
+ catch {
377
+ // A fixed sentence: the error could quote a path.
378
+ debugLog('enforcement: last work checkout unreadable; asking about the current folder');
379
+ return undefined;
380
+ }
381
+ }
382
+ /**
383
+ * The model to state on the gate request.
384
+ *
385
+ * Codex, Cursor, Gemini and Antigravity name their model on the prompt hook
386
+ * itself. Claude Code names it only when the session starts, so the tracker
387
+ * wrote it down and this reads it back — one small file, inside the same
388
+ * `Promise.all` as identity and checkout, so it adds no serial wait to the gate.
389
+ *
390
+ * Anything that goes wrong states nothing: the model narrows the question, and a
391
+ * question asked without it is still answered.
392
+ *
393
+ * @param state - Current flow state.
394
+ * @param prompt - The prompt event being gated.
395
+ * @returns The model, or undefined when none is known.
396
+ */
397
+ async function statedModel(state, prompt) {
398
+ if (prompt.ai?.model)
399
+ return prompt.ai.model;
400
+ const sessionId = prompt.session.id;
401
+ if (!sessionId)
402
+ return undefined;
403
+ try {
404
+ return await new TurnStateStore(state.paths.turnsDir).readModel(sessionId);
405
+ }
406
+ catch (error) {
407
+ debugLog('enforcement: session model unreadable; stating none:', error);
408
+ return undefined;
129
409
  }
130
- return false;
131
410
  }
132
411
  /**
133
412
  * Attach development context and scrub the events.
@@ -159,33 +438,70 @@ async function trackTurnStage(state) {
159
438
  // Assembly failing must not cost the *queue* its drain: a hook that produced
160
439
  // no summary still has a backlog to move, so this stage degrades to "no
161
440
  // summary" instead of ending the flow.
162
- const summary = await trackTurnSafely(state);
163
- const outbound = summary && state.config.emit.turnSummaries ? [summary] : [];
164
- return next({ ...state, summary, outbound });
441
+ const { summary, workRoot, capture } = await trackTurnSafely(state);
442
+ // Re-applied under the reported checkout's own policy when it has one: that
443
+ // checkout's file decides what is said about it, not the folder the Stop ran in.
444
+ const workCapture = capture ?? state.config.capture;
445
+ // A session started in no root, working in a checkout a root claims, sends as
446
+ // that root: its token, destination and queue, from this close on. The summary
447
+ // is the only thing that leaves, and it is built here, so nothing earlier in
448
+ // the session was sent under another identity.
449
+ const routed = inheritedRootConfig(state.globalConfig.config, summary?.work_evidence, workRoot);
450
+ const config = routed ? (await loadEffectiveConfig(state.paths, workRoot, state.globalConfig)).config : state.config;
451
+ const gated = summary && config.emit.turnSummaries ? applyProductCapture(summary, workCapture) : undefined;
452
+ const billing = config.emit.turnSummaries && !state.dryRun ? await billingFactSafely(state) : undefined;
453
+ const outbound = [...(billing ? [billing] : []), ...(gated ? [gated] : [])];
454
+ const scope = routed ? credentialScope(selectRoot(state.globalConfig.config.roots, workRoot)) : state.credentialScope;
455
+ return next({ ...state, config, credentialScope: scope, summary, workRoot, workCapture, outbound });
456
+ }
457
+ /**
458
+ * The session's billing fact, or nothing on any failure.
459
+ *
460
+ * Sent when the session opens rather than with the turn summary, because a turn
461
+ * that never reaches its Stop hook never produces one (AWT-476). Best effort:
462
+ * a hook never fails for it, and the offline queue carries it like any record.
463
+ *
464
+ * @param state - Current flow state.
465
+ * @returns The event, when this hook opened the session and its mode is known.
466
+ */
467
+ async function billingFactSafely(state) {
468
+ try {
469
+ const surface = await resolveSurface(state.events[0]?.agent.provider ?? state.provider.id, state.env, state.payload);
470
+ return await sessionBillingFact(new TurnStateStore(state.paths.turnsDir), state.events, state.provider.id, state.env, surface);
471
+ }
472
+ catch (error) {
473
+ debugLog('session billing fact failed:', error);
474
+ return undefined;
475
+ }
165
476
  }
166
477
  /**
167
478
  * Assemble the turn, degrading to no summary on any failure.
168
479
  *
169
480
  * @param state - Current flow state.
170
- * @returns The summary, or undefined.
481
+ * @returns The summary and the local root it reported, or neither.
171
482
  */
172
483
  async function trackTurnSafely(state) {
173
484
  try {
174
- return await trackTurn({
485
+ return await trackTurnOutcome({
175
486
  agentId: state.provider.id,
176
487
  rawPayload: state.payload,
177
488
  events: state.events,
178
489
  config: state.config,
490
+ globalConfig: state.globalConfig,
491
+ paths: state.paths,
179
492
  turnsDir: state.paths.turnsDir,
180
493
  locksDir: state.paths.locksDir,
181
494
  env: state.env,
182
495
  cwd: state.cwd,
183
- readOnly: state.dryRun
496
+ readOnly: state.dryRun,
497
+ failOpenReason: state.failOpenReason,
498
+ nominations: state.nominations,
499
+ workspaceRoots: state.workspaceRoots
184
500
  });
185
501
  }
186
502
  catch (error) {
187
503
  debugLog('turn summary failed:', error);
188
- return undefined;
504
+ return {};
189
505
  }
190
506
  }
191
507
  /**
@@ -197,11 +513,45 @@ async function trackTurnSafely(state) {
197
513
  async function deliver(state) {
198
514
  if (state.dryRun)
199
515
  return stop(state, STOP_DRY_RUN);
200
- const queue = buildQueue(state);
201
- const delivery = await deliverEvents(state.outbound, buildTransport(state), queue, state.config.delivery.drainBatchSize, new BackendCooldown(path.join(state.paths.dataDir, COOLDOWN_FILE_NAME), state.env.now), new DeliveryStats(path.join(state.paths.dataDir, DELIVERY_STATS_FILE_NAME), state.env.now, state.paths.locksDir));
516
+ // `globalConfig`, not `config`: roots are stripped from the effective config
517
+ // once applied, and the question is what the *machine* sends as.
518
+ await settleLegacyQueue(state.paths.queueDir, identityOf(state.config), servesMultipleIdentities(state.globalConfig.config));
519
+ const identity = identityPaths(state.paths, identityOf(state.config));
520
+ // One budget for the credential and the send: credential work (a keychain
521
+ // read, a refresh, an exchange) may spend its share of it and no more, and
522
+ // the send gets what is left. A hook never waits longer than it did before.
523
+ // `resolveBearer` never throws: a failure there leaves no bearer, and the
524
+ // transport defers, so the run's records queue.
525
+ const budgetMs = state.config.delivery.timeoutMs;
526
+ const started = performance.now();
527
+ const bearer = await resolveBearer({ ...credentialContext(state, budgetMs), deadline: started + budgetMs * CREDENTIAL_BUDGET_SHARE }, state.config);
528
+ const remaining = Math.max(0, budgetMs - (performance.now() - started));
529
+ const delivery = await deliverEvents(state.outbound, buildTransport(state, bearer, remaining), buildQueue(state), state.config.delivery.drainBatchSize, new BackendCooldown(identity.cooldownFile, state.env.now), new DeliveryStats(identity.statsFile, state.env.now, state.paths.locksDir), new BackendAuthBlock(identity.authBlockFile, state.env.now));
202
530
  debugLog(`delivery: sent=${delivery.delivered} queued=${delivery.queued} drained=${delivery.drained} rejected=${delivery.rejected}`);
203
531
  return next({ ...state, delivery });
204
532
  }
533
+ /**
534
+ * Keep Codex and Gemini on the machine's live access token (AWT-357).
535
+ *
536
+ * They read their OTLP header from their own config once, when a session
537
+ * starts, so a file still holding a replaced token would start the next
538
+ * session on one about to expire. After `deliver`, which refreshed the token
539
+ * when it was due, and from the cache only: no network, no keychain. The
540
+ * machine's token, whatever identity this payload sent as, because those files
541
+ * are machine-wide. Never fails the hook.
542
+ *
543
+ * @param state - Current flow state.
544
+ * @returns The state, unchanged.
545
+ */
546
+ async function rewriteBearers(state) {
547
+ const machine = state.globalConfig.config;
548
+ if (!deviceFor(machine) || (await isUninstalled(state.paths)))
549
+ return next(state);
550
+ const bearer = await cachedAccessToken(credentialContext(state, state.config.delivery.timeoutMs), machine).catch(() => undefined);
551
+ if (bearer)
552
+ await rewriteNativeBearers(state.paths, bearer);
553
+ return next(state);
554
+ }
205
555
  /**
206
556
  * Describe the repository's recent branches, after the turn has been delivered.
207
557
  *
@@ -220,11 +570,18 @@ async function deliver(state) {
220
570
  */
221
571
  async function snapshot(state) {
222
572
  const repository = state.summary?.repository;
223
- if (!repository || !state.config.capture.git)
573
+ // Never for an inherited repository: core may drop it when folder evidence
574
+ // disagrees, and a snapshot of it would mint a work unit for the wrong one.
575
+ const capture = state.workCapture ?? state.config.capture;
576
+ if (!repository || state.summary?.work_evidence === 'inherited' || !capture.git)
224
577
  return stop(state, STOP_NO_SNAPSHOT);
225
578
  await runSnapshotPipeline({
226
579
  input: {
227
- cwd: state.cwd,
580
+ // The checkout the summary named, which need not be the folder the agent sits in.
581
+ cwd: state.workRoot ?? state.cwd,
582
+ // The repository's own policy, which may lower the global one: file names
583
+ // off means the files listing never runs, not that it is emptied later.
584
+ files: capture.files !== false,
228
585
  repository,
229
586
  provider: state.summary?.provider ?? state.provider.id,
230
587
  surface: state.summary?.surface ?? state.provider.id,
@@ -244,38 +601,58 @@ async function snapshot(state) {
244
601
  return next(state);
245
602
  }
246
603
  /**
247
- * The offline queue for this run.
604
+ * The offline queue for this run, partitioned by the identity it sends as.
605
+ * `deliver` settles a pre-partition backlog before the first build.
248
606
  *
249
607
  * @param state - Current flow state.
250
608
  * @returns A queue bound to this run's paths and delivery limits.
251
609
  */
252
610
  function buildQueue(state) {
611
+ const identity = identityPaths(state.paths, identityOf(state.config));
253
612
  return new EventQueue({
254
- queueDir: state.paths.queueDir,
613
+ queueDir: identity.queueDir,
255
614
  locksDir: state.paths.locksDir,
256
615
  maxEvents: state.config.delivery.maxQueueEvents,
257
616
  maxAttempts: state.config.delivery.maxAttempts,
258
617
  maxEventAgeDays: state.config.delivery.maxEventAgeDays,
259
- now: state.env.now
618
+ now: state.env.now,
619
+ // So the entries the bound sacrifices are counted wherever an enqueue
620
+ // happens, the snapshot pipeline's included.
621
+ stats: new DeliveryStats(identity.statsFile, state.env.now, state.paths.locksDir)
260
622
  });
261
623
  }
262
624
  /**
263
625
  * The transport for this run, when a backend is configured.
264
626
  *
265
627
  * @param state - Current flow state.
628
+ * @param bearer - What to authenticate with; see `resolveBearer`.
629
+ * @param budgetMs - What is left of the delivery budget.
266
630
  * @returns The transport, or undefined before setup has run.
267
631
  */
268
- function buildTransport(state) {
632
+ function buildTransport(state, bearer, budgetMs) {
269
633
  const url = eventsUrl(state.config);
270
634
  if (!url)
271
635
  return undefined;
272
636
  return new HttpTransport({
273
637
  eventsUrl: url,
274
- token: state.config.token,
638
+ capture: state.config.capture,
639
+ token: bearer,
640
+ credentialPending: hasCredential(state.config) && !bearer,
275
641
  installationId: state.config.installationId,
276
- timeoutMs: state.config.delivery.timeoutMs
642
+ timeoutMs: state.config.delivery.timeoutMs,
643
+ budgetMs
277
644
  });
278
645
  }
646
+ /**
647
+ * What the credential code needs from this run.
648
+ *
649
+ * @param state - Current flow state.
650
+ * @param timeoutMs - Ceiling for one keychain read or gateway call.
651
+ * @returns The context.
652
+ */
653
+ function credentialContext(state, timeoutMs) {
654
+ return { env: state.env, paths: state.paths, timeoutMs, hookPath: true, scope: state.credentialScope };
655
+ }
279
656
  /**
280
657
  * Where this payload happened.
281
658
  *