@adhdev/daemon-core 0.9.82-rc.35 → 0.9.82-rc.350

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 (318) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +46 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +110 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +324 -1
  23. package/dist/commands/upgrade-helper.d.ts +12 -0
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +52 -13
  37. package/dist/index.js +39739 -14302
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +41369 -16055
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/mesh/contracts.d.ts +164 -0
  48. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  49. package/dist/mesh/coordinator-registry.d.ts +59 -0
  50. package/dist/mesh/mesh-active-work.d.ts +174 -0
  51. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  52. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  53. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  54. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  55. package/dist/mesh/mesh-events-utils.d.ts +62 -0
  56. package/dist/mesh/mesh-events.d.ts +6 -49
  57. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  58. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  59. package/dist/mesh/mesh-init.d.ts +86 -0
  60. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  61. package/dist/mesh/mesh-ledger.d.ts +77 -1
  62. package/dist/mesh/mesh-missions.d.ts +164 -0
  63. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  64. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  65. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  66. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  67. package/dist/mesh/mesh-routing.d.ts +70 -0
  68. package/dist/mesh/mesh-runtime-store.d.ts +419 -0
  69. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  70. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  71. package/dist/mesh/mesh-work-queue.d.ts +218 -5
  72. package/dist/mesh/preview-freshness.d.ts +18 -0
  73. package/dist/mesh/refine-config.d.ts +216 -0
  74. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  75. package/dist/providers/acp-provider-instance.d.ts +2 -0
  76. package/dist/providers/approval-utils.d.ts +13 -0
  77. package/dist/providers/chat-message-normalization.d.ts +12 -0
  78. package/dist/providers/cli-provider-instance.d.ts +77 -3
  79. package/dist/providers/contracts.d.ts +139 -6
  80. package/dist/providers/external-sources.d.ts +71 -0
  81. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  82. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  83. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  84. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  85. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  86. package/dist/providers/native-history/index.d.ts +13 -0
  87. package/dist/providers/provider-instance-manager.d.ts +14 -0
  88. package/dist/providers/provider-instance.d.ts +15 -1
  89. package/dist/providers/provider-loader.d.ts +26 -4
  90. package/dist/providers/provider-trust.d.ts +31 -0
  91. package/dist/providers/read-chat-contract.d.ts +29 -0
  92. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  93. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  94. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  95. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  96. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  97. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  98. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  99. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  100. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  101. package/dist/providers/sdk/v1/index.d.ts +30 -0
  102. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  103. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  104. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  105. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  106. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  107. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  108. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  109. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  110. package/dist/providers/spec/adapter.d.ts +69 -0
  111. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  112. package/dist/providers/spec/evaluator.d.ts +23 -0
  113. package/dist/providers/spec/fsm-driver.d.ts +322 -0
  114. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  115. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  116. package/dist/providers/spec/fsm-types.d.ts +144 -0
  117. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  118. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  119. package/dist/providers/spec/route.d.ts +4 -0
  120. package/dist/providers/spec/types.d.ts +180 -0
  121. package/dist/providers/status-monitor.d.ts +7 -7
  122. package/dist/providers/transcript-v2.d.ts +176 -0
  123. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  124. package/dist/providers/working-dir.d.ts +17 -0
  125. package/dist/repo-mesh-types.d.ts +295 -13
  126. package/dist/sessions/registry.d.ts +6 -0
  127. package/dist/shared-types-extra.d.ts +2 -4
  128. package/dist/shared-types.d.ts +59 -2
  129. package/dist/status/normalize.d.ts +1 -1
  130. package/dist/status/normalize.js +1 -0
  131. package/dist/status/normalize.js.map +1 -1
  132. package/dist/status/normalize.mjs +1 -0
  133. package/dist/status/normalize.mjs.map +1 -1
  134. package/dist/status/reporter.d.ts +2 -0
  135. package/dist/status/snapshot.d.ts +26 -0
  136. package/dist/system/load-better-sqlite3.d.ts +21 -0
  137. package/dist/types.d.ts +5 -0
  138. package/package.json +7 -3
  139. package/src/agent-stream/poller.ts +2 -3
  140. package/src/agent-stream/provider-adapter.ts +1 -1
  141. package/src/boot/daemon-lifecycle.ts +55 -12
  142. package/src/boot/process-hardening.ts +89 -0
  143. package/src/build-info.ts +73 -0
  144. package/src/chat/source-machine.ts +534 -0
  145. package/src/chat/source-resolver.ts +0 -0
  146. package/src/chat/subscription-updates.ts +20 -1
  147. package/src/cli-adapter-types.d.ts +1 -0
  148. package/src/cli-adapter-types.ts +47 -2
  149. package/src/cli-adapters/cli-script-runner.ts +421 -0
  150. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  151. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  152. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  153. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  154. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  155. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  156. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  157. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  158. package/src/cli-adapters/pty-transport.ts +2 -1
  159. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  160. package/src/cli-adapters/resolve-executable.ts +90 -0
  161. package/src/cli-adapters/session-host-transport.ts +2 -1
  162. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  163. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  164. package/src/cli-adapters/terminal-screen.ts +16 -81
  165. package/src/commands/chat-commands.ts +1823 -62
  166. package/src/commands/cli-manager.ts +304 -14
  167. package/src/commands/handler.ts +809 -2
  168. package/src/commands/mesh-coordinator.ts +332 -122
  169. package/src/commands/router.ts +7505 -1311
  170. package/src/commands/stream-commands.ts +8 -0
  171. package/src/commands/upgrade-helper.ts +81 -30
  172. package/src/config/chat-history.ts +483 -24
  173. package/src/config/config.ts +12 -0
  174. package/src/config/mesh-config.ts +388 -6
  175. package/src/config/recent-activity.ts +8 -2
  176. package/src/daemon/dev-auto-implement.ts +3 -2
  177. package/src/daemon/dev-cli-debug.ts +10 -1
  178. package/src/detection/cli-detector.ts +28 -9
  179. package/src/detection/ide-detector.ts +55 -16
  180. package/src/detection/win32-ide-version.ts +106 -0
  181. package/src/git/change-impact-config.ts +354 -0
  182. package/src/git/git-commands.ts +55 -14
  183. package/src/git/git-diff.ts +53 -0
  184. package/src/git/git-executor.ts +12 -0
  185. package/src/git/git-status.ts +574 -43
  186. package/src/git/git-types.ts +14 -62
  187. package/src/git/git-worktree.ts +8 -1
  188. package/src/git/index.ts +16 -0
  189. package/src/index.ts +146 -12
  190. package/src/installer.d.ts +1 -1
  191. package/src/installer.ts +8 -6
  192. package/src/ipc/local-ipc-server.ts +278 -0
  193. package/src/launch.d.ts +1 -1
  194. package/src/launch.ts +37 -28
  195. package/src/logging/async-batch-writer.ts +55 -0
  196. package/src/logging/log-redactor.ts +100 -0
  197. package/src/logging/log-tail-reader.ts +220 -0
  198. package/src/logging/logger.ts +2 -1
  199. package/src/mesh/contracts.ts +329 -0
  200. package/src/mesh/coordinator-prompt.ts +234 -31
  201. package/src/mesh/coordinator-registry.ts +121 -0
  202. package/src/mesh/mesh-active-work.ts +623 -0
  203. package/src/mesh/mesh-delivery-policy.ts +315 -0
  204. package/src/mesh/mesh-events-coordinator.ts +2224 -0
  205. package/src/mesh/mesh-events-pending.ts +558 -0
  206. package/src/mesh/mesh-events-stale.ts +290 -0
  207. package/src/mesh/mesh-events-utils.ts +381 -0
  208. package/src/mesh/mesh-events.ts +30 -1035
  209. package/src/mesh/mesh-fast-forward.ts +839 -0
  210. package/src/mesh/mesh-host-ownership.ts +73 -0
  211. package/src/mesh/mesh-init.ts +260 -0
  212. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  213. package/src/mesh/mesh-ledger.ts +590 -102
  214. package/src/mesh/mesh-missions.ts +322 -0
  215. package/src/mesh/mesh-reconcile-loop.ts +989 -0
  216. package/src/mesh/mesh-refine-batch.ts +197 -0
  217. package/src/mesh/mesh-refine-status.ts +231 -0
  218. package/src/mesh/mesh-review-inbox.ts +307 -0
  219. package/src/mesh/mesh-routing.ts +291 -0
  220. package/src/mesh/mesh-runtime-store.ts +1660 -0
  221. package/src/mesh/mesh-task-stats.ts +154 -0
  222. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  223. package/src/mesh/mesh-work-queue.ts +901 -141
  224. package/src/mesh/preview-freshness.ts +118 -0
  225. package/src/mesh/refine-config.ts +423 -0
  226. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  227. package/src/providers/acp-provider-instance.ts +25 -9
  228. package/src/providers/approval-utils.d.ts +4 -0
  229. package/src/providers/approval-utils.ts +47 -5
  230. package/src/providers/chat-message-normalization.ts +45 -5
  231. package/src/providers/cli-provider-instance.ts +1041 -99
  232. package/src/providers/contracts.d.ts +55 -0
  233. package/src/providers/contracts.ts +150 -6
  234. package/src/providers/extension-provider-instance.ts +12 -7
  235. package/src/providers/external-sources.ts +218 -0
  236. package/src/providers/ide-provider-instance.ts +35 -12
  237. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  238. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  239. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  240. package/src/providers/native-history/dispatcher.ts +340 -0
  241. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  242. package/src/providers/native-history/index.ts +30 -0
  243. package/src/providers/provider-instance-manager.ts +30 -0
  244. package/src/providers/provider-instance.ts +10 -1
  245. package/src/providers/provider-loader.ts +670 -50
  246. package/src/providers/provider-schema.ts +87 -14
  247. package/src/providers/provider-trust.ts +114 -0
  248. package/src/providers/read-chat-contract.ts +76 -16
  249. package/src/providers/sdk/README.md +49 -0
  250. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  251. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  252. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  253. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  254. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  255. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  256. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  257. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  258. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  259. package/src/providers/sdk/v1/index.ts +152 -0
  260. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  261. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  262. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  263. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  264. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  265. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  272. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  279. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  280. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  281. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  282. package/src/providers/sdk/v1/validators/index.ts +19 -0
  283. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  284. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  285. package/src/providers/spec/adapter.ts +168 -0
  286. package/src/providers/spec/cli-adapter.ts +986 -0
  287. package/src/providers/spec/evaluator.ts +345 -0
  288. package/src/providers/spec/fsm-driver.ts +1065 -0
  289. package/src/providers/spec/fsm-evaluator.ts +255 -0
  290. package/src/providers/spec/fsm-loader.ts +120 -0
  291. package/src/providers/spec/fsm-types.ts +238 -0
  292. package/src/providers/spec/native-history-executor.ts +1136 -0
  293. package/src/providers/spec/pre-launch-trust.ts +104 -0
  294. package/src/providers/spec/route.ts +51 -0
  295. package/src/providers/spec/types.ts +226 -0
  296. package/src/providers/status-monitor.d.ts +7 -7
  297. package/src/providers/status-monitor.ts +37 -22
  298. package/src/providers/transcript-v2.ts +567 -0
  299. package/src/providers/types/interactive-prompt.ts +536 -0
  300. package/src/providers/version-archive.ts +64 -24
  301. package/src/providers/working-dir.ts +23 -0
  302. package/src/repo-mesh-types.ts +378 -14
  303. package/src/sessions/registry.ts +6 -0
  304. package/src/shared-types-extra.ts +2 -4
  305. package/src/shared-types.d.ts +8 -0
  306. package/src/shared-types.ts +64 -1
  307. package/src/status/builders.ts +26 -6
  308. package/src/status/normalize.ts +2 -0
  309. package/src/status/reporter.ts +19 -1
  310. package/src/status/snapshot.ts +95 -26
  311. package/src/system/host-memory.ts +29 -12
  312. package/src/system/load-better-sqlite3.ts +68 -0
  313. package/src/types.ts +5 -0
  314. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  315. package/dist/mesh/mesh-sync.d.ts +0 -53
  316. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  317. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  318. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,986 @@
