@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,717 @@
1
+ // packages/cli/src/application/agent/providers/claude-code/provider.ts
2
+ //
3
+ // ClaudeCodeProvider — the secure Claude Code provider for Mode 1
4
+ // (kit-orchestrated) execution. ADR-0019 PR4 (security-critical).
5
+ //
6
+ // What this provider guarantees (and where each guarantee is tested):
7
+ // - HEADLESS: `claude -p --output-format stream-json` with an ARGV ARRAY,
8
+ // shell:false, cwd = the run's isolated workspace (worktree) — never
9
+ // the developer's tree. (provider.test.ts: argv assertions)
10
+ // - POLICY-DERIVED PERMISSIONS: the session's permission configuration is
11
+ // GENERATED from the canonical snapshot (permission-config.ts); no
12
+ // hand-maintained second policy (ADR-0020 §2). `bypassPermissions` and
13
+ // `--dangerously-skip-permissions` are never emitted (asserted at
14
+ // build time in claude-argv.ts and pinned by tests).
15
+ // - MODS PARITY: the kit's runtime Mods are linked into the workspace
16
+ // before the agent starts; the outcome is reported honestly
17
+ // (mod-parity.ts).
18
+ // - HONEST BUDGETS: duration + tool calls are gateway-enforced (the
19
+ // provider wires abort -> kill and streams tool.requested events LIVE
20
+ // so the gateway's counters actually fire mid-run); tokens and cost
21
+ // are reported best-effort from Claude's own usage telemetry — declared
22
+ // best-effort, never provider-enforced (revision C).
23
+ // - HONEST STATUSES: cancellation/crash/turn-limit are VALUES on the
24
+ // result (cancelled/interrupted/failed), never `completed`
25
+ // (provider.test.ts: cancel, crash, max-turns, error, no-result).
26
+ // - CROSS-PROCESS RESUME: the session id + resume token persist ONLY in
27
+ // the AES-256-GCM store (resume-store.ts); the token never appears in
28
+ // events, logs, or plaintext on disk. (resume-store.test.ts,
29
+ // provider.test.ts: resume round-trip with a fresh provider instance)
30
+ // - NO FABRICATED EVIDENCE: proposedArtifacts is always empty — the
31
+ // agent's claims are not evidence; Kit derives truth from git
32
+ // (ADR-0018).
33
+ //
34
+ // Approval policy: when the canonical policy does not allow autonomous
35
+ // execution for a capability that requires approval, the provider blocks
36
+ // with `needs_approval` BEFORE spawning anything — CI runs are autonomous
37
+ // but never silent.
38
+
39
+ import { spawn, type ChildProcess } from 'node:child_process';
40
+ import {
41
+ AGENT_EVENT_SCHEMA_VERSION,
42
+ AGENT_EXECUTION_SCHEMA_VERSION,
43
+ type AgentEventSink,
44
+ type AgentExecutionError,
45
+ type AgentExecutionEvent,
46
+ type AgentExecutionHandle,
47
+ type AgentExecutionRequest,
48
+ type AgentExecutionResult,
49
+ type AgentHealth,
50
+ type AgentProvider,
51
+ type AgentProviderCapabilities,
52
+ } from '@agentic-sdlc-kit/contracts';
53
+ import { buildClaudeArgv, buildClaudeResumeArgv, CLAUDE_VERSION_ARGS } from './claude-argv.js';
54
+ import { CLAUDE_CODE_SUPPORTED_CAPABILITIES } from './permission-config.js';
55
+ import { ensureRuntimeModsActive } from './mod-parity.js';
56
+ import {
57
+ generateResumeToken,
58
+ loadSessionRecord,
59
+ saveSessionRecord,
60
+ verifyResumeToken,
61
+ } from './resume-store.js';
62
+ import { capabilityOfToolUse, ClaudeStreamParser, type ClaudeFinalResult } from './stream-parser.js';
63
+ import { loadExecution } from '../../execution-store.js';
64
+
65
+ export interface ClaudeCodeProviderOptions {
66
+ /** Where the gateway persists execution records (also roots the encrypted resume store). */
67
+ readonly projectRoot: string;
68
+ /** The claude executable. Default 'claude'. */
69
+ readonly cliPath?: string;
70
+ /**
71
+ * Args inserted before the derived claude args (e.g. a fixture script path
72
+ * when cliPath is a runtime binary). Test seam only; default none.
73
+ */
74
+ readonly cliArgvPrefix?: readonly string[];
75
+ /** Probe timeout for healthCheck (default 3s). */
76
+ readonly healthTimeoutMs?: number;
77
+ /** Bounded output: kill the process past this many stdout+stderr bytes (default 16 MiB). */
78
+ readonly maxOutputBytes?: number;
79
+ /** Grace between SIGTERM and SIGKILL on cancel (default 5s). */
80
+ readonly killGraceMs?: number;
81
+ /** Extra env merged over process.env for the child (test seam). */
82
+ readonly env?: Readonly<Record<string, string>>;
83
+ }
84
+
85
+ const DEFAULT_CLI = 'claude';
86
+ const DEFAULT_HEALTH_TIMEOUT_MS = 3_000;
87
+ const DEFAULT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
88
+ const DEFAULT_KILL_GRACE_MS = 5_000;
89
+ const DEFAULT_RESUME_DURATION_MS = 600_000;
90
+
91
+ /**
92
+ * Honest enforcement levels (revision C): the gateway owns the process and
93
+ * the event counters, so duration and tool calls are gateway-enforced.
94
+ * Claude reports token usage and cost in its final result, but the provider
95
+ * cannot HARD-enforce them — declared best-effort and reported, never
96
+ * claimed enforced.
97
+ */
98
+ const CLAUDE_CODE_BUDGET_ENFORCEMENT: AgentProviderCapabilities['budgetEnforcement'] = {
99
+ maxDurationMs: 'gateway-enforced',
100
+ maxToolCalls: 'gateway-enforced',
101
+ maxInputTokens: 'best-effort',
102
+ maxOutputTokens: 'best-effort',
103
+ maxTotalTokens: 'best-effort',
104
+ maxEstimatedCost: 'best-effort',
105
+ };
106
+
107
+ /** Live, replayable event stream for one execution (same contract as the mock). */
108
+ class ExecutionEventStream {
109
+ private sequence = 0;
110
+ private readonly buffer: AgentExecutionEvent[] = [];
111
+ private readonly listeners = new Set<AgentEventSink>();
112
+
113
+ constructor(
114
+ private readonly executionId: string,
115
+ private readonly policyHash: string,
116
+ ) {}
117
+
118
+ emit(
119
+ payload: Record<string, unknown>,
120
+ ): void {
121
+ this.sequence += 1;
122
+ const event = {
123
+ schemaVersion: AGENT_EVENT_SCHEMA_VERSION,
124
+ eventId: `evt-${this.executionId}-${this.sequence}`,
125
+ executionId: this.executionId,
126
+ sequence: this.sequence,
127
+ policyHash: this.policyHash,
128
+ occurredAt: new Date().toISOString(),
129
+ ...payload,
130
+ } as AgentExecutionEvent;
131
+ this.buffer.push(event);
132
+ for (const sink of this.listeners) sink(event);
133
+ }
134
+
135
+ subscribe(sink: AgentEventSink): () => void {
136
+ for (const buffered of this.buffer) sink(buffered);
137
+ this.listeners.add(sink);
138
+ return () => {
139
+ this.listeners.delete(sink);
140
+ };
141
+ }
142
+ }
143
+
144
+ interface RunningExecution {
145
+ readonly child: ChildProcess;
146
+ kill: () => void;
147
+ }
148
+
149
+ interface SpawnContext {
150
+ readonly executionId: string;
151
+ readonly workflowRunId: AgentExecutionResult['workflowRunId'];
152
+ readonly taskId: AgentExecutionResult['taskId'];
153
+ readonly policyHash: string;
154
+ readonly args: readonly string[];
155
+ readonly cwd: string;
156
+ readonly stream: ExecutionEventStream;
157
+ readonly modsNote: string | undefined;
158
+ readonly signal: AbortSignal;
159
+ }
160
+
161
+ export class ClaudeCodeProvider implements AgentProvider {
162
+ readonly id = 'claude-code' as const;
163
+
164
+ private readonly opts: {
165
+ projectRoot: string;
166
+ cliPath: string;
167
+ cliArgvPrefix: readonly string[];
168
+ healthTimeoutMs: number;
169
+ maxOutputBytes: number;
170
+ killGraceMs: number;
171
+ env: Readonly<Record<string, string>>;
172
+ };
173
+
174
+ private readonly inFlight = new Map<string, RunningExecution>();
175
+
176
+ constructor(opts: ClaudeCodeProviderOptions) {
177
+ this.opts = {
178
+ projectRoot: opts.projectRoot,
179
+ cliPath: opts.cliPath ?? DEFAULT_CLI,
180
+ cliArgvPrefix: opts.cliArgvPrefix ?? [],
181
+ healthTimeoutMs: opts.healthTimeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS,
182
+ maxOutputBytes: opts.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
183
+ killGraceMs: opts.killGraceMs ?? DEFAULT_KILL_GRACE_MS,
184
+ env: opts.env ?? {},
185
+ };
186
+ }
187
+
188
+ async capabilities(): Promise<AgentProviderCapabilities> {
189
+ return {
190
+ capabilities: [...CLAUDE_CODE_SUPPORTED_CAPABILITIES],
191
+ budgetEnforcement: { ...CLAUDE_CODE_BUDGET_ENFORCEMENT },
192
+ };
193
+ }
194
+
195
+ async healthCheck(): Promise<AgentHealth> {
196
+ return this.probeVersion();
197
+ }
198
+
199
+ async start(request: AgentExecutionRequest, signal: AbortSignal): Promise<AgentExecutionHandle> {
200
+ const stream = new ExecutionEventStream(request.executionId, request.policyHash);
201
+
202
+ // 1. Already-aborted: a cancelled VALUE, never a spawn (mirrors the mock).
203
+ if (signal.aborted) {
204
+ return settledHandle(request.executionId, stream, () =>
205
+ directResult(request, 'cancelled', 'claude-code execution cancelled: aborted before start', [
206
+ { code: 'CANCELLED', message: 'execution aborted before start', retryable: false },
207
+ ]),
208
+ );
209
+ }
210
+
211
+ // 2. Approval policy: block BEFORE spawning anything when the policy
212
+ // requires human approval the run may not take autonomously.
213
+ // Autonomous-but-never-silent (ADR-0020 §4).
214
+ const approvalBlocked =
215
+ !request.approvalPolicy.allowAutonomousExecution &&
216
+ request.approvalPolicy.requireApprovalFor.some((c) =>
217
+ request.permissions.capabilities.includes(c),
218
+ );
219
+ if (approvalBlocked) {
220
+ const message =
221
+ `the policy snapshot requires human approval for ` +
222
+ `${request.approvalPolicy.requireApprovalFor.join(', ')} and autonomous execution ` +
223
+ `is disabled — the provider did not start the agent`;
224
+ stream.emit({ type: 'execution.started' });
225
+ stream.emit({ type: 'execution.completed', status: 'needs_approval' });
226
+ return settledHandle(request.executionId, stream, () =>
227
+ directResult(request, 'needs_approval', message, [
228
+ { code: 'APPROVAL_REQUIRED', message, retryable: false },
229
+ ]),
230
+ );
231
+ }
232
+
233
+ // 3. Runtime Mods parity: link the kit's Mods into the workspace before
234
+ // the agent can run (honest note either way).
235
+ const mods = await ensureRuntimeModsActive(request.workspace.rootPath);
236
+
237
+ // 4. Headless invocation, derived entirely from the canonical policy.
238
+ const { args } = buildClaudeArgv(request);
239
+
240
+ return this.spawnAndSettle({
241
+ executionId: request.executionId,
242
+ workflowRunId: request.workflowRunId,
243
+ taskId: request.taskId,
244
+ policyHash: request.policyHash,
245
+ args,
246
+ cwd: request.workspace.rootPath,
247
+ stream,
248
+ modsNote: mods.note,
249
+ signal,
250
+ });
251
+ }
252
+
253
+ async resume(executionId: string, resumeToken: string): Promise<AgentExecutionHandle> {
254
+ // The gateway owns the original request (revision A); the provider
255
+ // re-reads its own persisted execution record for the ids/policy it
256
+ // must echo, and the ENCRYPTED session record for the provider session.
257
+ const execution = await loadExecution(this.opts.projectRoot, executionId);
258
+ if (!execution) {
259
+ const stream = new ExecutionEventStream(executionId, 'no-policy');
260
+ return settledHandle(executionId, stream, () =>
261
+ resumeRefusal(executionId, `no persisted execution '${executionId}' — cannot resume`),
262
+ );
263
+ }
264
+ const record = await loadSessionRecord(this.opts.projectRoot, executionId);
265
+ if (!record) {
266
+ const stream = new ExecutionEventStream(executionId, execution.policyHash);
267
+ return settledHandle(executionId, stream, () =>
268
+ resumeRefusal(
269
+ executionId,
270
+ `no encrypted session record for '${executionId}' — the execution cannot be resumed cross-process`,
271
+ ),
272
+ );
273
+ }
274
+ if (!verifyResumeToken(record, resumeToken)) {
275
+ const stream = new ExecutionEventStream(executionId, execution.policyHash);
276
+ return settledHandle(executionId, stream, () =>
277
+ resumeRefusal(executionId, 'invalid resume token — refusing to resume'),
278
+ );
279
+ }
280
+
281
+ const { args } = buildClaudeResumeArgv(executionId, record.sessionId);
282
+ const stream = new ExecutionEventStream(executionId, execution.policyHash);
283
+ const budgetMs = execution.request.budget.maxDurationMs;
284
+ return this.spawnAndSettle({
285
+ executionId,
286
+ workflowRunId: execution.workflowRunId,
287
+ taskId: execution.taskId,
288
+ policyHash: execution.policyHash,
289
+ args,
290
+ cwd: execution.request.workspace.rootPath,
291
+ stream,
292
+ modsNote: undefined,
293
+ signal: AbortSignal.timeout(budgetMs > 0 ? budgetMs : DEFAULT_RESUME_DURATION_MS),
294
+ });
295
+ }
296
+
297
+ async cancel(executionId: string): Promise<void> {
298
+ // Unknown id: the execution is already stopped — a no-op by contract.
299
+ this.inFlight.get(executionId)?.kill();
300
+ }
301
+
302
+ // ---- internals ---------------------------------------------------------
303
+
304
+ private childEnv(): NodeJS.ProcessEnv {
305
+ // The child is the user's own claude runtime and needs its own auth
306
+ // config, so the environment is passed through; the provider injects
307
+ // NOTHING beyond the (non-secret) test seam values. ADR-0020 §6.4:
308
+ // environment secrets never enter the agent CONTEXT — the prompt is
309
+ // exactly the request's instructions.
310
+ return { ...process.env, ...this.opts.env };
311
+ }
312
+
313
+ private probeVersion(): Promise<AgentHealth> {
314
+ return new Promise<AgentHealth>((resolve) => {
315
+ let done = false;
316
+ const child = spawn(this.opts.cliPath, [...this.opts.cliArgvPrefix, ...CLAUDE_VERSION_ARGS], {
317
+ stdio: ['ignore', 'ignore', 'ignore'],
318
+ shell: false,
319
+ env: this.childEnv(),
320
+ });
321
+ const finish = (health: AgentHealth): void => {
322
+ if (done) return;
323
+ done = true;
324
+ clearTimeout(timer);
325
+ try {
326
+ child.removeAllListeners();
327
+ child.kill('SIGKILL');
328
+ } catch {
329
+ /* already gone */
330
+ }
331
+ resolve(health);
332
+ };
333
+ const timer = setTimeout(
334
+ () =>
335
+ finish({
336
+ available: false,
337
+ message: `claude CLI at '${this.opts.cliPath}' did not answer --version within ${this.opts.healthTimeoutMs}ms`,
338
+ }),
339
+ this.opts.healthTimeoutMs,
340
+ );
341
+ child.on('error', (err) =>
342
+ finish({
343
+ available: false,
344
+ message:
345
+ `claude CLI not found at '${this.opts.cliPath}' ` +
346
+ `(${(err as NodeJS.ErrnoException).code ?? 'error'}) — install Claude Code, or inject a ` +
347
+ `provider via createFeatureCommand({ agentProviders })`,
348
+ }),
349
+ );
350
+ child.on('exit', (code, sig) => {
351
+ if (code === 0) finish({ available: true, message: `claude CLI available at '${this.opts.cliPath}'` });
352
+ else
353
+ finish({
354
+ available: false,
355
+ message: `claude CLI at '${this.opts.cliPath}' exited ${code ?? `signal ${sig}`} on --version`,
356
+ });
357
+ });
358
+ });
359
+ }
360
+
361
+ private spawnAndSettle(ctx: SpawnContext): Promise<AgentExecutionHandle> {
362
+ return new Promise<AgentExecutionHandle>((resolveHandle) => {
363
+ let resolveResult!: (r: AgentExecutionResult) => void;
364
+ const resultPromise = new Promise<AgentExecutionResult>((res) => {
365
+ resolveResult = res;
366
+ });
367
+
368
+ let outputBytes = 0;
369
+ let finalResult: ClaudeFinalResult | undefined;
370
+ let weCancelled = false;
371
+ let boundExceeded = false;
372
+ let settled = false;
373
+ let exitInfo: { code: number | null; signal: NodeJS.Signals | null } | undefined;
374
+ let stderrTail = '';
375
+ const startedAt = Date.now();
376
+
377
+ const child = spawn(this.opts.cliPath, [...this.opts.cliArgvPrefix, ...ctx.args], {
378
+ cwd: ctx.cwd,
379
+ stdio: ['ignore', 'pipe', 'pipe'],
380
+ shell: false,
381
+ env: this.childEnv(),
382
+ });
383
+
384
+ const kill = (): void => {
385
+ if (weCancelled || boundExceeded) return;
386
+ weCancelled = true;
387
+ try {
388
+ child.kill('SIGTERM');
389
+ } catch {
390
+ /* already gone */
391
+ }
392
+ const grace = setTimeout(() => {
393
+ try {
394
+ child.kill('SIGKILL');
395
+ } catch {
396
+ /* already gone */
397
+ }
398
+ }, this.opts.killGraceMs);
399
+ grace.unref?.();
400
+ };
401
+ this.inFlight.set(ctx.executionId, { child, kill });
402
+
403
+ const onAbort = (): void => kill();
404
+ if (ctx.signal.aborted) kill();
405
+ else ctx.signal.addEventListener('abort', onAbort, { once: true });
406
+
407
+ const parser = new ClaudeStreamParser((obs) => {
408
+ switch (obs.kind) {
409
+ case 'init':
410
+ ctx.stream.emit({ type: 'execution.started' });
411
+ break;
412
+ case 'text-delta':
413
+ ctx.stream.emit({ type: 'message.delta', content: obs.content });
414
+ break;
415
+ case 'tool-use': {
416
+ const capability = capabilityOfToolUse(obs);
417
+ // An event never authorizes anything; if the tool is outside the
418
+ // derived table we skip the event rather than assert a capability
419
+ // we cannot honestly name (the gateway counts what it can see).
420
+ if (capability) {
421
+ ctx.stream.emit({
422
+ type: 'tool.requested',
423
+ toolCallId: obs.toolCallId,
424
+ capability,
425
+ });
426
+ }
427
+ break;
428
+ }
429
+ case 'tool-result':
430
+ ctx.stream.emit({
431
+ type: 'tool.result',
432
+ toolCallId: obs.toolCallId,
433
+ status: obs.status,
434
+ });
435
+ break;
436
+ case 'result':
437
+ finalResult = obs.result;
438
+ break;
439
+ }
440
+ });
441
+
442
+ const onStdout = (chunk: Buffer): void => {
443
+ outputBytes += chunk.length;
444
+ if (outputBytes > this.opts.maxOutputBytes) {
445
+ boundExceeded = true;
446
+ weCancelled = true; // we initiate this kill too
447
+ try {
448
+ child.kill('SIGTERM');
449
+ } catch {
450
+ /* already gone */
451
+ }
452
+ return;
453
+ }
454
+ for (const line of chunk.toString('utf8').split('\n')) parser.consume(line.trim());
455
+ };
456
+ const onStderr = (chunk: Buffer): void => {
457
+ outputBytes += chunk.length;
458
+ if (stderrTail.length < 8_192) stderrTail = (stderrTail + chunk.toString('utf8')).slice(-8_192);
459
+ };
460
+ child.stdout?.on('data', onStdout);
461
+ child.stderr?.on('data', onStderr);
462
+
463
+ const finalize = async (): Promise<void> => {
464
+ if (settled) return;
465
+ settled = true;
466
+ ctx.signal.removeEventListener('abort', onAbort);
467
+ this.inFlight.delete(ctx.executionId);
468
+
469
+ const result = this.buildResult({
470
+ ctx,
471
+ finalResult,
472
+ weCancelled,
473
+ boundExceeded,
474
+ durationMs: Date.now() - startedAt,
475
+ stderrTail,
476
+ exitInfo,
477
+ });
478
+ // The encrypted session record must exist before the result is
479
+ // observable, or a cross-process resume test could race it.
480
+ if (result.session?.sessionId) await this.persistSession(result);
481
+ ctx.stream.emit({ type: 'execution.completed', status: result.status });
482
+ resolveResult(result);
483
+ };
484
+
485
+ child.on('close', (code, signal) => {
486
+ exitInfo = { code, signal };
487
+ void finalize();
488
+ });
489
+ child.on('error', () => {
490
+ exitInfo = { code: null, signal: null };
491
+ void finalize();
492
+ });
493
+
494
+ resolveHandle({
495
+ executionId: ctx.executionId,
496
+ result: () => resultPromise,
497
+ events: (sink: AgentEventSink) => ctx.stream.subscribe(sink),
498
+ });
499
+ });
500
+ }
501
+
502
+ private buildResult(input: {
503
+ ctx: SpawnContext;
504
+ finalResult: ClaudeFinalResult | undefined;
505
+ weCancelled: boolean;
506
+ boundExceeded: boolean;
507
+ durationMs: number;
508
+ stderrTail: string;
509
+ exitInfo: { code: number | null; signal: NodeJS.Signals | null } | undefined;
510
+ }): AgentExecutionResult {
511
+ const { ctx, finalResult, weCancelled, boundExceeded, durationMs, stderrTail, exitInfo } = input;
512
+ const base = {
513
+ schemaVersion: AGENT_EXECUTION_SCHEMA_VERSION,
514
+ executionId: ctx.executionId,
515
+ workflowRunId: ctx.workflowRunId,
516
+ taskId: ctx.taskId,
517
+ providerId: this.id,
518
+ proposedArtifacts: [],
519
+ requestedApprovals: [],
520
+ errors: [] as AgentExecutionError[],
521
+ };
522
+
523
+ // Cancellation (SIGINT, gateway cancel, budget breach): a VALUE.
524
+ if (weCancelled && !boundExceeded) {
525
+ return {
526
+ ...base,
527
+ status: 'cancelled',
528
+ summary: withMods('claude-code execution cancelled before completion', ctx.modsNote),
529
+ usage: { durationMs },
530
+ errors: [
531
+ {
532
+ code: 'CANCELLED',
533
+ message: 'execution aborted (SIGINT, gateway cancel, or budget breach)',
534
+ retryable: false,
535
+ },
536
+ ],
537
+ };
538
+ }
539
+
540
+ // Bounded output: a budget-class failure, never silent continuation.
541
+ if (boundExceeded) {
542
+ return {
543
+ ...base,
544
+ status: 'failed',
545
+ summary: withMods(
546
+ `claude-code output exceeded the bounded limit of ${this.opts.maxOutputBytes} bytes and the process was killed`,
547
+ ctx.modsNote,
548
+ ),
549
+ usage: { durationMs },
550
+ errors: [{ code: 'BUDGET_EXCEEDED', message: 'output byte bound exceeded', retryable: false }],
551
+ };
552
+ }
553
+
554
+ if (finalResult) {
555
+ const usage = {
556
+ durationMs: finalResult.durationMs ?? durationMs,
557
+ ...(finalResult.inputTokens !== undefined ? { inputTokens: finalResult.inputTokens } : {}),
558
+ ...(finalResult.outputTokens !== undefined ? { outputTokens: finalResult.outputTokens } : {}),
559
+ ...(finalResult.totalCostUsd !== undefined
560
+ ? { estimatedCost: finalResult.totalCostUsd, currency: 'USD' }
561
+ : {}),
562
+ };
563
+ // The session + resume credential: token generated here, persisted
564
+ // ENCRYPTED below; the gateway holds it in memory only.
565
+ const session =
566
+ finalResult.sessionId !== undefined
567
+ ? { sessionId: finalResult.sessionId, resumeToken: generateResumeToken() }
568
+ : undefined;
569
+
570
+ if (finalResult.subtype === 'success' && !finalResult.isError) {
571
+ const result: AgentExecutionResult = {
572
+ ...base,
573
+ status: 'completed',
574
+ summary: withMods(finalResult.text || 'claude-code completed without a final message', ctx.modsNote),
575
+ ...(session ? { session } : {}),
576
+ usage,
577
+ };
578
+ return result;
579
+ }
580
+ if (finalResult.subtype === 'error_max_turns') {
581
+ const result: AgentExecutionResult = {
582
+ ...base,
583
+ status: 'failed',
584
+ summary: withMods(
585
+ finalResult.text || 'claude-code hit the derived --max-turns bound before completing',
586
+ ctx.modsNote,
587
+ ),
588
+ ...(session ? { session } : {}),
589
+ usage,
590
+ errors: [
591
+ {
592
+ code: 'BUDGET_EXCEEDED',
593
+ message: 'turn bound (--max-turns) reached before completion',
594
+ retryable: false,
595
+ },
596
+ ],
597
+ };
598
+ return result;
599
+ }
600
+ // error_during_execution — or an error shape we do not recognize:
601
+ // fail closed as a failure, never completed.
602
+ const blob = `${finalResult.text} ${stderrTail}`;
603
+ const denied = /permission|not allowed|denied|unauthorized/i.test(blob);
604
+ const result: AgentExecutionResult = {
605
+ ...base,
606
+ status: 'failed',
607
+ summary: withMods(finalResult.text || stderrTail || 'claude-code execution failed', ctx.modsNote),
608
+ ...(session ? { session } : {}),
609
+ usage,
610
+ errors: [
611
+ {
612
+ code: denied ? 'CAPABILITY_DENIED' : 'PROVIDER_INTERNAL',
613
+ message: (finalResult.text || stderrTail || 'claude-code reported an execution error').slice(0, 500),
614
+ retryable: false,
615
+ },
616
+ ],
617
+ };
618
+ return result;
619
+ }
620
+
621
+ // No final result object: the CLI crashed, was killed by a signal, or
622
+ // violated the stream contract. Honest statuses, never `completed`.
623
+ const killedBySignal = exitInfo?.signal !== null && exitInfo?.signal !== undefined;
624
+ const message = stderrTail
625
+ ? `claude-code process ended without a result object: ${stderrTail.slice(-300)}`
626
+ : 'claude-code process ended without a result object';
627
+ return {
628
+ ...base,
629
+ status: killedBySignal || exitInfo?.code === 0 || exitInfo === undefined ? 'interrupted' : 'failed',
630
+ summary: withMods(message, ctx.modsNote),
631
+ usage: { durationMs },
632
+ errors: [
633
+ {
634
+ code: exitInfo?.code !== undefined && exitInfo.code !== null && exitInfo.code !== 0 ? 'PROVIDER_INTERNAL' : 'UNKNOWN',
635
+ message:
636
+ `stream ended without a result object ` +
637
+ `(exit ${exitInfo?.code ?? 'n/a'}${exitInfo?.signal ? `, signal ${exitInfo.signal}` : ''})`,
638
+ retryable: false,
639
+ },
640
+ ],
641
+ };
642
+ }
643
+
644
+ /** Persist the session record for cross-process resume (encrypted at rest). */
645
+ private async persistSession(result: AgentExecutionResult): Promise<void> {
646
+ if (!result.session?.sessionId) return;
647
+ try {
648
+ await saveSessionRecord(this.opts.projectRoot, {
649
+ executionId: result.executionId,
650
+ providerId: this.id,
651
+ sessionId: result.session.sessionId,
652
+ resumeToken: result.session.resumeToken ?? '',
653
+ createdAt: new Date().toISOString(),
654
+ });
655
+ } catch {
656
+ // Honest degradation: without the encrypted record the session is
657
+ // simply not resumable cross-process; the in-memory token still
658
+ // serves the gateway's own resume API within this process.
659
+ result.session = undefined;
660
+ }
661
+ }
662
+ }
663
+
664
+ function withMods(summary: string, modsNote: string | undefined): string {
665
+ return modsNote ? `${summary} [${modsNote}]` : summary;
666
+ }
667
+
668
+ /** A result for paths that never spawned a process. */
669
+ function directResult(
670
+ request: AgentExecutionRequest,
671
+ status: AgentExecutionResult['status'],
672
+ summary: string,
673
+ errors: AgentExecutionError[],
674
+ ): AgentExecutionResult {
675
+ return {
676
+ schemaVersion: AGENT_EXECUTION_SCHEMA_VERSION,
677
+ executionId: request.executionId,
678
+ workflowRunId: request.workflowRunId,
679
+ taskId: request.taskId,
680
+ providerId: 'claude-code',
681
+ status,
682
+ summary,
683
+ proposedArtifacts: [],
684
+ requestedApprovals: [],
685
+ errors,
686
+ };
687
+ }
688
+
689
+ /** Resume refusals are failed results (honest values), never throws. */
690
+ function resumeRefusal(executionId: string, message: string): AgentExecutionResult {
691
+ return {
692
+ schemaVersion: AGENT_EXECUTION_SCHEMA_VERSION,
693
+ executionId,
694
+ workflowRunId: 'run-resume' as AgentExecutionResult['workflowRunId'],
695
+ taskId: 'task-resume' as AgentExecutionResult['taskId'],
696
+ providerId: 'claude-code',
697
+ status: 'failed',
698
+ summary: message,
699
+ proposedArtifacts: [],
700
+ requestedApprovals: [],
701
+ errors: [{ code: 'SESSION_EXPIRED', message, retryable: false }],
702
+ };
703
+ }
704
+
705
+ /** A handle whose result() is already decided (no spawn happened). */
706
+ function settledHandle(
707
+ executionId: string,
708
+ stream: ExecutionEventStream,
709
+ produce: () => AgentExecutionResult,
710
+ ): Promise<AgentExecutionHandle> {
711
+ const promise = Promise.resolve(produce());
712
+ return Promise.resolve({
713
+ executionId,
714
+ result: () => promise,
715
+ events: (sink: AgentEventSink) => stream.subscribe(sink),
716
+ });
717
+ }