@adhdev/daemon-core 0.9.82-rc.44 → 0.9.82-rc.441

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 (425) 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 +68 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -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 +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 +29 -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 +142 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router.d.ts +276 -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 +120 -1
  60. package/dist/config/mesh-json-config.d.ts +199 -0
  61. package/dist/config/repo-settings.d.ts +77 -0
  62. package/dist/daemon/dev-server.d.ts +0 -2
  63. package/dist/detection/ide-detector.d.ts +13 -0
  64. package/dist/detection/win32-ide-version.d.ts +37 -0
  65. package/dist/git/change-impact-config.d.ts +159 -0
  66. package/dist/git/git-commands.d.ts +11 -1
  67. package/dist/git/git-diff.d.ts +6 -0
  68. package/dist/git/git-executor.d.ts +11 -0
  69. package/dist/git/git-status.d.ts +57 -0
  70. package/dist/git/git-types.d.ts +2 -50
  71. package/dist/git/git-worktree.d.ts +71 -1
  72. package/dist/git/index.d.ts +3 -1
  73. package/dist/index.d.ts +64 -14
  74. package/dist/index.js +50719 -20120
  75. package/dist/index.js.map +1 -1
  76. package/dist/index.mjs +50317 -19882
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/installer.d.ts +1 -4
  79. package/dist/ipc/local-ipc-server.d.ts +91 -0
  80. package/dist/launch.d.ts +1 -1
  81. package/dist/logging/async-batch-writer.d.ts +10 -0
  82. package/dist/logging/log-redactor.d.ts +24 -0
  83. package/dist/logging/log-tail-reader.d.ts +81 -0
  84. package/dist/logging/logger.d.ts +1 -1
  85. package/dist/mesh/contracts.d.ts +164 -0
  86. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  87. package/dist/mesh/coordinator-registry.d.ts +59 -0
  88. package/dist/mesh/mesh-active-work.d.ts +174 -0
  89. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  90. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  91. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  92. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  93. package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
  94. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  95. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  96. package/dist/mesh/mesh-events-pending.d.ts +69 -0
  97. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  98. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  99. package/dist/mesh/mesh-events.d.ts +6 -49
  100. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  101. package/dist/mesh/mesh-host-ownership.d.ts +29 -0
  102. package/dist/mesh/mesh-init.d.ts +128 -0
  103. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  104. package/dist/mesh/mesh-ledger.d.ts +77 -1
  105. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  106. package/dist/mesh/mesh-missions.d.ts +189 -0
  107. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  108. package/dist/mesh/mesh-queue-assignment.d.ts +113 -0
  109. package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
  110. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  111. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  112. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  113. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  114. package/dist/mesh/mesh-routing.d.ts +70 -0
  115. package/dist/mesh/mesh-runtime-store.d.ts +450 -0
  116. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  117. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  118. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  119. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  120. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  121. package/dist/mesh/mesh-work-queue.d.ts +300 -5
  122. package/dist/mesh/preview-freshness.d.ts +18 -0
  123. package/dist/mesh/refine-config.d.ts +216 -0
  124. package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
  125. package/dist/providers/acp-provider-instance.d.ts +5 -0
  126. package/dist/providers/approval-utils.d.ts +20 -0
  127. package/dist/providers/chat-message-normalization.d.ts +31 -1
  128. package/dist/providers/cli-provider-instance.d.ts +252 -3
  129. package/dist/providers/contracts.d.ts +149 -6
  130. package/dist/providers/external-sources.d.ts +71 -0
  131. package/dist/providers/manual-attendance.d.ts +63 -0
  132. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  133. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  134. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  135. package/dist/providers/native-history/constants.d.ts +12 -0
  136. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  137. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  138. package/dist/providers/native-history/index.d.ts +13 -0
  139. package/dist/providers/provider-instance-manager.d.ts +29 -0
  140. package/dist/providers/provider-instance.d.ts +23 -1
  141. package/dist/providers/provider-loader.d.ts +26 -4
  142. package/dist/providers/provider-trust.d.ts +31 -0
  143. package/dist/providers/read-chat-contract.d.ts +29 -0
  144. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  145. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  146. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  147. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  148. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  149. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  150. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  151. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  152. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  153. package/dist/providers/sdk/v1/index.d.ts +30 -0
  154. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  155. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  156. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  157. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  158. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  159. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  160. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  161. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  162. package/dist/providers/spec/adapter.d.ts +91 -0
  163. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  164. package/dist/providers/spec/evaluator.d.ts +45 -0
  165. package/dist/providers/spec/fsm-driver.d.ts +422 -0
  166. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  167. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  168. package/dist/providers/spec/fsm-types.d.ts +174 -0
  169. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  170. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  171. package/dist/providers/spec/route.d.ts +4 -0
  172. package/dist/providers/spec/types.d.ts +222 -0
  173. package/dist/providers/status-monitor.d.ts +7 -7
  174. package/dist/providers/transcript-v2.d.ts +176 -0
  175. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  176. package/dist/providers/working-dir.d.ts +17 -0
  177. package/dist/repo-mesh-types.d.ts +509 -13
  178. package/dist/runtime-defaults.d.ts +2 -0
  179. package/dist/sessions/registry.d.ts +6 -0
  180. package/dist/shared-types-extra.d.ts +2 -4
  181. package/dist/shared-types.d.ts +59 -2
  182. package/dist/status/normalize.d.ts +1 -1
  183. package/dist/status/normalize.js +1 -0
  184. package/dist/status/normalize.js.map +1 -1
  185. package/dist/status/normalize.mjs +1 -0
  186. package/dist/status/normalize.mjs.map +1 -1
  187. package/dist/status/reporter.d.ts +2 -0
  188. package/dist/status/snapshot.d.ts +26 -0
  189. package/dist/system/hash.d.ts +8 -0
  190. package/dist/system/load-better-sqlite3.d.ts +21 -0
  191. package/dist/types.d.ts +5 -0
  192. package/package.json +7 -3
  193. package/src/agent-stream/poller.ts +2 -3
  194. package/src/agent-stream/provider-adapter.ts +1 -1
  195. package/src/boot/daemon-lifecycle.ts +63 -12
  196. package/src/boot/process-hardening.ts +89 -0
  197. package/src/build-info.ts +73 -0
  198. package/src/chat/source-machine.ts +534 -0
  199. package/src/chat/source-resolver.ts +0 -0
  200. package/src/chat/subscription-updates.ts +20 -1
  201. package/src/cli-adapter-types.d.ts +3 -1
  202. package/src/cli-adapter-types.ts +68 -2
  203. package/src/cli-adapters/cli-script-runner.ts +421 -0
  204. package/src/cli-adapters/cli-state-engine.ts +1246 -0
  205. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  206. package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
  207. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  208. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  209. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  210. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  211. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  212. package/src/cli-adapters/pty-transport.ts +2 -1
  213. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  214. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  215. package/src/cli-adapters/resolve-executable.ts +204 -0
  216. package/src/cli-adapters/session-host-transport.ts +2 -1
  217. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  218. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  219. package/src/cli-adapters/terminal-screen.ts +16 -81
  220. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  221. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  222. package/src/commands/chat-commands-read.ts +2447 -0
  223. package/src/commands/chat-commands-scope.ts +54 -0
  224. package/src/commands/chat-commands-shared.ts +114 -0
  225. package/src/commands/chat-commands-write.ts +891 -0
  226. package/src/commands/chat-commands.ts +19 -1841
  227. package/src/commands/cli-manager.ts +572 -27
  228. package/src/commands/handler.ts +841 -2
  229. package/src/commands/high-family/index.ts +28 -0
  230. package/src/commands/high-family/mesh-coordinator-launch.ts +678 -0
  231. package/src/commands/high-family/mesh-events.ts +80 -0
  232. package/src/commands/high-family/mesh-status.ts +714 -0
  233. package/src/commands/high-family/types.ts +76 -0
  234. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  235. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  236. package/src/commands/low-family/diagnostics.ts +57 -0
  237. package/src/commands/low-family/index.ts +37 -0
  238. package/src/commands/low-family/mesh-ledger.ts +62 -0
  239. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  240. package/src/commands/low-family/notification.ts +116 -0
  241. package/src/commands/low-family/refine-config.ts +106 -0
  242. package/src/commands/low-family/session-host.ts +274 -0
  243. package/src/commands/low-family/spec-providerdev.ts +217 -0
  244. package/src/commands/low-family/status-meta.ts +112 -0
  245. package/src/commands/low-family/types.ts +39 -0
  246. package/src/commands/med-family/cli-agent.ts +238 -0
  247. package/src/commands/med-family/fast-forward.ts +230 -0
  248. package/src/commands/med-family/ide.ts +163 -0
  249. package/src/commands/med-family/index.ts +37 -0
  250. package/src/commands/med-family/mesh-crud.ts +1242 -0
  251. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  252. package/src/commands/med-family/mesh-queue.ts +167 -0
  253. package/src/commands/med-family/mesh-restart.ts +92 -0
  254. package/src/commands/med-family/types.ts +143 -0
  255. package/src/commands/mesh-coordinator.ts +334 -124
  256. package/src/commands/router.ts +2846 -3484
  257. package/src/commands/stream-commands.ts +8 -0
  258. package/src/commands/upgrade-helper.ts +310 -45
  259. package/src/config/chat-history.ts +493 -24
  260. package/src/config/config.ts +12 -0
  261. package/src/config/mesh-config.ts +593 -22
  262. package/src/config/mesh-json-config.ts +376 -0
  263. package/src/config/recent-activity.ts +8 -2
  264. package/src/config/repo-settings.ts +111 -0
  265. package/src/daemon/dev-auto-implement.ts +3 -2
  266. package/src/daemon/dev-cli-debug.ts +10 -1
  267. package/src/daemon/dev-server.ts +0 -541
  268. package/src/detection/cli-detector.ts +28 -9
  269. package/src/detection/ide-detector.ts +55 -16
  270. package/src/detection/win32-ide-version.ts +106 -0
  271. package/src/git/change-impact-config.ts +354 -0
  272. package/src/git/git-commands.ts +59 -15
  273. package/src/git/git-diff.ts +81 -11
  274. package/src/git/git-executor.ts +12 -0
  275. package/src/git/git-status.ts +767 -48
  276. package/src/git/git-types.ts +14 -62
  277. package/src/git/git-worktree.ts +261 -4
  278. package/src/git/index.ts +17 -0
  279. package/src/index.ts +196 -12
  280. package/src/installer.d.ts +1 -1
  281. package/src/installer.ts +8 -6
  282. package/src/ipc/local-ipc-server.ts +278 -0
  283. package/src/launch.d.ts +1 -1
  284. package/src/launch.ts +37 -28
  285. package/src/logging/async-batch-writer.ts +55 -0
  286. package/src/logging/command-log.ts +7 -5
  287. package/src/logging/log-redactor.ts +100 -0
  288. package/src/logging/log-tail-reader.ts +341 -0
  289. package/src/logging/logger.ts +14 -7
  290. package/src/mesh/contracts.ts +338 -0
  291. package/src/mesh/coordinator-prompt.ts +415 -34
  292. package/src/mesh/coordinator-registry.ts +121 -0
  293. package/src/mesh/mesh-active-work.ts +645 -0
  294. package/src/mesh/mesh-clone-grace.ts +68 -0
  295. package/src/mesh/mesh-coordinator-config.ts +97 -0
  296. package/src/mesh/mesh-delivery-policy.ts +315 -0
  297. package/src/mesh/mesh-event-classify.ts +51 -0
  298. package/src/mesh/mesh-event-forwarding.ts +1897 -0
  299. package/src/mesh/mesh-event-trace.ts +67 -0
  300. package/src/mesh/mesh-events-coordinator.ts +32 -0
  301. package/src/mesh/mesh-events-pending.ts +656 -0
  302. package/src/mesh/mesh-events-stale.ts +389 -0
  303. package/src/mesh/mesh-events-utils.ts +443 -0
  304. package/src/mesh/mesh-events.ts +33 -1035
  305. package/src/mesh/mesh-fast-forward.ts +843 -0
  306. package/src/mesh/mesh-host-ownership.ts +111 -0
  307. package/src/mesh/mesh-init.ts +350 -0
  308. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  309. package/src/mesh/mesh-ledger.ts +656 -102
  310. package/src/mesh/mesh-magi-status.ts +223 -0
  311. package/src/mesh/mesh-missions.ts +449 -0
  312. package/src/mesh/mesh-node-identity.ts +1887 -0
  313. package/src/mesh/mesh-queue-assignment.ts +1924 -0
  314. package/src/mesh/mesh-reconcile-loop.ts +1997 -0
  315. package/src/mesh/mesh-refine-batch.ts +205 -0
  316. package/src/mesh/mesh-refine-gates.ts +1673 -0
  317. package/src/mesh/mesh-refine-status.ts +231 -0
  318. package/src/mesh/mesh-review-inbox.ts +307 -0
  319. package/src/mesh/mesh-routing.ts +291 -0
  320. package/src/mesh/mesh-runtime-store.ts +1853 -0
  321. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  322. package/src/mesh/mesh-task-inflight.ts +70 -0
  323. package/src/mesh/mesh-task-stats.ts +161 -0
  324. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  325. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  326. package/src/mesh/mesh-work-queue.ts +1254 -141
  327. package/src/mesh/preview-freshness.ts +118 -0
  328. package/src/mesh/refine-config.ts +423 -0
  329. package/src/mesh/worktree-bootstrap-config.ts +450 -0
  330. package/src/providers/acp-provider-instance.ts +43 -10
  331. package/src/providers/approval-utils.d.ts +5 -0
  332. package/src/providers/approval-utils.ts +57 -5
  333. package/src/providers/chat-message-normalization.ts +92 -4
  334. package/src/providers/cli-provider-instance.ts +2001 -106
  335. package/src/providers/contracts.d.ts +55 -0
  336. package/src/providers/contracts.ts +160 -6
  337. package/src/providers/extension-provider-instance.ts +12 -7
  338. package/src/providers/external-sources.ts +218 -0
  339. package/src/providers/ide-provider-instance.ts +35 -12
  340. package/src/providers/manual-attendance.ts +85 -0
  341. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  342. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  343. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  344. package/src/providers/native-history/constants.ts +19 -0
  345. package/src/providers/native-history/dispatcher.ts +345 -0
  346. package/src/providers/native-history/hermes-cli-transcript.ts +260 -0
  347. package/src/providers/native-history/index.ts +30 -0
  348. package/src/providers/provider-instance-manager.ts +71 -0
  349. package/src/providers/provider-instance.ts +19 -1
  350. package/src/providers/provider-loader.ts +668 -50
  351. package/src/providers/provider-schema.ts +87 -14
  352. package/src/providers/provider-trust.ts +114 -0
  353. package/src/providers/read-chat-contract.ts +76 -16
  354. package/src/providers/sdk/README.md +49 -0
  355. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  356. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  357. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  358. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  359. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  360. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  361. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  362. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  363. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  364. package/src/providers/sdk/v1/index.ts +152 -0
  365. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  366. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  367. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  368. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
  369. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  370. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  374. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  375. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  376. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  377. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  378. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  379. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  380. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  381. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  382. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  383. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  384. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  385. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  386. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  387. package/src/providers/sdk/v1/validators/index.ts +19 -0
  388. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  389. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  390. package/src/providers/spec/adapter.ts +235 -0
  391. package/src/providers/spec/cli-adapter.ts +1056 -0
  392. package/src/providers/spec/evaluator.ts +407 -0
  393. package/src/providers/spec/fsm-driver.ts +1410 -0
  394. package/src/providers/spec/fsm-evaluator.ts +272 -0
  395. package/src/providers/spec/fsm-loader.ts +120 -0
  396. package/src/providers/spec/fsm-types.ts +273 -0
  397. package/src/providers/spec/native-history-executor.ts +1143 -0
  398. package/src/providers/spec/pre-launch-trust.ts +104 -0
  399. package/src/providers/spec/route.ts +51 -0
  400. package/src/providers/spec/types.ts +262 -0
  401. package/src/providers/status-monitor.d.ts +7 -7
  402. package/src/providers/status-monitor.ts +37 -22
  403. package/src/providers/transcript-v2.ts +567 -0
  404. package/src/providers/types/interactive-prompt.ts +536 -0
  405. package/src/providers/version-archive.ts +64 -24
  406. package/src/providers/working-dir.ts +23 -0
  407. package/src/repo-mesh-types.ts +748 -14
  408. package/src/runtime-defaults.ts +39 -0
  409. package/src/sessions/registry.ts +6 -0
  410. package/src/shared-types-extra.ts +2 -4
  411. package/src/shared-types.d.ts +8 -0
  412. package/src/shared-types.ts +64 -1
  413. package/src/status/builders.ts +26 -6
  414. package/src/status/normalize.ts +2 -0
  415. package/src/status/reporter.ts +19 -1
  416. package/src/status/snapshot.ts +95 -26
  417. package/src/system/hash.ts +23 -0
  418. package/src/system/host-memory.ts +29 -12
  419. package/src/system/load-better-sqlite3.ts +68 -0
  420. package/src/types.ts +5 -0
  421. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  422. package/dist/mesh/mesh-sync.d.ts +0 -53
  423. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  424. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  425. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1410 @@