1
+ /**
2
+ * SpecCliAdapter — bridges SpecDriver into the daemon's CliAdapter
3
+ * interface so an existing CliProviderInstance can drive a spec-backed
4
+ * provider without rewriting the surrounding session machinery.
5
+ *
6
+ * Translation:
7
+ * spec state.id 'approval' (with modal_buttons that produced a modal)
8
+ * → CliAdapterStatus.status='waiting_approval', activeModal={...}
9
+ * spec state.id 'busy' / any non-decision state with a 'busy' label
10
+ * → status='generating'
11
+ * spec state.id 'idle' or default
12
+ * → status='idle'
13
+ *
14
+ * Methods that the round-3 spec model doesn't have an opinion on
15
+ * (transcript reading, slash commands, history, runtime metadata
16
+ * surfacing) are minimal stubs. They satisfy the daemon's call sites
17
+ * without pretending to implement anything.
18
+ */
19
+ 'use strict';
20
+
21
+ import { FsmDriver, type DashboardEvent, type ISpecDriver } from './fsm-driver.js';
22
+ import { executeNativeHistory } from './native-history-executor.js';
23
+ import * as fs from 'node:fs';
24
+ import type { NativeHistoryConfig, Control, ControlAction } from './types.js';
25
+ import type { CliAdapter, CliAdapterStatus } from '../../cli-adapter-types.js';
26
+ import type { ChatMessage } from '../../types.js';
27
+ import type { PtyTransportFactory } from '../../cli-adapters/pty-transport.js';
28
+ import { LOG } from '../../logging/logger.js';
29
+ import {
30
+ buildClaudeInteractiveTuiAnswerSteps,
31
+ buildClaudeInteractiveToolResult,
32
+ detectClaudeAskUserQuestionPromptFromJson,
33
+ detectClaudeAskUserQuestionPromptFromTuiPages,
34
+ detectClaudeTuiMultiSelect,
35
+ readFocusedClaudeTuiQuestion,
36
+ type ClaudeInteractiveTuiPage,
37
+ type InteractivePrompt,
38
+ type InteractivePromptResponse,
39
+ } from '../types/interactive-prompt.js';
40
+
41
+
42
+ function stripAnsi(text: string): string {
43
+ // eslint-disable-next-line no-control-regex
44
+ return String(text || '')
45
+ .replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, '')
46
+ .replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, '')
47
+ .replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, '');
48
+ }
49
+
50
+ function delay(ms: number): Promise<void> {
51
+ return new Promise(resolve => setTimeout(resolve, ms));
52
+ }
53
+
54
+ export class SpecCliAdapter implements CliAdapter {
55
+ readonly cliType: string;
56
+ readonly cliName: string;
57
+ readonly workingDir: string;
58
+ /**
59
+ * Marker the daemon's finalization gate checks: `getStatus()` returns
60
+ * `messages: []` by design here (chat history lives in the daemon's
61
+ * native-history pipeline, not the adapter). Without this flag,
62
+ * cli-provider-instance's `missing_final_assistant` gate would stall
63
+ * every turn until the 30s safety timeout because it expects the
64
+ * adapter to surface the final assistant message.
65
+ */
66
+ readonly chatMessagesOwnedExternally = true as const;
67
+
68
+ private driver: ISpecDriver;
69
+ /** Common spec fields the adapter reads, present in both v3 and v4. */
70
+ private spec: {
71
+ id: string;
72
+ name: string;
73
+ control_bar?: Control[];
74
+ native_history?: NativeHistoryConfig;
75
+ };
76
+ private lastEvent: DashboardEvent | null = null;
77
+ private latestState: { id: string; label: string; title: string | null; status: 'idle' | 'generating' | 'approval' } | null = null;
78
+ private latestModal: { title: string | null; buttons: { index: number; label: string }[] } | null = null;
79
+ private statusCallback: (() => void) | null = null;
80
+ private ptyDataCallback: ((data: string) => void) | null = null;
81
+ private partialResponse = '';
82
+ private activeInteractivePrompt: InteractivePrompt | null = null;
83
+ private interactivePromptTransport: 'stream-json' | 'tui' | null = null;
84
+ private claudeTuiPromptCaptureInFlight = false;
85
+ /**
86
+ * Wall clock of the first frame on which a held interactive prompt was
87
+ * observed to have left the screen. Mirrors the approval FSM's
88
+ * `modalLostAt` hysteresis (see cli-state-engine.ts): claude-cli's TUI
89
+ * repaints the choice picker as several PTY chunks, so a single frame
90
+ * with no "Enter to select" footer is not proof the prompt is gone — it
91
+ * may just be mid-repaint. We only clear the held prompt once it has
92
+ * been absent across a short grace window. Reset to null the moment the
93
+ * prompt footer reappears.
94
+ *
95
+ * Without this, a choice prompt resolved *directly in the terminal* (the
96
+ * user picked an option without going through ADHDev's
97
+ * setInteractivePromptResponse) was never cleared from
98
+ * `activeInteractivePrompt`, so getStatus() re-emitted the same prompt
99
+ * forever — the choice-resolve-stuck bug.
100
+ */
101
+ private interactivePromptLostAt: number | null = null;
102
+ private jsonLineTail = '';
103
+ private exited = false;
104
+ private spawned = false;
105
+ private providerSessionId: string | undefined;
106
+ /** Wall clock at the moment spawn() ran. Used as the cutoff for
107
+ * native-history file selection so a prior session's transcript
108
+ * can't leak into this session before the agent has written its
109
+ * own records. */
110
+ private spawnedAtMs = 0;
111
+ /** Env vars the daemon set on the spawned child. Mesh coordinator
112
+ * points hermes at a per-coordinator HERMES_HOME so the dashboard's
113
+ * native-history reader needs that override to find the right
114
+ * state.db; without it the reader sees ~/.hermes/state.db which
115
+ * the coordinator-launched hermes never writes to. The choice to
116
+ * redirect HERMES_HOME is a workaround for an unresolved hermes
117
+ * upstream feature gap (see hermes-agent#23130 — runtime-supplied
118
+ * MCP config), so this routing keeps the dashboard honest until
119
+ * hermes ships a runtime MCP override. */
120
+ private spawnedEnv: Record<string, string> = {};
121
+
122
+ constructor(
123
+ specPath: string,
124
+ workingDir: string,
125
+ cliArgs: string[],
126
+ extraEnv: Record<string, string>,
127
+ transportFactory?: PtyTransportFactory,
128
+ ) {
129
+ const raw = JSON.parse(fs.readFileSync(specPath, 'utf8'));
130
+ this.spec = {
131
+ id: raw.id,
132
+ name: raw.name,
133
+ control_bar: raw.control_bar,
134
+ native_history: raw.native_history,
135
+ };
136
+ this.cliType = this.spec.id;
137
+ this.cliName = this.spec.name;
138
+ this.workingDir = workingDir;
139
+ this.spawnedEnv = { ...extraEnv };
140
+
141
+ // cli-manager.ts allocates providerSessionId per launch and threads
142
+ // it through resume.newSessionArgs as additional cliArgs (e.g.
143
+ // ["--session-id", "<uuid>"]). We must hand those to the driver
144
+ // so the agent uses the daemon's id, otherwise (claude case) the
145
+ // agent generates its own id and the chat-history pipeline can't
146
+ // pair the on-disk transcript with the live session.
147
+ this.driver = new FsmDriver({
148
+ specPath,
149
+ workingDir,
150
+ extraEnv,
151
+ hotReload: true,
152
+ emitTrace: false,
153
+ transportFactory,
154
+ extraCliArgs: cliArgs,
155
+ });
156
+ this.driver.subscribe((ev) => this.handleEvent(ev));
157
+ }
158
+
159
+ async spawn(): Promise<void> {
160
+ if (this.spawned) return;
161
+ this.driver.start();
162
+ this.spawned = true;
163
+ this.spawnedAtMs = Date.now();
164
+ }
165
+
166
+ async sendMessage(text: string): Promise<void> {
167
+ // Content-free at info — the prompt body is user data.
168
+ LOG.info('SpecAdapter', `[${this.cliType}] sendMessage(len=${text.length})`);
169
+ LOG.debug('SpecAdapter', `[${this.cliType}] sendMessage body=${JSON.stringify(text.slice(0, 80))}${text.length > 80 ? '…' : ''}`);
170
+ this.driver.dispatch({ kind: 'send_message', text });
171
+ }
172
+
173
+ getStatus(): CliAdapterStatus {
174
+ const sessionFields = this.providerSessionId ? { providerSessionId: this.providerSessionId } : {};
175
+ if (this.exited) return { status: 'stopped', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
176
+ if (!this.spawned) return { status: 'starting', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
177
+
178
+ // Refresh native history lazily — the watch_path is cheap to stat,
179
+ // but parsing a full session.jsonl every call would be wasteful.
180
+ this.maybeRefreshNativeHistory();
181
+
182
+ const state = this.latestState;
183
+ if (!state) return { status: 'starting', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
184
+
185
+ // The FSM state is authoritative for status. We do NOT infer status from whether
186
+ // a modal was parsed this frame: a modal/approval state whose buttons briefly fail
187
+ // to parse (PTY repaint) must still report waiting_approval, not collapse to idle —
188
+ // that collapse fired false completions while a session sat at an approval prompt.
189
+ const modal = this.latestModal;
190
+ if (state.status === 'approval') {
191
+ return {
192
+ status: 'waiting_approval',
193
+ messages: [],
194
+ // Surface buttons when we have them; an approval state with no parsed
195
+ // modal this frame still stays waiting_approval (no activeModal yet).
196
+ activeModal: modal
197
+ ? { message: modal.title ?? state.label, buttons: modal.buttons.map(b => b.label) }
198
+ : null,
199
+ activeInteractivePrompt: this.activeInteractivePrompt,
200
+ ...sessionFields,
201
+ };
202
+ }
203
+ if (state.status === 'generating') {
204
+ return { status: 'generating', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
205
+ }
206
+ return { status: 'idle', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
207
+ }
208
+
209
+ private maybeRefreshNativeHistory(): void {
210
+ // Native history is now sourced by daemon's chat-history pipeline
211
+ // (which calls provider.scripts.readNativeHistory wired by
212
+ // provider-loader). SpecCliAdapter no longer polls or caches.
213
+ }
214
+
215
+ getScriptParsedStatus(): unknown {
216
+ const providerSessionId = this.extractProviderSessionIdFromScreen();
217
+ if (providerSessionId) this.providerSessionId = providerSessionId;
218
+ const status = this.getStatus();
219
+ return {
220
+ ...status,
221
+ messages: this.readClaudeScreenAssistantMessages(),
222
+ ...(this.providerSessionId ? { providerSessionId: this.providerSessionId } : {}),
223
+ };
224
+ }
225
+
226
+ getPartialResponse(): string {
227
+ return this.partialResponse;
228
+ }
229
+
230
+ shutdown(): void {
231
+ try { this.driver.dispatch({ kind: 'shutdown' }); } catch { /* ignore */ }
232
+ }
233
+
234
+ cancel(): void {
235
+ try { this.driver.dispatch({ kind: 'cancel' }); } catch { /* ignore */ }
236
+ }
237
+
238
+ isProcessing(): boolean {
239
+ return this.getStatus().status === 'generating';
240
+ }
241
+
242
+ isReady(): boolean {
243
+ return this.spawned && !this.exited;
244
+ }
245
+
246
+ setOnStatusChange(cb: () => void): void {
247
+ this.statusCallback = cb;
248
+ }
249
+
250
+ setOnPtyData(cb: (data: string) => void): void {
251
+ this.ptyDataCallback = cb;
252
+ }
253
+
254
+ writeRaw(data: string): void {
255
+ // Raw pty input — typed characters, escape codes, arrow keys —
256
+ // goes straight to the underlying terminal. send_message would
257
+ // append submit_key after every chunk, which is why typing in
258
+ // the dashboard terminal felt like "enter on every keystroke".
259
+ this.driver.dispatch({ kind: 'pty_write', data });
260
+ }
261
+
262
+ resize(cols: number, rows: number): void {
263
+ this.driver.dispatch({ kind: 'resize', cols, rows });
264
+ }
265
+
266
+ resolveModal(buttonIndex: number): void {
267
+ // CliAdapter buttonIndex is 0-based; spec buttons are 1-based.
268
+ this.driver.dispatch({ kind: 'click_modal_button', index: buttonIndex + 1 });
269
+ }
270
+
271
+ async resolveAction(data: unknown): Promise<void> {
272
+ const args = (data && typeof data === 'object') ? (data as any) : {};
273
+ const explicitIndex = typeof args.buttonIndex === 'number' ? args.buttonIndex : -1;
274
+ if (explicitIndex >= 0) { this.resolveModal(explicitIndex); return; }
275
+ const action = typeof args.action === 'string' ? args.action : 'approve';
276
+ const buttons = this.latestModal?.buttons ?? [];
277
+ if (buttons.length === 0) return;
278
+ let target = -1;
279
+ if (action === 'reject' || action === 'deny') {
280
+ target = buttons.findIndex(b => /^(no|deny|reject|cancel)\b/i.test(b.label));
281
+ if (target < 0) target = buttons.length - 1;
282
+ } else {
283
+ target = buttons.findIndex(b => /^(yes|allow|approve|accept|continue|proceed|update)\b/i.test(b.label));
284
+ if (target < 0) target = 0;
285
+ }
286
+ this.resolveModal(target);
287
+ }
288
+
289
+ async setInteractivePromptResponse(response: InteractivePromptResponse): Promise<void> {
290
+ const prompt = this.activeInteractivePrompt;
291
+ if (!prompt || prompt.promptId !== response.promptId) throw new Error('Interactive prompt response does not match active prompt');
292
+ if (this.cliType !== 'claude-cli') return;
293
+ if (this.interactivePromptTransport === 'tui') {
294
+ const steps = buildClaudeInteractiveTuiAnswerSteps(prompt, response);
295
+ for (const step of steps) {
296
+ this.driver.dispatch({ kind: 'pty_write', data: step });
297
+ await new Promise(resolve => setTimeout(resolve, 180));
298
+ }
299
+ } else {
300
+ this.driver.dispatch({ kind: 'pty_write', data: `${buildClaudeInteractiveToolResult(response)}\n` });
301
+ }
302
+ this.activeInteractivePrompt = null;
303
+ this.interactivePromptTransport = null;
304
+ this.statusCallback?.();
305
+ }
306
+
307
+ isApprovalRecentlyResolved(): boolean { return false; }
308
+ clearHistory(): void { /* no transcript buffer yet */ }
309
+ updateRuntimeSettings(): void { /* no runtime settings in spec model yet */ }
310
+ setServerConn(): void { /* server conn unused by SpecDriver */ }
311
+ /**
312
+ * Map an invokeScript(name, args) call onto a control_bar entry.
313
+ *
314
+ * scriptName is matched against control.id. The control's action.type
315
+ * drives the dispatch:
316
+ *
317
+ * send_keys → click_control (e.g. stop)
318
+ * open_picker → two roles, driven by the screen, not a hardcoded list:
319
+ * - LIST (no choice arg): open the picker, wait for it
320
+ * to render, parse the on-screen options via
321
+ * `extract_choices`, and return them as
322
+ * `controlResult.options` (+ `currentValue`). This is
323
+ * how the dashboard's Model/Mode controls learn what is
324
+ * actually selectable in this CLI right now.
325
+ * - SELECT (args.choiceIndex / args.choiceLabel): drive
326
+ * the picker to that option using `submit_key`.
327
+ * attach_image → attach_image dispatch; expects args.blob (data url
328
+ * or base64) and args.mime
329
+ *
330
+ * Callers that pass an unknown control id get a { not_found } response.
331
+ * No control matched, no driver call — keeps the surface honest.
332
+ */
333
+ invokeScript(scriptName: string, args?: Record<string, unknown>): Promise<unknown> {
334
+ const controls = this.spec.control_bar ?? [];
335
+ const ctl = controls.find(c => c.id === scriptName);
336
+ if (!ctl) {
337
+ return Promise.resolve({ ok: false, error: `unknown control: ${scriptName}` });
338
+ }
339
+ // Args may arrive as either { blob, mime } (direct invocation) or
340
+ // { params: { blob, mime } } (when the dashboard wraps script args
341
+ // in a params bag). Look at both.
342
+ const flat: Record<string, unknown> = { ...(args || {}) };
343
+ if (args && typeof args.params === 'object' && args.params) {
344
+ Object.assign(flat, args.params as Record<string, unknown>);
345
+ }
346
+ const action = ctl.action;
347
+ if (action.type === 'attach_image') {
348
+ const blob = typeof flat.blob === 'string' ? flat.blob : '';
349
+ const mime = typeof flat.mime === 'string' ? flat.mime : 'image/png';
350
+ if (!blob) return Promise.resolve({ ok: false, error: 'attach_image requires args.blob (base64 or data URL)' });
351
+ this.driver.dispatch({ kind: 'attach_image', blob, mime });
352
+ return Promise.resolve({ ok: true, effects: [{ type: 'attached_image', controlId: ctl.id }] });
353
+ }
354
+ if (action.type === 'open_picker') {
355
+ const choiceIndex = typeof flat.choiceIndex === 'number' ? flat.choiceIndex
356
+ : typeof flat.choiceIndex === 'string' && flat.choiceIndex.trim() ? Number(flat.choiceIndex)
357
+ : undefined;
358
+ // `value` is the arg the dashboard's generic value-control set path
359
+ // sends ({ value: <chosen option> }). control_bar pickers are
360
+ // surfaced to the dashboard as dynamic `select` controls whose
361
+ // option values are the screen-parsed labels, so a bare `value`
362
+ // is just a label to match against the live choices.
363
+ const choiceLabel = typeof flat.choiceLabel === 'string' ? flat.choiceLabel
364
+ : typeof flat.choice === 'string' ? flat.choice
365
+ : typeof flat.value === 'string' ? flat.value
366
+ : undefined;
367
+ if ((typeof choiceIndex === 'number' && Number.isFinite(choiceIndex)) || (choiceLabel && choiceLabel.trim())) {
368
+ return this.selectPickerChoice(ctl, action, choiceIndex, choiceLabel);
369
+ }
370
+ return this.openPickerAndListChoices(ctl, action);
371
+ }
372
+ // send_keys routes through click_control.
373
+ this.driver.dispatch({ kind: 'click_control', control_id: ctl.id, payload: flat });
374
+ return Promise.resolve({ ok: true, effects: [{ type: 'sent_keys', controlId: ctl.id }] });
375
+ }
376
+
377
+ /**
378
+ * Open an `open_picker` control and return the options the CLI is showing,
379
+ * parsed live from the screen via `extract_choices`. Nothing is selected —
380
+ * the picker is left open so a follow-up SELECT invoke can commit a choice.
381
+ */
382
+ private async openPickerAndListChoices(
383
+ ctl: Control,
384
+ action: Extract<ControlAction, { type: 'open_picker' }>,
385
+ ): Promise<unknown> {
386
+ this.driver.dispatch({ kind: 'click_control', control_id: ctl.id });
387
+ const ready = await this.waitForPickerRendered(action);
388
+ const options = this.extractPickerChoices(action);
389
+ const currentValue = options.find(o => o.current)?.label;
390
+ return {
391
+ ok: true,
392
+ effects: [{ type: 'opened_picker', controlId: ctl.id }],
393
+ controlResult: {
394
+ options: options.map(o => ({ value: o.label, label: o.label, current: o.current })),
395
+ ...(currentValue ? { currentValue } : {}),
396
+ source: 'screen-parse',
397
+ ...(ready ? {} : { warning: 'picker_render_timeout' }),
398
+ },
399
+ };
400
+ }
401
+
402
+ /**
403
+ * Drive an already-listable picker to a specific option. The option can be
404
+ * named (choiceLabel — matched against the parsed on-screen labels) or
405
+ * positional (choiceIndex — the on-screen number). The actual keystrokes
406
+ * come from the spec's `submit_key` with `{index}` substituted, so the spec
407
+ * — not this code — decides how a selection is keyed for each CLI.
408
+ */
409
+ private async selectPickerChoice(
410
+ ctl: Control,
411
+ action: Extract<ControlAction, { type: 'open_picker' }>,
412
+ choiceIndex: number | undefined,
413
+ choiceLabel: string | undefined,
414
+ ): Promise<unknown> {
415
+ // Open + wait so the choice list is on screen before we resolve the
416
+ // label → index mapping (a fresh invoke may arrive with the picker
417
+ // closed; re-opening an open picker is a no-op on these CLIs).
418
+ this.driver.dispatch({ kind: 'click_control', control_id: ctl.id });
419
+ await this.waitForPickerRendered(action);
420
+ const options = this.extractPickerChoices(action);
421
+
422
+ let index = choiceIndex;
423
+ if ((index == null || !Number.isFinite(index)) && choiceLabel) {
424
+ const needle = choiceLabel.trim().toLowerCase();
425
+ const match = options.find(o => o.label.toLowerCase().includes(needle));
426
+ if (!match) {
427
+ return { ok: false, error: `choice not found on screen: ${choiceLabel}`, controlResult: { options: options.map(o => ({ value: o.label, label: o.label })) } };
428
+ }
429
+ index = match.index;
430
+ }
431
+ if (index == null || !Number.isFinite(index)) {
432
+ return { ok: false, error: 'choiceIndex or choiceLabel required to select' };
433
+ }
434
+
435
+ const keys = (action.submit_key || '{index}\r').replace(/\{index\}/g, String(index));
436
+ this.driver.dispatch({ kind: 'pty_write', data: keys });
437
+ const selected = options.find(o => o.index === index);
438
+ return {
439
+ ok: true,
440
+ effects: [{ type: 'selected_choice', controlId: ctl.id }],
441
+ controlResult: {
442
+ ok: true,
443
+ ...(selected ? { currentValue: selected.label } : {}),
444
+ selectedIndex: index,
445
+ },
446
+ };
447
+ }
448
+
449
+ /** Poll the live screen until the picker's `wait_for` condition matches,
450
+ * up to a short budget. Returns true if it rendered, false on timeout. */
451
+ private async waitForPickerRendered(action: Extract<ControlAction, { type: 'open_picker' }>): Promise<boolean> {
452
+ const wf = action.wait_for;
453
+ if (!wf?.regex) { await delay(250); return true; }
454
+ const re = new RegExp(wf.regex, wf.flags ?? 'i');
455
+ const deadline = Date.now() + 2500;
456
+ while (Date.now() < deadline) {
457
+ await delay(120);
458
+ const hay = this.readScreenSectionText(wf.section);
459
+ if (re.test(hay)) return true;
460
+ }
461
+ return false;
462
+ }
463
+
464
+ /** Parse the picker's `extract_choices` pattern against the live screen.
465
+ * Each match yields { index, label, current }. `current` is true for the
466
+ * line the CLI marks with its cursor glyph (❯ ›). Purely screen-driven —
467
+ * no model/mode names are baked in. */
468
+ private extractPickerChoices(action: Extract<ControlAction, { type: 'open_picker' }>): Array<{ index: number; label: string; current: boolean }> {
469
+ const ec = action.extract_choices;
470
+ if (!ec?.pattern) return [];
471
+ const text = this.readScreenSectionText(ec.section);
472
+ const out: Array<{ index: number; label: string; current: boolean }> = [];
473
+ const seen = new Set<number>();
474
+ for (const rawLine of text.split('\n')) {
475
+ const line = rawLine.replace(/\r$/, '');
476
+ const m = new RegExp(ec.pattern, ec.flags ?? '').exec(line);
477
+ if (!m) continue;
478
+ const idx = Number(m[1]);
479
+ if (!Number.isFinite(idx) || seen.has(idx)) continue;
480
+ const label = (m[2] ?? '').replace(/\s+/g, ' ').trim();
481
+ if (!label) continue;
482
+ const current = /^\s*[❯›>]/.test(line) || /[✔✓●]\s*$/.test(label);
483
+ seen.add(idx);
484
+ out.push({ index: idx, label, current });
485
+ }
486
+ return out;
487
+ }
488
+
489
+ /** Live text of a named screen section (or the whole screen when no
490
+ * section is named), resolved from the driver's current sections. */
491
+ private readScreenSectionText(sectionId?: string): string {
492
+ try {
493
+ const sections = this.driver.getSections();
494
+ if (sectionId && sections) {
495
+ const hit = sections.find(s => s.id === sectionId);
496
+ if (hit) return hit.text;
497
+ }
498
+ return this.driver.getScreen();
499
+ } catch {
500
+ return '';
501
+ }
502
+ }
503
+ getDebugSnapshot(): unknown {
504
+ let screen = '';
505
+ let sections: Record<string, string> | undefined;
506
+ try {
507
+ screen = this.driver.snapshot();
508
+ const driverSections = this.driver.getSections?.();
509
+ if (driverSections) {
510
+ sections = Object.fromEntries(driverSections.map(s => [s.id, s.text]));
511
+ } else {
512
+ sections = this.readCurrentScreenSections(screen);
513
+ }
514
+ } catch { /* best-effort */ }
515
+ // Read native transcript messages for the debug snapshot
516
+ let messages: any[] = [];
517
+ if (this.spec.native_history?.source) {
518
+ try {
519
+ const nhResult = executeNativeHistory(this.spec.native_history, {
520
+ agentType: this.cliType,
521
+ providerSessionId: this.providerSessionId,
522
+ sessionStartedAtMs: this.spawnedAtMs,
523
+ envOverrides: this.spawnedEnv,
524
+ workspace: this.workingDir,
525
+ });
526
+ if (nhResult && Array.isArray(nhResult.messages)) messages = nhResult.messages;
527
+ } catch { /* best-effort */ }
528
+ } else {
529
+ messages = this.readClaudeScreenAssistantMessages();
530
+ }
531
+ return {
532
+ cliType: this.cliType,
533
+ spec_id: this.spec.id,
534
+ current_state: this.latestState,
535
+ current_modal: this.latestModal,
536
+ activeInteractivePrompt: this.activeInteractivePrompt,
537
+ exited: this.exited,
538
+ screen,
539
+ sections,
540
+ stateHistory: this.driver.getStateHistory(),
541
+ idleHoldPending: this.driver.hasIdleHoldPending(),
542
+ lastBusyAt: this.driver.getLastBusyAt(),
543
+ specPath: this.driver.getSpecPath(),
544
+ cursorPosition: this.driver.getCursorPosition(),
545
+ completionIdleDebounce: this.driver.getCompletionIdleDebounceState(),
546
+ // v4 FSM live transition table (null for v3 specs). Every outgoing
547
+ // transition from the current state with its per-condition match
548
+ // result + countdown — the canonical "why isn't it moving" answer.
549
+ fsm: this.driver.getFsmDebug?.() ?? null,
550
+ // v4 FSM transition snapshot history (null for v3 specs). The full
551
+ // pre-transition evaluation table captured at each transition —
552
+ // answers "why did this rule fire" after the fact, unlike the live
553
+ // `fsm` field which only reflects the current instant.
554
+ fsmHistory: this.driver.getFsmSnapshotHistory?.() ?? null,
555
+ // Extended fields
556
+ name: this.cliName,
557
+ status: this.getStatus().status,
558
+ workingDir: this.workingDir,
559
+ spawnedAtMs: this.spawnedAtMs,
560
+ providerSessionId: this.providerSessionId ?? null,
561
+ messages,
562
+ committedMessages: messages,
563
+ };
564
+ }
565
+ getRuntimeMetadata(): unknown {
566
+ return {
567
+ runtimeId: this.spec.id,
568
+ runtimeKey: this.spec.id,
569
+ displayName: this.spec.name,
570
+ spawnedAtMs: this.spawnedAtMs,
571
+ spawnedEnv: this.spawnedEnv,
572
+ ...(this.providerSessionId ? { providerSessionId: this.providerSessionId } : {}),
573
+ };
574
+ }
575
+ updateRuntimeMeta(meta?: Record<string, unknown>): void {
576
+ if (meta && typeof meta.providerSessionId === 'string') {
577
+ this.providerSessionId = meta.providerSessionId;
578
+ }
579
+ }
580
+ refreshProviderDefinition(): void { /* hot reload handled by SpecDriver fs.watch */ }
581
+
582
+ private handleEvent(ev: DashboardEvent): void {
583
+ this.lastEvent = ev;
584
+ switch (ev.kind) {
585
+ case 'state_changed':
586
+ this.latestState = ev.state;
587
+ this.latestModal = ev.modal;
588
+ // info-level keeps only spec-defined identifiers (state.id /
589
+ // state.label / button count). The extracted title can carry
590
+ // user data — file paths, command text, ticket titles — so
591
+ // it stays at debug.
592
+ LOG.info('SpecAdapter', `[${this.cliType}] state=${ev.state.id} (${ev.state.label}) modal=${ev.modal ? `${ev.modal.buttons.length}-buttons` : 'none'}`);
593
+ if (ev.state.title) {
594
+ LOG.debug('SpecAdapter', `[${this.cliType}] state.title=${JSON.stringify(ev.state.title)}`);
595
+ }
596
+ this.maybeClearResolvedClaudeTuiPrompt();
597
+ this.maybeCaptureClaudeTuiPrompt();
598
+ this.maybeUpgradeClaudeTuiMultiSelect();
599
+ this.statusCallback?.();
600
+ return;
601
+ case 'pty_data':
602
+ this.detectInteractivePromptFromPtyChunk(ev.chunk);
603
+ this.maybeClearResolvedClaudeTuiPrompt();
604
+ this.maybeCaptureClaudeTuiPrompt();
605
+ this.maybeUpgradeClaudeTuiMultiSelect();
606
+ try { this.ptyDataCallback?.(ev.chunk); } catch { /* ignore */ }
607
+ return;
608
+ case 'exit':
609
+ this.exited = true;
610
+ this.statusCallback?.();
611
+ return;
612
+ case 'spec_error':
613
+ LOG.warn('SpecAdapter', `[${this.cliType}] spec reload error: ${ev.errors.join('; ')}`);
614
+ return;
615
+ default:
616
+ return;
617
+ }
618
+ }
619
+
620
+ private detectInteractivePromptFromPtyChunk(chunk: string): void {
621
+ if (this.cliType !== 'claude-cli' || !chunk) return;
622
+ this.jsonLineTail += chunk;
623
+ if (this.jsonLineTail.length > 64 * 1024) this.jsonLineTail = this.jsonLineTail.slice(-64 * 1024);
624
+ const lines = this.jsonLineTail.split(/\r?\n/);
625
+ this.jsonLineTail = lines.pop() || '';
626
+ for (const line of lines) {
627
+ const trimmed = line.trim();
628
+ if (!trimmed.startsWith('{') || !trimmed.includes('AskUserQuestion')) continue;
629
+ try {
630
+ const parsed = JSON.parse(trimmed);
631
+ const prompt = detectClaudeAskUserQuestionPromptFromJson(parsed, this.cliType);
632
+ if (!prompt) continue;
633
+ this.activeInteractivePrompt = prompt;
634
+ this.interactivePromptTransport = 'stream-json';
635
+ this.interactivePromptLostAt = null;
636
+ this.statusCallback?.();
637
+ } catch {
638
+ // PTY output is not guaranteed to be machine JSON.
639
+ }
640
+ }
641
+ }
642
+
643
+ private readCurrentScreenSections(_screenText: string): Record<string, string> {
644
+ try {
645
+ const sections = this.driver.getSections() ?? [];
646
+ return Object.fromEntries(sections.map(section => [section.id, section.text]));
647
+ } catch {
648
+ return {};
649
+ }
650
+ }
651
+
652
+ private extractProviderSessionIdFromScreen(): string | undefined {
653
+ if (this.cliType !== 'codex-cli') return this.providerSessionId;
654
+ let screenText = '';
655
+ try {
656
+ screenText = this.driver.snapshot();
657
+ } catch {
658
+ return this.providerSessionId;
659
+ }
660
+ const clean = stripAnsi(screenText);
661
+ const match = clean.match(/(?:gpt-|o\d|codex-)[^\n·]*·[^\n·]*·\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
662
+ return match?.[1] || this.providerSessionId;
663
+ }
664
+
665
+ private readClaudeScreenAssistantMessages(): ChatMessage[] {
666
+ if (this.cliType !== 'claude-cli') return [];
667
+ let screenText = '';
668
+ try {
669
+ screenText = this.driver.snapshot();
670
+ } catch {
671
+ return [];
672
+ }
673
+ const sections = this.readCurrentScreenSections(screenText);
674
+ const body = sections.body || screenText;
675
+ const messages: ChatMessage[] = [];
676
+ const seen = new Set<string>();
677
+ for (const line of body.split(/\r?\n/)) {
678
+ const match = line.match(/^\s*⏺\s+(.+?)\s*$/);
679
+ const content = match?.[1]?.trim();
680
+ if (!content || seen.has(content)) continue;
681
+ seen.add(content);
682
+ messages.push({
683
+ role: 'assistant',
684
+ kind: 'standard',
685
+ content,
686
+ source: 'assistant_text',
687
+ userFacing: true,
688
+ bubbleState: 'final',
689
+ });
690
+ }
691
+ return messages;
692
+ }
693
+
694
+ /**
695
+ * Grace window a held interactive prompt must be absent from the screen
696
+ * before we treat it as resolved-in-terminal and clear it. claude-cli
697
+ * repaints the picker across multiple PTY chunks, so a single
698
+ * footer-less frame is not proof the prompt is gone. Sized in the same
699
+ * spirit as the approval FSM's `approvalCooldown` modal-lost hysteresis.
700
+ */
701
+ private static readonly INTERACTIVE_PROMPT_LOST_GRACE_MS = 1500;
702
+
703
+ /**
704
+ * Multi-question TUI capture: after Tabbing to a page, re-snapshot at this
705
+ * interval until its checkbox glyph column has settled, up to the timeout.
706
+ * The interval matches the legacy single fixed wait (120ms); the timeout
707
+ * bounds total capture time so a single-select page (which never shows
708
+ * glyphs) doesn't stall the capture indefinitely.
709
+ */
710
+ private static readonly CLAUDE_TUI_PAGE_POLL_INTERVAL_MS = 120;
711
+ private static readonly CLAUDE_TUI_PAGE_SETTLE_TIMEOUT_MS = 600;
712
+
713
+ /**
714
+ * Clear a held interactive prompt once the user has resolved it directly
715
+ * in the terminal (the choice picker leaves the screen without going
716
+ * through setInteractivePromptResponse). The approval path already does
717
+ * this via the FSM's modal-lost hysteresis; the interactive-prompt path
718
+ * had no equivalent, so a terminal-side answer left activeInteractivePrompt
719
+ * set and getStatus() re-emitted the same choice modal forever.
720
+ *
721
+ * Detection mirrors capture: the claude TUI picker is on-screen exactly
722
+ * while its "Enter to select" footer is rendered. When the footer is gone
723
+ * for INTERACTIVE_PROMPT_LOST_GRACE_MS the prompt is genuinely resolved.
724
+ */
725
+ private maybeClearResolvedClaudeTuiPrompt(): void {
726
+ if (this.cliType !== 'claude-cli' || !this.activeInteractivePrompt) return;
727
+ // stream-json prompts are tracked by their tool-call lifecycle, not by
728
+ // screen footer, but claude renders the same TUI picker for both
729
+ // transports while awaiting an answer — so screen presence is a valid
730
+ // resolved-signal for either. (If the screen read fails, keep holding.)
731
+ let screenText = '';
732
+ try {
733
+ screenText = this.driver.snapshot();
734
+ } catch {
735
+ return;
736
+ }
737
+ const stillOnScreen = screenText.includes('Enter to select');
738
+ if (stillOnScreen) {
739
+ // Prompt reappeared / never left — reset the hysteresis timer.
740
+ this.interactivePromptLostAt = null;
741
+ return;
742
+ }
743
+ const lostAt = this.interactivePromptLostAt ?? Date.now();
744
+ if (this.interactivePromptLostAt === null) this.interactivePromptLostAt = lostAt;
745
+ if (Date.now() - lostAt < SpecCliAdapter.INTERACTIVE_PROMPT_LOST_GRACE_MS) return;
746
+ // Resolved in the terminal — drop the held prompt so getStatus() stops
747
+ // re-emitting it.
748
+ this.activeInteractivePrompt = null;
749
+ this.interactivePromptTransport = null;
750
+ this.interactivePromptLostAt = null;
751
+ this.statusCallback?.();
752
+ }
753
+
754
+ private maybeCaptureClaudeTuiPrompt(): void {
755
+ if (this.cliType !== 'claude-cli'
756
+ || this.activeInteractivePrompt
757
+ || this.claudeTuiPromptCaptureInFlight) return;
758
+ const screenText = this.driver.snapshot();
759
+ const headers = this.readClaudeTuiHeaders(screenText);
760
+ if (!screenText.includes('Enter to select')) return;
761
+ if (headers.length === 0) {
762
+ const prompt = detectClaudeAskUserQuestionPromptFromTuiPages([{ screenText }], {
763
+ promptId: `ask-user-${this.providerSessionId || 'claude'}-${Date.now()}`,
764
+ providerType: this.cliType,
765
+ });
766
+ if (!prompt) return;
767
+ this.activeInteractivePrompt = prompt;
768
+ this.interactivePromptTransport = 'tui';
769
+ this.interactivePromptLostAt = null;
770
+ this.statusCallback?.();
771
+ return;
772
+ }
773
+ this.claudeTuiPromptCaptureInFlight = true;
774
+ void this.captureClaudeTuiPrompt(screenText, headers).finally(() => {
775
+ this.claudeTuiPromptCaptureInFlight = false;
776
+ });
777
+ }
778
+
779
+ /**
780
+ * The TUI prompt is captured on the FIRST frame that renders the
781
+ * "Enter to select" footer. At that instant the option rows' checkbox
782
+ * column may not have drawn yet, so `detectClaudeTuiMultiSelect` returns
783
+ * false and the prompt is frozen as single-select — the dashboard then
784
+ * renders radio buttons even though the picker is multi-select.
785
+ *
786
+ * While the same TUI prompt is still on screen, re-check the live snapshot:
787
+ * if checkbox glyphs have since appeared, promote any single-select
788
+ * question to multi-select and re-emit status. Promotion is one-way
789
+ * (false→true only) — once a question is known multi-select we never demote
790
+ * it, since the glyph column can scroll out of view on later frames.
791
+ *
792
+ * For MULTI-question prompts the per-page Tab capture is the actual source
793
+ * of the bug: pages 2..N are snapshotted ~120ms after the Tab keypress,
794
+ * before their option-row glyph column has redrawn, so those questions
795
+ * freeze as single-select while page 1 (already settled) is correct. We
796
+ * cannot upgrade blindly — the live snapshot shows only ONE focused page —
797
+ * but we CAN read that page's question text/header and upgrade the matching
798
+ * question. As the user navigates the picker (or it settles), each page is
799
+ * eventually re-read and repaired.
800
+ */
801
+ private maybeUpgradeClaudeTuiMultiSelect(): void {
802
+ if (this.cliType !== 'claude-cli'
803
+ || this.interactivePromptTransport !== 'tui'
804
+ || !this.activeInteractivePrompt) return;
805
+ const questions = this.activeInteractivePrompt.questions;
806
+ if (questions.every(q => q.multiSelect)) return;
807
+ let screenText = '';
808
+ try {
809
+ screenText = this.driver.snapshot();
810
+ } catch {
811
+ return;
812
+ }
813
+ if (!screenText.includes('Enter to select')) return;
814
+
815
+ if (questions.length === 1) {
816
+ if (questions[0].multiSelect) return;
817
+ if (!detectClaudeTuiMultiSelect(screenText)) return;
818
+ questions[0].multiSelect = true;
819
+ this.statusCallback?.();
820
+ return;
821
+ }
822
+
823
+ // Multi-question: attribute the focused page's glyphs to its question by
824
+ // matching header (preferred) or question text, then upgrade just that
825
+ // one. Never demote — a settled non-multi page is left as captured.
826
+ const focused = readFocusedClaudeTuiQuestion(screenText);
827
+ if (!focused || !focused.multiSelect) return;
828
+ const match = questions.find(q =>
829
+ (focused.header && q.header && q.header === focused.header)
830
+ || q.question === focused.question);
831
+ if (!match || match.multiSelect) return;
832
+ match.multiSelect = true;
833
+ this.statusCallback?.();
834
+ }
835
+
836
+ private readClaudeTuiHeaders(screenText: string): string[] {
837
+ const navLine = screenText.split(/\r?\n/).find(line => line.includes('✔ Submit') && /[☐☒]/.test(line));
838
+ if (!navLine) return [];
839
+ const headers: string[] = [];
840
+ for (const match of navLine.matchAll(/[☐☒]\s+(.+?)(?=\s+[☐☒]|\s+✔\s+Submit)/g)) {
841
+ const header = match[1]?.trim();
842
+ if (header) headers.push(header);
843
+ }
844
+ return headers;
845
+ }
846
+
847
+ /**
848
+ * Snapshot the currently-focused claude TUI page, polling until its
849
+ * option-row checkbox glyph column has settled (or a bounded timeout).
850
+ *
851
+ * Why poll: right after a Tab keypress the newly-focused page's glyph
852
+ * column has not redrawn yet, so an immediate snapshot shows the question +
853
+ * option labels but NO per-option checkbox markers — freezing that page as
854
+ * single-select. A fixed delay either races (too short) or is wasteful (too
855
+ * long). Instead we re-snapshot at a fixed interval and stop as soon as the
856
+ * frame shows multi-select glyphs, falling back to the last frame at the
857
+ * timeout. Single-select pages never show glyphs, so they always poll to the
858
+ * timeout — bounded small to keep capture snappy.
859
+ */
860
+ private async snapshotSettledClaudeTuiPage(): Promise<string> {
861
+ let screenText = this.driver.snapshot();
862
+ const deadline = Date.now() + SpecCliAdapter.CLAUDE_TUI_PAGE_SETTLE_TIMEOUT_MS;
863
+ while (!detectClaudeTuiMultiSelect(screenText) && Date.now() < deadline) {
864
+ await new Promise(resolve => setTimeout(resolve, SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
865
+ screenText = this.driver.snapshot();
866
+ }
867
+ return screenText;
868
+ }
869
+
870
+ private async captureClaudeTuiPrompt(firstScreen: string, headers: string[]): Promise<void> {
871
+ const pages: ClaudeInteractiveTuiPage[] = [{ screenText: firstScreen, header: headers[0] }];
872
+ // Forward pass: Tab to each page 2..N and snapshot once its glyph column
873
+ // has settled, so pages 2+ capture their checkbox markers (not a racy
874
+ // pre-redraw frame).
875
+ for (let index = 1; index < headers.length; index += 1) {
876
+ this.driver.dispatch({ kind: 'pty_write', data: '\t' });
877
+ await new Promise(resolve => setTimeout(resolve, SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
878
+ pages.push({ screenText: await this.snapshotSettledClaudeTuiPage(), header: headers[index] });
879
+ }
880
+ // Return pass: Shift-Tab back through pages N..2. As we land on each page
881
+ // again re-read it and OR-in any now-visible multi-select glyphs — a
882
+ // second chance to repair a page whose forward-pass frame was still racy.
883
+ for (let index = headers.length - 1; index > 0; index -= 1) {
884
+ this.driver.dispatch({ kind: 'pty_write', data: '\x1b[Z' });
885
+ await new Promise(resolve => setTimeout(resolve, SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
886
+ const reread = await this.snapshotSettledClaudeTuiPage();
887
+ // The page we just Shift-Tab'd ONTO is index-1 (we move backwards).
888
+ const landed = pages[index - 1];
889
+ if (landed
890
+ && !detectClaudeTuiMultiSelect(landed.screenText)
891
+ && detectClaudeTuiMultiSelect(reread)) {
892
+ landed.screenText = reread;
893
+ }
894
+ }
895
+
896
+ const prompt = detectClaudeAskUserQuestionPromptFromTuiPages(pages, {
897
+ promptId: `ask-user-${this.providerSessionId || 'claude'}-${Date.now()}`,
898
+ providerType: this.cliType,
899
+ });
900
+ if (!prompt) return;
901
+ this.activeInteractivePrompt = prompt;
902
+ this.interactivePromptTransport = 'tui';
903
+ this.interactivePromptLostAt = null;
904
+ this.statusCallback?.();
905
+ }
906
+
907
+ getDebugState(): Record<string, any> {
908
+ const screen = this.driver.getScreen?.() ?? '';
909
+ const history = this.driver.getStateHistory();
910
+ const status = this.getStatus();
911
+
912
+ let messages: any[] = [];
913
+ if (this.spec.native_history?.source) {
914
+ try {
915
+ const result = executeNativeHistory(this.spec.native_history, {
916
+ agentType: this.cliType,
917
+ providerSessionId: this.providerSessionId,
918
+ sessionStartedAtMs: this.spawnedAtMs,
919
+ envOverrides: this.spawnedEnv,
920
+ workspace: this.workingDir,
921
+ });
922
+ if (result && Array.isArray(result.messages)) {
923
+ messages = result.messages;
924
+ }
925
+ } catch (e) {
926
+ // Ignore native history read errors in debug state
927
+ }
928
+ } else {
929
+ messages = this.readClaudeScreenAssistantMessages();
930
+ }
931
+
932
+ const latestState = this.latestState;
933
+ const latestModal = this.latestModal;
934
+ return {
935
+ type: this.cliType,
936
+ name: this.cliName,
937
+ status: status.status,
938
+ rawStatus: status.status,
939
+ projectedStatus: status.status,
940
+ ready: this.spawned,
941
+ // Legacy snapshot-style fields for panels that read getDebugSnapshot shape
942
+ spec_id: this.spec.id,
943
+ current_state: latestState ?? null,
944
+ current_modal: latestModal ?? null,
945
+ exited: this.exited,
946
+ idleHoldPending: this.driver.hasIdleHoldPending?.() ?? false,
947
+ lastBusyAt: this.driver.getLastBusyAt?.() ?? 0,
948
+ screen: screen,
949
+ screenText: screen,
950
+ workingDir: this.workingDir,
951
+ spawnedAtMs: this.spawnedAtMs,
952
+ providerSessionId: this.providerSessionId ?? null,
953
+ sections: this.driver.getSections?.() ?? null,
954
+ stateHistory: history,
955
+ specPath: this.driver.getSpecPath?.() ?? null,
956
+ // v4 FSM live transition table — present only for FsmDriver. Lets
957
+ // the panel (and the daemon API) show, for the current instant,
958
+ // every outgoing transition with its per-condition match result
959
+ // and countdown. This is the canonical "why isn't it transitioning"
960
+ // answer — no screenshots needed.
961
+ fsm: this.driver.getFsmDebug?.() ?? null,
962
+ // v4 FSM transition snapshot history — the captured pre-transition
963
+ // evaluation table at each transition (null for v3 specs).
964
+ fsmHistory: this.driver.getFsmSnapshotHistory?.() ?? null,
965
+ messages,
966
+ committedMessages: messages,
967
+ };
968
+ }
969
+
970
+ getTraceState(limit = 120): Record<string, any> {
971
+ const history = this.driver.getStateHistory();
972
+ return {
973
+ status: this.getStatus().status,
974
+ stateHistory: history.slice(-limit),
975
+ screenText: this.driver.getScreen?.() ?? '',
976
+ };
977
+ }
978
+
979
+ getProviderResolutionMeta(): Record<string, any> {
980
+ return {
981
+ type: this.cliType,
982
+ providerDir: null,
983
+ resolvedVersion: null,
984
+ };
985
+ }
986
+ }