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

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 (294) 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 +214 -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 +34705 -11938
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +38412 -15757
  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 +169 -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 +395 -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 +204 -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 +217 -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 +180 -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 +291 -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 +1822 -61
  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 +6041 -589
  157. package/src/commands/stream-commands.ts +8 -0
  158. package/src/commands/upgrade-helper.ts +29 -0
  159. package/src/config/chat-history.ts +483 -24
  160. package/src/config/config.ts +12 -0
  161. package/src/config/mesh-config.ts +320 -4
  162. package/src/config/recent-activity.ts +8 -2
  163. package/src/daemon/dev-auto-implement.ts +3 -2
  164. package/src/daemon/dev-cli-debug.ts +10 -1
  165. package/src/detection/ide-detector.ts +26 -16
  166. package/src/git/git-commands.ts +42 -12
  167. package/src/git/git-diff.ts +53 -0
  168. package/src/git/git-executor.ts +12 -0
  169. package/src/git/git-status.ts +302 -18
  170. package/src/git/git-types.ts +14 -62
  171. package/src/git/git-worktree.ts +8 -1
  172. package/src/index.ts +142 -11
  173. package/src/installer.d.ts +1 -1
  174. package/src/installer.ts +8 -6
  175. package/src/ipc/local-ipc-server.ts +278 -0
  176. package/src/launch.d.ts +1 -1
  177. package/src/launch.ts +37 -28
  178. package/src/logging/async-batch-writer.ts +55 -0
  179. package/src/logging/logger.ts +2 -1
  180. package/src/mesh/contracts.ts +329 -0
  181. package/src/mesh/coordinator-prompt.ts +234 -31
  182. package/src/mesh/coordinator-registry.ts +121 -0
  183. package/src/mesh/mesh-active-work.ts +469 -0
  184. package/src/mesh/mesh-delivery-policy.ts +315 -0
  185. package/src/mesh/mesh-events-coordinator.ts +1942 -0
  186. package/src/mesh/mesh-events-pending.ts +508 -0
  187. package/src/mesh/mesh-events-stale.ts +290 -0
  188. package/src/mesh/mesh-events-utils.ts +254 -0
  189. package/src/mesh/mesh-events.ts +30 -1035
  190. package/src/mesh/mesh-fast-forward.ts +839 -0
  191. package/src/mesh/mesh-host-ownership.ts +73 -0
  192. package/src/mesh/mesh-init.ts +260 -0
  193. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  194. package/src/mesh/mesh-ledger.ts +589 -102
  195. package/src/mesh/mesh-missions.ts +248 -0
  196. package/src/mesh/mesh-reconcile-loop.ts +466 -0
  197. package/src/mesh/mesh-refine-batch.ts +197 -0
  198. package/src/mesh/mesh-refine-status.ts +231 -0
  199. package/src/mesh/mesh-review-inbox.ts +307 -0
  200. package/src/mesh/mesh-routing.ts +291 -0
  201. package/src/mesh/mesh-runtime-store.ts +1565 -0
  202. package/src/mesh/mesh-task-stats.ts +154 -0
  203. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  204. package/src/mesh/mesh-work-queue.ts +703 -140
  205. package/src/mesh/preview-freshness.ts +118 -0
  206. package/src/mesh/refine-config.ts +403 -0
  207. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  208. package/src/providers/acp-provider-instance.ts +15 -1
  209. package/src/providers/approval-utils.d.ts +4 -0
  210. package/src/providers/approval-utils.ts +47 -5
  211. package/src/providers/chat-message-normalization.ts +4 -11
  212. package/src/providers/cli-provider-instance.ts +953 -87
  213. package/src/providers/contracts.d.ts +55 -0
  214. package/src/providers/contracts.ts +141 -6
  215. package/src/providers/extension-provider-instance.ts +5 -1
  216. package/src/providers/external-sources.ts +218 -0
  217. package/src/providers/ide-provider-instance.ts +25 -6
  218. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  219. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  220. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  221. package/src/providers/native-history/dispatcher.ts +340 -0
  222. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  223. package/src/providers/native-history/index.ts +30 -0
  224. package/src/providers/provider-instance-manager.ts +30 -0
  225. package/src/providers/provider-instance.ts +10 -1
  226. package/src/providers/provider-loader.ts +584 -50
  227. package/src/providers/provider-schema.ts +87 -14
  228. package/src/providers/provider-trust.ts +114 -0
  229. package/src/providers/read-chat-contract.ts +76 -16
  230. package/src/providers/sdk/README.md +49 -0
  231. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  232. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  233. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  234. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  235. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  236. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  237. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  238. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  239. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  240. package/src/providers/sdk/v1/index.ts +152 -0
  241. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  242. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  243. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  244. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  245. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  246. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  247. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  248. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  249. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  250. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  251. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  252. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  253. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  254. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  255. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  256. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  257. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  258. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  259. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  260. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  261. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  262. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  263. package/src/providers/sdk/v1/validators/index.ts +19 -0
  264. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  265. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  266. package/src/providers/spec/adapter.ts +155 -0
  267. package/src/providers/spec/cli-adapter.ts +980 -0
  268. package/src/providers/spec/evaluator.ts +345 -0
  269. package/src/providers/spec/fsm-driver.ts +888 -0
  270. package/src/providers/spec/fsm-evaluator.ts +255 -0
  271. package/src/providers/spec/fsm-loader.ts +112 -0
  272. package/src/providers/spec/fsm-types.ts +222 -0
  273. package/src/providers/spec/native-history-executor.ts +1035 -0
  274. package/src/providers/spec/pre-launch-trust.ts +104 -0
  275. package/src/providers/spec/route.ts +51 -0
  276. package/src/providers/spec/types.ts +226 -0
  277. package/src/providers/transcript-v2.ts +567 -0
  278. package/src/providers/types/interactive-prompt.ts +536 -0
  279. package/src/providers/version-archive.ts +38 -20
  280. package/src/repo-mesh-types.ts +376 -13
  281. package/src/sessions/registry.ts +6 -0
  282. package/src/shared-types-extra.ts +2 -4
  283. package/src/shared-types.ts +45 -1
  284. package/src/status/builders.ts +26 -6
  285. package/src/status/normalize.ts +2 -0
  286. package/src/status/reporter.ts +15 -0
  287. package/src/status/snapshot.ts +84 -25
  288. package/src/system/host-memory.ts +29 -12
  289. package/src/types.ts +5 -0
  290. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  291. package/dist/mesh/mesh-sync.d.ts +0 -53
  292. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  293. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  294. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,980 @@
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
+ const choiceLabel = typeof flat.choiceLabel === 'string' ? flat.choiceLabel
359
+ : typeof flat.choice === 'string' ? flat.choice
360
+ : undefined;
361
+ if ((typeof choiceIndex === 'number' && Number.isFinite(choiceIndex)) || (choiceLabel && choiceLabel.trim())) {
362
+ return this.selectPickerChoice(ctl, action, choiceIndex, choiceLabel);
363
+ }
364
+ return this.openPickerAndListChoices(ctl, action);
365
+ }
366
+ // send_keys routes through click_control.
367
+ this.driver.dispatch({ kind: 'click_control', control_id: ctl.id, payload: flat });
368
+ return Promise.resolve({ ok: true, effects: [{ type: 'sent_keys', controlId: ctl.id }] });
369
+ }
370
+
371
+ /**
372
+ * Open an `open_picker` control and return the options the CLI is showing,
373
+ * parsed live from the screen via `extract_choices`. Nothing is selected —
374
+ * the picker is left open so a follow-up SELECT invoke can commit a choice.
375
+ */
376
+ private async openPickerAndListChoices(
377
+ ctl: Control,
378
+ action: Extract<ControlAction, { type: 'open_picker' }>,
379
+ ): Promise<unknown> {
380
+ this.driver.dispatch({ kind: 'click_control', control_id: ctl.id });
381
+ const ready = await this.waitForPickerRendered(action);
382
+ const options = this.extractPickerChoices(action);
383
+ const currentValue = options.find(o => o.current)?.label;
384
+ return {
385
+ ok: true,
386
+ effects: [{ type: 'opened_picker', controlId: ctl.id }],
387
+ controlResult: {
388
+ options: options.map(o => ({ value: o.label, label: o.label, current: o.current })),
389
+ ...(currentValue ? { currentValue } : {}),
390
+ source: 'screen-parse',
391
+ ...(ready ? {} : { warning: 'picker_render_timeout' }),
392
+ },
393
+ };
394
+ }
395
+
396
+ /**
397
+ * Drive an already-listable picker to a specific option. The option can be
398
+ * named (choiceLabel — matched against the parsed on-screen labels) or
399
+ * positional (choiceIndex — the on-screen number). The actual keystrokes
400
+ * come from the spec's `submit_key` with `{index}` substituted, so the spec
401
+ * — not this code — decides how a selection is keyed for each CLI.
402
+ */
403
+ private async selectPickerChoice(
404
+ ctl: Control,
405
+ action: Extract<ControlAction, { type: 'open_picker' }>,
406
+ choiceIndex: number | undefined,
407
+ choiceLabel: string | undefined,
408
+ ): Promise<unknown> {
409
+ // Open + wait so the choice list is on screen before we resolve the
410
+ // label → index mapping (a fresh invoke may arrive with the picker
411
+ // closed; re-opening an open picker is a no-op on these CLIs).
412
+ this.driver.dispatch({ kind: 'click_control', control_id: ctl.id });
413
+ await this.waitForPickerRendered(action);
414
+ const options = this.extractPickerChoices(action);
415
+
416
+ let index = choiceIndex;
417
+ if ((index == null || !Number.isFinite(index)) && choiceLabel) {
418
+ const needle = choiceLabel.trim().toLowerCase();
419
+ const match = options.find(o => o.label.toLowerCase().includes(needle));
420
+ if (!match) {
421
+ return { ok: false, error: `choice not found on screen: ${choiceLabel}`, controlResult: { options: options.map(o => ({ value: o.label, label: o.label })) } };
422
+ }
423
+ index = match.index;
424
+ }
425
+ if (index == null || !Number.isFinite(index)) {
426
+ return { ok: false, error: 'choiceIndex or choiceLabel required to select' };
427
+ }
428
+
429
+ const keys = (action.submit_key || '{index}\r').replace(/\{index\}/g, String(index));
430
+ this.driver.dispatch({ kind: 'pty_write', data: keys });
431
+ const selected = options.find(o => o.index === index);
432
+ return {
433
+ ok: true,
434
+ effects: [{ type: 'selected_choice', controlId: ctl.id }],
435
+ controlResult: {
436
+ ok: true,
437
+ ...(selected ? { currentValue: selected.label } : {}),
438
+ selectedIndex: index,
439
+ },
440
+ };
441
+ }
442
+
443
+ /** Poll the live screen until the picker's `wait_for` condition matches,
444
+ * up to a short budget. Returns true if it rendered, false on timeout. */
445
+ private async waitForPickerRendered(action: Extract<ControlAction, { type: 'open_picker' }>): Promise<boolean> {
446
+ const wf = action.wait_for;
447
+ if (!wf?.regex) { await delay(250); return true; }
448
+ const re = new RegExp(wf.regex, wf.flags ?? 'i');
449
+ const deadline = Date.now() + 2500;
450
+ while (Date.now() < deadline) {
451
+ await delay(120);
452
+ const hay = this.readScreenSectionText(wf.section);
453
+ if (re.test(hay)) return true;
454
+ }
455
+ return false;
456
+ }
457
+
458
+ /** Parse the picker's `extract_choices` pattern against the live screen.
459
+ * Each match yields { index, label, current }. `current` is true for the
460
+ * line the CLI marks with its cursor glyph (❯ ›). Purely screen-driven —
461
+ * no model/mode names are baked in. */
462
+ private extractPickerChoices(action: Extract<ControlAction, { type: 'open_picker' }>): Array<{ index: number; label: string; current: boolean }> {
463
+ const ec = action.extract_choices;
464
+ if (!ec?.pattern) return [];
465
+ const text = this.readScreenSectionText(ec.section);
466
+ const out: Array<{ index: number; label: string; current: boolean }> = [];
467
+ const seen = new Set<number>();
468
+ for (const rawLine of text.split('\n')) {
469
+ const line = rawLine.replace(/\r$/, '');
470
+ const m = new RegExp(ec.pattern, ec.flags ?? '').exec(line);
471
+ if (!m) continue;
472
+ const idx = Number(m[1]);
473
+ if (!Number.isFinite(idx) || seen.has(idx)) continue;
474
+ const label = (m[2] ?? '').replace(/\s+/g, ' ').trim();
475
+ if (!label) continue;
476
+ const current = /^\s*[❯›>]/.test(line) || /[✔✓●]\s*$/.test(label);
477
+ seen.add(idx);
478
+ out.push({ index: idx, label, current });
479
+ }
480
+ return out;
481
+ }
482
+
483
+ /** Live text of a named screen section (or the whole screen when no
484
+ * section is named), resolved from the driver's current sections. */
485
+ private readScreenSectionText(sectionId?: string): string {
486
+ try {
487
+ const sections = this.driver.getSections();
488
+ if (sectionId && sections) {
489
+ const hit = sections.find(s => s.id === sectionId);
490
+ if (hit) return hit.text;
491
+ }
492
+ return this.driver.getScreen();
493
+ } catch {
494
+ return '';
495
+ }
496
+ }
497
+ getDebugSnapshot(): unknown {
498
+ let screen = '';
499
+ let sections: Record<string, string> | undefined;
500
+ try {
501
+ screen = this.driver.snapshot();
502
+ const driverSections = this.driver.getSections?.();
503
+ if (driverSections) {
504
+ sections = Object.fromEntries(driverSections.map(s => [s.id, s.text]));
505
+ } else {
506
+ sections = this.readCurrentScreenSections(screen);
507
+ }
508
+ } catch { /* best-effort */ }
509
+ // Read native transcript messages for the debug snapshot
510
+ let messages: any[] = [];
511
+ if (this.spec.native_history?.source) {
512
+ try {
513
+ const nhResult = executeNativeHistory(this.spec.native_history, {
514
+ agentType: this.cliType,
515
+ providerSessionId: this.providerSessionId,
516
+ sessionStartedAtMs: this.spawnedAtMs,
517
+ envOverrides: this.spawnedEnv,
518
+ workspace: this.workingDir,
519
+ });
520
+ if (nhResult && Array.isArray(nhResult.messages)) messages = nhResult.messages;
521
+ } catch { /* best-effort */ }
522
+ } else {
523
+ messages = this.readClaudeScreenAssistantMessages();
524
+ }
525
+ return {
526
+ cliType: this.cliType,
527
+ spec_id: this.spec.id,
528
+ current_state: this.latestState,
529
+ current_modal: this.latestModal,
530
+ activeInteractivePrompt: this.activeInteractivePrompt,
531
+ exited: this.exited,
532
+ screen,
533
+ sections,
534
+ stateHistory: this.driver.getStateHistory(),
535
+ idleHoldPending: this.driver.hasIdleHoldPending(),
536
+ lastBusyAt: this.driver.getLastBusyAt(),
537
+ specPath: this.driver.getSpecPath(),
538
+ cursorPosition: this.driver.getCursorPosition(),
539
+ completionIdleDebounce: this.driver.getCompletionIdleDebounceState(),
540
+ // v4 FSM live transition table (null for v3 specs). Every outgoing
541
+ // transition from the current state with its per-condition match
542
+ // result + countdown — the canonical "why isn't it moving" answer.
543
+ fsm: this.driver.getFsmDebug?.() ?? null,
544
+ // v4 FSM transition snapshot history (null for v3 specs). The full
545
+ // pre-transition evaluation table captured at each transition —
546
+ // answers "why did this rule fire" after the fact, unlike the live
547
+ // `fsm` field which only reflects the current instant.
548
+ fsmHistory: this.driver.getFsmSnapshotHistory?.() ?? null,
549
+ // Extended fields
550
+ name: this.cliName,
551
+ status: this.getStatus().status,
552
+ workingDir: this.workingDir,
553
+ spawnedAtMs: this.spawnedAtMs,
554
+ providerSessionId: this.providerSessionId ?? null,
555
+ messages,
556
+ committedMessages: messages,
557
+ };
558
+ }
559
+ getRuntimeMetadata(): unknown {
560
+ return {
561
+ runtimeId: this.spec.id,
562
+ runtimeKey: this.spec.id,
563
+ displayName: this.spec.name,
564
+ spawnedAtMs: this.spawnedAtMs,
565
+ spawnedEnv: this.spawnedEnv,
566
+ ...(this.providerSessionId ? { providerSessionId: this.providerSessionId } : {}),
567
+ };
568
+ }
569
+ updateRuntimeMeta(meta?: Record<string, unknown>): void {
570
+ if (meta && typeof meta.providerSessionId === 'string') {
571
+ this.providerSessionId = meta.providerSessionId;
572
+ }
573
+ }
574
+ refreshProviderDefinition(): void { /* hot reload handled by SpecDriver fs.watch */ }
575
+
576
+ private handleEvent(ev: DashboardEvent): void {
577
+ this.lastEvent = ev;
578
+ switch (ev.kind) {
579
+ case 'state_changed':
580
+ this.latestState = ev.state;
581
+ this.latestModal = ev.modal;
582
+ // info-level keeps only spec-defined identifiers (state.id /
583
+ // state.label / button count). The extracted title can carry
584
+ // user data — file paths, command text, ticket titles — so
585
+ // it stays at debug.
586
+ LOG.info('SpecAdapter', `[${this.cliType}] state=${ev.state.id} (${ev.state.label}) modal=${ev.modal ? `${ev.modal.buttons.length}-buttons` : 'none'}`);
587
+ if (ev.state.title) {
588
+ LOG.debug('SpecAdapter', `[${this.cliType}] state.title=${JSON.stringify(ev.state.title)}`);
589
+ }
590
+ this.maybeClearResolvedClaudeTuiPrompt();
591
+ this.maybeCaptureClaudeTuiPrompt();
592
+ this.maybeUpgradeClaudeTuiMultiSelect();
593
+ this.statusCallback?.();
594
+ return;
595
+ case 'pty_data':
596
+ this.detectInteractivePromptFromPtyChunk(ev.chunk);
597
+ this.maybeClearResolvedClaudeTuiPrompt();
598
+ this.maybeCaptureClaudeTuiPrompt();
599
+ this.maybeUpgradeClaudeTuiMultiSelect();
600
+ try { this.ptyDataCallback?.(ev.chunk); } catch { /* ignore */ }
601
+ return;
602
+ case 'exit':
603
+ this.exited = true;
604
+ this.statusCallback?.();
605
+ return;
606
+ case 'spec_error':
607
+ LOG.warn('SpecAdapter', `[${this.cliType}] spec reload error: ${ev.errors.join('; ')}`);
608
+ return;
609
+ default:
610
+ return;
611
+ }
612
+ }
613
+
614
+ private detectInteractivePromptFromPtyChunk(chunk: string): void {
615
+ if (this.cliType !== 'claude-cli' || !chunk) return;
616
+ this.jsonLineTail += chunk;
617
+ if (this.jsonLineTail.length > 64 * 1024) this.jsonLineTail = this.jsonLineTail.slice(-64 * 1024);
618
+ const lines = this.jsonLineTail.split(/\r?\n/);
619
+ this.jsonLineTail = lines.pop() || '';
620
+ for (const line of lines) {
621
+ const trimmed = line.trim();
622
+ if (!trimmed.startsWith('{') || !trimmed.includes('AskUserQuestion')) continue;
623
+ try {
624
+ const parsed = JSON.parse(trimmed);
625
+ const prompt = detectClaudeAskUserQuestionPromptFromJson(parsed, this.cliType);
626
+ if (!prompt) continue;
627
+ this.activeInteractivePrompt = prompt;
628
+ this.interactivePromptTransport = 'stream-json';
629
+ this.interactivePromptLostAt = null;
630
+ this.statusCallback?.();
631
+ } catch {
632
+ // PTY output is not guaranteed to be machine JSON.
633
+ }
634
+ }
635
+ }
636
+
637
+ private readCurrentScreenSections(_screenText: string): Record<string, string> {
638
+ try {
639
+ const sections = this.driver.getSections() ?? [];
640
+ return Object.fromEntries(sections.map(section => [section.id, section.text]));
641
+ } catch {
642
+ return {};
643
+ }
644
+ }
645
+
646
+ private extractProviderSessionIdFromScreen(): string | undefined {
647
+ if (this.cliType !== 'codex-cli') return this.providerSessionId;
648
+ let screenText = '';
649
+ try {
650
+ screenText = this.driver.snapshot();
651
+ } catch {
652
+ return this.providerSessionId;
653
+ }
654
+ const clean = stripAnsi(screenText);
655
+ 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);
656
+ return match?.[1] || this.providerSessionId;
657
+ }
658
+
659
+ private readClaudeScreenAssistantMessages(): ChatMessage[] {
660
+ if (this.cliType !== 'claude-cli') return [];
661
+ let screenText = '';
662
+ try {
663
+ screenText = this.driver.snapshot();
664
+ } catch {
665
+ return [];
666
+ }
667
+ const sections = this.readCurrentScreenSections(screenText);
668
+ const body = sections.body || screenText;
669
+ const messages: ChatMessage[] = [];
670
+ const seen = new Set<string>();
671
+ for (const line of body.split(/\r?\n/)) {
672
+ const match = line.match(/^\s*⏺\s+(.+?)\s*$/);
673
+ const content = match?.[1]?.trim();
674
+ if (!content || seen.has(content)) continue;
675
+ seen.add(content);
676
+ messages.push({
677
+ role: 'assistant',
678
+ kind: 'standard',
679
+ content,
680
+ source: 'assistant_text',
681
+ userFacing: true,
682
+ bubbleState: 'final',
683
+ });
684
+ }
685
+ return messages;
686
+ }
687
+
688
+ /**
689
+ * Grace window a held interactive prompt must be absent from the screen
690
+ * before we treat it as resolved-in-terminal and clear it. claude-cli
691
+ * repaints the picker across multiple PTY chunks, so a single
692
+ * footer-less frame is not proof the prompt is gone. Sized in the same
693
+ * spirit as the approval FSM's `approvalCooldown` modal-lost hysteresis.
694
+ */
695
+ private static readonly INTERACTIVE_PROMPT_LOST_GRACE_MS = 1500;
696
+
697
+ /**
698
+ * Multi-question TUI capture: after Tabbing to a page, re-snapshot at this
699
+ * interval until its checkbox glyph column has settled, up to the timeout.
700
+ * The interval matches the legacy single fixed wait (120ms); the timeout
701
+ * bounds total capture time so a single-select page (which never shows
702
+ * glyphs) doesn't stall the capture indefinitely.
703
+ */
704
+ private static readonly CLAUDE_TUI_PAGE_POLL_INTERVAL_MS = 120;
705
+ private static readonly CLAUDE_TUI_PAGE_SETTLE_TIMEOUT_MS = 600;
706
+
707
+ /**
708
+ * Clear a held interactive prompt once the user has resolved it directly
709
+ * in the terminal (the choice picker leaves the screen without going
710
+ * through setInteractivePromptResponse). The approval path already does
711
+ * this via the FSM's modal-lost hysteresis; the interactive-prompt path
712
+ * had no equivalent, so a terminal-side answer left activeInteractivePrompt
713
+ * set and getStatus() re-emitted the same choice modal forever.
714
+ *
715
+ * Detection mirrors capture: the claude TUI picker is on-screen exactly
716
+ * while its "Enter to select" footer is rendered. When the footer is gone
717
+ * for INTERACTIVE_PROMPT_LOST_GRACE_MS the prompt is genuinely resolved.
718
+ */
719
+ private maybeClearResolvedClaudeTuiPrompt(): void {
720
+ if (this.cliType !== 'claude-cli' || !this.activeInteractivePrompt) return;
721
+ // stream-json prompts are tracked by their tool-call lifecycle, not by
722
+ // screen footer, but claude renders the same TUI picker for both
723
+ // transports while awaiting an answer — so screen presence is a valid
724
+ // resolved-signal for either. (If the screen read fails, keep holding.)
725
+ let screenText = '';
726
+ try {
727
+ screenText = this.driver.snapshot();
728
+ } catch {
729
+ return;
730
+ }
731
+ const stillOnScreen = screenText.includes('Enter to select');
732
+ if (stillOnScreen) {
733
+ // Prompt reappeared / never left — reset the hysteresis timer.
734
+ this.interactivePromptLostAt = null;
735
+ return;
736
+ }
737
+ const lostAt = this.interactivePromptLostAt ?? Date.now();
738
+ if (this.interactivePromptLostAt === null) this.interactivePromptLostAt = lostAt;
739
+ if (Date.now() - lostAt < SpecCliAdapter.INTERACTIVE_PROMPT_LOST_GRACE_MS) return;
740
+ // Resolved in the terminal — drop the held prompt so getStatus() stops
741
+ // re-emitting it.
742
+ this.activeInteractivePrompt = null;
743
+ this.interactivePromptTransport = null;
744
+ this.interactivePromptLostAt = null;
745
+ this.statusCallback?.();
746
+ }
747
+
748
+ private maybeCaptureClaudeTuiPrompt(): void {
749
+ if (this.cliType !== 'claude-cli'
750
+ || this.activeInteractivePrompt
751
+ || this.claudeTuiPromptCaptureInFlight) return;
752
+ const screenText = this.driver.snapshot();
753
+ const headers = this.readClaudeTuiHeaders(screenText);
754
+ if (!screenText.includes('Enter to select')) return;
755
+ if (headers.length === 0) {
756
+ const prompt = detectClaudeAskUserQuestionPromptFromTuiPages([{ screenText }], {
757
+ promptId: `ask-user-${this.providerSessionId || 'claude'}-${Date.now()}`,
758
+ providerType: this.cliType,
759
+ });
760
+ if (!prompt) return;
761
+ this.activeInteractivePrompt = prompt;
762
+ this.interactivePromptTransport = 'tui';
763
+ this.interactivePromptLostAt = null;
764
+ this.statusCallback?.();
765
+ return;
766
+ }
767
+ this.claudeTuiPromptCaptureInFlight = true;
768
+ void this.captureClaudeTuiPrompt(screenText, headers).finally(() => {
769
+ this.claudeTuiPromptCaptureInFlight = false;
770
+ });
771
+ }
772
+
773
+ /**
774
+ * The TUI prompt is captured on the FIRST frame that renders the
775
+ * "Enter to select" footer. At that instant the option rows' checkbox
776
+ * column may not have drawn yet, so `detectClaudeTuiMultiSelect` returns
777
+ * false and the prompt is frozen as single-select — the dashboard then
778
+ * renders radio buttons even though the picker is multi-select.
779
+ *
780
+ * While the same TUI prompt is still on screen, re-check the live snapshot:
781
+ * if checkbox glyphs have since appeared, promote any single-select
782
+ * question to multi-select and re-emit status. Promotion is one-way
783
+ * (false→true only) — once a question is known multi-select we never demote
784
+ * it, since the glyph column can scroll out of view on later frames.
785
+ *
786
+ * For MULTI-question prompts the per-page Tab capture is the actual source
787
+ * of the bug: pages 2..N are snapshotted ~120ms after the Tab keypress,
788
+ * before their option-row glyph column has redrawn, so those questions
789
+ * freeze as single-select while page 1 (already settled) is correct. We
790
+ * cannot upgrade blindly — the live snapshot shows only ONE focused page —
791
+ * but we CAN read that page's question text/header and upgrade the matching
792
+ * question. As the user navigates the picker (or it settles), each page is
793
+ * eventually re-read and repaired.
794
+ */
795
+ private maybeUpgradeClaudeTuiMultiSelect(): void {
796
+ if (this.cliType !== 'claude-cli'
797
+ || this.interactivePromptTransport !== 'tui'
798
+ || !this.activeInteractivePrompt) return;
799
+ const questions = this.activeInteractivePrompt.questions;
800
+ if (questions.every(q => q.multiSelect)) return;
801
+ let screenText = '';
802
+ try {
803
+ screenText = this.driver.snapshot();
804
+ } catch {
805
+ return;
806
+ }
807
+ if (!screenText.includes('Enter to select')) return;
808
+
809
+ if (questions.length === 1) {
810
+ if (questions[0].multiSelect) return;
811
+ if (!detectClaudeTuiMultiSelect(screenText)) return;
812
+ questions[0].multiSelect = true;
813
+ this.statusCallback?.();
814
+ return;
815
+ }
816
+
817
+ // Multi-question: attribute the focused page's glyphs to its question by
818
+ // matching header (preferred) or question text, then upgrade just that
819
+ // one. Never demote — a settled non-multi page is left as captured.
820
+ const focused = readFocusedClaudeTuiQuestion(screenText);
821
+ if (!focused || !focused.multiSelect) return;
822
+ const match = questions.find(q =>
823
+ (focused.header && q.header && q.header === focused.header)
824
+ || q.question === focused.question);
825
+ if (!match || match.multiSelect) return;
826
+ match.multiSelect = true;
827
+ this.statusCallback?.();
828
+ }
829
+
830
+ private readClaudeTuiHeaders(screenText: string): string[] {
831
+ const navLine = screenText.split(/\r?\n/).find(line => line.includes('✔ Submit') && /[☐☒]/.test(line));
832
+ if (!navLine) return [];
833
+ const headers: string[] = [];
834
+ for (const match of navLine.matchAll(/[☐☒]\s+(.+?)(?=\s+[☐☒]|\s+✔\s+Submit)/g)) {
835
+ const header = match[1]?.trim();
836
+ if (header) headers.push(header);
837
+ }
838
+ return headers;
839
+ }
840
+
841
+ /**
842
+ * Snapshot the currently-focused claude TUI page, polling until its
843
+ * option-row checkbox glyph column has settled (or a bounded timeout).
844
+ *
845
+ * Why poll: right after a Tab keypress the newly-focused page's glyph
846
+ * column has not redrawn yet, so an immediate snapshot shows the question +
847
+ * option labels but NO per-option checkbox markers — freezing that page as
848
+ * single-select. A fixed delay either races (too short) or is wasteful (too
849
+ * long). Instead we re-snapshot at a fixed interval and stop as soon as the
850
+ * frame shows multi-select glyphs, falling back to the last frame at the
851
+ * timeout. Single-select pages never show glyphs, so they always poll to the
852
+ * timeout — bounded small to keep capture snappy.
853
+ */
854
+ private async snapshotSettledClaudeTuiPage(): Promise<string> {
855
+ let screenText = this.driver.snapshot();
856
+ const deadline = Date.now() + SpecCliAdapter.CLAUDE_TUI_PAGE_SETTLE_TIMEOUT_MS;
857
+ while (!detectClaudeTuiMultiSelect(screenText) && Date.now() < deadline) {
858
+ await new Promise(resolve => setTimeout(resolve, SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
859
+ screenText = this.driver.snapshot();
860
+ }
861
+ return screenText;
862
+ }
863
+
864
+ private async captureClaudeTuiPrompt(firstScreen: string, headers: string[]): Promise<void> {
865
+ const pages: ClaudeInteractiveTuiPage[] = [{ screenText: firstScreen, header: headers[0] }];
866
+ // Forward pass: Tab to each page 2..N and snapshot once its glyph column
867
+ // has settled, so pages 2+ capture their checkbox markers (not a racy
868
+ // pre-redraw frame).
869
+ for (let index = 1; index < headers.length; index += 1) {
870
+ this.driver.dispatch({ kind: 'pty_write', data: '\t' });
871
+ await new Promise(resolve => setTimeout(resolve, SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
872
+ pages.push({ screenText: await this.snapshotSettledClaudeTuiPage(), header: headers[index] });
873
+ }
874
+ // Return pass: Shift-Tab back through pages N..2. As we land on each page
875
+ // again re-read it and OR-in any now-visible multi-select glyphs — a
876
+ // second chance to repair a page whose forward-pass frame was still racy.
877
+ for (let index = headers.length - 1; index > 0; index -= 1) {
878
+ this.driver.dispatch({ kind: 'pty_write', data: '\x1b[Z' });
879
+ await new Promise(resolve => setTimeout(resolve, SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
880
+ const reread = await this.snapshotSettledClaudeTuiPage();
881
+ // The page we just Shift-Tab'd ONTO is index-1 (we move backwards).
882
+ const landed = pages[index - 1];
883
+ if (landed
884
+ && !detectClaudeTuiMultiSelect(landed.screenText)
885
+ && detectClaudeTuiMultiSelect(reread)) {
886
+ landed.screenText = reread;
887
+ }
888
+ }
889
+
890
+ const prompt = detectClaudeAskUserQuestionPromptFromTuiPages(pages, {
891
+ promptId: `ask-user-${this.providerSessionId || 'claude'}-${Date.now()}`,
892
+ providerType: this.cliType,
893
+ });
894
+ if (!prompt) return;
895
+ this.activeInteractivePrompt = prompt;
896
+ this.interactivePromptTransport = 'tui';
897
+ this.interactivePromptLostAt = null;
898
+ this.statusCallback?.();
899
+ }
900
+
901
+ getDebugState(): Record<string, any> {
902
+ const screen = this.driver.getScreen?.() ?? '';
903
+ const history = this.driver.getStateHistory();
904
+ const status = this.getStatus();
905
+
906
+ let messages: any[] = [];
907
+ if (this.spec.native_history?.source) {
908
+ try {
909
+ const result = executeNativeHistory(this.spec.native_history, {
910
+ agentType: this.cliType,
911
+ providerSessionId: this.providerSessionId,
912
+ sessionStartedAtMs: this.spawnedAtMs,
913
+ envOverrides: this.spawnedEnv,
914
+ workspace: this.workingDir,
915
+ });
916
+ if (result && Array.isArray(result.messages)) {
917
+ messages = result.messages;
918
+ }
919
+ } catch (e) {
920
+ // Ignore native history read errors in debug state
921
+ }
922
+ } else {
923
+ messages = this.readClaudeScreenAssistantMessages();
924
+ }
925
+
926
+ const latestState = this.latestState;
927
+ const latestModal = this.latestModal;
928
+ return {
929
+ type: this.cliType,
930
+ name: this.cliName,
931
+ status: status.status,
932
+ rawStatus: status.status,
933
+ projectedStatus: status.status,
934
+ ready: this.spawned,
935
+ // Legacy snapshot-style fields for panels that read getDebugSnapshot shape
936
+ spec_id: this.spec.id,
937
+ current_state: latestState ?? null,
938
+ current_modal: latestModal ?? null,
939
+ exited: this.exited,
940
+ idleHoldPending: this.driver.hasIdleHoldPending?.() ?? false,
941
+ lastBusyAt: this.driver.getLastBusyAt?.() ?? 0,
942
+ screen: screen,
943
+ screenText: screen,
944
+ workingDir: this.workingDir,
945
+ spawnedAtMs: this.spawnedAtMs,
946
+ providerSessionId: this.providerSessionId ?? null,
947
+ sections: this.driver.getSections?.() ?? null,
948
+ stateHistory: history,
949
+ specPath: this.driver.getSpecPath?.() ?? null,
950
+ // v4 FSM live transition table — present only for FsmDriver. Lets
951
+ // the panel (and the daemon API) show, for the current instant,
952
+ // every outgoing transition with its per-condition match result
953
+ // and countdown. This is the canonical "why isn't it transitioning"
954
+ // answer — no screenshots needed.
955
+ fsm: this.driver.getFsmDebug?.() ?? null,
956
+ // v4 FSM transition snapshot history — the captured pre-transition
957
+ // evaluation table at each transition (null for v3 specs).
958
+ fsmHistory: this.driver.getFsmSnapshotHistory?.() ?? null,
959
+ messages,
960
+ committedMessages: messages,
961
+ };
962
+ }
963
+
964
+ getTraceState(limit = 120): Record<string, any> {
965
+ const history = this.driver.getStateHistory();
966
+ return {
967
+ status: this.getStatus().status,
968
+ stateHistory: history.slice(-limit),
969
+ screenText: this.driver.getScreen?.() ?? '',
970
+ };
971
+ }
972
+
973
+ getProviderResolutionMeta(): Record<string, any> {
974
+ return {
975
+ type: this.cliType,
976
+ providerDir: null,
977
+ resolvedVersion: null,
978
+ };
979
+ }
980
+ }