@adhdev/daemon-core 0.9.82-rc.38 → 0.9.82-rc.381

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