@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
@@ -0,0 +1,195 @@
1
+ import type { z } from 'zod';
2
+ import type { issuedDeviceCredentialSchema, refreshedAccessTokenSchema, startedEnrollmentSessionSchema } from '../schemas/device-api.schema.js';
3
+ import type { accessTokenCacheSchema, deviceStateSchema } from '../schemas/device-state.schema.js';
4
+ import type { Env } from '../../core/types/core.types.js';
5
+ import type { AgentWatchPaths } from '../../storage/types/storage.types.js';
6
+ import type { CREDENTIAL_STORE_KINDS } from '../constants/credentials.constants.js';
7
+ /** Which backend holds a device secret. */
8
+ export type CredentialStoreKind = (typeof CREDENTIAL_STORE_KINDS)[number];
9
+ /**
10
+ * What the config holds in place of an install key once it is exchanged: no
11
+ * secret, only where to find one.
12
+ */
13
+ export interface DeviceCredentialRef {
14
+ /** Fingerprint of the install key it replaced; the keychain account name. */
15
+ readonly id: string;
16
+ readonly store: CredentialStoreKind;
17
+ /**
18
+ * The gateway the device was enrolled with: where uninstall revokes it, even
19
+ * after the entry has been pointed elsewhere. Absent on a device enrolled
20
+ * before it was recorded.
21
+ */
22
+ readonly endpoint?: string;
23
+ }
24
+ /** The credential fields of a config, a root override or an effective config. */
25
+ export interface CredentialFields {
26
+ readonly token?: string;
27
+ readonly device?: DeviceCredentialRef;
28
+ }
29
+ /** What one keychain tool run produced. */
30
+ export interface CommandResult {
31
+ /** Exit code; null when the tool could not start or was killed on timeout. */
32
+ readonly code: number | null;
33
+ readonly stdout: string;
34
+ }
35
+ /** Runs one tool; injectable so tests can stand in for each OS's keychain. */
36
+ export type CommandRunner = (file: string, args: readonly string[], options: {
37
+ readonly input?: string;
38
+ readonly timeoutMs: number;
39
+ readonly env: Record<string, string | undefined>;
40
+ }) => Promise<CommandResult>;
41
+ /** What a secret store needs from its surroundings. */
42
+ export interface StoreDeps {
43
+ readonly env: Env;
44
+ readonly paths: AgentWatchPaths;
45
+ /** Ceiling for one keychain tool run or gateway call. */
46
+ readonly timeoutMs: number;
47
+ /**
48
+ * When all credential work must be done, on the `performance.now()` clock.
49
+ * Each step gets what is left, never a full `timeoutMs` of its own, so a slow
50
+ * keychain and a dead gateway together cost the hook its credential share of
51
+ * the delivery budget, not two timeouts. Absent outside the hook path.
52
+ */
53
+ readonly deadline?: number;
54
+ /** Injected by tests; spawns the real tool otherwise. */
55
+ readonly run?: CommandRunner;
56
+ }
57
+ /** One place a device secret can be kept. */
58
+ export interface SecretStore {
59
+ readonly kind: CredentialStoreKind;
60
+ /** The secret, or undefined when absent or unreadable right now. */
61
+ get(id: string): Promise<string | undefined>;
62
+ /** True when the store took it; the caller verifies with `get`. */
63
+ set(id: string, secret: string): Promise<boolean>;
64
+ remove(id: string): Promise<void>;
65
+ }
66
+ /** A device credential as the gateway issues it. */
67
+ export type IssuedDeviceCredential = z.infer<typeof issuedDeviceCredentialSchema>;
68
+ /** The codes of one started browser sign-in. */
69
+ export type StartedEnrollmentSession = z.infer<typeof startedEnrollmentSessionSchema>;
70
+ /** A refreshed access token. */
71
+ export type RefreshedAccessToken = z.infer<typeof refreshedAccessTokenSchema>;
72
+ /**
73
+ * What a device route answered. `refusal` only for a reason the edge knows how
74
+ * to act on; any other failure is "try again later".
75
+ */
76
+ export type DeviceApiResult<T> = {
77
+ readonly ok: true;
78
+ readonly value: T;
79
+ } | {
80
+ readonly ok: false;
81
+ readonly status?: number;
82
+ readonly refusal?: string;
83
+ };
84
+ /** What every call to a device route needs. */
85
+ export interface DeviceRouteInput {
86
+ /** Gateway base URL. */
87
+ readonly endpoint: string;
88
+ readonly timeoutMs: number;
89
+ /** Injected by tests; the real fetch otherwise. */
90
+ readonly fetchFn?: typeof fetch;
91
+ }
92
+ /** The install-key exchange. */
93
+ export interface EnrollInput extends DeviceRouteInput {
94
+ readonly installKey: string;
95
+ /** The developer this machine reports; recorded as unverified. */
96
+ readonly developerId: string;
97
+ /** This machine's label, shown to admins. */
98
+ readonly name: string;
99
+ }
100
+ /** Start a browser sign-in for an organization. */
101
+ export interface StartSessionInput extends DeviceRouteInput {
102
+ readonly organizationId: string;
103
+ readonly installationId: string;
104
+ /** This machine's label, shown to the member who approves it. */
105
+ readonly name: string;
106
+ }
107
+ /** One poll of a started sign-in. */
108
+ export interface PollSessionInput extends DeviceRouteInput {
109
+ readonly deviceCode: string;
110
+ readonly installationId: string;
111
+ }
112
+ /** A browser sign-in the gateway approved and this machine kept. */
113
+ export interface SignedIn {
114
+ readonly device: DeviceCredentialRef;
115
+ /** Kept only to undo the sign-in if the config cannot be written. */
116
+ readonly deviceSecret: string;
117
+ /** Who approved it; absent from a gateway older than AWT-555. */
118
+ readonly developerEmail?: string;
119
+ }
120
+ /** Everything a browser sign-in needs from setup. */
121
+ export interface SignInInput {
122
+ readonly endpoint: string;
123
+ readonly organizationId: string;
124
+ readonly installationId: string;
125
+ /** This machine's label, shown to the member who approves it. */
126
+ readonly name: string;
127
+ /** Where the verification code is shown. */
128
+ readonly print: (line: string) => void;
129
+ /** Opens the verification link in a browser; absent where none should open. */
130
+ readonly open?: (url: string) => void;
131
+ /** Injected by tests; a real timer otherwise. */
132
+ readonly sleep?: (ms: number) => Promise<void>;
133
+ }
134
+ /** One refresh. */
135
+ export interface RefreshInput extends DeviceRouteInput {
136
+ readonly deviceSecret: string;
137
+ }
138
+ /** A self-revoke: the secret is both the credential and what is switched off. */
139
+ export interface RevokeInput extends DeviceRouteInput {
140
+ readonly deviceSecret: string;
141
+ }
142
+ /**
143
+ * What uninstall did about one device: switched off on the platform, removed
144
+ * from this machine, and why not when either failed. `reason` is a short phrase
145
+ * for a person and never carries the secret.
146
+ */
147
+ export interface DeviceRevocation {
148
+ readonly revoked: boolean;
149
+ readonly removed: boolean;
150
+ readonly reason?: string;
151
+ /**
152
+ * Where the secret is still kept when it could not be removed. The config no
153
+ * longer names it, so a second uninstall cannot find it; a person must.
154
+ */
155
+ readonly leftover?: string;
156
+ }
157
+ /** What uninstall did about this machine's device credentials. */
158
+ export interface DeviceForgetResult {
159
+ /** The uninstall marker was written; false leaves a later run free to enroll. */
160
+ readonly marked: boolean;
161
+ /** `ok` when the references left the config; otherwise nothing was revoked or removed. */
162
+ readonly config: 'ok' | 'busy' | 'invalid';
163
+ /** One per distinct device, every one of them, failures included. */
164
+ readonly revocations: readonly DeviceRevocation[];
165
+ }
166
+ export type AccessTokenCache = z.infer<typeof accessTokenCacheSchema>;
167
+ export type DeviceState = z.infer<typeof deviceStateSchema>;
168
+ /** What the refresher and the exchange need from their surroundings. */
169
+ export interface CredentialContext extends StoreDeps {
170
+ /** Injected by tests; the real fetch otherwise. */
171
+ readonly fetchFn?: typeof fetch;
172
+ /**
173
+ * Running inside a hook. On Windows the hook never starts PowerShell itself:
174
+ * no exchange, and a DPAPI-held device uses its cached token while a due
175
+ * refresh runs in a detached `agentwatch refresh-credential`.
176
+ */
177
+ readonly hookPath?: boolean;
178
+ /**
179
+ * The uninstall-marker scope of this config's credential: the root path when
180
+ * a root names its own credential, absent for the machine's.
181
+ */
182
+ readonly scope?: string;
183
+ /**
184
+ * Refresh whenever less than this is left, whatever the 25% rule says. For
185
+ * the OTel headers helper, whose output Claude Code reuses for its debounce.
186
+ */
187
+ readonly minRemainingMs?: number;
188
+ /** Injected by tests; spawns the detached refresher otherwise. */
189
+ readonly startBackgroundRefresh?: (cwd: string) => void;
190
+ }
191
+ /** What `status` and `doctor` say about an identity's credential. */
192
+ export interface CredentialReport {
193
+ readonly level: 'ok' | 'warn' | 'fail';
194
+ readonly detail: string;
195
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,4 +1,4 @@
1
- import type { EnforcementDecision } from '../types/enforcement.types.js';
1
+ import type { EnforcementDecision, FailOpenReason } from '../types/enforcement.types.js';
2
2
  /** The two decisions, as both the wire and the cache file spell them. */
3
3
  export declare const DECISION_ALLOW = "allow";
4
4
  export declare const DECISION_BLOCK = "block";
@@ -11,6 +11,31 @@ export declare const DECISION_BLOCK = "block";
11
11
  export declare const ALLOW: EnforcementDecision;
12
12
  /** Local cache file under the data directory. */
13
13
  export declare const ENFORCEMENT_CACHE_FILE_NAME = "enforcement-cache.json";
14
+ /**
15
+ * The enforcement breaker's file, in the identity's state directory beside the
16
+ * delivery breaker and never the same file: an outage on one path is not an
17
+ * outage on the other, and the two are tripped by different signals. Suffixed
18
+ * with a digest of the decision URL, because what the breaker records is that
19
+ * one endpoint did not answer.
20
+ */
21
+ export declare const ENFORCEMENT_COOLDOWN_FILE_PREFIX = "enforcement-cooldown-";
22
+ export declare const ENFORCEMENT_COOLDOWN_FILE_SUFFIX = ".json";
23
+ export declare const ENFORCEMENT_COOLDOWN_URL_CHARS = 12;
24
+ /**
25
+ * How long turns skip the check after the platform failed to answer one: 30 s.
26
+ *
27
+ * Only a submitted prompt asks, so this is measured against how often a person
28
+ * presses enter. Inside the 5 s window it would expire between almost every pair
29
+ * of turns and save nothing — every turn of an outage would pay the timeout
30
+ * again, which is what `edge-resilience` §1 forbids. Longer is not free: a turn
31
+ * the breaker skips is not checked, so after a blip clears a tenant over its cap
32
+ * can run for up to this long. That is at most a turn or two at human pace, it
33
+ * is the same outcome the failed request itself already produced, and each
34
+ * skipped turn is a fail-open like any other, with the breaker as its reason.
35
+ * Half the delivery breaker's 60 s because an unchecked turn costs a
36
+ * tenant money and a late event costs nothing.
37
+ */
38
+ export declare const ENFORCEMENT_COOLDOWN_MS = 30000;
14
39
  /**
15
40
  * Entries kept in the cache file.
16
41
  *
@@ -21,3 +46,24 @@ export declare const ENFORCEMENT_CACHE_FILE_NAME = "enforcement-cache.json";
21
46
  export declare const MAX_CACHE_ENTRIES = 16;
22
47
  /** Query parameter the endpoint reads the identity from. */
23
48
  export declare const DEVELOPER_ID_PARAM = "developer_id";
49
+ /** And the checkout, which is what lets a cap on a feature be judged. */
50
+ export declare const REPOSITORY_PARAM = "repository";
51
+ export declare const BRANCH_PARAM = "branch";
52
+ /** And the model, which is what lets a cap on one model be judged. */
53
+ export declare const MODEL_PARAM = "model";
54
+ /**
55
+ * The fail-open reasons the platform accepts, for checking a value read back
56
+ * from disk before it is sent. Anything else is dropped rather than sent:
57
+ * the platform would file it as `unknown`, and a hand-edited file is not a
58
+ * reason to report anything.
59
+ */
60
+ export declare const FAIL_OPEN_REASONS: ReadonlySet<FailOpenReason>;
61
+ /**
62
+ * The error names a timed-out request rejects with. `AbortSignal.timeout`
63
+ * rejects with a TimeoutError, but a body stream cancelled by that signal can
64
+ * surface as a plain AbortError depending on the runtime — and the timeout is
65
+ * the only signal this request carries, so either name means it timed out.
66
+ */
67
+ export declare const TIMEOUT_ERROR_NAMES: ReadonlySet<string>;
68
+ /** The error name `JSON.parse` throws on a body that is not JSON. */
69
+ export declare const SYNTAX_ERROR_NAME = "SyntaxError";
@@ -10,6 +10,31 @@ export const DECISION_BLOCK = 'block';
10
10
  export const ALLOW = Object.freeze({ decision: DECISION_ALLOW });
11
11
  /** Local cache file under the data directory. */
12
12
  export const ENFORCEMENT_CACHE_FILE_NAME = 'enforcement-cache.json';
13
+ /**
14
+ * The enforcement breaker's file, in the identity's state directory beside the
15
+ * delivery breaker and never the same file: an outage on one path is not an
16
+ * outage on the other, and the two are tripped by different signals. Suffixed
17
+ * with a digest of the decision URL, because what the breaker records is that
18
+ * one endpoint did not answer.
19
+ */
20
+ export const ENFORCEMENT_COOLDOWN_FILE_PREFIX = 'enforcement-cooldown-';
21
+ export const ENFORCEMENT_COOLDOWN_FILE_SUFFIX = '.json';
22
+ export const ENFORCEMENT_COOLDOWN_URL_CHARS = 12;
23
+ /**
24
+ * How long turns skip the check after the platform failed to answer one: 30 s.
25
+ *
26
+ * Only a submitted prompt asks, so this is measured against how often a person
27
+ * presses enter. Inside the 5 s window it would expire between almost every pair
28
+ * of turns and save nothing — every turn of an outage would pay the timeout
29
+ * again, which is what `edge-resilience` §1 forbids. Longer is not free: a turn
30
+ * the breaker skips is not checked, so after a blip clears a tenant over its cap
31
+ * can run for up to this long. That is at most a turn or two at human pace, it
32
+ * is the same outcome the failed request itself already produced, and each
33
+ * skipped turn is a fail-open like any other, with the breaker as its reason.
34
+ * Half the delivery breaker's 60 s because an unchecked turn costs a
35
+ * tenant money and a late event costs nothing.
36
+ */
37
+ export const ENFORCEMENT_COOLDOWN_MS = 30_000;
13
38
  /**
14
39
  * Entries kept in the cache file.
15
40
  *
@@ -20,3 +45,34 @@ export const ENFORCEMENT_CACHE_FILE_NAME = 'enforcement-cache.json';
20
45
  export const MAX_CACHE_ENTRIES = 16;
21
46
  /** Query parameter the endpoint reads the identity from. */
22
47
  export const DEVELOPER_ID_PARAM = 'developer_id';
48
+ /** And the checkout, which is what lets a cap on a feature be judged. */
49
+ export const REPOSITORY_PARAM = 'repository';
50
+ export const BRANCH_PARAM = 'branch';
51
+ /** And the model, which is what lets a cap on one model be judged. */
52
+ export const MODEL_PARAM = 'model';
53
+ /**
54
+ * The fail-open reasons the platform accepts, for checking a value read back
55
+ * from disk before it is sent. Anything else is dropped rather than sent:
56
+ * the platform would file it as `unknown`, and a hand-edited file is not a
57
+ * reason to report anything.
58
+ */
59
+ export const FAIL_OPEN_REASONS = new Set([
60
+ 'timeout',
61
+ 'http_error',
62
+ 'network_error',
63
+ 'unreadable_response',
64
+ 'circuit_open',
65
+ // A device credential with no valid cached access token (AWT-356). Until
66
+ // the platform names it, it files it as `unknown`.
67
+ 'token_unavailable',
68
+ 'unknown'
69
+ ]);
70
+ /**
71
+ * The error names a timed-out request rejects with. `AbortSignal.timeout`
72
+ * rejects with a TimeoutError, but a body stream cancelled by that signal can
73
+ * surface as a plain AbortError depending on the runtime — and the timeout is
74
+ * the only signal this request carries, so either name means it timed out.
75
+ */
76
+ export const TIMEOUT_ERROR_NAMES = new Set(['TimeoutError', 'AbortError']);
77
+ /** The error name `JSON.parse` throws on a body that is not JSON. */
78
+ export const SYNTAX_ERROR_NAME = 'SyntaxError';
@@ -33,6 +33,18 @@ export declare class DecisionCache {
33
33
  * @param ttlMs - How long it stays usable.
34
34
  */
35
35
  write(key: string, decision: EnforcementDecision, ttlMs: number): Promise<void>;
36
+ /**
37
+ * Drop what has expired, without storing anything new.
38
+ *
39
+ * `write` was the only thing that pruned this file, and an answer the platform
40
+ * says not to keep is never written — which is every answer once a tenant sets
41
+ * a feature cap. Without this the file stops being rewritten at the moment it
42
+ * stops being added to, and the entries already in it stay on disk long past
43
+ * their expiry. Reads reject them, so nothing is decided wrongly; but each one
44
+ * holds a sentence naming a person and what they spent, which is why the file
45
+ * is 0600, and there is no reason to keep them.
46
+ */
47
+ prune(): Promise<void>;
36
48
  /**
37
49
  * Raw entries of the cache file.
38
50
  *
@@ -52,6 +64,13 @@ export declare class DecisionCache {
52
64
  * @param url - The decision endpoint.
53
65
  * @param token - Edge token the question is asked with.
54
66
  * @param developerId - Identity the question is about.
67
+ * @param checkout - Where the turn is happening, when the caller could say.
68
+ * @param checkout.repository - Canonical remote of that checkout.
69
+ * @param checkout.branch - Its checked-out branch.
70
+ * @param model - The model stated on the question, when one was stated.
55
71
  * @returns The key.
56
72
  */
57
- export declare function decisionKey(url: string, token: string, developerId: string): string;
73
+ export declare function decisionKey(url: string, token: string, developerId: string, checkout?: {
74
+ repository: string;
75
+ branch: string;
76
+ }, model?: string): string;
@@ -1,4 +1,5 @@
1
1
  import crypto from 'node:crypto';
2
+ import fs from 'node:fs/promises';
2
3
  import { asRecord } from '../core/object.js';
3
4
  import { writeFileAtomic } from '../storage/atomic-file.js';
4
5
  import { SECRET_FILE_MODE } from '../storage/constants/storage.constants.js';
@@ -57,6 +58,31 @@ export class DecisionCache {
57
58
  // its answer and the next hook simply asks again.
58
59
  }
59
60
  }
61
+ /**
62
+ * Drop what has expired, without storing anything new.
63
+ *
64
+ * `write` was the only thing that pruned this file, and an answer the platform
65
+ * says not to keep is never written — which is every answer once a tenant sets
66
+ * a feature cap. Without this the file stops being rewritten at the moment it
67
+ * stops being added to, and the entries already in it stay on disk long past
68
+ * their expiry. Reads reject them, so nothing is decided wrongly; but each one
69
+ * holds a sentence naming a person and what they spent, which is why the file
70
+ * is 0600, and there is no reason to keep them.
71
+ */
72
+ async prune() {
73
+ const at = this.now().getTime();
74
+ const live = liveEntries(await this.entries(), at);
75
+ try {
76
+ if (Object.keys(live).length === 0) {
77
+ await fs.rm(this.file, { force: true });
78
+ return;
79
+ }
80
+ await writeFileAtomic(this.file, JSON.stringify(bounded(live)), SECRET_FILE_MODE);
81
+ }
82
+ catch {
83
+ // Housekeeping. A file that cannot be tidied is still a correct cache.
84
+ }
85
+ }
60
86
  /**
61
87
  * Raw entries of the cache file.
62
88
  *
@@ -81,10 +107,47 @@ export class DecisionCache {
81
107
  * @param url - The decision endpoint.
82
108
  * @param token - Edge token the question is asked with.
83
109
  * @param developerId - Identity the question is about.
110
+ * @param checkout - Where the turn is happening, when the caller could say.
111
+ * @param checkout.repository - Canonical remote of that checkout.
112
+ * @param checkout.branch - Its checked-out branch.
113
+ * @param model - The model stated on the question, when one was stated.
84
114
  * @returns The key.
85
115
  */
86
- export function decisionKey(url, token, developerId) {
87
- return crypto.createHash('sha256').update(`${url}|${token}|${developerId}`).digest('hex');
116
+ export function decisionKey(url, token, developerId, checkout, model) {
117
+ // The checkout is part of the question, so it is part of the key. Left out, an
118
+ // answer earned on one branch is served on another for as long as the entry
119
+ // lives — and it lives whenever the platform does not say otherwise, which is
120
+ // every tenant without a feature cap and every platform predating the field.
121
+ // A cache whose correctness depends on the server remembering to disable it is
122
+ // not correct.
123
+ const scope = checkout ? `${separable(checkout.repository)}|${separable(checkout.branch)}` : '';
124
+ // The same argument for the model: an answer is about one model, so a prompt on
125
+ // another must not be served it. Appended only when there is one, so a
126
+ // collector that states no model keeps the key it had before this field —
127
+ // including the entries an earlier version of it wrote.
128
+ const stated = model ? `|${separable(model)}` : '';
129
+ return crypto
130
+ .createHash('sha256')
131
+ .update(`${url}|${token}|${developerId}|${scope}${stated}`)
132
+ .digest('hex');
133
+ }
134
+ /**
135
+ * One component of the key, unable to look like two.
136
+ *
137
+ * `|` is legal in a git ref name, so joined raw a branch called `main|opus`
138
+ * stating no model composes exactly what branch `main` stating model `opus`
139
+ * composes — and one question's cached answer is served for the other, which is
140
+ * the failure the join exists to prevent.
141
+ *
142
+ * Only the separator is escaped, and only where it appears. Every ordinary
143
+ * repository, branch and model contains none, so their keys are byte-identical
144
+ * to the ones already on disk: closing this costs no collector a cold cache.
145
+ *
146
+ * @param value - A component about to be joined.
147
+ * @returns The component with any separator made unambiguous.
148
+ */
149
+ function separable(value) {
150
+ return value.replaceAll('|', '%7C');
88
151
  }
89
152
  /**
90
153
  * One entry, if it both validates and is still live.
@@ -1,14 +1,15 @@
1
- import type { AnsweredDecision, DecisionRequest } from './types/enforcement.types.js';
1
+ import type { DecisionOutcome, DecisionRequest } from './types/enforcement.types.js';
2
2
  /**
3
3
  * Ask the platform whether one developer may make an LLM call.
4
4
  *
5
- * Never throws, and answers `undefined` — "nobody said no" — for everything
6
- * that is not a complete, valid decision: a timeout, a network error, any
7
- * non-2xx status, a body that is not JSON, and a body whose decision this code
8
- * cannot read. Only the caller's own allow default gets built out of those; a
9
- * refusal can only ever come from a body that validates.
5
+ * Never throws, and answers with a fail-open reason — "nobody said no, and
6
+ * this is why" — for everything that is not a complete, valid decision: a
7
+ * timeout, a network error, any non-2xx status, a body that is not JSON, a body
8
+ * too large to be a decision, and a body whose decision this code cannot read.
9
+ * Only the caller's own allow default gets built out of those; a refusal can
10
+ * only ever come from a body that validates.
10
11
  *
11
12
  * @param request - Destination, credentials, identity and timeout.
12
- * @returns The platform's decision, or undefined when it did not give one.
13
+ * @returns The platform's decision, or the reason it did not give one.
13
14
  */
14
- export declare function requestDecision(request: DecisionRequest): Promise<AnsweredDecision | undefined>;
15
+ export declare function requestDecision(request: DecisionRequest): Promise<DecisionOutcome>;
@@ -1,18 +1,21 @@
1
1
  import { debugLog } from '../core/logger.js';
2
2
  import { edgeHeaders } from '../transport/headers.js';
3
- import { DEVELOPER_ID_PARAM } from './constants/enforcement.constants.js';
3
+ import { BODY_TOO_LARGE } from '../transport/constants/transport.constants.js';
4
+ import { discardResponseBody, readCappedJson } from '../transport/response-body.js';
5
+ import { BRANCH_PARAM, DEVELOPER_ID_PARAM, MODEL_PARAM, REPOSITORY_PARAM, SYNTAX_ERROR_NAME, TIMEOUT_ERROR_NAMES } from './constants/enforcement.constants.js';
4
6
  import { cacheTtlSchema, decisionSchema } from './schemas/enforcement.schema.js';
5
7
  /**
6
8
  * Ask the platform whether one developer may make an LLM call.
7
9
  *
8
- * Never throws, and answers `undefined` — "nobody said no" — for everything
9
- * that is not a complete, valid decision: a timeout, a network error, any
10
- * non-2xx status, a body that is not JSON, and a body whose decision this code
11
- * cannot read. Only the caller's own allow default gets built out of those; a
12
- * refusal can only ever come from a body that validates.
10
+ * Never throws, and answers with a fail-open reason — "nobody said no, and
11
+ * this is why" — for everything that is not a complete, valid decision: a
12
+ * timeout, a network error, any non-2xx status, a body that is not JSON, a body
13
+ * too large to be a decision, and a body whose decision this code cannot read.
14
+ * Only the caller's own allow default gets built out of those; a refusal can
15
+ * only ever come from a body that validates.
13
16
  *
14
17
  * @param request - Destination, credentials, identity and timeout.
15
- * @returns The platform's decision, or undefined when it did not give one.
18
+ * @returns The platform's decision, or the reason it did not give one.
16
19
  */
17
20
  export async function requestDecision(request) {
18
21
  const fetchFn = request.fetchFn ?? fetch;
@@ -22,21 +25,46 @@ export async function requestDecision(request) {
22
25
  // A GET carries no body, so no content type: the identifying triple is all
23
26
  // the platform needs to resolve the tenant.
24
27
  headers: edgeHeaders(request.token, request.installationId),
28
+ // The identity travels in the headers, so a redirect would hand the
29
+ // bearer to somewhere nothing configured.
30
+ redirect: 'error',
25
31
  signal: AbortSignal.timeout(request.timeoutMs)
26
32
  });
27
33
  if (!response.ok) {
34
+ discardResponseBody(response);
28
35
  debugLog(`enforcement: HTTP ${response.status}; allowing`);
29
- return undefined;
36
+ return { failOpenReason: 'http_error' };
30
37
  }
31
- return readDecision(await response.json());
38
+ return readDecision(await readCappedJson(response));
32
39
  }
33
40
  catch (error) {
34
- // Never log the response body: the message names a person and what they
35
- // spent, and this line goes to the developer's terminal.
36
- debugLog('enforcement: check failed; allowing:', error.name || 'network error');
37
- return undefined;
41
+ const reason = thrownReason(error);
42
+ // Never log or report the response body: the message names a person and
43
+ // what they spent, and this line goes to the developer's terminal.
44
+ debugLog('enforcement: check failed; allowing:', reason);
45
+ return { failOpenReason: reason };
38
46
  }
39
47
  }
