@agentic-sdlc-kit/cli 0.0.0-stage → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (309) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +32 -2
  3. package/dist/application/agent/execution-store.d.ts +55 -0
  4. package/dist/application/agent/execution-store.d.ts.map +1 -0
  5. package/dist/application/agent/execution-store.js +91 -0
  6. package/dist/application/agent/execution-store.js.map +1 -0
  7. package/dist/application/agent/gateway.d.ts +74 -0
  8. package/dist/application/agent/gateway.d.ts.map +1 -0
  9. package/dist/application/agent/gateway.js +580 -0
  10. package/dist/application/agent/gateway.js.map +1 -0
  11. package/dist/application/agent/index.d.ts +6 -0
  12. package/dist/application/agent/index.d.ts.map +1 -0
  13. package/dist/application/agent/index.js +18 -0
  14. package/dist/application/agent/index.js.map +1 -0
  15. package/dist/application/agent/orchestrator.d.ts +76 -0
  16. package/dist/application/agent/orchestrator.d.ts.map +1 -0
  17. package/dist/application/agent/orchestrator.js +422 -0
  18. package/dist/application/agent/orchestrator.js.map +1 -0
  19. package/dist/application/agent/providers/claude-code/claude-argv.d.ts +15 -0
  20. package/dist/application/agent/providers/claude-code/claude-argv.d.ts.map +1 -0
  21. package/dist/application/agent/providers/claude-code/claude-argv.js +98 -0
  22. package/dist/application/agent/providers/claude-code/claude-argv.js.map +1 -0
  23. package/dist/application/agent/providers/claude-code/index.d.ts +7 -0
  24. package/dist/application/agent/providers/claude-code/index.d.ts.map +1 -0
  25. package/dist/application/agent/providers/claude-code/index.js +13 -0
  26. package/dist/application/agent/providers/claude-code/index.js.map +1 -0
  27. package/dist/application/agent/providers/claude-code/mod-parity.d.ts +15 -0
  28. package/dist/application/agent/providers/claude-code/mod-parity.d.ts.map +1 -0
  29. package/dist/application/agent/providers/claude-code/mod-parity.js +41 -0
  30. package/dist/application/agent/providers/claude-code/mod-parity.js.map +1 -0
  31. package/dist/application/agent/providers/claude-code/permission-config.d.ts +59 -0
  32. package/dist/application/agent/providers/claude-code/permission-config.d.ts.map +1 -0
  33. package/dist/application/agent/providers/claude-code/permission-config.js +189 -0
  34. package/dist/application/agent/providers/claude-code/permission-config.js.map +1 -0
  35. package/dist/application/agent/providers/claude-code/provider.d.ts +38 -0
  36. package/dist/application/agent/providers/claude-code/provider.d.ts.map +1 -0
  37. package/dist/application/agent/providers/claude-code/provider.js +577 -0
  38. package/dist/application/agent/providers/claude-code/provider.js.map +1 -0
  39. package/dist/application/agent/providers/claude-code/resume-store.d.ts +25 -0
  40. package/dist/application/agent/providers/claude-code/resume-store.d.ts.map +1 -0
  41. package/dist/application/agent/providers/claude-code/resume-store.js +120 -0
  42. package/dist/application/agent/providers/claude-code/resume-store.js.map +1 -0
  43. package/dist/application/agent/providers/claude-code/stream-parser.d.ts +50 -0
  44. package/dist/application/agent/providers/claude-code/stream-parser.d.ts.map +1 -0
  45. package/dist/application/agent/providers/claude-code/stream-parser.js +129 -0
  46. package/dist/application/agent/providers/claude-code/stream-parser.js.map +1 -0
  47. package/dist/application/agent/test-fixture.d.ts +15 -0
  48. package/dist/application/agent/test-fixture.d.ts.map +1 -0
  49. package/dist/application/agent/test-fixture.js +93 -0
  50. package/dist/application/agent/test-fixture.js.map +1 -0
  51. package/dist/application/agent/workspace.d.ts +24 -0
  52. package/dist/application/agent/workspace.d.ts.map +1 -0
  53. package/dist/application/agent/workspace.js +139 -0
  54. package/dist/application/agent/workspace.js.map +1 -0
  55. package/dist/application/dispatcher.d.ts +13 -0
  56. package/dist/application/dispatcher.d.ts.map +1 -0
  57. package/dist/application/dispatcher.js +116 -0
  58. package/dist/application/dispatcher.js.map +1 -0
  59. package/dist/application/index.d.ts +5 -0
  60. package/dist/application/index.d.ts.map +1 -0
  61. package/dist/application/index.js +6 -0
  62. package/dist/application/index.js.map +1 -0
  63. package/dist/application/registry.d.ts +8 -0
  64. package/dist/application/registry.d.ts.map +1 -0
  65. package/dist/application/registry.js +17 -0
  66. package/dist/application/registry.js.map +1 -0
  67. package/dist/application/version.d.ts +2 -0
  68. package/dist/application/version.d.ts.map +1 -0
  69. package/dist/application/version.js +7 -0
  70. package/dist/application/version.js.map +1 -0
  71. package/dist/commands/attach-exclude.d.ts +8 -0
  72. package/dist/commands/attach-exclude.d.ts.map +1 -0
  73. package/dist/commands/attach-exclude.js +48 -0
  74. package/dist/commands/attach-exclude.js.map +1 -0
  75. package/dist/commands/attach-git.d.ts +11 -0
  76. package/dist/commands/attach-git.d.ts.map +1 -0
  77. package/dist/commands/attach-git.js +40 -0
  78. package/dist/commands/attach-git.js.map +1 -0
  79. package/dist/commands/attach-store.d.ts +10 -0
  80. package/dist/commands/attach-store.d.ts.map +1 -0
  81. package/dist/commands/attach-store.js +107 -0
  82. package/dist/commands/attach-store.js.map +1 -0
  83. package/dist/commands/attach.d.ts +8 -0
  84. package/dist/commands/attach.d.ts.map +1 -0
  85. package/dist/commands/attach.js +124 -0
  86. package/dist/commands/attach.js.map +1 -0
  87. package/dist/commands/doctor.d.ts +3 -0
  88. package/dist/commands/doctor.d.ts.map +1 -0
  89. package/dist/commands/doctor.js +68 -0
  90. package/dist/commands/doctor.js.map +1 -0
  91. package/dist/commands/elicit.d.ts +3 -0
  92. package/dist/commands/elicit.d.ts.map +1 -0
  93. package/dist/commands/elicit.js +163 -0
  94. package/dist/commands/elicit.js.map +1 -0
  95. package/dist/commands/evolve.d.ts +3 -0
  96. package/dist/commands/evolve.d.ts.map +1 -0
  97. package/dist/commands/evolve.js +165 -0
  98. package/dist/commands/evolve.js.map +1 -0
  99. package/dist/commands/feature.d.ts +13 -0
  100. package/dist/commands/feature.d.ts.map +1 -0
  101. package/dist/commands/feature.js +326 -0
  102. package/dist/commands/feature.js.map +1 -0
  103. package/dist/commands/fix.d.ts +4 -0
  104. package/dist/commands/fix.d.ts.map +1 -0
  105. package/dist/commands/fix.js +53 -0
  106. package/dist/commands/fix.js.map +1 -0
  107. package/dist/commands/help.d.ts +4 -0
  108. package/dist/commands/help.d.ts.map +1 -0
  109. package/dist/commands/help.js +32 -0
  110. package/dist/commands/help.js.map +1 -0
  111. package/dist/commands/host-apply.d.ts +12 -0
  112. package/dist/commands/host-apply.d.ts.map +1 -0
  113. package/dist/commands/host-apply.js +43 -0
  114. package/dist/commands/host-apply.js.map +1 -0
  115. package/dist/commands/host.d.ts +3 -0
  116. package/dist/commands/host.d.ts.map +1 -0
  117. package/dist/commands/host.js +107 -0
  118. package/dist/commands/host.js.map +1 -0
  119. package/dist/commands/index.d.ts +25 -0
  120. package/dist/commands/index.d.ts.map +1 -0
  121. package/dist/commands/index.js +26 -0
  122. package/dist/commands/index.js.map +1 -0
  123. package/dist/commands/init.d.ts +3 -0
  124. package/dist/commands/init.d.ts.map +1 -0
  125. package/dist/commands/init.js +92 -0
  126. package/dist/commands/init.js.map +1 -0
  127. package/dist/commands/inspect.d.ts +3 -0
  128. package/dist/commands/inspect.d.ts.map +1 -0
  129. package/dist/commands/inspect.js +64 -0
  130. package/dist/commands/inspect.js.map +1 -0
  131. package/dist/commands/install.d.ts +3 -0
  132. package/dist/commands/install.d.ts.map +1 -0
  133. package/dist/commands/install.js +337 -0
  134. package/dist/commands/install.js.map +1 -0
  135. package/dist/commands/journal.d.ts +3 -0
  136. package/dist/commands/journal.d.ts.map +1 -0
  137. package/dist/commands/journal.js +107 -0
  138. package/dist/commands/journal.js.map +1 -0
  139. package/dist/commands/memory.d.ts +3 -0
  140. package/dist/commands/memory.d.ts.map +1 -0
  141. package/dist/commands/memory.js +85 -0
  142. package/dist/commands/memory.js.map +1 -0
  143. package/dist/commands/new.d.ts +3 -0
  144. package/dist/commands/new.d.ts.map +1 -0
  145. package/dist/commands/new.js +68 -0
  146. package/dist/commands/new.js.map +1 -0
  147. package/dist/commands/next.d.ts +3 -0
  148. package/dist/commands/next.d.ts.map +1 -0
  149. package/dist/commands/next.js +107 -0
  150. package/dist/commands/next.js.map +1 -0
  151. package/dist/commands/optimize.d.ts +3 -0
  152. package/dist/commands/optimize.d.ts.map +1 -0
  153. package/dist/commands/optimize.js +28 -0
  154. package/dist/commands/optimize.js.map +1 -0
  155. package/dist/commands/plugin-linker.d.ts +43 -0
  156. package/dist/commands/plugin-linker.d.ts.map +1 -0
  157. package/dist/commands/plugin-linker.js +216 -0
  158. package/dist/commands/plugin-linker.js.map +1 -0
  159. package/dist/commands/refactor.d.ts +3 -0
  160. package/dist/commands/refactor.d.ts.map +1 -0
  161. package/dist/commands/refactor.js +32 -0
  162. package/dist/commands/refactor.js.map +1 -0
  163. package/dist/commands/skills-install-commit.d.ts +34 -0
  164. package/dist/commands/skills-install-commit.d.ts.map +1 -0
  165. package/dist/commands/skills-install-commit.js +113 -0
  166. package/dist/commands/skills-install-commit.js.map +1 -0
  167. package/dist/commands/skills-install-manifest.d.ts +35 -0
  168. package/dist/commands/skills-install-manifest.d.ts.map +1 -0
  169. package/dist/commands/skills-install-manifest.js +89 -0
  170. package/dist/commands/skills-install-manifest.js.map +1 -0
  171. package/dist/commands/skills-install-report.d.ts +12 -0
  172. package/dist/commands/skills-install-report.d.ts.map +1 -0
  173. package/dist/commands/skills-install-report.js +44 -0
  174. package/dist/commands/skills-install-report.js.map +1 -0
  175. package/dist/commands/skills-install-secure.d.ts +14 -0
  176. package/dist/commands/skills-install-secure.d.ts.map +1 -0
  177. package/dist/commands/skills-install-secure.js +96 -0
  178. package/dist/commands/skills-install-secure.js.map +1 -0
  179. package/dist/commands/skills-install.d.ts +15 -0
  180. package/dist/commands/skills-install.d.ts.map +1 -0
  181. package/dist/commands/skills-install.js +182 -0
  182. package/dist/commands/skills-install.js.map +1 -0
  183. package/dist/commands/skills.d.ts +3 -0
  184. package/dist/commands/skills.d.ts.map +1 -0
  185. package/dist/commands/skills.js +217 -0
  186. package/dist/commands/skills.js.map +1 -0
  187. package/dist/commands/types.d.ts +19 -0
  188. package/dist/commands/types.d.ts.map +1 -0
  189. package/dist/commands/types.js +7 -0
  190. package/dist/commands/types.js.map +1 -0
  191. package/dist/commands/uninstall.d.ts +3 -0
  192. package/dist/commands/uninstall.d.ts.map +1 -0
  193. package/dist/commands/uninstall.js +113 -0
  194. package/dist/commands/uninstall.js.map +1 -0
  195. package/dist/commands/validate-plan.d.ts +3 -0
  196. package/dist/commands/validate-plan.d.ts.map +1 -0
  197. package/dist/commands/validate-plan.js +62 -0
  198. package/dist/commands/validate-plan.js.map +1 -0
  199. package/dist/commands/validate-spec.d.ts +3 -0
  200. package/dist/commands/validate-spec.d.ts.map +1 -0
  201. package/dist/commands/validate-spec.js +62 -0
  202. package/dist/commands/validate-spec.js.map +1 -0
  203. package/dist/commands/verify.d.ts +3 -0
  204. package/dist/commands/verify.d.ts.map +1 -0
  205. package/dist/commands/verify.js +103 -0
  206. package/dist/commands/verify.js.map +1 -0
  207. package/dist/commands/version.d.ts +3 -0
  208. package/dist/commands/version.d.ts.map +1 -0
  209. package/dist/commands/version.js +12 -0
  210. package/dist/commands/version.js.map +1 -0
  211. package/dist/index.d.ts +3 -0
  212. package/dist/index.d.ts.map +1 -0
  213. package/dist/index.js +27 -0
  214. package/dist/index.js.map +1 -0
  215. package/dist/output/formatter.d.ts +2 -0
  216. package/dist/output/formatter.d.ts.map +1 -0
  217. package/dist/output/formatter.js +10 -0
  218. package/dist/output/formatter.js.map +1 -0
  219. package/dist/output/index.d.ts +2 -0
  220. package/dist/output/index.d.ts.map +1 -0
  221. package/dist/output/index.js +3 -0
  222. package/dist/output/index.js.map +1 -0
  223. package/package.json +37 -3
  224. package/src/application/agent/execution-store.ts +163 -0
  225. package/src/application/agent/gateway.test.ts +529 -0
  226. package/src/application/agent/gateway.ts +744 -0
  227. package/src/application/agent/index.ts +18 -0
  228. package/src/application/agent/orchestrator.test.ts +341 -0
  229. package/src/application/agent/orchestrator.ts +629 -0
  230. package/src/application/agent/providers/claude-code/claude-argv.ts +119 -0
  231. package/src/application/agent/providers/claude-code/claude-code-smoke.test.ts +139 -0
  232. package/src/application/agent/providers/claude-code/fixtures/fake-claude.mjs +125 -0
  233. package/src/application/agent/providers/claude-code/index.ts +28 -0
  234. package/src/application/agent/providers/claude-code/mod-parity.ts +50 -0
  235. package/src/application/agent/providers/claude-code/permission-config.test.ts +221 -0
  236. package/src/application/agent/providers/claude-code/permission-config.ts +242 -0
  237. package/src/application/agent/providers/claude-code/provider.test.ts +378 -0
  238. package/src/application/agent/providers/claude-code/provider.ts +717 -0
  239. package/src/application/agent/providers/claude-code/resume-store.test.ts +161 -0
  240. package/src/application/agent/providers/claude-code/resume-store.ts +157 -0
  241. package/src/application/agent/providers/claude-code/stream-parser.ts +166 -0
  242. package/src/application/agent/test-fixture.ts +131 -0
  243. package/src/application/agent/workspace.test.ts +104 -0
  244. package/src/application/agent/workspace.ts +156 -0
  245. package/src/application/dispatcher.test.ts +108 -0
  246. package/src/application/dispatcher.ts +106 -0
  247. package/src/application/index.ts +5 -0
  248. package/src/application/registry.ts +24 -0
  249. package/src/application/version.ts +7 -0
  250. package/src/commands/attach-exclude.ts +50 -0
  251. package/src/commands/attach-git.ts +50 -0
  252. package/src/commands/attach-store.ts +107 -0
  253. package/src/commands/attach.test.ts +192 -0
  254. package/src/commands/attach.ts +143 -0
  255. package/src/commands/clse.test.ts +181 -0
  256. package/src/commands/doctor.test.ts +29 -0
  257. package/src/commands/doctor.ts +78 -0
  258. package/src/commands/elicit.test.ts +111 -0
  259. package/src/commands/elicit.ts +188 -0
  260. package/src/commands/evolve.ts +209 -0
  261. package/src/commands/feature.test.ts +323 -0
  262. package/src/commands/feature.ts +405 -0
  263. package/src/commands/fix.test.ts +118 -0
  264. package/src/commands/fix.ts +58 -0
  265. package/src/commands/help.test.ts +33 -0
  266. package/src/commands/help.ts +35 -0
  267. package/src/commands/host-apply.ts +61 -0
  268. package/src/commands/host.test.ts +120 -0
  269. package/src/commands/host.ts +125 -0
  270. package/src/commands/index.ts +25 -0
  271. package/src/commands/init.test.ts +87 -0
  272. package/src/commands/init.ts +110 -0
  273. package/src/commands/inspect.test.ts +57 -0
  274. package/src/commands/inspect.ts +73 -0
  275. package/src/commands/install.test.ts +92 -0
  276. package/src/commands/install.ts +389 -0
  277. package/src/commands/journal.ts +118 -0
  278. package/src/commands/memory.ts +96 -0
  279. package/src/commands/new.test.ts +44 -0
  280. package/src/commands/new.ts +77 -0
  281. package/src/commands/next.test.ts +241 -0
  282. package/src/commands/next.ts +124 -0
  283. package/src/commands/optimize.ts +30 -0
  284. package/src/commands/plugin-linker.test.ts +219 -0
  285. package/src/commands/plugin-linker.ts +244 -0
  286. package/src/commands/refactor.ts +34 -0
  287. package/src/commands/skills-install-commit.ts +149 -0
  288. package/src/commands/skills-install-manifest.ts +124 -0
  289. package/src/commands/skills-install-report.ts +60 -0
  290. package/src/commands/skills-install-secure.ts +113 -0
  291. package/src/commands/skills-install.ts +245 -0
  292. package/src/commands/skills.test.ts +449 -0
  293. package/src/commands/skills.ts +247 -0
  294. package/src/commands/stack-commands.test.ts +67 -0
  295. package/src/commands/tier-c-conformance.test.ts +194 -0
  296. package/src/commands/types.ts +26 -0
  297. package/src/commands/uninstall.test.ts +122 -0
  298. package/src/commands/uninstall.ts +116 -0
  299. package/src/commands/validate-plan.test.ts +107 -0
  300. package/src/commands/validate-plan.ts +67 -0
  301. package/src/commands/validate-spec.test.ts +59 -0
  302. package/src/commands/validate-spec.ts +68 -0
  303. package/src/commands/verify.test.ts +117 -0
  304. package/src/commands/verify.ts +112 -0
  305. package/src/commands/version.test.ts +11 -0
  306. package/src/commands/version.ts +14 -0
  307. package/src/index.ts +30 -0
  308. package/src/output/formatter.ts +10 -0
  309. package/src/output/index.ts +2 -0