1
+ /**
2
+ * FsmDriver — runs an adhdev:cli/spec@4 finite state machine against a PTY.
3
+ *
4
+ * Drop-in compatible with SpecDriver's public surface (subscribe / dispatch /
5
+ * start / snapshot / getStateHistory / getDebugState / …) so the cli-adapter
6
+ * can use either driver behind one interface. The difference is entirely
7
+ * internal: instead of a stack of hard-coded debounce layers, this driver
8
+ * holds ONE piece of state — the current FSM node — and on every screen change
9
+ * asks the FSM evaluator "which outgoing transition fires?". All timing
10
+ * (startup grace, busy hold, completion stability) is expressed in the spec as
11
+ * transition guards (min_hold_ms) and time conditions (elapsed_ms / stable_ms).
12
+ *
13
+ * Because the engine carries no CLI knowledge, the only way it can be "wrong"
14
+ * is if a spec's transitions are wrong — and that is fully inspectable via
15
+ * getFsmDebug(), which reports every outgoing transition with its per-condition
16
+ * match result and countdown. That is the contract: debug the spec, not the
17
+ * engine.
18
+ */
19
+ 'use strict';
20
+
21
+ import * as fs from 'node:fs';
22
+ import * as os from 'node:os';
23
+ import * as path from 'node:path';
24
+ import { TerminalAdapter, type TerminalAdapterOpts, type SpecPtyEvent } from './adapter.js';
25
+ import { resolveCliSpawnPlanFromParts } from '../../cli-adapters/provider-cli-runtime.js';
26
+ import type { PtyTransportFactory } from '../../cli-adapters/pty-transport.js';
27
+ import { DEFAULT_SESSION_HOST_COLS, DEFAULT_SESSION_HOST_ROWS } from '@adhdev/session-host-core';
28
+ import {
29
+ resolveSections, sectionText, extractTitle, extractButtonsFromRule,
30
+ type ResolvedSection, type TraceEntry,
31
+ } from './evaluator.js';
32
+ import { evaluateFsm, type FsmClock, type TransitionEval, type FsmEvaluation } from './fsm-evaluator.js';
33
+ import {
34
+ type CliSpecV4, type FsmState, type FsmTransition,
35
+ initialState, stateById, statusForState, modalKindForState, outgoingTransitions,
36
+ } from './fsm-types.js';
37
+ import { loadFsmSpec } from './fsm-loader.js';
38
+ import { applyPreLaunchTrust } from './pre-launch-trust.js';
39
+ import type { Control, DelegateTrigger } from './types.js';
40
+ import { LOG } from '../../logging/logger.js';
41
+ import {
42
+ WIN32_PTY_WRITE_CHUNK_CHARS,
43
+ WIN32_PTY_WRITE_CHUNK_GAP_MS,
44
+ chunkPreservingSurrogates as chunkPreservingSurrogatesShared,
45
+ } from '../../cli-adapters/pty-write-chunking.js';
46
+
47
+ // ── Shared driver types (formerly in driver.ts) ───────────────────────────
48
+
49
+ export type DashboardEvent =
50
+ | { kind: 'pty_data'; chunk: string }
51
+ | { kind: 'state_changed'; state: { id: string; label: string; title: string | null; status: 'idle' | 'generating' | 'approval' };
52
+ modal: { title: string | null; buttons: { index: number; label: string }[]; kind: 'approval' | 'picker' | 'confirm' | null } | null;
53
+ controls: { id: string; label: string; action_type: string }[] }
54
+ | { kind: 'notification'; id: string; title: string; body: string }
55
+ | { kind: 'delegate'; id: string; task: string }
56
+ | { kind: 'spec_trace'; entries: TraceEntry[] }
57
+ | { kind: 'exit'; exit_code: number }
58
+ | { kind: 'spec_error'; errors: string[] };
59
+
60
+ export type DashboardCommand =
61
+ | { kind: 'send_message'; text: string }
62
+ | { kind: 'pty_write'; data: string }
63
+ | { kind: 'click_control'; control_id: string; payload?: unknown }
64
+ | { kind: 'click_modal_button'; index: number }
65
+ | { kind: 'attach_image'; blob: string; mime: string }
66
+ | { kind: 'resize'; cols: number; rows: number }
67
+ | { kind: 'cancel' }
68
+ | { kind: 'shutdown' };
69
+
70
+ export interface DriverHistoryEntry {
71
+ stateId: string;
72
+ label: string;
73
+ at: number;
74
+ durationMs: number;
75
+ reason: string;
76
+ matchedStateId?: string;
77
+ matchedRules?: string[];
78
+ debounceKind?: string;
79
+ idleHoldMs?: number;
80
+ busyHoldMs?: number;
81
+ via?: string;
82
+ }
83
+
84
+ /**
85
+ * A frozen snapshot of the FULL FSM evaluation captured at the instant a
86
+ * transition fired — the rich `transitions[]` table (per-transition eligible /
87
+ * hold countdown / per-condition CondResult + remainingMs) that `getFsmDebug()`
88
+ * otherwise only computes live for the current instant. Kept in a separate ring
89
+ * buffer from `stateHistory` (which stays intentionally lightweight) so the
90
+ * "why did this rule fire just before the transition" question is answerable
91
+ * after the fact. before-only: this is the evaluation that PRODUCED the
92
+ * transition, not the post-transition state.
93
+ */
94
+ export interface FsmSnapshotEntry {
95
+ /** State we transitioned out of. */
96
+ stateFrom: string;
97
+ /** State we transitioned into (the fired transition's destination). */
98
+ stateTo: string;
99
+ /** Wall-clock time the transition committed (ms). */
100
+ at: number;
101
+ /** The fired transition's destination state id (== stateTo; kept explicit
102
+ * to mirror the rule that fired). */
103
+ firedTo: string;
104
+ /** Human label of the fired transition (e.g. "approval→busy"). */
105
+ firedLabel: string;
106
+ /** Why-it-fired summary, same shape produced for stateHistory.matchedRules. */
107
+ reason: string[];
108
+ /** Every outgoing transition from `stateFrom` as evaluated at `at`, each
109
+ * with its eligible / hold / per-condition CondResult + remainingMs. This
110
+ * is the full pre-transition evaluation table — the whole point of the
111
+ * snapshot. */
112
+ transitions: TransitionEval[];
113
+ }
114
+
115
+ export interface ISpecDriver {
116
+ subscribe(listener: (ev: DashboardEvent) => void): () => void;
117
+ start(): void;
118
+ dispatch(cmd: DashboardCommand): void;
119
+ snapshot(): string;
120
+ getCursorPosition(): { row: number; col: number };
121
+ getScreen(): string;
122
+ getSpecPath(): string;
123
+ shutdown(): void;
124
+ getStateHistory(): ReadonlyArray<DriverHistoryEntry>;
125
+ getSections(): Array<{ id: string; text: string }> | null;
126
+ getLastBusyAt(): number;
127
+ hasIdleHoldPending(): boolean;
128
+ hasSeenReady(): boolean;
129
+ getCompletionIdleDebounceState(): { active: boolean; ageMs: number; holdMs: number; forceAfterMs: number } | null;
130
+ getFsmDebug?(): unknown;
131
+ getFsmSnapshotHistory?(): ReadonlyArray<FsmSnapshotEntry>;
132
+ getEventTimeline?(limit?: number): ReadonlyArray<SpecPtyEvent>;
133
+ }
134
+
135
+ export interface SpecDriverOpts {
136
+ specPath: string;
137
+ workingDir: string;
138
+ extraEnv?: Record<string, string>;
139
+ cols?: number;
140
+ rows?: number;
141
+ hotReload?: boolean;
142
+ emitTrace?: boolean;
143
+ transportFactory?: PtyTransportFactory;
144
+ extraCliArgs?: string[];
145
+ }
146
+
147
+ function countNewlines(s: string): number {
148
+ let n = 0;
149
+ for (let i = 0; i < s.length; i += 1) if (s.charCodeAt(i) === 10) n += 1;
150
+ return n;
151
+ }
152
+
153
+ const SUBMIT_DELAY_FLOOR_MS = 200;
154
+
155
+ // win32 ConPTY submit reliability — TWO independent concerns, do not conflate:
156
+ //
157
+ // (A) WHEN the single real submit CR fires. The first CR must not fire until
158
+ // the WHOLE body has echoed into the composer; a MULTILINE body also opens
159
+ // an Ink paste/newline-accumulation window during which a lone CR can be
160
+ // absorbed as a literal newline rather than submitting, with a
161
+ // nondeterministic length (observed 0–~2s, driven by ConPTY byte timing).
162
+ // So we VERIFY instead of guessing: hold the CR behind the head+tail
163
+ // echo-gate (scheduleWin32Submit phase 1), then resend the submit key on a
164
+ // fixed cadence until the FSM observes the agent has actually left the idle
165
+ // composer (status flips away from 'idle' — submitted / generating / modal),
166
+ // bounded by a retry budget (phase 2). Once submission is observed we stop
167
+ // so we don't spam Enter into the next turn. Single-line messages satisfy
168
+ // the check after the first CR, so their behaviour is unchanged.
169
+ //
170
+ // (B) HOW the body's OWN embedded newlines are written (FIX-B-v2). On the real
171
+ // win32 Ink/ConPTY composer each embedded '\n' in the body SUBMITS the
172
+ // preceding line as a separate composer entry, so writing the raw body
173
+ // (writeWin32Body) submitted every line but the last BEFORE the trailing
174
+ // echo-gated CR (A) ever ran — the prompt was truncated to only the tail
175
+ // fragment after the last '\n' (failure_category=per_newline_submit). The
176
+ // body must therefore land atomically as composer TEXT with ZERO per-line
177
+ // submits. writeWin32Body now does that: it wraps a newline-bearing body in
178
+ // a bracketed-paste (ESC[200~ … ESC[201~) so the composer takes the whole
179
+ // thing — embedded newlines and all — as pasted text (PRIMARY mode), or in
180
+ // the soft_newline fallback rewrites each embedded newline as a
181
+ // non-submitting Shift+Enter sequence. EITHER way the trailing submit CR is
182
+ // NOT part of this write — it stays separate and is fired later by (A).
183
+ //
184
+ // NOTE on the old "bracketed-paste wrapping does NOT help" claim that used to live
185
+ // here: that A/B fused the submit CR *inside* the paste (…body\r…201~), so the
186
+ // paste-closing still carried a submit and was never a clean text-only paste. The
187
+ // correct shape — paste wraps ONLY the body, CR stays separate — is what FIX-B-v2
188
+ // implements; it was never actually tested by that earlier A/B.
189
+ const WIN32_SUBMIT_RESEND_GAP_MS = 350;
190
+ const WIN32_SUBMIT_MAX_RESENDS = 14;
191
+ // Quiet window the win32 echo-gate (below) requires AFTER the body is seen in the
192
+ // composer, so a CR fires only once the FULL (possibly multi-KB / multiline) body has
193
+ // finished arriving and echoing — not mid-arrival. POLL_MS is the gate's recheck
194
+ // cadence while it waits for the body to echo.
195
+ const WIN32_SUBMIT_SETTLE_MS = 500;
196
+ const WIN32_SUBMIT_SETTLE_POLL_MS = 120;
197
+ // Defensive paced PTY write tuning (WIN32_PTY_WRITE_CHUNK_CHARS / _GAP_MS) and the
198
+ // surrogate-safe splitter now live in the shared pty-write-chunking module so this
199
+ // driver and the legacy ProviderCliAdapter cannot drift apart — see the import above.
200
+ // Echo-gate for the win32 FIRST submit CR (supersedes the bare output-quiet settle).
201
+ // The body write can race claude-cli's boot — its stdin reader is not wired until the
202
+ // composer renders (~5–7s in, later under load), so a too-early write is buffered and
203
+ // the output goes quiet with a still-EMPTY composer; a quiet-only gate then fires a CR
204
+ // into nothing. Instead, hold the CR until the body text has actually ECHOED into the
205
+ // composer (effect-confirmed, not readiness-signal-guessed) — the buffered write lands
206
+ // once claude wires up, just late. WIN32_ECHO_MAX_WAIT_MS bounds the wait so a body
207
+ // that truly never confirms still fires a blind CR (resend net) rather than hanging; it
208
+ // is set generously so even a slow/contended boot lands its body before the blind fire.
209
+ const WIN32_ECHO_PROBE_CHARS = 16;
210
+ const WIN32_ECHO_MAX_WAIT_MS = 20_000;
211
+
212
+ // FIX-B-v2 — how a newline-bearing win32 body's OWN embedded newlines are written
213
+ // (see concern (B) above). 'paste' (default) wraps the body in a bracketed-paste so
214
+ // the Ink composer absorbs the whole thing as text; 'soft_newline' rewrites each
215
+ // embedded newline as a non-submitting Shift+Enter. Whether THIS ConPTY honors
216
+ // bracketed-paste can only be confirmed by the live deploy A/B (we cannot A/B it via
217
+ // delegation — win32 truncates any newline-bearing task), so both modes ship and the
218
+ // fallback is selectable at runtime via ADHDEV_WIN32_SUBMIT_MODE.
219
+ export type Win32SubmitMode = 'paste' | 'soft_newline';
220
+ const WIN32_BRACKETED_PASTE_OPEN = '\x1b[200~';
221
+ const WIN32_BRACKETED_PASTE_CLOSE = '\x1b[201~';
222
+ // Non-submitting soft-newline for the claude-cli Ink composer. The spec
223
+ // (cli/claude-cli/specs/4.0.json) declares no soft-newline keycode, so we use the
224
+ // CSI-u encoding of Shift+Enter (modifyOtherKeys form: keycode 13 = Enter, modifier
225
+ // 2 = Shift). This inserts a literal newline into the composer WITHOUT submitting,
226
+ // unlike a bare CR (\r) which is reserved for the single real submit via (A).
227
+ const WIN32_SOFT_NEWLINE = '\x1b[27;2;13~';
228
+
229
+ export function resolveWin32SubmitMode(env: NodeJS.ProcessEnv = process.env): Win32SubmitMode {
230
+ return env.ADHDEV_WIN32_SUBMIT_MODE === 'soft_newline' ? 'soft_newline' : 'paste';
231
+ }
232
+
233
+ /** Collapse a string to its non-whitespace characters for echo comparison: the
234
+ * composer wraps, indents, and prefixes the body (with the `❯ ` prompt), so a raw
235
+ * substring test against the rendered screen fails. Stripping all whitespace makes
236
+ * "❯ hello world" reliably contain the probe "helloworld". */
237
+ function normalizeForEcho(s: string): string {
238
+ return s.replace(/\s+/g, '');
239
+ }
240
+
241
+ export function resolveSubmitDelayMs(specBeforeSubmit: number | undefined, text: string): number {
242
+ const lines = countNewlines(text);
243
+ const linesBonus = Math.min(800, lines * 80);
244
+ const spec = typeof specBeforeSubmit === 'number' && specBeforeSubmit > 0 ? specBeforeSubmit : 0;
245
+ return Math.max(spec, SUBMIT_DELAY_FLOOR_MS + linesBonus);
246
+ }
247
+
248
+ /** Re-export of the shared surrogate-safe splitter so existing imports of
249
+ * `chunkPreservingSurrogates` from this module keep working. The implementation
250
+ * lives in ../../cli-adapters/pty-write-chunking so the spec driver and the
251
+ * legacy adapter share one definition. */
252
+ export const chunkPreservingSurrogates = chunkPreservingSurrogatesShared;
253
+
254
+ export function guessExt(mime: string): string {
255
+ if (/png/i.test(mime)) return '.png';
256
+ if (/jpe?g/i.test(mime)) return '.jpg';
257
+ if (/gif/i.test(mime)) return '.gif';
258
+ if (/webp/i.test(mime)) return '.webp';
259
+ return '.bin';
260
+ }
261
+
262
+ // ─────────────────────────────────────────────────────────────────────────────
263
+
264
+ interface ModalSnapshot {
265
+ title: string | null;
266
+ buttons: { index: number; label: string; key: string; current: boolean }[];
267
+ }
268
+
269
+ interface VisibleControl {
270
+ id: string;
271
+ label: string;
272
+ actionType: 'send_keys' | 'open_picker' | 'attach_image';
273
+ }
274
+
275
+ type HistoryEntry = DriverHistoryEntry;
276
+
277
+ /** Per-state evaluation snapshot (mirrors v3 SpecEvaluation shape for the
278
+ * parts the cli-adapter / panel consume). */
279
+ interface CurrentEval {
280
+ state: { id: string; label: string; title: string | null; status: 'idle' | 'generating' | 'approval' };
281
+ modal: ModalSnapshot | null;
282
+ controls: VisibleControl[];
283
+ }
284
+
285
+ export class FsmDriver implements ISpecDriver {
286
+ private spec!: CliSpecV4;
287
+ private adapter: TerminalAdapter;
288
+ private listeners = new Set<(ev: DashboardEvent) => void>();
289
+
290
+ // ── The entire FSM state: which node we're in, and when we entered it.
291
+ private currentStateId = '';
292
+ private stateEnteredAt = 0;
293
+
294
+ // ── Clock bookkeeping for time conditions.
295
+ private startedAtMs = 0;
296
+ private prevScreenLines: string[] = [];
297
+ /** Per cursor_above region (key: cursor_above, -1 = whole screen) → last
298
+ * time that region's content changed. Drives stable_ms conditions. */
299
+ private regionLastChangedAt = new Map<number, number>();
300
+ /** Timer that re-runs evaluate() when a time-condition would flip true
301
+ * with no PTY frame to trigger it. */
302
+ private wakeTimer: ReturnType<typeof setTimeout> | null = null;
303
+ /** Timer driving the focus-gated stall watchdog (refocus_when_stalled_ms).
304
+ * Re-arms itself while the machine is generating so a re-prime can fire
305
+ * even when the PTY has gone completely quiet. */
306
+ private stallTimer: ReturnType<typeof setTimeout> | null = null;
307
+ /** Wall-clock time the last stall re-prime was injected. The cooldown gate:
308
+ * after a re-prime we don't re-inject until the screen changes (which
309
+ * resets the stall reference) or another full stall window lapses. */
310
+ private lastRefocusAt = 0;
311
+ /** Timer driving the win32 verification-based submit resend loop (see
312
+ * WIN32_SUBMIT_* and scheduleWin32Submit). Re-arms itself until the FSM
313
+ * leaves idle (submitted) or the resend budget is spent. */
314
+ private win32SubmitTimer: ReturnType<typeof setTimeout> | null = null;
315
+ /** Wall-clock (ms) of the most recent raw PTY output chunk. Advances on every
316
+ * on_pty_data — including the echo of text written into the composer — so the
317
+ * win32 submit settle-gate can tell when input has finished landing. */
318
+ private lastPtyDataAt = 0;
319
+ /** Wall-clock (ms) of the most recent win32 message-body input write. Bridges
320
+ * the gap between writing a chunk and its echo so the settle-gate does not
321
+ * declare "quiet" mid-write. */
322
+ private lastWin32WriteAt = 0;
323
+ /** Pending paced chunk-write timer for a large win32 body (see writeWin32Body). */
324
+ private win32WriteTimer: ReturnType<typeof setTimeout> | null = null;
325
+ /** Timer driving the win32 verification-based modal-confirm CR resend loop (see
326
+ * scheduleWin32ModalConfirm). A lone CR that confirms an approval/picker choice
327
+ * is absorbed by ConPTY the same way a send_message submit CR is, so the confirm
328
+ * must be resent until the modal actually resolves (status leaves 'approval'). */
329
+ private win32ModalConfirmTimer: ReturnType<typeof setTimeout> | null = null;
330
+
331
+ private currentEval: CurrentEval | null = null;
332
+ private stateHistory: HistoryEntry[] = [];
333
+ private prevStateAt = 0;
334
+
335
+ // ── send_message queueing until the machine first reaches a non-initial,
336
+ // non-busy ("ready") state — same contract as v3's idleSeenOnce.
337
+ private readySeenOnce = false;
338
+ private pendingSends: string[] = [];
339
+
340
+ private pickerInProgress: { control_id: string; spec: Control } | null = null;
341
+ private delegateTimers = new Map<string, ReturnType<typeof setTimeout>>();
342
+ private specWatcher: fs.FSWatcher | null = null;
343
+ /** Last full FSM evaluation, kept for the debugger. */
344
+ private lastFsmEval: ReturnType<typeof evaluateFsm> | null = null;
345
+ /** Ring buffer (max 20) of the full FSM evaluation captured at each
346
+ * transition — the rich pre-transition table that lastFsmEval only keeps
347
+ * for the single most recent evaluation. Separate from stateHistory. */
348
+ private fsmSnapshotHistory: FsmSnapshotEntry[] = [];
349
+
350
+ constructor(private readonly opts: SpecDriverOpts) {
351
+ this.loadSpecOrThrow();
352
+ this.adapter = new TerminalAdapter(
353
+ this.buildAdapterOpts(),
354
+ {
355
+ init: () => this.emitInitialState(),
356
+ on_pty_data: (chunk) => { this.lastPtyDataAt = Date.now(); this.emit({ kind: 'pty_data', chunk }); },
357
+ on_screen_changed: () => this.reevaluate(),
358
+ on_exit: ({ exitCode }) => this.handleExit(exitCode),
359
+ },
360
+ );
361
+ if (this.opts.hotReload !== false) this.armSpecWatcher();
362
+ }
363
+
364
+ subscribe(listener: (ev: DashboardEvent) => void): () => void {
365
+ this.listeners.add(listener);
366
+ return () => { this.listeners.delete(listener); };
367
+ }
368
+
369
+ start(): void {
370
+ const now = Date.now();
371
+ this.startedAtMs = now;
372
+ const init = initialState(this.spec);
373
+ this.currentStateId = init.id;
374
+ this.stateEnteredAt = now;
375
+ this.prevStateAt = now;
376
+ // Pre-trust the workspace before spawning so a first-run folder-trust
377
+ // prompt never appears (best-effort; failures fall back to the FSM's
378
+ // trust-modal detection). Only runs for specs that declare it.
379
+ if (this.spec.pre_launch_trust) {
380
+ applyPreLaunchTrust(this.spec.pre_launch_trust, this.opts.workingDir);
381
+ }
382
+ this.adapter.start();
383
+ // Prime focus-gated TUIs (see CliSpecV4.send_on_spawn). Written once,
384
+ // shortly after spawn, so the input stream is awake before the first
385
+ // delegated message — without this, a focus-event CLI like antigravity
386
+ // drops the first programmatic write until a manual keystroke.
387
+ this.scheduleSpawnPrime();
388
+ // The initial state may have a purely time-based exit (elapsed_ms);
389
+ // schedule a wake so we leave it even if the PTY goes quiet.
390
+ this.scheduleWakeForState();
391
+ }
392
+
393
+ private scheduleSpawnPrime(): void {
394
+ const seqs = this.spec.send_on_spawn;
395
+ if (!Array.isArray(seqs) || seqs.length === 0) return;
396
+ const delay = Math.max(0, this.spec.send_on_spawn_delay_ms ?? 250);
397
+ setTimeout(() => this.sendSpawnPrime(), delay);
398
+ }
399
+
400
+ /** Write the declared `send_on_spawn` sequences to the PTY once. Used both
401
+ * at spawn (scheduleSpawnPrime) and, for focus-gated TUIs, by the stall
402
+ * watchdog to re-inject the focus-in wake mid-turn. No-op when the spec
403
+ * declares no prime, so non-focus-gated CLIs are never poked. */
404
+ private sendSpawnPrime(): void {
405
+ const seqs = this.spec.send_on_spawn;
406
+ if (!Array.isArray(seqs) || seqs.length === 0) return;
407
+ for (const seq of seqs) {
408
+ if (typeof seq === 'string' && seq.length > 0) this.adapter.send_keys(seq);
409
+ }
410
+ }
411
+
412
+ dispatch(cmd: DashboardCommand): void {
413
+ switch (cmd.kind) {
414
+ case 'send_message': this.handleSendMessage(cmd.text); return;
415
+ case 'pty_write': this.adapter.send_keys(cmd.data); return;
416
+ case 'click_control': this.handleClickControl(cmd.control_id, cmd.payload); return;
417
+ case 'click_modal_button': this.handleClickModalButton(cmd.index); return;
418
+ case 'attach_image': this.handleAttachImage(cmd.blob, cmd.mime); return;
419
+ case 'resize': this.adapter.resize(cmd.cols, cmd.rows); return;
420
+ case 'cancel': this.adapter.send_keys('\x03'); return;
421
+ case 'shutdown': this.shutdown(); return;
422
+ }
423
+ }
424
+
425
+ snapshot(): string { return this.adapter.snapshot(); }
426
+ getCursorPosition(): { row: number; col: number } { return this.adapter.getCursorPosition(); }
427
+ getScreen(): string { return this.adapter.snapshot(); }
428
+
429
+ /** Scrollback-inclusive screen as line array — used only for modal/button
430
+ * content extraction so a tall prompt's off-screen anchors stay matchable.
431
+ * Falls back to the viewport snapshot if scrollback read is unavailable. */
432
+ private scrollbackLines(): string[] {
433
+ let screen = '';
434
+ try {
435
+ screen = this.adapter.snapshotWithScrollback();
436
+ } catch { /* fall through to viewport */ }
437
+ if (!screen) screen = this.adapter.snapshot();
438
+ return screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
439
+ }
440
+ getSpecPath(): string { return this.opts.specPath; }
441
+
442
+ shutdown(): void {
443
+ for (const t of this.delegateTimers.values()) clearTimeout(t);
444
+ this.delegateTimers.clear();
445
+ if (this.wakeTimer) { clearTimeout(this.wakeTimer); this.wakeTimer = null; }
446
+ if (this.stallTimer) { clearTimeout(this.stallTimer); this.stallTimer = null; }
447
+ if (this.win32SubmitTimer) { clearTimeout(this.win32SubmitTimer); this.win32SubmitTimer = null; }
448
+ if (this.win32WriteTimer) { clearTimeout(this.win32WriteTimer); this.win32WriteTimer = null; }
449
+ if (this.win32ModalConfirmTimer) { clearTimeout(this.win32ModalConfirmTimer); this.win32ModalConfirmTimer = null; }
450
+ this.specWatcher?.close();
451
+ this.adapter.kill();
452
+ }
453
+
454
+ // ── Debug surface (the whole reason for the rewrite) ──────────────────
455
+ //
456
+ // getFsmDebug() answers, for the CURRENT instant: which state am I in,
457
+ // how long have I been here, and for every outgoing transition — does its
458
+ // guard pass right now, and if not, which sub-condition is blocking and
459
+ // how many ms until it would flip. No screenshots required.
460
+
461
+ getFsmDebug(): {
462
+ currentState: string;
463
+ label: string;
464
+ stateAgeMs: number;
465
+ status: string;
466
+ cursor: { row: number; col: number };
467
+ transitions: TransitionEval[];
468
+ } {
469
+ const now = Date.now();
470
+ const cursor = this.adapter.getCursorPosition();
471
+ const screen = this.adapter.snapshot();
472
+ const ev = this.evalFsmNow(screen, cursor, now);
473
+ const state = stateById(this.spec, this.currentStateId);
474
+ return {
475
+ currentState: this.currentStateId,
476
+ label: state?.label ?? this.currentStateId,
477
+ stateAgeMs: now - this.stateEnteredAt,
478
+ status: state ? statusForState(state) : 'idle',
479
+ cursor,
480
+ transitions: ev.transitions,
481
+ };
482
+ }
483
+
484
+ getStateHistory(): ReadonlyArray<HistoryEntry> { return this.stateHistory; }
485
+ getFsmSnapshotHistory(): ReadonlyArray<FsmSnapshotEntry> { return this.fsmSnapshotHistory; }
486
+ /** Debug-only PTY input/output/resize/cursor timeline from the adapter. */
487
+ getEventTimeline(limit?: number): ReadonlyArray<SpecPtyEvent> {
488
+ return this.adapter.getEventTimeline(limit);
489
+ }
490
+ getSections(): Array<{ id: string; text: string }> | null {
491
+ try {
492
+ const screen = this.adapter.snapshot();
493
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
494
+ return resolveSections(this.spec.sections ?? {}, lines).map(s => ({ id: s.id, text: s.text }));
495
+ } catch { return null; }
496
+ }
497
+
498
+ /** v3-compat shims so the cli-adapter's existing debug snapshot keeps
499
+ * working without branching on driver type. */
500
+ getLastBusyAt(): number {
501
+ // Approximate: time we entered a generating-status state.
502
+ const st = stateById(this.spec, this.currentStateId);
503
+ return st && statusForState(st) === 'generating' ? this.stateEnteredAt : 0;
504
+ }
505
+ hasIdleHoldPending(): boolean {
506
+ // FSM has no separate idle-hold timer; min_hold_ms is the analog.
507
+ // Report true while any outgoing transition is hold-blocked.
508
+ return (this.lastFsmEval?.transitions ?? []).some(t => !t.holdSatisfied && t.condResult);
509
+ }
510
+ /**
511
+ * True once the machine has reached its first non-initial idle state (the
512
+ * prompt is genuinely drawn — see maybeMarkReady). The cli-adapter surfaces
513
+ * this on its idle status so CliProviderInstance can re-arm the queue-claim
514
+ * agent:ready on the first genuine ready, independent of the boot-time
515
+ * starting→idle one-shot (which is consumed too early for specs whose
516
+ * initial state already reports idle).
517
+ */
518
+ hasSeenReady(): boolean {
519
+ return this.readySeenOnce;
520
+ }
521
+ getCompletionIdleDebounceState(): { active: boolean; ageMs: number; holdMs: number; forceAfterMs: number } | null {
522
+ // Surface the busy→ready transition's stable countdown, if any, so the
523
+ // existing panel field stays meaningful.
524
+ const out = outgoingTransitions(this.spec, this.currentStateId);
525
+ const toReady = this.lastFsmEval?.transitions.find((t, i) => {
526
+ const st = stateById(this.spec, out[i]?.to ?? '');
527
+ return st && statusForState(st) === 'idle';
528
+ });
529
+ if (!toReady || !toReady.cond) return null;
530
+ const stable = findStable(toReady.cond);
531
+ if (!stable) return null;
532
+ return { active: true, ageMs: 0, holdMs: stable.totalMs, forceAfterMs: 0 };
533
+ }
534
+
535
+ // ────────────────────────────────────────────────────────────────────
536
+ // Loading & adapter wiring
537
+ // ────────────────────────────────────────────────────────────────────
538
+
539
+ private loadSpecOrThrow(): void {
540
+ const res = loadFsmSpec(this.opts.specPath);
541
+ if (!res.ok) throw new Error(`fsm spec invalid: ${res.errors.join('; ')}`);
542
+ this.spec = res.spec;
543
+ }
544
+
545
+ private buildAdapterOpts(): TerminalAdapterOpts {
546
+ // Single-source spawn resolution: route the spec's binary/args/env
547
+ // through the SAME planner the legacy ProviderCliAdapter uses
548
+ // (resolveCliSpawnPlanFromParts). This gives the spec/FSM path
549
+ // findBinary (PATH + npm-global / Node-dir fallback so an off-PATH
550
+ // `codex`/`claude` resolves), `{{workingDir}}` token substitution, shell
551
+ // wrapping for script-shims / non-absolute / non-native binaries, and a
552
+ // sanitized env with TERMINAL_CWD — none of which it had when it passed
553
+ // `this.spec.binary` straight to the PTY.
554
+ const cols = this.opts.cols ?? DEFAULT_SESSION_HOST_COLS;
555
+ const rows = this.opts.rows ?? DEFAULT_SESSION_HOST_ROWS;
556
+ const plan = resolveCliSpawnPlanFromParts({
557
+ command: this.spec.binary,
558
+ baseArgs: this.spec.spawn_args ?? [],
559
+ baseEnv: this.spec.env ?? {},
560
+ workingDir: this.opts.workingDir,
561
+ extraArgs: this.opts.extraCliArgs ?? [],
562
+ extraEnv: this.opts.extraEnv ?? {},
563
+ geometry: { cols, rows },
564
+ });
565
+ return {
566
+ binary: plan.shellCmd,
567
+ args: plan.shellArgs,
568
+ cwd: plan.ptyOptions.cwd,
569
+ // plan.ptyOptions.env is already a complete, sanitized environment —
570
+ // pass it verbatim, do not overlay process.env (see envIsComplete).
571
+ env: plan.ptyOptions.env,
572
+ envIsComplete: true,
573
+ cols,
574
+ rows,
575
+ transportFactory: this.opts.transportFactory,
576
+ };
577
+ }
578
+
579
+ private armSpecWatcher(): void {
580
+ try {
581
+ const dir = path.dirname(this.opts.specPath);
582
+ const base = path.basename(this.opts.specPath);
583
+ this.specWatcher = fs.watch(dir, { persistent: false }, (_event, filename) => {
584
+ if (filename && filename !== base) return;
585
+ const res = loadFsmSpec(this.opts.specPath);
586
+ if (!res.ok) {
587
+ this.emit({ kind: 'spec_error', errors: res.errors });
588
+ return;
589
+ }
590
+ this.spec = res.spec;
591
+ LOG.info('FsmDriver', `[${this.specTag()}] spec hot-reloaded`);
592
+ // Re-evaluate immediately with the new transitions.
593
+ this.reevaluate(true);
594
+ });
595
+ } catch { /* best-effort */ }
596
+ }
597
+
598
+ private emitInitialState(): void {
599
+ this.reevaluate(true);
600
+ }
601
+
602
+ // ────────────────────────────────────────────────────────────────────
603
+ // Core: evaluate the FSM and commit transitions
604
+ // ────────────────────────────────────────────────────────────────────
605
+
606
+ private buildClock(now: number): FsmClock {
607
+ return {
608
+ now,
609
+ stateEnteredAt: this.stateEnteredAt,
610
+ regionLastChangedAt: this.regionLastChangedAt,
611
+ };
612
+ }
613
+
614
+ private evalFsmNow(screen: string, cursor: { row: number; col: number }, now: number) {
615
+ const prev = this.prevScreenLines.length > 0 ? this.prevScreenLines : undefined;
616
+ return evaluateFsm(this.spec, this.currentStateId, screen, cursor, prev, this.buildClock(now));
617
+ }
618
+
619
+ private reevaluate(forceEmit = false): void {
620
+ const now = Date.now();
621
+ const screen = this.adapter.snapshot();
622
+ const cursor = this.adapter.getCursorPosition();
623
+ const currentLines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
624
+
625
+ // Track per-region change timestamps for stable_ms conditions BEFORE
626
+ // we overwrite prevScreenLines.
627
+ this.trackRegionChanges(currentLines, cursor, now);
628
+
629
+ const ev = this.evalFsmNow(screen, cursor, now);
630
+ this.lastFsmEval = ev;
631
+ this.prevScreenLines = currentLines;
632
+
633
+ if (ev.fired) {
634
+ this.commitTransition(ev.fired, now, ev);
635
+ // After a transition, immediately re-derive controls/modal for the
636
+ // new state and emit. Re-run once so a chain like approval→busy
637
+ // that's already satisfied doesn't wait for the next PTY frame.
638
+ this.emitStateChanged(forceEmit);
639
+ this.scheduleWakeForState();
640
+ this.scheduleStallWatchdog();
641
+ // Drain queued sends on the SAME frame the machine reaches "ready".
642
+ // The first delegated message is queued in pendingSends until the
643
+ // FSM first enters a non-initial idle state (the prompt is drawn).
644
+ // That readiness is normally reached BY a transition (e.g.
645
+ // signing_in→idle / starting→idle) — and an idle state has no
646
+ // pending time-condition, so scheduleWakeForState() arms no timer
647
+ // and, agy being quiet at the prompt, no further PTY frame arrives.
648
+ // Without this call the queued first message would strand here
649
+ // forever (the "first input never processed" bug). maybeMarkReady is
650
+ // idempotent (guarded by readySeenOnce) so calling it on both
651
+ // branches is safe.
652
+ this.maybeMarkReady();
653
+ return;
654
+ }
655
+
656
+ // No transition — refresh modal/controls (content inside the same
657
+ // state can still change, e.g. modal title/buttons) and emit if changed.
658
+ this.emitStateChanged(forceEmit);
659
+ // Schedule a wake for the soonest pending time-condition.
660
+ this.scheduleWakeForState();
661
+ this.scheduleStallWatchdog();
662
+ // Drain queued sends once we first reach a "ready" state.
663
+ this.maybeMarkReady();
664
+ }
665
+
666
+ private commitTransition(fired: TransitionEval, now: number, ev: FsmEvaluation): void {
667
+ const from = this.currentStateId;
668
+ // Capture the full pre-transition evaluation BEFORE we mutate state, so
669
+ // the snapshot records why this transition fired from `from`.
670
+ this.pushFsmSnapshot(from, fired, now, ev);
671
+ this.currentStateId = fired.to;
672
+ this.stateEnteredAt = now;
673
+ // Region change timestamps are relative to the previous state's
674
+ // activity; reset so stable_ms in the new state measures from entry.
675
+ this.regionLastChangedAt.clear();
676
+ this.pushHistory(fired.to, stateById(this.spec, fired.to)?.label ?? fired.to, {
677
+ reason: 'transition',
678
+ via: `${from}→${fired.to}`,
679
+ matchedRules: summarizeTransition(fired),
680
+ });
681
+ LOG.info('FsmDriver', `[${this.specTag()}] ${from} → ${fired.to} (${fired.label})`);
682
+ }
683
+
684
+ /** Snapshot the full FSM evaluation that produced a transition into the
685
+ * separate fsmSnapshotHistory ring buffer (max 20). The transitions[]
686
+ * table is captured by reference — it is freshly built per evaluation in
687
+ * evaluateFsm and never mutated after, so no clone is needed. */
688
+ private pushFsmSnapshot(from: string, fired: TransitionEval, now: number, ev: FsmEvaluation): void {
689
+ this.fsmSnapshotHistory.push({
690
+ stateFrom: from,
691
+ stateTo: fired.to,
692
+ at: now,
693
+ firedTo: fired.to,
694
+ firedLabel: fired.label,
695
+ reason: summarizeTransition(fired),
696
+ transitions: ev.transitions,
697
+ });
698
+ if (this.fsmSnapshotHistory.length > 20) this.fsmSnapshotHistory.shift();
699
+ }
700
+
701
+ /** Re-derive the visible modal + controls for the current state and emit a
702
+ * state_changed if anything differs from the last emit. */
703
+ private emitStateChanged(forceEmit: boolean): void {
704
+ const state = stateById(this.spec, this.currentStateId);
705
+ if (!state) return;
706
+ const screen = this.adapter.snapshot();
707
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
708
+ const sections = resolveSections(this.spec.sections ?? {}, lines);
709
+
710
+ // Modal states (approval / picker) extract their buttons + title from a
711
+ // SCROLLBACK-INCLUSIVE buffer: claude-cli renders an approval as a box,
712
+ // and when the prompt body (a big diff / long explanation) is tall the
713
+ // top of the box — including the `─────` separator that anchors the
714
+ // `modal` section — scrolls above the viewport. Matching only the
715
+ // viewport then yields < min_count buttons, deriveModal returns null,
716
+ // and auto-approve never fires (the "long prompts never auto-approve"
717
+ // bug). The viewport stays authoritative for transitions / cursor
718
+ // conditions; only this content-pattern extraction reads scrollback.
719
+ const modalLines = state.modal
720
+ ? this.scrollbackLines()
721
+ : lines;
722
+ const modalSections = state.modal
723
+ ? resolveSections(this.spec.sections ?? {}, modalLines)
724
+ : sections;
725
+ const modalFullScreen = modalLines.join('\n');
726
+
727
+ const modal = this.deriveModal(state, modalSections, modalFullScreen);
728
+ const controls = this.deriveControls(state.id);
729
+ const title = modal?.title ?? this.deriveTitle(state, modalSections, modalFullScreen);
730
+
731
+ const next: CurrentEval = {
732
+ // status is derived from the FSM state itself (statusForState), NOT from
733
+ // whether a modal was parsed this frame. A modal state whose buttons briefly
734
+ // fail to parse (PTY repaint → deriveModal returns null) must still report
735
+ // its authoritative status (e.g. 'approval'), so the adapter never collapses
736
+ // an approval/busy state to idle on a transient modal-parse miss.
737
+ state: { id: state.id, label: state.label, title, status: statusForState(state) },
738
+ modal,
739
+ controls,
740
+ };
741
+
742
+ const changed = forceEmit
743
+ || !this.currentEval
744
+ || this.currentEval.state.id !== next.state.id
745
+ || this.currentEval.state.title !== next.state.title
746
+ || !sameModal(this.currentEval.modal, next.modal)
747
+ || !sameControls(this.currentEval.controls, next.controls);
748
+
749
+ this.currentEval = next;
750
+ if (this.pickerInProgress) this.tryAdvancePicker(screen);
751
+
752
+ if (changed) {
753
+ this.emit({
754
+ kind: 'state_changed',
755
+ state: next.state,
756
+ // kind is the SEMANTIC modal class (approval vs picker/confirm)
757
+ // derived from the FSM state, NOT from the parsed buttons — the
758
+ // status field already collapsed it to 'approval' so the modal is
759
+ // surfaced. The auto-approve worker needs the distinction back to
760
+ // avoid answering a /model picker on the user's behalf.
761
+ modal: next.modal ? { title: next.modal.title, buttons: next.modal.buttons.map(b => ({ index: b.index, label: b.label })), kind: modalKindForState(state) } : null,
762
+ controls: next.controls.map(c => ({ id: c.id, label: c.label, action_type: c.actionType })),
763
+ });
764
+ this.fireNotifications(state.id, title);
765
+ this.armOrCancelDelegateTimers(state.id);
766
+ }
767
+ }
768
+
769
+ private deriveModal(state: FsmState, sections: ResolvedSection[], fullScreen: string): ModalSnapshot | null {
770
+ const rule = state.extract?.buttons;
771
+ if (!rule) return null;
772
+ const hay = sectionText(sections, rule.section, fullScreen);
773
+ const minCount = rule.min_count ?? 2;
774
+ const buttons = extractButtonsFromRule(rule, hay);
775
+ if (buttons.length < minCount) return null;
776
+ const title = this.deriveTitle(state, sections, fullScreen);
777
+ return { title, buttons };
778
+ }
779
+
780
+ private deriveTitle(state: FsmState, sections: ResolvedSection[], fullScreen: string): string | null {
781
+ const rule = state.extract?.title;
782
+ if (!rule) return null;
783
+ return extractTitle(rule, sections, fullScreen);
784
+ }
785
+
786
+ private deriveControls(stateId: string): VisibleControl[] {
787
+ const out: VisibleControl[] = [];
788
+ for (const c of this.spec.control_bar ?? []) {
789
+ if (c.visible_when_state && !c.visible_when_state.includes(stateId)) continue;
790
+ out.push({ id: c.id, label: c.label, actionType: c.action.type });
791
+ }
792
+ return out;
793
+ }
794
+
795
+ /** Track which cursor_above regions changed since the previous frame so
796
+ * stable_ms conditions can measure quiet time. We record every region
797
+ * size referenced by a stable_ms condition in the spec, plus the whole
798
+ * screen (-1). */
799
+ private trackRegionChanges(currentLines: string[], cursor: { row: number; col: number }, now: number): void {
800
+ if (this.prevScreenLines.length === 0) return;
801
+ const sizes = this.stableRegionSizes();
802
+ for (const size of sizes) {
803
+ let cur: string; let prev: string;
804
+ if (size < 0) {
805
+ cur = currentLines.join('\n');
806
+ prev = this.prevScreenLines.join('\n');
807
+ } else {
808
+ const start = Math.max(0, cursor.row - size);
809
+ cur = currentLines.slice(start, cursor.row).join('\n');
810
+ prev = this.prevScreenLines.slice(start, cursor.row).join('\n');
811
+ }
812
+ if (cur !== prev) this.regionLastChangedAt.set(size, now);
813
+ }
814
+ }
815
+
816
+ /** All cursor_above region sizes referenced by stable_ms conditions in the
817
+ * current state's outgoing transitions, plus whole-screen. Cached lazily
818
+ * per spec load would be nicer but the set is tiny. */
819
+ private stableRegionSizes(): Set<number> {
820
+ const sizes = new Set<number>([-1]);
821
+ for (const t of outgoingTransitions(this.spec, this.currentStateId)) {
822
+ collectStableSizes(t.when, sizes);
823
+ }
824
+ return sizes;
825
+ }
826
+
827
+ /** Schedule a re-evaluation for the soonest pending time-condition on any
828
+ * outgoing transition (elapsed_ms / stable_ms / min_hold_ms). Without
829
+ * this, a state whose only exit is time-based would never leave once the
830
+ * PTY goes quiet. */
831
+ private scheduleWakeForState(): void {
832
+ if (this.wakeTimer) { clearTimeout(this.wakeTimer); this.wakeTimer = null; }
833
+ const ev = this.lastFsmEval;
834
+ if (!ev) return;
835
+ let soonest = Infinity;
836
+ for (const t of ev.transitions) {
837
+ if (t.fires) continue;
838
+ if (!t.holdSatisfied) soonest = Math.min(soonest, t.holdRemainingMs);
839
+ const condRemain = t.cond ? t.cond.remainingMs ?? Infinity : Infinity;
840
+ // Only treat the cond countdown as a wake source when the rest of
841
+ // the guard (hold) is already or will be satisfied.
842
+ if (Number.isFinite(condRemain) && condRemain > 0) soonest = Math.min(soonest, condRemain);
843
+ }
844
+ if (!Number.isFinite(soonest)) return;
845
+ this.wakeTimer = setTimeout(() => { this.wakeTimer = null; this.reevaluate(); }, Math.max(soonest + 30, 50));
846
+ }
847
+
848
+ // ── Focus-gated stall watchdog (refocus_when_stalled_ms) ──────────────────
849
+ //
850
+ // A focus-event TUI (antigravity's `agy`) freezes its render loop the moment
851
+ // it thinks it has lost focus mid-turn: the screen stops updating and only
852
+ // repaints on the next keypress, which the daemon never sends. The output
853
+ // pump is wired entirely to PTY onData (no PTY data → no reevaluate, no
854
+ // on_screen_changed), so a normal time-wake that only re-reads the screen
855
+ // can't help — there is nothing new to read. The fix is to re-inject the
856
+ // focus-in wake (`send_on_spawn`) so the CLI flushes the held output itself.
857
+
858
+ /** True when this spec opts into stall recovery (declares a positive
859
+ * refocus window AND a wake sequence to re-inject). */
860
+ private stallRecoveryEnabled(): boolean {
861
+ const ms = this.spec.refocus_when_stalled_ms;
862
+ return typeof ms === 'number' && ms > 0
863
+ && Array.isArray(this.spec.send_on_spawn) && this.spec.send_on_spawn.length > 0;
864
+ }
865
+
866
+ /** Wall-clock time the screen last changed in the current state, falling
867
+ * back to state entry when it has not changed since (i.e. fully stalled
868
+ * from the start of the state). */
869
+ private lastScreenChangeAt(): number {
870
+ return this.regionLastChangedAt.get(-1) ?? this.stateEnteredAt;
871
+ }
872
+
873
+ /** Arm a timer to re-inject the focus-in prime if the screen stays frozen
874
+ * through a `generating` state. Only active for opted-in focus-gated specs;
875
+ * a no-op (and cleared) for every other CLI and every non-generating state.
876
+ * Re-arms itself so it keeps watching while the PTY is quiet. */
877
+ private scheduleStallWatchdog(): void {
878
+ if (this.stallTimer) { clearTimeout(this.stallTimer); this.stallTimer = null; }
879
+ if (!this.stallRecoveryEnabled()) return;
880
+ const st = stateById(this.spec, this.currentStateId);
881
+ if (!st || statusForState(st) !== 'generating') return;
882
+ const windowMs = this.spec.refocus_when_stalled_ms as number;
883
+ // Cooldown reference: a re-prime defers the next one by a full window,
884
+ // even if the screen has not yet repainted, so we don't tight-loop.
885
+ const since = Math.max(this.lastScreenChangeAt(), this.lastRefocusAt);
886
+ const remaining = windowMs - (Date.now() - since);
887
+ this.stallTimer = setTimeout(
888
+ () => { this.stallTimer = null; this.onStallTick(); },
889
+ Math.max(remaining + 30, 50),
890
+ );
891
+ }
892
+
893
+ /** Fire when the stall window elapses: if the screen is still frozen and we
894
+ * are still generating, re-inject the focus-in wake once, then re-arm. */
895
+ private onStallTick(): void {
896
+ if (!this.stallRecoveryEnabled()) return;
897
+ const st = stateById(this.spec, this.currentStateId);
898
+ if (!st || statusForState(st) !== 'generating') return;
899
+ const windowMs = this.spec.refocus_when_stalled_ms as number;
900
+ const now = Date.now();
901
+ const stalledFor = now - this.lastScreenChangeAt();
902
+ const sinceLastRefocus = now - this.lastRefocusAt;
903
+ if (stalledFor >= windowMs && sinceLastRefocus >= windowMs) {
904
+ LOG.info('FsmDriver', `[${this.specTag()}] stall detected (${stalledFor}ms quiet, generating) — re-injecting focus-in`);
905
+ this.sendSpawnPrime();
906
+ this.lastRefocusAt = now;
907
+ }
908
+ // Keep watching: the re-prime may not flush instantly, and a still-quiet
909
+ // screen needs the next window to come around.
910
+ this.scheduleStallWatchdog();
911
+ }
912
+
913
+ private maybeMarkReady(): void {
914
+ if (this.readySeenOnce) return;
915
+ const st = stateById(this.spec, this.currentStateId);
916
+ if (!st) return;
917
+ // "Ready" = a non-initial state whose status is idle (the prompt is up).
918
+ if (!st.initial && statusForState(st) === 'idle') {
919
+ this.readySeenOnce = true;
920
+ const queued = this.pendingSends.splice(0);
921
+ for (const text of queued) setTimeout(() => this.actuallySendMessage(text), 50);
922
+ }
923
+ }
924
+
925
+ // ────────────────────────────────────────────────────────────────────
926
+ // Notifications & delegates
927
+ // ────────────────────────────────────────────────────────────────────
928
+
929
+ private fireNotifications(stateId: string, title: string | null): void {
930
+ for (const n of this.spec.notifications ?? []) {
931
+ if (n.when_state !== stateId) continue;
932
+ const body = (n.body ?? '').replace(/\{state\.title\}/g, title ?? '');
933
+ this.emit({ kind: 'notification', id: n.id, title: n.title, body });
934
+ }
935
+ }
936
+
937
+ private armOrCancelDelegateTimers(currentStateId: string): void {
938
+ for (const d of this.spec.delegate ?? []) {
939
+ const armed = this.delegateTimers.has(d.id);
940
+ const shouldFire = d.when_state === currentStateId;
941
+ if (shouldFire && !armed) {
942
+ const delay = d.after_duration_ms ?? 0;
943
+ const t = setTimeout(() => { this.fireDelegate(d); this.delegateTimers.delete(d.id); }, delay);
944
+ this.delegateTimers.set(d.id, t);
945
+ } else if (!shouldFire && armed) {
946
+ clearTimeout(this.delegateTimers.get(d.id)!);
947
+ this.delegateTimers.delete(d.id);
948
+ }
949
+ }
950
+ }
951
+
952
+ private fireDelegate(d: DelegateTrigger): void {
953
+ const ev = this.currentEval;
954
+ const task = d.task_template
955
+ .replace(/\{node\}/g, os.hostname())
956
+ .replace(/\{state\.label\}/g, ev?.state.label ?? '')
957
+ .replace(/\{state\.title\}/g, ev?.state.title ?? '')
958
+ .replace(/\{duration_ms\}/g, String(d.after_duration_ms ?? 0));
959
+ this.emit({ kind: 'delegate', id: d.id, task });
960
+ }
961
+
962
+ // ────────────────────────────────────────────────────────────────────
963
+ // Dashboard commands (identical semantics to v3)
964
+ // ────────────────────────────────────────────────────────────────────
965
+
966
+ private handleSendMessage(text: string): void {
967
+ if (!this.readySeenOnce) { this.pendingSends.push(text); return; }
968
+ this.actuallySendMessage(text);
969
+ }
970
+
971
+ private actuallySendMessage(text: string): void {
972
+ const sm = this.spec.send_message;
973
+ const perChar = sm.delay_ms_per_char ?? 0;
974
+ const beforeSubmit = resolveSubmitDelayMs(sm.delay_ms_before_submit, text);
975
+
976
+ // win32 ConPTY submit: the text and the submit key (CR) must NOT be
977
+ // combined into one PTY write — Ink-based TUIs (claude-cli) treat a
978
+ // single write that carries text + a trailing CR as a bracketed/multi-line
979
+ // paste and absorb the CR as a literal newline. So we write the text on
980
+ // its own, then resend the submit key on a fixed cadence, VERIFYING after
981
+ // each that the agent actually left the idle composer (status flipped away
982
+ // from 'idle'). This handles the nondeterministic multiline
983
+ // paste-accumulation window where a variable number of CRs is needed; a
984
+ // fixed double-CR fails for multiline (see WIN32_SUBMIT_* above). perChar
985
+ // typing simulation is skipped on win32; correctness of submission wins
986
+ // over the typing visual there.
987
+ if (process.platform === 'win32') {
988
+ this.writeWin32Body(text);
989
+ this.scheduleWin32Submit(sm.submit_key, beforeSubmit, text);
990
+ return;
991
+ }
992
+
993
+ if (perChar === 0) {
994
+ this.adapter.send_keys(text);
995
+ if (beforeSubmit > 0) setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
996
+ else this.adapter.send_keys(sm.submit_key);
997
+ return;
998
+ }
999
+ let i = 0;
1000
+ const iv = setInterval(() => {
1001
+ if (i >= text.length) {
1002
+ clearInterval(iv);
1003
+ setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
1004
+ return;
1005
+ }
1006
+ this.adapter.send_keys(text[i]);
1007
+ i += 1;
1008
+ }, perChar);
1009
+ }
1010
+
1011
+ /** The agent's current coarse status, derived from the FSM node we're in. */
1012
+ private currentStatus(): 'idle' | 'generating' | 'approval' {
1013
+ const st = stateById(this.spec, this.currentStateId);
1014
+ return st ? statusForState(st) : 'idle';
1015
+ }
1016
+
1017
+ /** Record a win32 body write so the settle-gate counts it as input activity
1018
+ * even before the echo arrives. */
1019
+ private markWin32Write(): void {
1020
+ this.lastWin32WriteAt = Date.now();
1021
+ }
1022
+
1023
+ /** Most recent win32 input activity — a write we issued OR a PTY output chunk
1024
+ * (echo). The submit settle-gate waits for this to go quiet. */
1025
+ private lastWin32InputActivityAt(): number {
1026
+ return Math.max(this.lastPtyDataAt, this.lastWin32WriteAt);
1027
+ }
1028
+
1029
+ /**
1030
+ * Write the message body to the PTY for win32, paced into bounded chunks. A
1031
+ * single unbounded ConPTY write can overflow the input pipe and drop leading
1032
+ * bytes; splitting it with a short inter-chunk gap keeps the console input
1033
+ * buffer from overflowing. Small bodies still go out in a single write. Each
1034
+ * write advances lastWin32WriteAt so the submit settle-gate keeps waiting until
1035
+ * the final segment is out and echoed.
1036
+ *
1037
+ * FIX-B-v2: a body that contains an embedded newline cannot be written raw —
1038
+ * on the real win32 Ink/ConPTY composer each '\n' SUBMITS the preceding line as
1039
+ * its own entry, truncating the prompt to only the tail fragment. So a
1040
+ * newline-bearing body is rewritten so its embedded newlines never submit:
1041
+ * - 'paste' (default): wrap the body in a bracketed-paste (ESC[200~ … ESC[201~)
1042
+ * — the composer takes the whole thing, newlines and all, as pasted text.
1043
+ * - 'soft_newline': replace each embedded newline with a non-submitting
1044
+ * Shift+Enter (CSI-u) so the body is typed as one multi-line entry.
1045
+ * The trailing submit CR is NOT written here — it stays separate and is fired
1046
+ * later by scheduleWin32Submit (concern (A)). The bracketed-paste markers are
1047
+ * written as their own atomic segments (never chunked), so chunking can never
1048
+ * split ESC[200~ / ESC[201~ mid-sequence regardless of body length.
1049
+ */
1050
+ private writeWin32Body(text: string): void {
1051
+ if (this.win32WriteTimer) { clearTimeout(this.win32WriteTimer); this.win32WriteTimer = null; }
1052
+
1053
+ const hasNewline = /\r?\n/.test(text);
1054
+ const mode = resolveWin32SubmitMode();
1055
+
1056
+ // Build the ordered list of segments to write. Bracketed-paste markers are
1057
+ // their OWN segments so chunking only ever splits the body, never a marker.
1058
+ let segments: string[];
1059
+ if (!hasNewline) {
1060
+ // Single-line: unchanged behaviour — just (chunk and) write the body.
1061
+ segments = chunkPreservingSurrogates(text, WIN32_PTY_WRITE_CHUNK_CHARS);
1062
+ } else if (mode === 'soft_newline') {
1063
+ // Rewrite embedded newlines as non-submitting soft-newlines, THEN chunk.
1064
+ // The soft-newline sequence (ESC[27;2;13~) contains no '\n', so it is
1065
+ // never re-interpreted as a submit, and chunking it like ordinary text is
1066
+ // safe (a split mid-sequence is avoided below by chunking the whole
1067
+ // rewritten string — see the marker-safety note for paste; for soft_newline
1068
+ // the only ESC seq is short and self-contained, so we keep it simple and
1069
+ // chunk the rewritten body, accepting that the 1024-char chunk boundary is
1070
+ // astronomically unlikely to land inside a 9-byte CSI-u seq — and even if
1071
+ // it did, ConPTY reassembles the byte stream, the composer parses the full
1072
+ // sequence across the boundary).
1073
+ const rewritten = text.split(/\r?\n/).join(WIN32_SOFT_NEWLINE);
1074
+ segments = chunkPreservingSurrogates(rewritten, WIN32_PTY_WRITE_CHUNK_CHARS);
1075
+ } else {
1076
+ // paste: [OPEN marker] [body chunks…] [CLOSE marker]. Markers are atomic
1077
+ // segments — never merged with body bytes — so they cannot be split.
1078
+ segments = [
1079
+ WIN32_BRACKETED_PASTE_OPEN,
1080
+ ...chunkPreservingSurrogates(text, WIN32_PTY_WRITE_CHUNK_CHARS),
1081
+ WIN32_BRACKETED_PASTE_CLOSE,
1082
+ ];
1083
+ }
1084
+
1085
+ if (segments.length <= 1) {
1086
+ this.markWin32Write();
1087
+ this.adapter.send_keys(segments[0] ?? text);
1088
+ return;
1089
+ }
1090
+ let idx = 0;
1091
+ const writeNext = (): void => {
1092
+ this.win32WriteTimer = null;
1093
+ if (idx >= segments.length) return;
1094
+ this.markWin32Write();
1095
+ this.adapter.send_keys(segments[idx]);
1096
+ idx += 1;
1097
+ if (idx < segments.length) {
1098
+ this.win32WriteTimer = setTimeout(writeNext, WIN32_PTY_WRITE_CHUNK_GAP_MS);
1099
+ }
1100
+ };
1101
+ writeNext();
1102
+ }
1103
+
1104
+ /**
1105
+ * win32 submit. Two phases:
1106
+ *
1107
+ * Phase 1 (echo-gate): hold the first CR until the body text is CONFIRMED in the
1108
+ * composer (its whitespace-collapsed tail appears in the rendered screen) AND the
1109
+ * PTY output is then quiet for WIN32_SUBMIT_SETTLE_MS (the full, possibly multi-KB
1110
+ * / multiline body has finished arriving). This replaces a bare output-quiet
1111
+ * settle: an early write that races claude's boot is buffered, not dropped, so the
1112
+ * screen can go quiet with the body NOT YET in the composer — a quiet-only gate
1113
+ * would then fire a CR into an empty composer (no submit). Waiting on the echo
1114
+ * closes that. Honors an initial minimum delay and a generous WIN32_ECHO_MAX_WAIT_MS
1115
+ * last-resort blind fire so a body that truly never confirms still submits (carried
1116
+ * by phase 2) rather than hanging. A settled session echoes immediately → no delay.
1117
+ *
1118
+ * Phase 2 (verified resend — unchanged): send the submit key, wait a gap, and
1119
+ * if the FSM is still 'idle' (the CR was absorbed as a multiline-paste
1120
+ * newline) resend, up to WIN32_SUBMIT_MAX_RESENDS. The first CR always fires
1121
+ * (a stale/edge status never suppresses it); resends are gated on still being
1122
+ * idle and stop the instant the agent leaves idle (submitted → generating /
1123
+ * approval). This preserves the win32 lone-CR-swallow handling.
1124
+ */
1125
+ private scheduleWin32Submit(submitKey: string, initialDelayMs: number, body: string): void {
1126
+ if (this.win32SubmitTimer) { clearTimeout(this.win32SubmitTimer); this.win32SubmitTimer = null; }
1127
+ const startedAt = Date.now();
1128
+
1129
+ // FULL-BODY echo confirmation. A tail-only probe (slice(-N)) was insufficient
1130
+ // for multi-line prompts: a multiline body echoes line-by-line, so its TAIL can
1131
+ // appear in the composer (and the screen settle) while the HEAD / middle is still
1132
+ // arriving. Releasing the first CR on the tail alone then submits a PARTIAL body:
1133
+ // the early CR commits whatever has accumulated and the remainder is lost, so only
1134
+ // the trailing segment survives (the cross-machine MAGI replica receiving only the
1135
+ // prompt's boilerplate suffix). We now require BOTH the head probe AND the tail
1136
+ // probe to be present in the echo before releasing the CR.
1137
+ //
1138
+ // Crucially, the head check runs against snapshotWithScrollback(), NOT the visible
1139
+ // viewport: a tall body scrolls its leading lines off-screen (the very reason the
1140
+ // original gate used the tail), so the head is only ever observable in the
1141
+ // scrollback-inclusive buffer. The tail check stays on the visible snapshot (the
1142
+ // cursor / body end is always on screen). Both present ⇒ the whole body, head
1143
+ // through tail, has echoed — not just its end with a still-streaming middle.
1144
+ // Single-line / short bodies have overlapping head and tail probes and the
1145
+ // scrollback buffer is a superset of the viewport, so behaviour is unchanged. The
1146
+ // WIN32_ECHO_MAX_WAIT_MS blind-fire backstop below still bounds the wait so a body
1147
+ // that never fully confirms cannot hang.
1148
+ const normBody = normalizeForEcho(body);
1149
+ const headProbe = normBody.slice(0, WIN32_ECHO_PROBE_CHARS);
1150
+ const tailProbe = normBody.slice(-WIN32_ECHO_PROBE_CHARS);
1151
+ const bodyEchoed = (): boolean => {
1152
+ if (!normBody) return true;
1153
+ // Tail on the visible viewport (cursor end is always on screen); head on the
1154
+ // scrollback-inclusive buffer (leading lines of a tall body scroll off-screen).
1155
+ const visible = normalizeForEcho(this.adapter.snapshot());
1156
+ if (!visible.includes(tailProbe)) return false;
1157
+ const full = normalizeForEcho(this.adapter.snapshotWithScrollback());
1158
+ return full.includes(headProbe);
1159
+ };
1160
+
1161
+ const fire = (attempt: number): void => {
1162
+ this.win32SubmitTimer = null;
1163
+ this.adapter.send_keys(submitKey);
1164
+ if (attempt + 1 >= WIN32_SUBMIT_MAX_RESENDS) return;
1165
+ this.win32SubmitTimer = setTimeout(() => {
1166
+ // Left the idle composer → it submitted; stop resending.
1167
+ if (this.currentStatus() !== 'idle') { this.win32SubmitTimer = null; return; }
1168
+ fire(attempt + 1);
1169
+ }, WIN32_SUBMIT_RESEND_GAP_MS);
1170
+ };
1171
+
1172
+ // Echo-gate: hold the first CR until the body is CONFIRMED in the composer, not
1173
+ // merely until output goes quiet — a quiet screen with a not-yet-arrived body is
1174
+ // the exact empty-submit failure this replaces. The body is NOT re-written: on
1175
+ // the session-host IPC transport an early write is buffered, not dropped, so it
1176
+ // lands once claude's stdin reader wires up (just late on a slow/contended boot);
1177
+ // re-writing would risk a duplicated body when several buffered writes drain
1178
+ // together. So we simply WAIT for the echo. The hard upper bound only fires a
1179
+ // blind CR if the body never confirms at all (resend net carries it), set
1180
+ // generously so a slow boot still lands its body first.
1181
+ const waitForEcho = (): void => {
1182
+ this.win32SubmitTimer = null;
1183
+ const now = Date.now();
1184
+ const quietFor = now - this.lastWin32InputActivityAt();
1185
+ const waited = now - startedAt;
1186
+ const settled = quietFor >= WIN32_SUBMIT_SETTLE_MS;
1187
+ // Body present in the composer AND output quiet (full body arrived) → submit.
1188
+ if (bodyEchoed() && settled) { fire(0); return; }
1189
+ // Last-resort blind fire so a body that truly never confirms cannot hang.
1190
+ if (waited >= WIN32_ECHO_MAX_WAIT_MS) { fire(0); return; }
1191
+ this.win32SubmitTimer = setTimeout(waitForEcho, WIN32_SUBMIT_SETTLE_POLL_MS);
1192
+ };
1193
+
1194
+ if (initialDelayMs > 0) this.win32SubmitTimer = setTimeout(waitForEcho, initialDelayMs);
1195
+ else waitForEcho();
1196
+ }
1197
+
1198
+ private handleClickControl(controlId: string, payload?: unknown): void {
1199
+ const ctl = (this.spec.control_bar ?? []).find(c => c.id === controlId);
1200
+ if (!ctl) return;
1201
+ if (ctl.visible_when_state && !ctl.visible_when_state.includes(this.currentStateId)) return;
1202
+ const a = ctl.action;
1203
+ switch (a.type) {
1204
+ case 'send_keys': this.adapter.send_keys(a.keys); return;
1205
+ case 'open_picker':
1206
+ // Some TUIs (e.g. codex) don't register a slash command if its
1207
+ // text and the submitting Enter arrive in the same write — the
1208
+ // composer needs a beat to recognise the command before the CR.
1209
+ // Split a trailing CR/LF off the trigger and send it after a
1210
+ // short delay, mirroring send_message's delay_ms_before_submit.
1211
+ {
1212
+ const m = /^([\s\S]*?)([\r\n]+)$/.exec(a.trigger_keys);
1213
+ if (m && m[1]) {
1214
+ this.adapter.send_keys(m[1]);
1215
+ setTimeout(() => this.adapter.send_keys(m[2]), 200);
1216
+ } else {
1217
+ this.adapter.send_keys(a.trigger_keys);
1218
+ }
1219
+ }
1220
+ this.pickerInProgress = { control_id: ctl.id, spec: ctl };
1221
+ return;
1222
+ case 'attach_image': {
1223
+ const p = typeof payload === 'object' && payload && (payload as any).path;
1224
+ if (typeof p === 'string') this.adapter.send_keys(a.keys_template.replace(/\{path\}/g, p));
1225
+ return;
1226
+ }
1227
+ }
1228
+ }
1229
+
1230
+ private handleClickModalButton(index: number): void {
1231
+ const m = this.currentEval?.modal;
1232
+ if (!m) return;
1233
+ const btn = m.buttons.find(b => b.index === index);
1234
+ if (!btn) return;
1235
+
1236
+ const rule = stateById(this.spec, this.currentStateId)?.extract?.buttons;
1237
+ if (rule?.select_mode === 'arrow_keys') {
1238
+ // Cursor-list approval modal (claude-cli new TUI): number keys are
1239
+ // IGNORED — sending `btn.key` ("1\r") types a literal "1" into the
1240
+ // composer and the trailing CR submits it as a chat message. Drive
1241
+ // the cursor from its current row to the target row with arrows,
1242
+ // then confirm. The cursor opens on the first option, so when the
1243
+ // marker isn't detected we step down from row 1 (index - 1).
1244
+ const from = m.buttons.find(b => b.current)?.index ?? 1;
1245
+ const up = rule.cursor_keys?.up ?? '\x1b[A';
1246
+ const down = rule.cursor_keys?.down ?? '\x1b[B';
1247
+ const delta = btn.index - from;
1248
+ const step = delta >= 0 ? down : up;
1249
+ const nav = step.repeat(Math.abs(delta));
1250
+ // Confirm = key_for_index with the (now unused) {index} stripped:
1251
+ // `{index}\r` → `\r`.
1252
+ const confirm = (rule.key_for_index || '\r').replace(/\{index\}/g, '') || '\r';
1253
+ if (nav) this.adapter.send_keys(nav);
1254
+ this.submitModalConfirm(confirm);
1255
+ return;
1256
+ }
1257
+ this.submitModalConfirm(btn.key);
1258
+ }
1259
+
1260
+ /**
1261
+ * Submit a modal-confirm key sequence (the choice key + its trailing CR).
1262
+ *
1263
+ * On win32 the trailing CR is the SAME lone-CR-swallow case as a send_message
1264
+ * submit: ConPTY can absorb a single CR as a literal newline instead of a
1265
+ * confirm, so the approval/picker modal never resolves and the FSM flaps
1266
+ * approval↔busy while auto-approve keeps firing into the void (APPROVESTUCK).
1267
+ * So we split any non-CR prefix (e.g. the "1" of "1\r") off, write it once, and
1268
+ * resend the CR on a fixed cadence until the modal actually resolves (status
1269
+ * leaves 'approval'). Non-win32 keeps the single direct write — its CR submits
1270
+ * on the first try.
1271
+ */
1272
+ private submitModalConfirm(keys: string): void {
1273
+ if (process.platform !== 'win32') {
1274
+ this.adapter.send_keys(keys);
1275
+ return;
1276
+ }
1277
+ const m = /^([\s\S]*?)([\r\n]+)$/.exec(keys);
1278
+ const prefix = m ? m[1] : keys;
1279
+ const cr = m ? m[2] : '';
1280
+ if (prefix) this.adapter.send_keys(prefix);
1281
+ if (!cr) return;
1282
+ this.scheduleWin32ModalConfirm(cr);
1283
+ }
1284
+
1285
+ /**
1286
+ * win32 modal-confirm CR resend loop. Mirrors scheduleWin32Submit's phase-2
1287
+ * verified resend, but gated on still being IN a modal (status 'approval')
1288
+ * rather than still idle: the first CR fires immediately, then resends every
1289
+ * WIN32_SUBMIT_RESEND_GAP_MS while the FSM is still showing the modal, up to
1290
+ * WIN32_SUBMIT_MAX_RESENDS. The instant the modal resolves (status flips to
1291
+ * generating/idle) we stop, so no stray CR leaks into the next turn's composer.
1292
+ */
1293
+ private scheduleWin32ModalConfirm(submitKey: string): void {
1294
+ if (this.win32ModalConfirmTimer) { clearTimeout(this.win32ModalConfirmTimer); this.win32ModalConfirmTimer = null; }
1295
+ const fire = (attempt: number): void => {
1296
+ this.win32ModalConfirmTimer = null;
1297
+ this.adapter.send_keys(submitKey);
1298
+ if (attempt + 1 >= WIN32_SUBMIT_MAX_RESENDS) return;
1299
+ this.win32ModalConfirmTimer = setTimeout(() => {
1300
+ // Left the modal → it resolved; stop resending.
1301
+ if (this.currentStatus() !== 'approval') { this.win32ModalConfirmTimer = null; return; }
1302
+ fire(attempt + 1);
1303
+ }, WIN32_SUBMIT_RESEND_GAP_MS);
1304
+ };
1305
+ fire(0);
1306
+ }
1307
+
1308
+ private handleAttachImage(blob: string, mime: string): void {
1309
+ const ctl = (this.spec.control_bar ?? []).find(c => c.action.type === 'attach_image');
1310
+ if (!ctl || ctl.action.type !== 'attach_image') return;
1311
+ const ext = guessExt(mime);
1312
+ const tmp = path.join(os.tmpdir(), `adhdev-attach-${Date.now()}${ext}`);
1313
+ try { fs.writeFileSync(tmp, Buffer.from(blob, 'base64')); } catch { return; }
1314
+ this.adapter.send_keys(ctl.action.keys_template.replace(/\{path\}/g, tmp));
1315
+ }
1316
+
1317
+ private tryAdvancePicker(screen: string): void {
1318
+ const picker = this.pickerInProgress;
1319
+ if (!picker) return;
1320
+ const action = picker.spec.action;
1321
+ if (action.type !== 'open_picker' || !action.wait_for.regex) return;
1322
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
1323
+ const sections = resolveSections(this.spec.sections ?? {}, lines);
1324
+ const hay = sectionText(sections, action.wait_for.section, lines.join('\n'));
1325
+ const re = new RegExp(action.wait_for.regex, action.wait_for.flags ?? 'i');
1326
+ if (!re.test(hay)) return;
1327
+ this.pickerInProgress = null;
1328
+ }
1329
+
1330
+ private handleExit(exitCode: number): void {
1331
+ this.emit({ kind: 'exit', exit_code: exitCode });
1332
+ this.shutdown();
1333
+ }
1334
+
1335
+ private pushHistory(stateId: string, label: string, meta: { reason: string; via?: string; matchedRules?: string[] }): void {
1336
+ const now = Date.now();
1337
+ const durationMs = this.prevStateAt > 0 ? now - this.prevStateAt : 0;
1338
+ this.prevStateAt = now;
1339
+ this.stateHistory.push({
1340
+ stateId, label, at: now, durationMs,
1341
+ reason: meta.reason,
1342
+ ...(meta.via ? { via: meta.via } : {}),
1343
+ ...(meta.matchedRules ? { matchedRules: meta.matchedRules } : {}),
1344
+ });
1345
+ if (this.stateHistory.length > 50) this.stateHistory.shift();
1346
+ }
1347
+
1348
+ private specTag(): string {
1349
+ return this.opts.specPath.split('/').slice(-3).join('/');
1350
+ }
1351
+
1352
+ private emit(ev: DashboardEvent): void {
1353
+ for (const l of this.listeners) {
1354
+ try { l(ev); } catch { /* listener side */ }
1355
+ }
1356
+ }
1357
+ }
1358
+
1359
+ // ── helpers ──────────────────────────────────────────────────────────────
1360
+
1361
+ function sameModal(a: ModalSnapshot | null, b: ModalSnapshot | null): boolean {
1362
+ if (!a && !b) return true;
1363
+ if (!a || !b) return false;
1364
+ if (a.title !== b.title) return false;
1365
+ if (a.buttons.length !== b.buttons.length) return false;
1366
+ for (let i = 0; i < a.buttons.length; i += 1) {
1367
+ if (a.buttons[i].label !== b.buttons[i].label) return false;
1368
+ }
1369
+ return true;
1370
+ }
1371
+
1372
+ function sameControls(a: VisibleControl[], b: VisibleControl[]): boolean {
1373
+ if (a.length !== b.length) return false;
1374
+ for (let i = 0; i < a.length; i += 1) if (a[i].id !== b[i].id) return false;
1375
+ return true;
1376
+ }
1377
+
1378
+ /** A compact one-line-per-condition summary of why a transition fired. */
1379
+ function summarizeTransition(t: TransitionEval): string[] {
1380
+ const out: string[] = [`${t.label} fired`];
1381
+ if (t.cond) flattenCond(t.cond, out, 1);
1382
+ return out;
1383
+ }
1384
+
1385
+ function flattenCond(c: import('./fsm-evaluator.js').CondResult, out: string[], depth: number): void {
1386
+ const matched = c.matchedText ? ` matched=${JSON.stringify(c.matchedText)}` : '';
1387
+ out.push(`${' '.repeat(depth)}${c.kind} ${c.detail} = ${c.result}${c.remainingMs ? ` (${c.remainingMs}ms left)` : ''}${matched}`);
1388
+ for (const child of c.children ?? []) flattenCond(child, out, depth + 1);
1389
+ }
1390
+
1391
+ function findStable(c: import('./fsm-evaluator.js').CondResult): { totalMs: number } | null {
1392
+ if (c.kind === 'stable') {
1393
+ const m = /\/ (\d+)ms/.exec(c.detail);
1394
+ return { totalMs: m ? Number(m[1]) : 0 };
1395
+ }
1396
+ for (const child of c.children ?? []) {
1397
+ const r = findStable(child);
1398
+ if (r) return r;
1399
+ }
1400
+ return null;
1401
+ }
1402
+
1403
+ function collectStableSizes(when: FsmTransition['when'], sizes: Set<number>): void {
1404
+ if (!when) return;
1405
+ const w = when as any;
1406
+ if ('stable_ms' in w) { sizes.add(w.cursor_above && w.cursor_above > 0 ? w.cursor_above : -1); return; }
1407
+ if ('all' in w) { for (const c of w.all) collectStableSizes(c, sizes); return; }
1408
+ if ('any' in w) { for (const c of w.any) collectStableSizes(c, sizes); return; }
1409
+ if ('not' in w) { collectStableSizes(w.not, sizes); return; }
1410
+ }