@adhdev/daemon-core 0.9.82-rc.45 → 0.9.82-rc.451

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