@adhdev/daemon-core 0.9.82-rc.39 → 0.9.82-rc.390

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