@nathapp/nax 0.50.3 → 0.51.2

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 (353) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +177 -104
  3. package/dist/nax.js +417 -213
  4. package/package.json +1 -3
  5. package/bin/nax.ts +0 -1195
  6. package/src/acceptance/fix-generator.ts +0 -322
  7. package/src/acceptance/generator.ts +0 -415
  8. package/src/acceptance/index.ts +0 -42
  9. package/src/acceptance/refinement.ts +0 -224
  10. package/src/acceptance/templates/cli.ts +0 -47
  11. package/src/acceptance/templates/component.ts +0 -78
  12. package/src/acceptance/templates/e2e.ts +0 -43
  13. package/src/acceptance/templates/index.ts +0 -21
  14. package/src/acceptance/templates/snapshot.ts +0 -50
  15. package/src/acceptance/templates/unit.ts +0 -48
  16. package/src/acceptance/types.ts +0 -138
  17. package/src/agents/acp/adapter.ts +0 -888
  18. package/src/agents/acp/cost.ts +0 -9
  19. package/src/agents/acp/index.ts +0 -7
  20. package/src/agents/acp/interaction-bridge.ts +0 -126
  21. package/src/agents/acp/parser.ts +0 -119
  22. package/src/agents/acp/spawn-client.ts +0 -373
  23. package/src/agents/acp/types.ts +0 -22
  24. package/src/agents/aider/adapter.ts +0 -135
  25. package/src/agents/claude/adapter.ts +0 -258
  26. package/src/agents/claude/complete.ts +0 -80
  27. package/src/agents/claude/cost.ts +0 -16
  28. package/src/agents/claude/execution.ts +0 -215
  29. package/src/agents/claude/index.ts +0 -3
  30. package/src/agents/claude/interactive.ts +0 -77
  31. package/src/agents/claude/plan.ts +0 -179
  32. package/src/agents/codex/adapter.ts +0 -153
  33. package/src/agents/cost/calculate.ts +0 -154
  34. package/src/agents/cost/index.ts +0 -10
  35. package/src/agents/cost/parse.ts +0 -97
  36. package/src/agents/cost/pricing.ts +0 -59
  37. package/src/agents/cost/types.ts +0 -45
  38. package/src/agents/gemini/adapter.ts +0 -177
  39. package/src/agents/index.ts +0 -18
  40. package/src/agents/opencode/adapter.ts +0 -106
  41. package/src/agents/registry.ts +0 -136
  42. package/src/agents/shared/decompose.ts +0 -154
  43. package/src/agents/shared/model-resolution.ts +0 -43
  44. package/src/agents/shared/types-extended.ts +0 -164
  45. package/src/agents/shared/validation.ts +0 -69
  46. package/src/agents/shared/version-detection.ts +0 -109
  47. package/src/agents/types.ts +0 -205
  48. package/src/analyze/classifier.ts +0 -282
  49. package/src/analyze/index.ts +0 -16
  50. package/src/analyze/scanner.ts +0 -171
  51. package/src/analyze/types.ts +0 -51
  52. package/src/cli/accept.ts +0 -108
  53. package/src/cli/agents.ts +0 -87
  54. package/src/cli/analyze-parser.ts +0 -291
  55. package/src/cli/analyze.ts +0 -352
  56. package/src/cli/config-descriptions.ts +0 -219
  57. package/src/cli/config-diff.ts +0 -103
  58. package/src/cli/config-display.ts +0 -285
  59. package/src/cli/config-get.ts +0 -55
  60. package/src/cli/config.ts +0 -14
  61. package/src/cli/constitution.ts +0 -17
  62. package/src/cli/diagnose-analysis.ts +0 -159
  63. package/src/cli/diagnose-formatter.ts +0 -87
  64. package/src/cli/diagnose.ts +0 -203
  65. package/src/cli/generate.ts +0 -250
  66. package/src/cli/index.ts +0 -42
  67. package/src/cli/init-context.ts +0 -405
  68. package/src/cli/init-detect.ts +0 -303
  69. package/src/cli/init.ts +0 -296
  70. package/src/cli/interact.ts +0 -295
  71. package/src/cli/plan.ts +0 -509
  72. package/src/cli/plugins.ts +0 -122
  73. package/src/cli/prompts-export.ts +0 -58
  74. package/src/cli/prompts-init.ts +0 -200
  75. package/src/cli/prompts-main.ts +0 -183
  76. package/src/cli/prompts-shared.ts +0 -70
  77. package/src/cli/prompts-tdd.ts +0 -88
  78. package/src/cli/prompts.ts +0 -17
  79. package/src/cli/runs.ts +0 -174
  80. package/src/cli/status-cost.ts +0 -151
  81. package/src/cli/status-features.ts +0 -405
  82. package/src/cli/status.ts +0 -13
  83. package/src/commands/common.ts +0 -171
  84. package/src/commands/diagnose.ts +0 -17
  85. package/src/commands/index.ts +0 -9
  86. package/src/commands/logs-formatter.ts +0 -201
  87. package/src/commands/logs-reader.ts +0 -171
  88. package/src/commands/logs.ts +0 -103
  89. package/src/commands/precheck.ts +0 -86
  90. package/src/commands/runs.ts +0 -220
  91. package/src/commands/unlock.ts +0 -96
  92. package/src/config/defaults.ts +0 -218
  93. package/src/config/index.ts +0 -22
  94. package/src/config/loader.ts +0 -143
  95. package/src/config/merge.ts +0 -106
  96. package/src/config/merger.ts +0 -147
  97. package/src/config/path-security.ts +0 -121
  98. package/src/config/paths.ts +0 -27
  99. package/src/config/permissions.ts +0 -63
  100. package/src/config/runtime-types.ts +0 -522
  101. package/src/config/schema-types.ts +0 -53
  102. package/src/config/schema.ts +0 -60
  103. package/src/config/schemas.ts +0 -426
  104. package/src/config/test-strategy.ts +0 -71
  105. package/src/config/types.ts +0 -57
  106. package/src/config/validate.ts +0 -103
  107. package/src/constitution/generator.ts +0 -158
  108. package/src/constitution/generators/aider.ts +0 -41
  109. package/src/constitution/generators/claude.ts +0 -35
  110. package/src/constitution/generators/cursor.ts +0 -36
  111. package/src/constitution/generators/opencode.ts +0 -38
  112. package/src/constitution/generators/types.ts +0 -33
  113. package/src/constitution/generators/windsurf.ts +0 -36
  114. package/src/constitution/index.ts +0 -11
  115. package/src/constitution/loader.ts +0 -121
  116. package/src/constitution/types.ts +0 -31
  117. package/src/context/auto-detect.ts +0 -228
  118. package/src/context/builder.ts +0 -299
  119. package/src/context/elements.ts +0 -122
  120. package/src/context/formatter.ts +0 -107
  121. package/src/context/generator.ts +0 -343
  122. package/src/context/generators/aider.ts +0 -34
  123. package/src/context/generators/claude.ts +0 -28
  124. package/src/context/generators/codex.ts +0 -28
  125. package/src/context/generators/cursor.ts +0 -28
  126. package/src/context/generators/gemini.ts +0 -28
  127. package/src/context/generators/opencode.ts +0 -30
  128. package/src/context/generators/windsurf.ts +0 -28
  129. package/src/context/greenfield.ts +0 -114
  130. package/src/context/index.ts +0 -34
  131. package/src/context/injector.ts +0 -279
  132. package/src/context/parent-context.ts +0 -39
  133. package/src/context/test-scanner.ts +0 -370
  134. package/src/context/types.ts +0 -98
  135. package/src/decompose/apply.ts +0 -50
  136. package/src/decompose/builder.ts +0 -181
  137. package/src/decompose/index.ts +0 -8
  138. package/src/decompose/sections/codebase.ts +0 -26
  139. package/src/decompose/sections/constraints.ts +0 -32
  140. package/src/decompose/sections/index.ts +0 -4
  141. package/src/decompose/sections/sibling-stories.ts +0 -25
  142. package/src/decompose/sections/target-story.ts +0 -31
  143. package/src/decompose/types.ts +0 -55
  144. package/src/decompose/validators/complexity.ts +0 -45
  145. package/src/decompose/validators/coverage.ts +0 -134
  146. package/src/decompose/validators/dependency.ts +0 -91
  147. package/src/decompose/validators/index.ts +0 -35
  148. package/src/decompose/validators/overlap.ts +0 -128
  149. package/src/errors.ts +0 -67
  150. package/src/execution/batching.ts +0 -157
  151. package/src/execution/crash-heartbeat.ts +0 -77
  152. package/src/execution/crash-recovery.ts +0 -79
  153. package/src/execution/crash-signals.ts +0 -165
  154. package/src/execution/crash-writer.ts +0 -154
  155. package/src/execution/deferred-review.ts +0 -105
  156. package/src/execution/dry-run.ts +0 -81
  157. package/src/execution/escalation/escalation.ts +0 -46
  158. package/src/execution/escalation/index.ts +0 -13
  159. package/src/execution/escalation/tier-escalation.ts +0 -346
  160. package/src/execution/escalation/tier-outcome.ts +0 -143
  161. package/src/execution/executor-types.ts +0 -73
  162. package/src/execution/helpers.ts +0 -38
  163. package/src/execution/index.ts +0 -27
  164. package/src/execution/iteration-runner.ts +0 -160
  165. package/src/execution/lifecycle/acceptance-loop.ts +0 -309
  166. package/src/execution/lifecycle/headless-formatter.ts +0 -83
  167. package/src/execution/lifecycle/index.ts +0 -11
  168. package/src/execution/lifecycle/parallel-lifecycle.ts +0 -101
  169. package/src/execution/lifecycle/precheck-runner.ts +0 -140
  170. package/src/execution/lifecycle/run-cleanup.ts +0 -81
  171. package/src/execution/lifecycle/run-completion.ts +0 -247
  172. package/src/execution/lifecycle/run-initialization.ts +0 -187
  173. package/src/execution/lifecycle/run-regression.ts +0 -305
  174. package/src/execution/lifecycle/run-setup.ts +0 -240
  175. package/src/execution/lifecycle/story-size-prompts.ts +0 -123
  176. package/src/execution/lock.ts +0 -129
  177. package/src/execution/parallel-coordinator.ts +0 -281
  178. package/src/execution/parallel-executor-rectification-pass.ts +0 -117
  179. package/src/execution/parallel-executor-rectify.ts +0 -136
  180. package/src/execution/parallel-executor.ts +0 -330
  181. package/src/execution/parallel-worker.ts +0 -149
  182. package/src/execution/parallel.ts +0 -13
  183. package/src/execution/pid-registry.ts +0 -275
  184. package/src/execution/pipeline-result-handler.ts +0 -221
  185. package/src/execution/progress.ts +0 -27
  186. package/src/execution/queue-handler.ts +0 -109
  187. package/src/execution/runner-completion.ts +0 -171
  188. package/src/execution/runner-execution.ts +0 -243
  189. package/src/execution/runner-setup.ts +0 -86
  190. package/src/execution/runner.ts +0 -265
  191. package/src/execution/sequential-executor.ts +0 -219
  192. package/src/execution/status-file.ts +0 -264
  193. package/src/execution/status-writer.ts +0 -181
  194. package/src/execution/story-context.ts +0 -266
  195. package/src/execution/story-selector.ts +0 -76
  196. package/src/execution/test-output-parser.ts +0 -14
  197. package/src/execution/timeout-handler.ts +0 -100
  198. package/src/hooks/index.ts +0 -2
  199. package/src/hooks/runner.ts +0 -280
  200. package/src/hooks/types.ts +0 -79
  201. package/src/interaction/chain.ts +0 -170
  202. package/src/interaction/index.ts +0 -61
  203. package/src/interaction/init.ts +0 -84
  204. package/src/interaction/plugins/auto.ts +0 -243
  205. package/src/interaction/plugins/cli.ts +0 -300
  206. package/src/interaction/plugins/telegram.ts +0 -384
  207. package/src/interaction/plugins/webhook.ts +0 -286
  208. package/src/interaction/state.ts +0 -171
  209. package/src/interaction/triggers.ts +0 -250
  210. package/src/interaction/types.ts +0 -170
  211. package/src/logger/formatters.ts +0 -84
  212. package/src/logger/index.ts +0 -16
  213. package/src/logger/logger.ts +0 -296
  214. package/src/logger/types.ts +0 -48
  215. package/src/logging/formatter.ts +0 -355
  216. package/src/logging/index.ts +0 -22
  217. package/src/logging/types.ts +0 -93
  218. package/src/metrics/aggregator.ts +0 -191
  219. package/src/metrics/index.ts +0 -14
  220. package/src/metrics/tracker.ts +0 -200
  221. package/src/metrics/types.ts +0 -115
  222. package/src/optimizer/index.ts +0 -63
  223. package/src/optimizer/noop.optimizer.ts +0 -24
  224. package/src/optimizer/rule-based.optimizer.ts +0 -248
  225. package/src/optimizer/types.ts +0 -53
  226. package/src/pipeline/event-bus.ts +0 -297
  227. package/src/pipeline/events.ts +0 -130
  228. package/src/pipeline/index.ts +0 -19
  229. package/src/pipeline/runner.ts +0 -149
  230. package/src/pipeline/stages/acceptance-setup.ts +0 -144
  231. package/src/pipeline/stages/acceptance.ts +0 -215
  232. package/src/pipeline/stages/autofix.ts +0 -262
  233. package/src/pipeline/stages/completion.ts +0 -110
  234. package/src/pipeline/stages/constitution.ts +0 -63
  235. package/src/pipeline/stages/context.ts +0 -122
  236. package/src/pipeline/stages/execution.ts +0 -359
  237. package/src/pipeline/stages/index.ts +0 -86
  238. package/src/pipeline/stages/optimizer.ts +0 -74
  239. package/src/pipeline/stages/prompt.ts +0 -79
  240. package/src/pipeline/stages/queue-check.ts +0 -103
  241. package/src/pipeline/stages/rectify.ts +0 -101
  242. package/src/pipeline/stages/regression.ts +0 -99
  243. package/src/pipeline/stages/review.ts +0 -94
  244. package/src/pipeline/stages/routing.ts +0 -276
  245. package/src/pipeline/stages/verify.ts +0 -286
  246. package/src/pipeline/subscribers/events-writer.ts +0 -135
  247. package/src/pipeline/subscribers/hooks.ts +0 -179
  248. package/src/pipeline/subscribers/interaction.ts +0 -103
  249. package/src/pipeline/subscribers/registry.ts +0 -73
  250. package/src/pipeline/subscribers/reporters.ts +0 -174
  251. package/src/pipeline/types.ts +0 -220
  252. package/src/plugins/extensions.ts +0 -225
  253. package/src/plugins/index.ts +0 -33
  254. package/src/plugins/loader.ts +0 -352
  255. package/src/plugins/plugin-logger.ts +0 -41
  256. package/src/plugins/registry.ts +0 -168
  257. package/src/plugins/types.ts +0 -206
  258. package/src/plugins/validator.ts +0 -352
  259. package/src/prd/index.ts +0 -220
  260. package/src/prd/schema.ts +0 -268
  261. package/src/prd/types.ts +0 -273
  262. package/src/prd/validate.ts +0 -41
  263. package/src/precheck/checks-agents.ts +0 -63
  264. package/src/precheck/checks-blockers.ts +0 -23
  265. package/src/precheck/checks-cli.ts +0 -68
  266. package/src/precheck/checks-config.ts +0 -102
  267. package/src/precheck/checks-git.ts +0 -117
  268. package/src/precheck/checks-system.ts +0 -101
  269. package/src/precheck/checks-warnings.ts +0 -221
  270. package/src/precheck/checks.ts +0 -36
  271. package/src/precheck/index.ts +0 -374
  272. package/src/precheck/story-size-gate.ts +0 -144
  273. package/src/precheck/types.ts +0 -31
  274. package/src/prompts/builder.ts +0 -166
  275. package/src/prompts/index.ts +0 -2
  276. package/src/prompts/loader.ts +0 -43
  277. package/src/prompts/sections/conventions.ts +0 -19
  278. package/src/prompts/sections/hermetic.ts +0 -41
  279. package/src/prompts/sections/index.ts +0 -12
  280. package/src/prompts/sections/isolation.ts +0 -70
  281. package/src/prompts/sections/role-task.ts +0 -182
  282. package/src/prompts/sections/story.ts +0 -55
  283. package/src/prompts/sections/verdict.ts +0 -70
  284. package/src/prompts/types.ts +0 -21
  285. package/src/queue/index.ts +0 -2
  286. package/src/queue/manager.ts +0 -254
  287. package/src/queue/types.ts +0 -54
  288. package/src/review/index.ts +0 -8
  289. package/src/review/orchestrator.ts +0 -154
  290. package/src/review/runner.ts +0 -303
  291. package/src/review/types.ts +0 -70
  292. package/src/routing/batch-route.ts +0 -35
  293. package/src/routing/builder.ts +0 -81
  294. package/src/routing/chain.ts +0 -75
  295. package/src/routing/content-hash.ts +0 -25
  296. package/src/routing/index.ts +0 -20
  297. package/src/routing/loader.ts +0 -62
  298. package/src/routing/router.ts +0 -305
  299. package/src/routing/strategies/adaptive.ts +0 -215
  300. package/src/routing/strategies/index.ts +0 -8
  301. package/src/routing/strategies/keyword.ts +0 -180
  302. package/src/routing/strategies/llm-prompts.ts +0 -224
  303. package/src/routing/strategies/llm.ts +0 -320
  304. package/src/routing/strategies/manual.ts +0 -50
  305. package/src/routing/strategy.ts +0 -102
  306. package/src/tdd/cleanup.ts +0 -120
  307. package/src/tdd/index.ts +0 -22
  308. package/src/tdd/isolation.ts +0 -117
  309. package/src/tdd/orchestrator.ts +0 -406
  310. package/src/tdd/prompts.ts +0 -40
  311. package/src/tdd/rectification-gate.ts +0 -274
  312. package/src/tdd/session-runner.ts +0 -263
  313. package/src/tdd/types.ts +0 -84
  314. package/src/tdd/verdict-reader.ts +0 -266
  315. package/src/tdd/verdict.ts +0 -152
  316. package/src/tui/App.tsx +0 -265
  317. package/src/tui/components/AgentPanel.tsx +0 -75
  318. package/src/tui/components/CostOverlay.tsx +0 -118
  319. package/src/tui/components/HelpOverlay.tsx +0 -107
  320. package/src/tui/components/StatusBar.tsx +0 -63
  321. package/src/tui/components/StoriesPanel.tsx +0 -177
  322. package/src/tui/hooks/useKeyboard.ts +0 -142
  323. package/src/tui/hooks/useLayout.ts +0 -137
  324. package/src/tui/hooks/usePipelineEvents.ts +0 -183
  325. package/src/tui/hooks/usePty.ts +0 -189
  326. package/src/tui/index.tsx +0 -38
  327. package/src/tui/types.ts +0 -76
  328. package/src/utils/errors.ts +0 -12
  329. package/src/utils/git.ts +0 -245
  330. package/src/utils/json-file.ts +0 -72
  331. package/src/utils/log-test-output.ts +0 -25
  332. package/src/utils/path-security.ts +0 -73
  333. package/src/utils/queue-writer.ts +0 -54
  334. package/src/verification/crash-detector.ts +0 -34
  335. package/src/verification/executor.ts +0 -250
  336. package/src/verification/index.ts +0 -12
  337. package/src/verification/orchestrator-types.ts +0 -154
  338. package/src/verification/orchestrator.ts +0 -76
  339. package/src/verification/parser.ts +0 -220
  340. package/src/verification/rectification-loop.ts +0 -172
  341. package/src/verification/rectification.ts +0 -108
  342. package/src/verification/runners.ts +0 -129
  343. package/src/verification/smart-runner.ts +0 -307
  344. package/src/verification/strategies/acceptance.ts +0 -136
  345. package/src/verification/strategies/regression.ts +0 -90
  346. package/src/verification/strategies/scoped.ts +0 -154
  347. package/src/verification/types.ts +0 -117
  348. package/src/version.ts +0 -40
  349. package/src/worktree/dispatcher.ts +0 -6
  350. package/src/worktree/index.ts +0 -2
  351. package/src/worktree/manager.ts +0 -193
  352. package/src/worktree/merge.ts +0 -302
  353. package/src/worktree/types.ts +0 -4
