@adhdev/daemon-core 0.9.82-rc.50 → 0.9.82-rc.500

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