@@ -0,0 +1,744 @@
1
+ // packages/cli/src/application/agent/gateway.ts
2
+ //
3
+ // Agent gateway (ADR-0019 v2 revision A + §4, PR3). The gateway sits
4
+ // between the orchestrator and every AgentProvider and owns everything
5
+ // durable about an execution:
6
+ //
7
+ // - the ORIGINAL request, frozen and persisted BEFORE the provider is
8
+ // called, so it can never drift between attempts (revision A);
9
+ // - the canonical policy snapshot the execution was granted under, and
10
+ // its hash — every event must echo it or be rejected (fail closed,
11
+ // ADR-0020 §4);
12
+ // - the event stream, persisted idempotently (dedupe on eventId) with
13
+ // an audit trail of rejections and sequence anomalies (revision D);
14
+ // - the final result, validated for correlation before it is trusted;
15
+ // - gateway-enforced bounds the gateway can always keep: duration
16
+ // (it owns the abort signal and cancels the provider) and tool-call
17
+ // count (counted from tool.requested events). Exceeding an enforced
18
+ // bound is a terminal outcome, never silent continuation.
19
+ //
20
+ // Providers are INJECTED. The shipped CLI registers none, so
21
+ // `kit feature <id> run` fails with AGENT_PROVIDER_NOT_CONFIGURED until a
22
+ // provider is configured (PR4 adds claude-code). Embedding code (tests,
23
+ // tooling) constructs the gateway with its own provider list.
24
+ //
25
+ // SECURITY: resume tokens are credentials (ADR-0020 §6). The gateway
26
+ // holds them in memory only and never writes them to the execution
27
+ // record. `resume(executionId, token)` is addressed by the persisted
28
+ // execution id; the original request is NEVER re-submitted to the
29
+ // provider on resume.
30
+
31
+ import {
32
+ AgentExecutionEventSchema,
33
+ AgentExecutionRequestSchema,
34
+ AgentExecutionResultSchema,
35
+ Errors,
36
+ computePolicyHash,
37
+ type AgentEventSink,
38
+ type AgentExecutionHandle,
39
+ type AgentExecutionRequest,
40
+ type AgentExecutionResult,
41
+ type AgentPolicySnapshot,
42
+ type AgentProvider,
43
+ type AgentProviderCapabilities,
44
+ type AgentProviderId,
45
+ type ExecutionBudget,
46
+ type KitError,
47
+ type Result,
48
+ } from '@agentic-sdlc-kit/contracts';
49
+ import {
50
+ listExecutionIds,
51
+ loadExecution,
52
+ saveExecution,
53
+ type EventAuditKind,
54
+ type EventAuditNote,
55
+ type StoredAgentExecution,
56
+ } from './execution-store.js';
57
+
58
+ export interface AgentGatewayOptions {
59
+ /** Providers this gateway can dispatch to. Empty = nothing configured. */
60
+ readonly providers: ReadonlyArray<AgentProvider>;
61
+ /** Project root; execution records persist under .ai-kit/state/. */
62
+ readonly projectRoot: string;
63
+ /** Injectable clock for deterministic tests. */
64
+ readonly now?: () => Date;
65
+ /** Bounded drain window after a cancel/timeout before the gateway concludes (default 5s). */
66
+ readonly drainMs?: number;
67
+ }
68
+
69
+ export interface StartExecutionOptions {
70
+ /**
71
+ * The canonical policy snapshot freezing what this execution may do.
72
+ * Must equal the request's inline permissions/budget/approvalPolicy,
73
+ * and request.policyHash must be computePolicyHash(snapshot).
74
+ */
75
+ readonly policySnapshot: AgentPolicySnapshot;
76
+ /** External cancellation (SIGINT, orchestrator shutdown). */
77
+ readonly signal?: AbortSignal;
78
+ }
79
+
80
+ /** How long to wait for the provider to land its result after the gateway cancels. */
81
+ const DEFAULT_CANCEL_DRAIN_MS = 5_000;
82
+
83
+ export class AgentGateway {
84
+ private readonly providers: Map<AgentProviderId, AgentProvider>;
85
+ private readonly projectRoot: string;
86
+ private readonly now: () => Date;
87
+ private readonly drainMs: number;
88
+ /** Resume tokens, held in memory ONLY (never persisted). */
89
+ private readonly resumeTokens = new Map<string, string>();
90
+ /** In-flight execution controllers, so cancel() can reach them. */
91
+ private readonly inFlight = new Map<string, AbortController>();
92
+ /**
93
+ * Per-execution persistence queue. Event arrivals, the terminal result,
94
+ * and late drain reports all write the SAME record file; concurrent
95
+ * writes would race on the tmp file. Saves for one execution are
96
+ * strictly serialized — last enqueued state wins on disk.
97
+ */
98
+ private readonly persistQueues = new Map<string, Promise<void>>();
99
+
100
+ constructor(opts: AgentGatewayOptions) {
101
+ this.providers = new Map(opts.providers.map((p) => [p.id, p]));
102
+ this.projectRoot = opts.projectRoot;
103
+ this.now = opts.now ?? (() => new Date());
104
+ this.drainMs = opts.drainMs ?? DEFAULT_CANCEL_DRAIN_MS;
105
+ }
106
+
107
+ hasProvider(id: string): boolean {
108
+ return this.providers.has(id);
109
+ }
110
+
111
+ listProviders(): AgentProviderId[] {
112
+ return [...this.providers.keys()];
113
+ }
114
+
115
+ /** The in-memory resume token for an execution, if one was issued. */
116
+ resumeTokenFor(executionId: string): string | undefined {
117
+ return this.resumeTokens.get(executionId);
118
+ }
119
+
120
+ async start(
121
+ request: AgentExecutionRequest,
122
+ opts: StartExecutionOptions,
123
+ ): Promise<Result<StoredAgentExecution>> {
124
+ // 1. Contract validation — a malformed request never reaches a provider.
125
+ const parsed = AgentExecutionRequestSchema.safeParse(request);
126
+ if (!parsed.success) {
127
+ return {
128
+ ok: false,
129
+ error: Errors.contractInvalid(
130
+ `Agent execution request failed contract validation: ${formatIssues(parsed.error.issues)}`,
131
+ ),
132
+ };
133
+ }
134
+ const valid = parsed.data;
135
+
136
+ // 2. Provider must be configured.
137
+ const provider = this.providers.get(valid.providerId);
138
+ if (!provider) {
139
+ return {
140
+ ok: false,
141
+ error: Errors.agentProviderNotConfigured(
142
+ `No agent provider '${valid.providerId}' is configured ` +
143
+ `(registered: ${this.listProviders().join(', ') || 'none'}). ` +
144
+ `Mode 1 execution requires a provider; it will not fall back to ` +
145
+ `pretending a manual workflow completed.`,
146
+ ),
147
+ };
148
+ }
149
+
150
+ // 3. Policy chain: the snapshot is the frozen policy; the request's
151
+ // inline policy fields must match it exactly and its policyHash
152
+ // must be the hash of the snapshot. Any drift fails closed.
153
+ const policyCheck = validatePolicyChain(valid, opts.policySnapshot);
154
+ if (!policyCheck.ok) return { ok: false, error: policyCheck.error };
155
+
156
+ // 4. Provider capability + budget honesty cross-checks (rev C).
157
+ const caps = await provider.capabilities();
158
+ const capCheck = checkCapabilityGrant(valid, caps);
159
+ if (!capCheck.ok) return { ok: false, error: capCheck.error };
160
+ const budgetCheck = checkBudgetEnforceability(valid.budget, caps, provider.id);
161
+ if (!budgetCheck.ok) return { ok: false, error: budgetCheck.error };
162
+
163
+ // 5. Persist the ORIGINAL request before the provider sees it (rev A).
164
+ const createdAt = this.now().toISOString();
165
+ const execution: StoredAgentExecution = {
166
+ executionId: valid.executionId,
167
+ workflowRunId: valid.workflowRunId,
168
+ taskId: valid.taskId,
169
+ providerId: valid.providerId,
170
+ policyHash: valid.policyHash,
171
+ policySnapshot: opts.policySnapshot,
172
+ request: valid,
173
+ status: 'running',
174
+ attempts: 1,
175
+ events: [],
176
+ eventAudit: [],
177
+ gatewayNotes: [],
178
+ createdAt,
179
+ updatedAt: createdAt,
180
+ };
181
+ const persistErr = await this.persist(execution);
182
+ if (persistErr) return { ok: false, error: persistErr };
183
+
184
+ // 6. Run under the gateway's controller, which links the external
185
+ // signal and the duration budget.
186
+ const controller = new AbortController();
187
+ const onExternalAbort = () => controller.abort();
188
+ if (opts.signal) {
189
+ if (opts.signal.aborted) controller.abort();
190
+ else opts.signal.addEventListener('abort', onExternalAbort, { once: true });
191
+ }
192
+ try {
193
+ const handle = await provider.start(valid, controller.signal);
194
+ return await this.awaitSettlement(execution, handle, controller, valid.budget);
195
+ } finally {
196
+ if (opts.signal) opts.signal.removeEventListener('abort', onExternalAbort);
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Resume a persisted execution by (executionId, resumeToken). The
202
+ * original request is NOT re-submitted — the gateway already froze it
203
+ * (revision A). The token is a credential: used, never stored.
204
+ */
205
+ async resume(executionId: string, resumeToken: string): Promise<Result<StoredAgentExecution>> {
206
+ const existing = await loadExecution(this.projectRoot, executionId);
207
+ if (!existing) {
208
+ return {
209
+ ok: false,
210
+ error: Errors.contractInvalid(
211
+ `Unknown agent execution '${executionId}' — nothing to resume`,
212
+ ),
213
+ };
214
+ }
215
+ const provider = this.providers.get(existing.providerId);
216
+ if (!provider) {
217
+ return {
218
+ ok: false,
219
+ error: Errors.agentProviderNotConfigured(
220
+ `Provider '${existing.providerId}' for execution ${executionId} is not configured`,
221
+ ),
222
+ };
223
+ }
224
+ const execution: StoredAgentExecution = {
225
+ ...existing,
226
+ attempts: existing.attempts + 1,
227
+ status: 'running',
228
+ updatedAt: this.now().toISOString(),
229
+ };
230
+ const persistErr = await this.persist(execution);
231
+ if (persistErr) return { ok: false, error: persistErr };
232
+
233
+ const controller = new AbortController();
234
+ const handle = await provider.resume(executionId, resumeToken);
235
+ return await this.awaitSettlement(execution, handle, controller, execution.request.budget);
236
+ }
237
+
238
+ /** Cancel an execution (idempotent; unknown ids are an error, not a guess). */
239
+ async cancel(executionId: string): Promise<Result<StoredAgentExecution>> {
240
+ const existing = await loadExecution(this.projectRoot, executionId);
241
+ if (!existing) {
242
+ return {
243
+ ok: false,
244
+ error: Errors.contractInvalid(`Unknown agent execution '${executionId}'`),
245
+ };
246
+ }
247
+ const provider = this.providers.get(existing.providerId);
248
+ if (provider) await provider.cancel(executionId); // unknown id: no-op by contract
249
+ // Reach the in-flight execution: aborting its controller starts the
250
+ // bounded drain inside awaitSettlement, which finalizes the record.
251
+ this.inFlight.get(executionId)?.abort();
252
+ if (isTerminal(existing.status)) return { ok: true, value: existing };
253
+ const now = this.now().toISOString();
254
+ const execution: StoredAgentExecution = {
255
+ ...existing,
256
+ status: 'cancelled',
257
+ completedAt: now,
258
+ updatedAt: now,
259
+ };
260
+ const persistErr = await this.persist(execution);
261
+ if (persistErr) return { ok: false, error: persistErr };
262
+ return { ok: true, value: execution };
263
+ }
264
+
265
+ async getExecution(executionId: string): Promise<StoredAgentExecution | undefined> {
266
+ return loadExecution(this.projectRoot, executionId);
267
+ }
268
+
269
+ async listExecutions(): Promise<StoredAgentExecution[]> {
270
+ const out: StoredAgentExecution[] = [];
271
+ for (const id of await listExecutionIds(this.projectRoot)) {
272
+ const record = await loadExecution(this.projectRoot, id);
273
+ if (record) out.push(record);
274
+ }
275
+ return out;
276
+ }
277
+
278
+ // ---- internals -------------------------------------------------------
279
+
280
+ /**
281
+ * Wire a provider handle into the durable record: subscribe events,
282
+ * race the result against the duration budget, count tool calls, and
283
+ * persist the terminal state. `handle.result()` rejecting is a
284
+ * transport-level failure: the record ends `interrupted`, and the
285
+ * gateway surfaces an INTERNAL error (the provider was unreachable or
286
+ * violated the handle contract) — it is never reported as `completed`.
287
+ */
288
+ private async awaitSettlement(
289
+ initial: StoredAgentExecution,
290
+ handle: AgentExecutionHandle,
291
+ controller: AbortController,
292
+ budget: ExecutionBudget,
293
+ ): Promise<Result<StoredAgentExecution>> {
294
+ let current = initial;
295
+ let lastAcceptedSequence = 0;
296
+ let toolCalls = 0;
297
+
298
+ const sink: AgentEventSink = (event: unknown) => {
299
+ const outcome = this.acceptEvent(current, event, lastAcceptedSequence);
300
+ current = outcome.execution;
301
+ lastAcceptedSequence = outcome.lastAcceptedSequence;
302
+ if (outcome.toolCall) toolCalls += 1;
303
+ };
304
+ const unsubscribe = handle.events(sink);
305
+ this.inFlight.set(initial.executionId, controller);
306
+
307
+ type Settlement = { kind: 'result'; result: AgentExecutionResult } | { kind: 'breach' } | { kind: 'transport' };
308
+ let breachNotifier: (() => void) | undefined;
309
+ let durationBreached = false;
310
+ const breach = new Promise<void>((resolve) => {
311
+ breachNotifier = resolve;
312
+ });
313
+
314
+ const durationTimer = setTimeout(() => {
315
+ // Gateway-enforced duration: abort, cancel, then allow a bounded
316
+ // drain for the provider's own result before declaring timed_out.
317
+ durationBreached = true;
318
+ controller.abort();
319
+ void this.providers.get(current.providerId)?.cancel(current.executionId);
320
+ breachNotifier?.();
321
+ }, budget.maxDurationMs);
322
+ // Any OTHER abort (external signal, gateway.cancel) also starts the
323
+ // bounded drain: the provider gets the window to land its own result;
324
+ // if it never does, the gateway concludes cancelled.
325
+ const onAbortDrain = (): void => breachNotifier?.();
326
+ controller.signal.addEventListener('abort', onAbortDrain, { once: true });
327
+
328
+ let drainTimer: ReturnType<typeof setTimeout> | undefined;
329
+ const settlement: Settlement = await new Promise<Settlement>((resolve) => {
330
+ let settled = false;
331
+ const settle = (value: Settlement): void => {
332
+ if (settled) return;
333
+ settled = true;
334
+ clearTimeout(durationTimer);
335
+ if (drainTimer) clearTimeout(drainTimer);
336
+ resolve(value);
337
+ };
338
+ void handle
339
+ .result()
340
+ .then((result) => settle({ kind: 'result', result }))
341
+ .catch(() => settle({ kind: 'transport' }));
342
+ void breach.then(() => {
343
+ drainTimer = setTimeout(() => settle({ kind: 'breach' }), this.drainMs);
344
+ });
345
+ });
346
+ clearTimeout(durationTimer);
347
+ if (drainTimer) clearTimeout(drainTimer);
348
+ controller.signal.removeEventListener('abort', onAbortDrain);
349
+ unsubscribe();
350
+ this.inFlight.delete(initial.executionId);
351
+
352
+ if (settlement.kind === 'transport') {
353
+ return this.finalize(current, {
354
+ status: 'interrupted',
355
+ gatewayNotes: [
356
+ ...current.gatewayNotes,
357
+ 'gateway: handle.result() rejected — transport-level failure (provider unreachable or handle contract violated)',
358
+ ],
359
+ error: Errors.internal(
360
+ `Provider '${current.providerId}' transport-level failure for execution ` +
361
+ `'${current.executionId}' — recorded as interrupted, never completed`,
362
+ ),
363
+ });
364
+ }
365
+
366
+ if (settlement.kind === 'breach') {
367
+ // The provider did not land a result inside the drain window. If the
368
+ // duration budget fired, the outcome is timed_out; any other abort
369
+ // (external signal, gateway.cancel) is a cancellation. Either way it
370
+ // is terminal — a hung execution is never left "running".
371
+ const outcome: StoredAgentExecution['status'] = durationBreached ? 'timed_out' : 'cancelled';
372
+ // If the provider's own result lands after the breach, record what
373
+ // it reported verbatim; the enforced outcome stands.
374
+ void handle
375
+ .result()
376
+ .then(async (late) => {
377
+ const stored = await loadExecution(this.projectRoot, current.executionId);
378
+ if (stored && stored.status === outcome && !stored.providerReportedStatus) {
379
+ await this.persist({ ...stored, providerReportedStatus: late.status });
380
+ }
381
+ })
382
+ .catch(() => undefined);
383
+ return this.finalize(current, {
384
+ status: outcome,
385
+ gatewayNotes: [
386
+ ...current.gatewayNotes,
387
+ durationBreached
388
+ ? `gateway: duration budget of ${budget.maxDurationMs}ms exceeded (gateway-enforced; provider cancelled)`
389
+ : `gateway: execution aborted and the provider landed no result within the ${this.drainMs}ms drain window — concluded cancelled`,
390
+ ],
391
+ });
392
+ }
393
+
394
+ const rawResult = settlement.result;
395
+
396
+ // If the duration budget fired but the provider still landed a result
397
+ // inside the drain window, the enforced outcome is timed_out: the
398
+ // provider's report is kept verbatim, but a budget breach is not
399
+ // negotiable (a provider cannot out-run the gateway's clock).
400
+ if (durationBreached) {
401
+ const drained = AgentExecutionResultSchema.safeParse(rawResult);
402
+ return this.finalize(current, {
403
+ status: 'timed_out',
404
+ ...(drained.success ? { result: drained.data } : {}),
405
+ ...(drained.success ? { providerReportedStatus: drained.data.status } : {}),
406
+ gatewayNotes: [
407
+ ...current.gatewayNotes,
408
+ `gateway: duration budget of ${budget.maxDurationMs}ms exceeded (gateway-enforced; provider cancelled)`,
409
+ ...(drained.success
410
+ ? [`gateway: provider reported '${drained.data.status}' within the drain window — recorded verbatim`]
411
+ : []),
412
+ ],
413
+ });
414
+ }
415
+
416
+ // The result must parse and correlate to THIS execution.
417
+ const parsedResult = AgentExecutionResultSchema.safeParse(rawResult);
418
+ if (!parsedResult.success) {
419
+ return this.finalize(current, {
420
+ status: 'interrupted',
421
+ gatewayNotes: [
422
+ ...current.gatewayNotes,
423
+ `gateway: provider result failed contract validation: ${formatIssues(parsedResult.error.issues)}`,
424
+ ],
425
+ error: Errors.contractInvalid(
426
+ `Provider '${current.providerId}' returned an invalid result for ${current.executionId}`,
427
+ ),
428
+ });
429
+ }
430
+ const result = parsedResult.data;
431
+ if (result.executionId !== current.executionId) {
432
+ return this.finalize(current, {
433
+ status: 'interrupted',
434
+ gatewayNotes: [
435
+ ...current.gatewayNotes,
436
+ `gateway: result claims executionId '${result.executionId}' — correlation refused`,
437
+ ],
438
+ error: Errors.contractInvalid(
439
+ `Provider result for execution '${current.executionId}' claims to be for ` +
440
+ `'${result.executionId}' — refusing to trust it`,
441
+ ),
442
+ });
443
+ }
444
+
445
+ // Tool-call budget (gateway-enforced): counted from tool.requested events.
446
+ if (toolCalls > budget.maxToolCalls) {
447
+ controller.abort();
448
+ void this.providers.get(current.providerId)?.cancel(current.executionId);
449
+ return this.finalize(current, {
450
+ status: 'failed',
451
+ result,
452
+ gatewayNotes: [
453
+ ...current.gatewayNotes,
454
+ `gateway: tool-call budget of ${budget.maxToolCalls} exceeded (${toolCalls} tool calls observed)`,
455
+ ],
456
+ });
457
+ }
458
+
459
+ // A session resume token is a credential: memory only, never the record.
460
+ if (result.session?.resumeToken) {
461
+ this.resumeTokens.set(result.executionId, result.session.resumeToken);
462
+ }
463
+
464
+ return this.finalize(current, { status: result.status, result });
465
+ }
466
+
467
+ private async finalize(
468
+ current: StoredAgentExecution,
469
+ outcome: {
470
+ status: StoredAgentExecution['status'];
471
+ result?: AgentExecutionResult;
472
+ providerReportedStatus?: AgentExecutionResult['status'];
473
+ gatewayNotes?: string[];
474
+ error?: KitError;
475
+ },
476
+ ): Promise<Result<StoredAgentExecution>> {
477
+ const now = this.now().toISOString();
478
+ const final: StoredAgentExecution = {
479
+ ...current,
480
+ status: outcome.status,
481
+ // RESUME TOKENS ARE CREDENTIALS (ADR-0020 §6.8): the gateway may hold
482
+ // them in memory (this.resumeTokens) but must NEVER write them to
483
+ // the execution record. The session id is not secret and stays;
484
+ // the token is scrubbed from the persisted copy of the result. PR4
485
+ // hardening: the first real provider to issue session tokens exposed
486
+ // that the original persist path wrote the result verbatim.
487
+ ...(outcome.result !== undefined ? { result: scrubResultForDisk(outcome.result) } : {}),
488
+ ...(outcome.providerReportedStatus !== undefined
489
+ ? { providerReportedStatus: outcome.providerReportedStatus }
490
+ : {}),
491
+ ...(outcome.gatewayNotes !== undefined ? { gatewayNotes: outcome.gatewayNotes } : {}),
492
+ completedAt: now,
493
+ updatedAt: now,
494
+ };
495
+ const persistErr = await this.persist(final);
496
+ if (persistErr) return { ok: false, error: persistErr };
497
+ if (outcome.error) return { ok: false, error: outcome.error };
498
+ return { ok: true, value: final };
499
+ }
500
+
501
+ /**
502
+ * Accept-or-reject one provider event against the frozen policy chain:
503
+ * schema validity, execution correlation, policyHash echo (fail
504
+ * closed), eventId idempotency, and sequence monotonicity. Rejected
505
+ * events are audited, never silently dropped.
506
+ */
507
+ private acceptEvent(
508
+ execution: StoredAgentExecution,
509
+ rawEvent: unknown,
510
+ lastAcceptedSequence: number,
511
+ ): { execution: StoredAgentExecution; lastAcceptedSequence: number; toolCall: boolean } {
512
+ const at = this.now().toISOString();
513
+ const audit = (kind: EventAuditKind, detail: string): EventAuditNote => ({ kind, at, detail });
514
+
515
+ const parsed = AgentExecutionEventSchema.safeParse(rawEvent);
516
+ if (!parsed.success) {
517
+ return {
518
+ execution: withAudit(
519
+ execution,
520
+ audit(
521
+ 'invalid-event',
522
+ `event failed schema validation: ${JSON.stringify(rawEvent).slice(0, 160)}`,
523
+ ),
524
+ ),
525
+ lastAcceptedSequence,
526
+ toolCall: false,
527
+ };
528
+ }
529
+ const event = parsed.data;
530
+
531
+ if (event.executionId !== execution.executionId) {
532
+ return {
533
+ execution: withAudit(
534
+ execution,
535
+ audit(
536
+ 'wrong-execution-id',
537
+ `event for '${event.executionId}' arrived on '${execution.executionId}'`,
538
+ ),
539
+ ),
540
+ lastAcceptedSequence,
541
+ toolCall: false,
542
+ };
543
+ }
544
+
545
+ // Policy traceability (rev D): the echo must match the frozen hash.
546
+ if (event.policyHash !== execution.policyHash) {
547
+ return {
548
+ execution: withAudit(
549
+ execution,
550
+ audit(
551
+ 'policy-hash-mismatch',
552
+ `event ${event.eventId} echoed policyHash '${event.policyHash}' but the ` +
553
+ `execution runs under '${execution.policyHash}' — rejected (fail closed)`,
554
+ ),
555
+ ),
556
+ lastAcceptedSequence,
557
+ toolCall: false,
558
+ };
559
+ }
560
+
561
+ // Idempotent persistence: a repeated eventId is a no-op, not a duplicate row.
562
+ if (execution.events.some((e) => e.eventId === event.eventId)) {
563
+ return {
564
+ execution: withAudit(
565
+ execution,
566
+ audit('duplicate-event-id', `eventId ${event.eventId} already persisted — skipped`),
567
+ ),
568
+ lastAcceptedSequence,
569
+ toolCall: false,
570
+ };
571
+ }
572
+
573
+ const notes: EventAuditNote[] = [];
574
+ if (event.sequence <= lastAcceptedSequence) {
575
+ notes.push(
576
+ audit(
577
+ 'sequence-anomaly',
578
+ `sequence ${event.sequence} is not greater than the last accepted ${lastAcceptedSequence}`,
579
+ ),
580
+ );
581
+ } else if (event.sequence > lastAcceptedSequence + 1) {
582
+ notes.push(
583
+ audit(
584
+ 'sequence-anomaly',
585
+ `sequence jumps from ${lastAcceptedSequence} to ${event.sequence} — events were skipped or lost`,
586
+ ),
587
+ );
588
+ }
589
+
590
+ const updated: StoredAgentExecution = {
591
+ ...execution,
592
+ events: [...execution.events, event],
593
+ eventAudit: [...execution.eventAudit, ...notes],
594
+ updatedAt: at,
595
+ };
596
+ // Best-effort durability per event; the terminal persist is authoritative.
597
+ void this.persist(updated);
598
+ return {
599
+ execution: updated,
600
+ lastAcceptedSequence: Math.max(lastAcceptedSequence, event.sequence),
601
+ toolCall: event.type === 'tool.requested',
602
+ };
603
+ }
604
+
605
+ private async persist(execution: StoredAgentExecution): Promise<KitError | undefined> {
606
+ const previous = this.persistQueues.get(execution.executionId) ?? Promise.resolve();
607
+ let report: (error: KitError | undefined) => void = () => undefined;
608
+ const settled = new Promise<KitError | undefined>((resolve) => {
609
+ report = resolve;
610
+ });
611
+ const chained = previous.then(async () => {
612
+ try {
613
+ await saveExecution(this.projectRoot, execution);
614
+ report(undefined);
615
+ } catch (e) {
616
+ report(
617
+ Errors.internal(
618
+ `Failed to persist agent execution ${execution.executionId}: ${String(e)}`,
619
+ ),
620
+ );
621
+ }
622
+ });
623
+ this.persistQueues.set(execution.executionId, chained);
624
+ return settled;
625
+ }
626
+ }
627
+
628
+ function withAudit(execution: StoredAgentExecution, note: EventAuditNote): StoredAgentExecution {
629
+ return { ...execution, eventAudit: [...execution.eventAudit, note] };
630
+ }
631
+
632
+ function isTerminal(status: StoredAgentExecution['status']): boolean {
633
+ return (
634
+ status === 'completed' ||
635
+ status === 'failed' ||
636
+ status === 'cancelled' ||
637
+ status === 'timed_out' ||
638
+ status === 'interrupted' ||
639
+ status === 'needs_approval'
640
+ );
641
+ }
642
+
643
+ function formatIssues(issues: ReadonlyArray<{ path: (string | number | symbol)[]; message: string }>): string {
644
+ return issues.map((i) => `${i.path.map(String).join('.')}: ${i.message}`).join('; ');
645
+ }
646
+
647
+ /**
648
+ * Scrub the resume credential from a result before it reaches disk. The
649
+ * token lives in memory only (this.resumeTokens); the persisted execution
650
+ * record keeps the session id — which is not a credential — but never the
651
+ * token. First exercised for real by the PR4 claude-code provider, whose
652
+ * results carry session tokens by contract.
653
+ */
654
+ function scrubResultForDisk(result: AgentExecutionResult): AgentExecutionResult {
655
+ if (!result.session?.resumeToken) return result;
656
+ return { ...result, session: { sessionId: result.session.sessionId } };
657
+ }
658
+
659
+ /** The request's policy fields must be exactly the frozen snapshot's. */
660
+ function validatePolicyChain(
661
+ request: AgentExecutionRequest,
662
+ snapshot: AgentPolicySnapshot,
663
+ ): Result<true> {
664
+ const inline = {
665
+ permissions: request.permissions,
666
+ budget: request.budget,
667
+ approvalPolicy: request.approvalPolicy,
668
+ };
669
+ const rendered = {
670
+ permissions: snapshot.permissions,
671
+ budget: snapshot.budget,
672
+ approvalPolicy: snapshot.approvalPolicy,
673
+ };
674
+ if (JSON.stringify(inline) !== JSON.stringify(rendered)) {
675
+ return {
676
+ ok: false,
677
+ error: Errors.policyViolation(
678
+ 'Request policy fields diverge from the policy snapshot — ' +
679
+ 'the provider must receive exactly the frozen policy (fail closed)',
680
+ ),
681
+ };
682
+ }
683
+ const hash = computePolicyHash(snapshot);
684
+ if (request.policyHash !== hash) {
685
+ return {
686
+ ok: false,
687
+ error: Errors.policyViolation(
688
+ `request.policyHash '${request.policyHash}' is not the hash of the supplied ` +
689
+ `policy snapshot ('${hash}') — policy traceability is broken`,
690
+ ),
691
+ };
692
+ }
693
+ return { ok: true, value: true };
694
+ }
695
+
696
+ /** Requested capabilities must be a subset of what the provider supports. */
697
+ function checkCapabilityGrant(
698
+ request: AgentExecutionRequest,
699
+ caps: AgentProviderCapabilities,
700
+ ): Result<true> {
701
+ const missing = request.permissions.capabilities.filter((c) => !caps.capabilities.includes(c));
702
+ if (missing.length > 0) {
703
+ return {
704
+ ok: false,
705
+ error: Errors.policyViolation(
706
+ `Provider '${request.providerId}' does not support the granted capabilities: ` +
707
+ `${missing.join(', ')} (supports: ${caps.capabilities.join(', ') || 'none'}) — ` +
708
+ `refusing to grant what cannot be exercised`,
709
+ ),
710
+ };
711
+ }
712
+ return { ok: true, value: true };
713
+ }
714
+
715
+ /**
716
+ * Budget honesty (rev C): a limit the provider cannot enforce or report
717
+ * must not be silently accepted. Monetary cost is the hard case — a
718
+ * provider without reliable cost telemetry declares `best-effort`, and a
719
+ * cost limit under `best-effort` is REJECTED: the evidence could never
720
+ * honestly state the limit held. Token limits at `best-effort` are
721
+ * accepted (the provider reports usage best-effort); duration and tool
722
+ * calls are always gateway-enforced regardless of declaration, because
723
+ * the gateway enforces them itself.
724
+ */
725
+ function checkBudgetEnforceability(
726
+ budget: ExecutionBudget,
727
+ caps: AgentProviderCapabilities,
728
+ providerId: string,
729
+ ): Result<true> {
730
+ if (
731
+ budget.maxEstimatedCost !== undefined &&
732
+ caps.budgetEnforcement.maxEstimatedCost === 'best-effort'
733
+ ) {
734
+ return {
735
+ ok: false,
736
+ error: Errors.policyViolation(
737
+ `Execution budget sets maxEstimatedCost but provider '${providerId}' declares ` +
738
+ `cost enforcement 'best-effort' (no reliable cost telemetry) — the limit ` +
739
+ `cannot be honestly enforced, so the execution is refused (fail closed)`,
740
+ ),
741
+ };
742
+ }
743
+ return { ok: true, value: true };
744
+ }