@adhdev/daemon-core 0.9.82-rc.31 → 0.9.82-rc.310

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