@@ -1,888 +0,0 @@
1
- /**
2
- * ACP Agent Adapter — implements AgentAdapter interface via ACP session protocol.
3
- *
4
- * All methods use the createClient injectable as the transport layer.
5
- * Session lifecycle (naming, persistence, ensure/close) is handled by
6
- * thin wrapper functions on top of AcpClient/AcpSession.
7
- *
8
- * Session naming: nax-<gitRootHash8>-<feature>-<story>[-<role>]
9
- * Persistence: nax/features/<feature>/acp-sessions.json sidecar
10
- *
11
- * See: docs/specs/acp-session-mode.md
12
- */
13
-
14
- import { createHash } from "node:crypto";
15
- import { join } from "node:path";
16
- import { resolvePermissions } from "../../config/permissions";
17
- import { getSafeLogger } from "../../logger";
18
- import { buildDecomposePrompt, parseDecomposeOutput } from "../shared/decompose";
19
- import { createSpawnAcpClient } from "./spawn-client";
20
-
21
- import type {
22
- AgentAdapter,
23
- AgentCapabilities,
24
- AgentResult,
25
- AgentRunOptions,
26
- CompleteOptions,
27
- DecomposeOptions,
28
- DecomposeResult,
29
- PlanOptions,
30
- PlanResult,
31
- } from "../types";
32
- import { CompleteError } from "../types";
33
- import { estimateCostFromTokenUsage } from "./cost";
34
- import type { AgentRegistryEntry } from "./types";
35
-
36
- // ─────────────────────────────────────────────────────────────────────────────
37
- // Constants
38
- // ─────────────────────────────────────────────────────────────────────────────
39
-
40
- const MAX_AGENT_OUTPUT_CHARS = 5000;
41
- const MAX_RATE_LIMIT_RETRIES = 3;
42
- const INTERACTION_TIMEOUT_MS = 5 * 60 * 1000; // 5 min for human to respond
43
-
44
- // ─────────────────────────────────────────────────────────────────────────────
45
- // Agent registry
46
- // ─────────────────────────────────────────────────────────────────────────────
47
-
48
- const AGENT_REGISTRY: Record<string, AgentRegistryEntry> = {
49
- claude: {
50
- binary: "claude",
51
- displayName: "Claude Code (ACP)",
52
- supportedTiers: ["fast", "balanced", "powerful"],
53
- maxContextTokens: 200_000,
54
- },
55
- codex: {
56
- binary: "codex",
57
- displayName: "OpenAI Codex (ACP)",
58
- supportedTiers: ["fast", "balanced"],
59
- maxContextTokens: 128_000,
60
- },
61
- gemini: {
62
- binary: "gemini",
63
- displayName: "Gemini CLI (ACP)",
64
- supportedTiers: ["fast", "balanced", "powerful"],
65
- maxContextTokens: 1_000_000,
66
- },
67
- };
68
-
69
- const DEFAULT_ENTRY: AgentRegistryEntry = {
70
- binary: "claude",
71
- displayName: "ACP Agent",
72
- supportedTiers: ["balanced"],
73
- maxContextTokens: 128_000,
74
- };
75
-
76
- // ─────────────────────────────────────────────────────────────────────────────
77
- // ACP session interfaces
78
- // ─────────────────────────────────────────────────────────────────────────────
79
-
80
- export interface AcpSessionResponse {
81
- messages: Array<{ role: string; content: string }>;
82
- stopReason: string;
83
- cumulative_token_usage?: {
84
- input_tokens: number;
85
- output_tokens: number;
86
- cache_read_input_tokens?: number;
87
- cache_creation_input_tokens?: number;
88
- };
89
- /** Exact cost in USD from acpx usage_update event. Preferred over token-based estimation. */
90
- exactCostUsd?: number;
91
- }
92
-
93
- export interface AcpSession {
94
- prompt(text: string): Promise<AcpSessionResponse>;
95
- close(): Promise<void>;
96
- cancelActivePrompt(): Promise<void>;
97
- }
98
-
99
- export interface AcpClient {
100
- start(): Promise<void>;
101
- createSession(opts: { agentName: string; permissionMode: string; sessionName?: string }): Promise<AcpSession>;
102
- /** Resume an existing named session. Returns null if the session is not found. */
103
- loadSession?(sessionName: string, agentName: string, permissionMode: string): Promise<AcpSession | null>;
104
- close(): Promise<void>;
105
- }
106
-
107
- // ─────────────────────────────────────────────────────────────────────────────
108
- // Injectable dependencies
109
- // ─────────────────────────────────────────────────────────────────────────────
110
-
111
- export const _acpAdapterDeps = {
112
- which(name: string): string | null {
113
- return Bun.which(name);
114
- },
115
-
116
- async sleep(ms: number): Promise<void> {
117
- await Bun.sleep(ms);
118
- },
119
-
120
- /**
121
- * Create an ACP client for the given command string.
122
- * Default: spawn-based client (shells out to acpx CLI).
123
- * Override in tests via: _acpAdapterDeps.createClient = mock(...)
124
- */
125
- createClient(
126
- cmdStr: string,
127
- cwd?: string,
128
- timeoutSeconds?: number,
129
- pidRegistry?: import("../../execution/pid-registry").PidRegistry,
130
- ): AcpClient {
131
- return createSpawnAcpClient(cmdStr, cwd, timeoutSeconds, pidRegistry);
132
- },
133
- };
134
-
135
- // ─────────────────────────────────────────────────────────────────────────────
136
- // Helpers
137
- // ─────────────────────────────────────────────────────────────────────────────
138
-
139
- function resolveRegistryEntry(agentName: string): AgentRegistryEntry {
140
- return AGENT_REGISTRY[agentName] ?? DEFAULT_ENTRY;
141
- }
142
-
143
- function isRateLimitError(err: unknown): boolean {
144
- if (!(err instanceof Error)) return false;
145
- const msg = err.message.toLowerCase();
146
- return msg.includes("rate limit") || msg.includes("rate_limit") || msg.includes("429");
147
- }
148
-
149
- // ─────────────────────────────────────────────────────────────────────────────
150
- // Session naming
151
- // ─────────────────────────────────────────────────────────────────────────────
152
-
153
- /**
154
- * Build a deterministic ACP session name.
155
- *
156
- * Format: nax-<gitRootHash8>-<featureName>-<storyId>[-<sessionRole>]
157
- *
158
- * The workdir hash (first 8 chars of SHA-256) prevents cross-repo and
159
- * cross-worktree session name collisions. Each git worktree has a distinct
160
- * root path, so different worktrees of the same repo get different hashes.
161
- */
162
- export function buildSessionName(
163
- workdir: string,
164
- featureName?: string,
165
- storyId?: string,
166
- sessionRole?: string,
167
- ): string {
168
- const hash = createHash("sha256").update(workdir).digest("hex").slice(0, 8);
169
- const sanitize = (s: string) =>
170
- s
171
- .replace(/[^a-z0-9]+/gi, "-")
172
- .toLowerCase()
173
- .replace(/^-+|-+$/g, "");
174
-
175
- const parts = ["nax", hash];
176
- if (featureName) parts.push(sanitize(featureName));
177
- if (storyId) parts.push(sanitize(storyId));
178
- if (sessionRole) parts.push(sanitize(sessionRole));
179
- return parts.join("-");
180
- }
181
-
182
- // ─────────────────────────────────────────────────────────────────────────────
183
- // Session lifecycle functions (createClient-backed)
184
- // ─────────────────────────────────────────────────────────────────────────────
185
-
186
- /**
187
- * Ensure an ACP session exists: try to resume via loadSession, fall back to
188
- * createSession. Returns the AcpSession ready for prompt() calls.
189
- */
190
- export async function ensureAcpSession(
191
- client: AcpClient,
192
- sessionName: string,
193
- agentName: string,
194
- permissionMode: string,
195
- ): Promise<AcpSession> {
196
- if (!agentName) {
197
- throw new Error("[acp-adapter] agentName is required for ensureAcpSession");
198
- }
199
-
200
- // Try to resume existing session first
201
- if (client.loadSession) {
202
- try {
203
- const existing = await client.loadSession(sessionName, agentName, permissionMode);
204
- if (existing) {
205
- getSafeLogger()?.debug("acp-adapter", `Resumed existing session: ${sessionName}`);
206
- return existing;
207
- }
208
- } catch {
209
- // loadSession failed — fall through to createSession
210
- }
211
- }
212
-
213
- // Create a new named session
214
- getSafeLogger()?.debug("acp-adapter", `Creating new session: ${sessionName}`);
215
- return client.createSession({ agentName, permissionMode, sessionName });
216
- }
217
-
218
- /**
219
- * Send a prompt turn to the session with timeout.
220
- * If the timeout fires, attempts to cancel the active prompt and returns timedOut=true.
221
- */
222
- export async function runSessionPrompt(
223
- session: AcpSession,
224
- prompt: string,
225
- timeoutMs: number,
226
- ): Promise<{ response: AcpSessionResponse | null; timedOut: boolean }> {
227
- const promptPromise = session.prompt(prompt);
228
- const timeoutPromise = new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), timeoutMs));
229
-
230
- const winner = await Promise.race([promptPromise, timeoutPromise]);
231
-
232
- if (winner === "timeout") {
233
- try {
234
- await session.cancelActivePrompt();
235
- } catch {
236
- await session.close().catch(() => {});
237
- }
238
- return { response: null, timedOut: true };
239
- }
240
-
241
- return { response: winner as AcpSessionResponse, timedOut: false };
242
- }
243
-
244
- /**
245
- * Close an ACP session — best-effort, swallows errors.
246
- */
247
- export async function closeAcpSession(session: AcpSession): Promise<void> {
248
- try {
249
- await session.close();
250
- } catch (err) {
251
- getSafeLogger()?.warn("acp-adapter", "Failed to close session", { error: String(err) });
252
- }
253
- }
254
-
255
- // ─────────────────────────────────────────────────────────────────────────────
256
- // ACP session sidecar persistence
257
- // ─────────────────────────────────────────────────────────────────────────────
258
-
259
- /** Path to the ACP sessions sidecar file for a feature. */
260
- function acpSessionsPath(workdir: string, featureName: string): string {
261
- return join(workdir, "nax", "features", featureName, "acp-sessions.json");
262
- }
263
-
264
- /** Sidecar entry — session name + agent name for correct sweep/close. */
265
- type SidecarEntry = string | { sessionName: string; agentName: string };
266
-
267
- /** Extract sessionName from a sidecar entry (handles legacy string format). */
268
- function sidecarSessionName(entry: SidecarEntry): string {
269
- return typeof entry === "string" ? entry : entry.sessionName;
270
- }
271
-
272
- /** Extract agentName from a sidecar entry (defaults to "claude" for legacy entries). */
273
- function sidecarAgentName(entry: SidecarEntry): string {
274
- return typeof entry === "string" ? "claude" : entry.agentName;
275
- }
276
-
277
- /** Persist a session name to the sidecar file. Best-effort — errors are swallowed. */
278
- export async function saveAcpSession(
279
- workdir: string,
280
- featureName: string,
281
- storyId: string,
282
- sessionName: string,
283
- agentName = "claude",
284
- ): Promise<void> {
285
- try {
286
- const path = acpSessionsPath(workdir, featureName);
287
- let data: Record<string, SidecarEntry> = {};
288
- try {
289
- const existing = await Bun.file(path).text();
290
- data = JSON.parse(existing);
291
- } catch {
292
- // File doesn't exist yet — start fresh
293
- }
294
- data[storyId] = { sessionName, agentName };
295
- await Bun.write(path, JSON.stringify(data, null, 2));
296
- } catch (err) {
297
- getSafeLogger()?.warn("acp-adapter", "Failed to save session to sidecar", { error: String(err) });
298
- }
299
- }
300
-
301
- /** Clear a session name from the sidecar file. Best-effort — errors are swallowed. */
302
- export async function clearAcpSession(workdir: string, featureName: string, storyId: string): Promise<void> {
303
- try {
304
- const path = acpSessionsPath(workdir, featureName);
305
- let data: Record<string, string> = {};
306
- try {
307
- const existing = await Bun.file(path).text();
308
- data = JSON.parse(existing);
309
- } catch {
310
- return; // File doesn't exist — nothing to clear
311
- }
312
- delete data[storyId];
313
- await Bun.write(path, JSON.stringify(data, null, 2));
314
- } catch (err) {
315
- getSafeLogger()?.warn("acp-adapter", "Failed to clear session from sidecar", { error: String(err) });
316
- }
317
- }
318
-
319
- /** Read a persisted session name from the sidecar file. Returns null if not found. */
320
- export async function readAcpSession(workdir: string, featureName: string, storyId: string): Promise<string | null> {
321
- try {
322
- const path = acpSessionsPath(workdir, featureName);
323
- const existing = await Bun.file(path).text();
324
- const data: Record<string, SidecarEntry> = JSON.parse(existing);
325
- const entry = data[storyId];
326
- return entry ? sidecarSessionName(entry) : null;
327
- } catch {
328
- return null;
329
- }
330
- }
331
-
332
- // ─────────────────────────────────────────────────────────────────────────────
333
- // Session sweep — close open sessions at run boundaries
334
- // ─────────────────────────────────────────────────────────────────────────────
335
-
336
- const MAX_SESSION_AGE_MS = 2 * 60 * 60 * 1000; // 2 hours
337
-
338
- /**
339
- * Close all open sessions tracked in the sidecar file for a feature.
340
- * Called at run-end to ensure no sessions leak past the run boundary.
341
- */
342
- export async function sweepFeatureSessions(workdir: string, featureName: string): Promise<void> {
343
- const path = acpSessionsPath(workdir, featureName);
344
- let sessions: Record<string, SidecarEntry>;
345
- try {
346
- const text = await Bun.file(path).text();
347
- sessions = JSON.parse(text) as Record<string, SidecarEntry>;
348
- } catch {
349
- return; // No sidecar — nothing to sweep
350
- }
351
-
352
- const entries = Object.entries(sessions);
353
- if (entries.length === 0) return;
354
-
355
- const logger = getSafeLogger();
356
- logger?.info("acp-adapter", `[sweep] Closing ${entries.length} open sessions for feature: ${featureName}`);
357
-
358
- // Group sessions by agent name so we create one client per agent
359
- const byAgent = new Map<string, string[]>();
360
- for (const [, entry] of entries) {
361
- const agent = sidecarAgentName(entry);
362
- const name = sidecarSessionName(entry);
363
- if (!byAgent.has(agent)) byAgent.set(agent, []);
364
- byAgent.get(agent)?.push(name);
365
- }
366
-
367
- for (const [agentName, sessionNames] of byAgent) {
368
- const cmdStr = `acpx ${agentName}`;
369
- const client = _acpAdapterDeps.createClient(cmdStr, workdir);
370
- try {
371
- await client.start();
372
- for (const sessionName of sessionNames) {
373
- try {
374
- if (client.loadSession) {
375
- const session = await client.loadSession(sessionName, agentName, "approve-reads");
376
- if (session) {
377
- await session.close().catch(() => {});
378
- }
379
- }
380
- } catch (err) {
381
- logger?.warn("acp-adapter", `[sweep] Failed to close session ${sessionName}`, { error: String(err) });
382
- }
383
- }
384
- } finally {
385
- await client.close().catch(() => {});
386
- }
387
- }
388
-
389
- // Clear sidecar after sweep
390
- try {
391
- await Bun.write(path, JSON.stringify({}, null, 2));
392
- } catch (err) {
393
- logger?.warn("acp-adapter", "[sweep] Failed to clear sidecar after sweep", { error: String(err) });
394
- }
395
- }
396
-
397
- /**
398
- * Sweep stale sessions if the sidecar file is older than maxAgeMs.
399
- * Called at startup as a safety net for sessions orphaned by crashes.
400
- */
401
- export async function sweepStaleFeatureSessions(
402
- workdir: string,
403
- featureName: string,
404
- maxAgeMs = MAX_SESSION_AGE_MS,
405
- ): Promise<void> {
406
- const path = acpSessionsPath(workdir, featureName);
407
- const file = Bun.file(path);
408
- if (!(await file.exists())) return;
409
-
410
- const ageMs = Date.now() - file.lastModified;
411
- if (ageMs < maxAgeMs) return; // Recent sidecar — skip
412
-
413
- getSafeLogger()?.info(
414
- "acp-adapter",
415
- `[sweep] Sidecar is ${Math.round(ageMs / 60000)}m old — sweeping stale sessions`,
416
- {
417
- featureName,
418
- ageMs,
419
- },
420
- );
421
-
422
- await sweepFeatureSessions(workdir, featureName);
423
- }
424
-
425
- // ─────────────────────────────────────────────────────────────────────────────
426
- // Output helpers
427
- // ─────────────────────────────────────────────────────────────────────────────
428
-
429
- /**
430
- * Extract combined assistant output text from a session response.
431
- */
432
- function extractOutput(response: AcpSessionResponse | null): string {
433
- if (!response) return "";
434
- return response.messages
435
- .filter((m) => m.role === "assistant")
436
- .map((m) => m.content)
437
- .join("\n")
438
- .trim();
439
- }
440
-
441
- /**
442
- * Extract a question from agent output text, if present.
443
- */
444
- function extractQuestion(output: string): string | null {
445
- const text = output.trim();
446
- if (!text) return null;
447
-
448
- const sentences = text.split(/(?<=[.!?])\s+/);
449
- const questionSentences = sentences.filter((s) => s.trim().endsWith("?"));
450
- if (questionSentences.length > 0) {
451
- const q = questionSentences[questionSentences.length - 1].trim();
452
- if (q.length > 10) return q;
453
- }
454
-
455
- const lower = text.toLowerCase();
456
- const markers = [
457
- "please confirm",
458
- "please specify",
459
- "please provide",
460
- "which would you",
461
- "should i ",
462
- "do you want",
463
- "can you clarify",
464
- ];
465
- for (const marker of markers) {
466
- if (lower.includes(marker)) {
467
- return text.slice(-200).trim();
468
- }
469
- }
470
-
471
- return null;
472
- }
473
-
474
- // ─────────────────────────────────────────────────────────────────────────────
475
- // AcpAgentAdapter
476
- // ─────────────────────────────────────────────────────────────────────────────
477
-
478
- export class AcpAgentAdapter implements AgentAdapter {
479
- readonly name: string;
480
- readonly displayName: string;
481
- readonly binary: string;
482
- readonly capabilities: AgentCapabilities;
483
-
484
- constructor(agentName: string) {
485
- const entry = resolveRegistryEntry(agentName);
486
- this.name = agentName;
487
- this.displayName = entry.displayName;
488
- this.binary = entry.binary;
489
- this.capabilities = {
490
- supportedTiers: entry.supportedTiers,
491
- maxContextTokens: entry.maxContextTokens,
492
- features: new Set<"tdd" | "review" | "refactor" | "batch">(["tdd", "review", "refactor"]),
493
- };
494
- }
495
-
496
- async isInstalled(): Promise<boolean> {
497
- const path = _acpAdapterDeps.which(this.binary);
498
- return path !== null;
499
- }
500
-
501
- buildCommand(_options: AgentRunOptions): string[] {
502
- // ACP adapter uses createClient, not direct CLI invocation.
503
- // Return a descriptive command for logging/display purposes only.
504
- return ["acpx", this.name, "session"];
505
- }
506
-
507
- buildAllowedEnv(_options?: AgentRunOptions): Record<string, string | undefined> {
508
- // createClient manages its own env; no separate env building needed.
509
- return {};
510
- }
511
-
512
- async run(options: AgentRunOptions): Promise<AgentResult> {
513
- const startTime = Date.now();
514
- let lastError: Error | undefined;
515
-
516
- getSafeLogger()?.debug("acp-adapter", `Starting run for ${this.name}`, {
517
- model: options.modelDef.model,
518
- workdir: options.workdir,
519
- featureName: options.featureName,
520
- storyId: options.storyId,
521
- sessionRole: options.sessionRole,
522
- });
523
-
524
- for (let attempt = 0; attempt < MAX_RATE_LIMIT_RETRIES; attempt++) {
525
- try {
526
- const result = await this._runWithClient(options, startTime);
527
- if (!result.success) {
528
- getSafeLogger()?.warn("acp-adapter", `Run failed for ${this.name}`, { exitCode: result.exitCode });
529
- }
530
- return result;
531
- } catch (err) {
532
- const error = err instanceof Error ? err : new Error(String(err));
533
- lastError = error;
534
-
535
- const shouldRetry = isRateLimitError(error) && attempt < MAX_RATE_LIMIT_RETRIES - 1;
536
- if (!shouldRetry) break;
537
-
538
- const backoffMs = 2 ** (attempt + 1) * 1000;
539
- getSafeLogger()?.warn("acp-adapter", "Retrying after rate limit", {
540
- backoffSeconds: backoffMs / 1000,
541
- attempt: attempt + 1,
542
- });
543
- await _acpAdapterDeps.sleep(backoffMs);
544
- }
545
- }
546
-
547
- const durationMs = Date.now() - startTime;
548
- return {
549
- success: false,
550
- exitCode: 1,
551
- output: lastError?.message ?? "Run failed",
552
- rateLimited: isRateLimitError(lastError),
553
- durationMs,
554
- estimatedCost: 0,
555
- };
556
- }
557
-
558
- private async _runWithClient(options: AgentRunOptions, startTime: number): Promise<AgentResult> {
559
- const cmdStr = `acpx --model ${options.modelDef.model} ${this.name}`;
560
- const client = _acpAdapterDeps.createClient(cmdStr, options.workdir, options.timeoutSeconds, options.pidRegistry);
561
- await client.start();
562
-
563
- // 1. Resolve session name: explicit > sidecar > derived
564
- let sessionName = options.acpSessionName;
565
- if (!sessionName && options.featureName && options.storyId) {
566
- sessionName = (await readAcpSession(options.workdir, options.featureName, options.storyId)) ?? undefined;
567
- }
568
- sessionName ??= buildSessionName(options.workdir, options.featureName, options.storyId, options.sessionRole);
569
-
570
- // 2. Resolve permission mode from config via single source of truth.
571
- const resolvedPerm = resolvePermissions(options.config, options.pipelineStage ?? "run");
572
- const permissionMode = resolvedPerm.mode;
573
- getSafeLogger()?.info("acp-adapter", "Permission mode resolved", {
574
- permission: permissionMode,
575
- stage: options.pipelineStage ?? "run",
576
- });
577
-
578
- // 3. Ensure session (resume existing or create new)
579
- const session = await ensureAcpSession(client, sessionName, this.name, permissionMode);
580
-
581
- // 4. Persist for plan→run continuity
582
- if (options.featureName && options.storyId) {
583
- await saveAcpSession(options.workdir, options.featureName, options.storyId, sessionName, this.name);
584
- }
585
-
586
- let lastResponse: AcpSessionResponse | null = null;
587
- let timedOut = false;
588
- // Tracks whether the run completed successfully — used by finally to decide
589
- // whether to close the session (success) or keep it open for retry (failure).
590
- const runState = { succeeded: false };
591
- const totalTokenUsage = {
592
- input_tokens: 0,
593
- output_tokens: 0,
594
- cache_read_input_tokens: 0,
595
- cache_creation_input_tokens: 0,
596
- };
597
- let totalExactCostUsd: number | undefined;
598
-
599
- try {
600
- // 5. Multi-turn loop
601
- let currentPrompt = options.prompt;
602
- let turnCount = 0;
603
- const MAX_TURNS = options.interactionBridge ? (options.maxInteractionTurns ?? 10) : 1;
604
-
605
- while (turnCount < MAX_TURNS) {
606
- turnCount++;
607
- getSafeLogger()?.debug("acp-adapter", `Session turn ${turnCount}/${MAX_TURNS}`, { sessionName });
608
-
609
- const turnResult = await runSessionPrompt(session, currentPrompt, options.timeoutSeconds * 1000);
610
-
611
- if (turnResult.timedOut) {
612
- timedOut = true;
613
- break;
614
- }
615
-
616
- lastResponse = turnResult.response;
617
- if (!lastResponse) break;
618
-
619
- // Accumulate token usage and exact cost
620
- if (lastResponse.cumulative_token_usage) {
621
- totalTokenUsage.input_tokens += lastResponse.cumulative_token_usage.input_tokens ?? 0;
622
- totalTokenUsage.output_tokens += lastResponse.cumulative_token_usage.output_tokens ?? 0;
623
- totalTokenUsage.cache_read_input_tokens += lastResponse.cumulative_token_usage.cache_read_input_tokens ?? 0;
624
- totalTokenUsage.cache_creation_input_tokens +=
625
- lastResponse.cumulative_token_usage.cache_creation_input_tokens ?? 0;
626
- }
627
- if (lastResponse.exactCostUsd !== undefined) {
628
- totalExactCostUsd = (totalExactCostUsd ?? 0) + lastResponse.exactCostUsd;
629
- }
630
-
631
- // Check for agent question → route to interaction bridge
632
- const outputText = extractOutput(lastResponse);
633
- const question = extractQuestion(outputText);
634
- if (!question || !options.interactionBridge) break;
635
-
636
- getSafeLogger()?.debug("acp-adapter", "Agent asked question, routing to interactionBridge", { question });
637
-
638
- try {
639
- const answer = await Promise.race([
640
- options.interactionBridge.onQuestionDetected(question),
641
- new Promise<never>((_, reject) =>
642
- setTimeout(() => reject(new Error("interaction timeout")), INTERACTION_TIMEOUT_MS),
643
- ),
644
- ]);
645
- currentPrompt = answer;
646
- } catch (err) {
647
- const msg = err instanceof Error ? err.message : String(err);
648
- getSafeLogger()?.warn("acp-adapter", `InteractionBridge failed: ${msg}`);
649
- break;
650
- }
651
- }
652
-
653
- // Only warn if we exhausted turns while still receiving questions (interactive mode).
654
- // In non-interactive mode (MAX_TURNS=1) the loop always completes in 1 turn — not a warning.
655
- if (turnCount >= MAX_TURNS && options.interactionBridge) {
656
- getSafeLogger()?.warn("acp-adapter", "Reached max turns limit", { sessionName, maxTurns: MAX_TURNS });
657
- }
658
-
659
- // Compute success here so finally can use it for conditional close.
660
- runState.succeeded = !timedOut && lastResponse?.stopReason === "end_turn";
661
- } finally {
662
- // 6. Cleanup — close session and clear sidecar only on success.
663
- // On failure, keep session open so retry can resume with full context.
664
- // When keepSessionOpen=true (e.g. rectification loop), skip close even on success
665
- // so all attempts share the same conversation context.
666
- if (runState.succeeded && !options.keepSessionOpen) {
667
- await closeAcpSession(session);
668
- if (options.featureName && options.storyId) {
669
- await clearAcpSession(options.workdir, options.featureName, options.storyId);
670
- }
671
- } else if (!runState.succeeded) {
672
- getSafeLogger()?.info("acp-adapter", "Keeping session open for retry", { sessionName });
673
- } else {
674
- getSafeLogger()?.debug("acp-adapter", "Keeping session open (keepSessionOpen=true)", { sessionName });
675
- }
676
- await client.close().catch(() => {});
677
- }
678
-
679
- const durationMs = Date.now() - startTime;
680
-
681
- if (timedOut) {
682
- return {
683
- success: false,
684
- exitCode: 124,
685
- output: `Session timed out after ${options.timeoutSeconds}s`,
686
- rateLimited: false,
687
- durationMs,
688
- estimatedCost: 0,
689
- };
690
- }
691
-
692
- const success = lastResponse?.stopReason === "end_turn";
693
- const output = extractOutput(lastResponse);
694
-
695
- // Prefer exact cost from acpx usage_update; fall back to token-based estimation
696
- const estimatedCost =
697
- totalExactCostUsd ??
698
- (totalTokenUsage.input_tokens > 0 || totalTokenUsage.output_tokens > 0
699
- ? estimateCostFromTokenUsage(totalTokenUsage, options.modelDef.model)
700
- : 0);
701
-
702
- return {
703
- success,
704
- exitCode: success ? 0 : 1,
705
- output: output.slice(-MAX_AGENT_OUTPUT_CHARS),
706
- rateLimited: false,
707
- durationMs,
708
- estimatedCost,
709
- };
710
- }
711
-
712
- async complete(prompt: string, _options?: CompleteOptions): Promise<string> {
713
- const model = _options?.model ?? "default";
714
- const timeoutMs = _options?.timeoutMs ?? 120_000; // 2-min safety net by default
715
- const permissionMode = resolvePermissions(_options?.config, "complete").mode;
716
- const workdir = _options?.workdir;
717
-
718
- let lastError: Error | undefined;
719
-
720
- for (let attempt = 0; attempt < MAX_RATE_LIMIT_RETRIES; attempt++) {
721
- const cmdStr = `acpx --model ${model} ${this.name}`;
722
- const client = _acpAdapterDeps.createClient(cmdStr, workdir);
723
- await client.start();
724
-
725
- let session: AcpSession | null = null;
726
- try {
727
- // complete() is one-shot — ephemeral session, no sidecar
728
- // Use caller-provided sessionName if available (aids tracing), otherwise timestamp-based
729
- session = await client.createSession({
730
- agentName: this.name,
731
- permissionMode,
732
- sessionName: _options?.sessionName,
733
- });
734
-
735
- // Enforce timeout via Promise.race — session.prompt() can hang indefinitely
736
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
737
- const timeoutPromise = new Promise<never>((_, reject) => {
738
- timeoutId = setTimeout(() => reject(new Error(`complete() timed out after ${timeoutMs}ms`)), timeoutMs);
739
- });
740
- timeoutPromise.catch(() => {}); // prevent unhandled rejection if promptPromise wins
741
-
742
- const promptPromise = session.prompt(prompt);
743
-
744
- let response: AcpSessionResponse;
745
- try {
746
- response = await Promise.race([promptPromise, timeoutPromise]);
747
- } finally {
748
- clearTimeout(timeoutId);
749
- }
750
-
751
- if (response.stopReason === "error") {
752
- throw new CompleteError("complete() failed: stop reason is error");
753
- }
754
-
755
- const text = response.messages
756
- .filter((m) => m.role === "assistant")
757
- .map((m) => m.content)
758
- .join("\n")
759
- .trim();
760
-
761
- // ACP one-shot sessions wrap the response in a result envelope:
762
- // {"type":"result","subtype":"success","result":"<actual output>"}
763
- // Unwrap to return the actual content.
764
- let unwrapped = text;
765
- try {
766
- const envelope = JSON.parse(text) as Record<string, unknown>;
767
- if (envelope?.type === "result" && typeof envelope?.result === "string") {
768
- unwrapped = envelope.result;
769
- }
770
- } catch {
771
- // Not an envelope — use text as-is
772
- }
773
-
774
- if (!unwrapped) {
775
- throw new CompleteError("complete() returned empty output");
776
- }
777
-
778
- if (response.exactCostUsd !== undefined) {
779
- getSafeLogger()?.info("acp-adapter", "complete() cost", {
780
- costUsd: response.exactCostUsd,
781
- model,
782
- });
783
- }
784
-
785
- return unwrapped;
786
- } catch (err) {
787
- const error = err instanceof Error ? err : new Error(String(err));
788
- lastError = error;
789
-
790
- const shouldRetry = isRateLimitError(error) && attempt < MAX_RATE_LIMIT_RETRIES - 1;
791
- if (!shouldRetry) throw error;
792
-
793
- const backoffMs = 2 ** (attempt + 1) * 1000;
794
- getSafeLogger()?.warn("acp-adapter", "complete() rate limited, retrying", {
795
- backoffSeconds: backoffMs / 1000,
796
- attempt: attempt + 1,
797
- });
798
- await _acpAdapterDeps.sleep(backoffMs);
799
- } finally {
800
- if (session) {
801
- await session.close().catch(() => {});
802
- }
803
- await client.close().catch(() => {});
804
- }
805
- }
806
-
807
- throw lastError ?? new CompleteError("complete() failed with unknown error");
808
- }
809
-
810
- async plan(options: PlanOptions): Promise<PlanResult> {
811
- // Resolve model: explicit > config.models[tier] > config.models.balanced > fallback
812
- let modelDef = options.modelDef;
813
- if (!modelDef && options.config?.models) {
814
- const tier = options.modelTier ?? "balanced";
815
- const { resolveModel } = await import("../../config/schema");
816
- const models = options.config.models as Record<string, unknown>;
817
- const entry = models[tier] ?? models.balanced;
818
- if (entry) {
819
- try {
820
- modelDef = resolveModel(entry as Parameters<typeof resolveModel>[0]);
821
- } catch {
822
- // resolveModel can throw on malformed entries
823
- }
824
- }
825
- }
826
- modelDef ??= { provider: "anthropic", model: "claude-sonnet-4-5-20250514" };
827
- // Timeout: from options, or config, or fallback to 600s
828
- const timeoutSeconds =
829
- options.timeoutSeconds ?? (options.config?.execution?.sessionTimeoutSeconds as number | undefined) ?? 600;
830
-
831
- const result = await this.run({
832
- prompt: options.prompt,
833
- workdir: options.workdir,
834
- modelTier: options.modelTier ?? "balanced",
835
- modelDef,
836
- timeoutSeconds,
837
- dangerouslySkipPermissions: resolvePermissions(
838
- options.config as import("../../config").NaxConfig | undefined,
839
- "plan",
840
- ).skipPermissions,
841
- pipelineStage: "plan",
842
- config: options.config as import("../../config").NaxConfig | undefined,
843
- interactionBridge: options.interactionBridge,
844
- maxInteractionTurns: options.maxInteractionTurns,
845
- featureName: options.featureName,
846
- storyId: options.storyId,
847
- sessionRole: options.sessionRole,
848
- pidRegistry: options.pidRegistry,
849
- });
850
-
851
- if (!result.success) {
852
- throw new Error(`[acp-adapter] plan() failed: ${result.output}`);
853
- }
854
-
855
- const specContent = result.output.trim();
856
- if (!specContent) {
857
- throw new Error("[acp-adapter] plan() returned empty spec content");
858
- }
859
-
860
- return { specContent };
861
- }
862
-
863
- async decompose(options: DecomposeOptions): Promise<DecomposeResult> {
864
- const model = options.modelDef?.model;
865
- const prompt = buildDecomposePrompt(options);
866
-
867
- let output: string;
868
- try {
869
- output = await this.complete(prompt, {
870
- model,
871
- jsonMode: true,
872
- config: options.config as import("../../config").NaxConfig | undefined,
873
- });
874
- } catch (err) {
875
- const msg = err instanceof Error ? err.message : String(err);
876
- throw new Error(`[acp-adapter] decompose() failed: ${msg}`, { cause: err });
877
- }
878
-
879
- let stories: ReturnType<typeof parseDecomposeOutput>;
880
- try {
881
- stories = parseDecomposeOutput(output);
882
- } catch (err) {
883
- throw new Error(`[acp-adapter] decompose() failed to parse stories: ${(err as Error).message}`, { cause: err });
884
- }
885
-
886
- return { stories };
887
- }
888
- }