48
+ /**
49
+ * The category of a failure that threw, and nothing else about it.
50
+ *
51
+ * The timeout covers the body read too, so a slow body is a timeout. A body
52
+ * that is not JSON, or too large to be a decision, is unreadable. Everything
53
+ * else — refused, reset, DNS, a redirect the request forbids — is the network.
54
+ *
55
+ * @param error - Whatever was thrown.
56
+ * @returns The reason to report.
57
+ */
58
+ function thrownReason(error) {
59
+ // By shape, not by class: the timeout is a DOMException, and a fetch
60
+ // injected by a test or a polyfill need not share this realm's Error.
61
+ const thrown = typeof error === 'object' && error !== null ? error : {};
62
+ if (thrown.name !== undefined && TIMEOUT_ERROR_NAMES.has(thrown.name))
63
+ return 'timeout';
64
+ if (thrown.name === SYNTAX_ERROR_NAME || thrown.message === BODY_TOO_LARGE)
65
+ return 'unreadable_response';
66
+ return 'network_error';
67
+ }
40
68
  /**
41
69
  * The endpoint with the identity attached.
42
70
  *
@@ -46,21 +74,39 @@ export async function requestDecision(request) {
46
74
  function decisionUrl(request) {
47
75
  const url = new URL(request.url);
48
76
  url.searchParams.set(DEVELOPER_ID_PARAM, request.developerId);
77
+ // Both or neither. The platform drops a half-stated pair, so sending one half
78
+ // would only cost the request a parameter nobody reads.
79
+ if (request.checkout) {
80
+ url.searchParams.set(REPOSITORY_PARAM, request.checkout.repository);
81
+ url.searchParams.set(BRANCH_PARAM, request.checkout.branch);
82
+ }
83
+ // Only when there is one. A collector that never learned its model asks the
84
+ // question it asked before this parameter existed, byte for byte.
85
+ if (request.model) {
86
+ url.searchParams.set(MODEL_PARAM, request.model);
87
+ // Named in the debug log because a cap is defined against the spelling the
88
+ // platform sees in reported usage, and a model stated under a different
89
+ // spelling matches no cap — which is indistinguishable, from the answer
90
+ // alone, from a model nobody capped. This line is what makes the difference
91
+ // visible. A model id is not content; nothing else about the request is
92
+ // logged.
93
+ debugLog('enforcement: asking about model', request.model);
94
+ }
49
95
  return url.toString();
50
96
  }
51
97
  /**
52
98
  * A decoded body, if it is a decision at all.
53
99
  *
54
100
  * @param body - Whatever the endpoint returned.
55
- * @returns The decision, or undefined when the body is not one.
101
+ * @returns The decision, or the reason when the body is not one.
56
102
  */
