@adhdev/daemon-core 0.9.82-rc.36 → 0.9.82-rc.360

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