57
103
  function readDecision(body) {
58
104
  const parsed = decisionSchema.safeParse(body);
59
105
  if (!parsed.success) {
60
106
  debugLog('enforcement: unreadable decision; allowing');
61
- return undefined;
107
+ return { failOpenReason: 'unreadable_response' };
62
108
  }
63
- return { ...parsed.data, cacheTtlMs: readCacheTtlMs(body) };
109
+ return { answered: { ...parsed.data, cacheTtlMs: readCacheTtlMs(body) } };
64
110
  }
65
111
  /**
66
112
  * How long the platform asked this answer to be kept, when it asked usably.
@@ -1,4 +1,5 @@
1
- import type { EnforcementDecision, EnforcementOptions } from './types/enforcement.types.js';
1
+ import type { AgentWatchConfig } from '../config/types/config.types.js';
2
+ import type { EnforcementOptions, GateDecision } from './types/enforcement.types.js';
2
3
  /**
3
4
  * Whether this developer may start a turn right now.
4
5
  *
@@ -9,9 +10,29 @@ import type { EnforcementDecision, EnforcementOptions } from './types/enforcemen
9
10
  * front of every developer's tooling, so a check that failed closed would turn
10
11
  * an alerts-service hiccup into an outage for a whole engineering organization.
11
12
  *
13
+ * An allow that exists only because nothing answered carries the reason, so
14
+ * the turn it lets through can say it ran unchecked. An allow because nothing
15
+ * was asked carries none: there was no check to fail.
16
+ *
12
17
  * Never throws: a caller on the hook path has to answer the agent either way.
13
18
  *
14
19
  * @param options - Effective config, paths, the identity to ask about, clock.
15
20
  * @returns The decision to act on.
16
21
  */
17
- export declare function resolveEnforcement(options: EnforcementOptions): Promise<EnforcementDecision>;
22
+ export declare function resolveEnforcement(options: EnforcementOptions): Promise<GateDecision>;
23
+ /**
24
+ * Whether a decision would be asked for at all, from configuration alone.
25
+ *
26
+ * Exported because the caller has to know before it pays for anything the
27
+ * question needs. Working out where a prompt is happening costs a walk of the
28
+ * working copy and, on a cold checkout, a git process; spending that on a
29
+ * machine that will not ask is the one cost this feature must not add to the
30
+ * gate.
31
+ *
32
+ * Identity is not part of it: resolving that is the caller's own decision, and
33
+ * it is already paid for elsewhere.
34
+ *
35
+ * @param config - Effective configuration.
36
+ * @returns True when a configured, enabled check would reach the platform.
37
+ */
38
+ export declare function enforcementWouldAsk(config: AgentWatchConfig): boolean;