@adhdev/daemon-core 0.9.82-rc.32 → 0.9.82-rc.321

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 (306) 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 +46 -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 +115 -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 +38 -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 +110 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +229 -1
  23. package/dist/commands/upgrade-helper.d.ts +12 -0
  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 +72 -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/git-commands.d.ts +9 -1
  30. package/dist/git/git-diff.d.ts +6 -0
  31. package/dist/git/git-executor.d.ts +11 -0
  32. package/dist/git/git-status.d.ts +9 -0
  33. package/dist/git/git-types.d.ts +2 -50
  34. package/dist/index.d.ts +51 -12
  35. package/dist/index.js +35378 -11873
  36. package/dist/index.js.map +1 -1
  37. package/dist/index.mjs +38854 -15461
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/installer.d.ts +1 -4
  40. package/dist/ipc/local-ipc-server.d.ts +91 -0
  41. package/dist/launch.d.ts +1 -1
  42. package/dist/logging/async-batch-writer.d.ts +10 -0
  43. package/dist/logging/log-redactor.d.ts +24 -0
  44. package/dist/logging/log-tail-reader.d.ts +46 -0
  45. package/dist/mesh/contracts.d.ts +164 -0
  46. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  47. package/dist/mesh/coordinator-registry.d.ts +59 -0
  48. package/dist/mesh/mesh-active-work.d.ts +108 -0
  49. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  50. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  51. package/dist/mesh/mesh-events-pending.d.ts +45 -0
  52. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  53. package/dist/mesh/mesh-events-utils.d.ts +47 -0
  54. package/dist/mesh/mesh-events.d.ts +6 -49
  55. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  56. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  57. package/dist/mesh/mesh-init.d.ts +86 -0
  58. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  59. package/dist/mesh/mesh-ledger.d.ts +77 -1
  60. package/dist/mesh/mesh-missions.d.ts +116 -0
  61. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  62. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  63. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  64. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  65. package/dist/mesh/mesh-routing.d.ts +70 -0
  66. package/dist/mesh/mesh-runtime-store.d.ts +401 -0
  67. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  68. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  69. package/dist/mesh/mesh-work-queue.d.ts +204 -5
  70. package/dist/mesh/preview-freshness.d.ts +18 -0
  71. package/dist/mesh/refine-config.d.ts +215 -0
  72. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  73. package/dist/providers/acp-provider-instance.d.ts +2 -0
  74. package/dist/providers/approval-utils.d.ts +13 -0
  75. package/dist/providers/cli-provider-instance.d.ts +61 -3
  76. package/dist/providers/contracts.d.ts +130 -6
  77. package/dist/providers/external-sources.d.ts +71 -0
  78. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  79. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  80. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  81. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  82. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  83. package/dist/providers/native-history/index.d.ts +13 -0
  84. package/dist/providers/provider-instance-manager.d.ts +13 -0
  85. package/dist/providers/provider-instance.d.ts +13 -1
  86. package/dist/providers/provider-loader.d.ts +26 -4
  87. package/dist/providers/provider-trust.d.ts +31 -0
  88. package/dist/providers/read-chat-contract.d.ts +29 -0
  89. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  90. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  91. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  92. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  93. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  94. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  95. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  96. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  97. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  98. package/dist/providers/sdk/v1/index.d.ts +30 -0
  99. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  100. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  101. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  102. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  103. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  104. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  105. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  106. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  107. package/dist/providers/spec/adapter.d.ts +69 -0
  108. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  109. package/dist/providers/spec/evaluator.d.ts +23 -0
  110. package/dist/providers/spec/fsm-driver.d.ts +278 -0
  111. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  112. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  113. package/dist/providers/spec/fsm-types.d.ts +128 -0
  114. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  115. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  116. package/dist/providers/spec/route.d.ts +4 -0
  117. package/dist/providers/spec/types.d.ts +180 -0
  118. package/dist/providers/transcript-v2.d.ts +176 -0
  119. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  120. package/dist/providers/working-dir.d.ts +17 -0
  121. package/dist/repo-mesh-types.d.ts +277 -13
  122. package/dist/sessions/registry.d.ts +6 -0
  123. package/dist/shared-types-extra.d.ts +2 -4
  124. package/dist/shared-types.d.ts +42 -1
  125. package/dist/status/normalize.d.ts +1 -1
  126. package/dist/status/normalize.js +1 -0
  127. package/dist/status/normalize.js.map +1 -1
  128. package/dist/status/normalize.mjs +1 -0
  129. package/dist/status/normalize.mjs.map +1 -1
  130. package/dist/status/reporter.d.ts +2 -0
  131. package/dist/status/snapshot.d.ts +1 -0
  132. package/dist/types.d.ts +5 -0
  133. package/package.json +7 -3
  134. package/src/agent-stream/poller.ts +2 -3
  135. package/src/boot/daemon-lifecycle.ts +55 -12
  136. package/src/boot/process-hardening.ts +89 -0
  137. package/src/build-info.ts +73 -0
  138. package/src/chat/source-machine.ts +534 -0
  139. package/src/chat/source-resolver.ts +0 -0
  140. package/src/chat/subscription-updates.ts +20 -1
  141. package/src/cli-adapter-types.d.ts +1 -0
  142. package/src/cli-adapter-types.ts +47 -2
  143. package/src/cli-adapters/cli-script-runner.ts +421 -0
  144. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  145. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  146. package/src/cli-adapters/provider-cli-adapter.ts +710 -1140
  147. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  148. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  149. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  150. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  151. package/src/cli-adapters/provider-cli-shared.ts +85 -11
  152. package/src/cli-adapters/pty-transport.ts +2 -1
  153. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  154. package/src/cli-adapters/resolve-executable.ts +90 -0
  155. package/src/cli-adapters/session-host-transport.ts +2 -1
  156. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  157. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  158. package/src/cli-adapters/terminal-screen.ts +16 -81
  159. package/src/commands/chat-commands.ts +1822 -61
  160. package/src/commands/cli-manager.ts +286 -14
  161. package/src/commands/handler.ts +809 -2
  162. package/src/commands/mesh-coordinator.ts +332 -122
  163. package/src/commands/router.ts +6369 -704
  164. package/src/commands/stream-commands.ts +8 -0
  165. package/src/commands/upgrade-helper.ts +81 -30
  166. package/src/config/chat-history.ts +483 -24
  167. package/src/config/config.ts +12 -0
  168. package/src/config/mesh-config.ts +320 -4
  169. package/src/config/recent-activity.ts +8 -2
  170. package/src/daemon/dev-auto-implement.ts +3 -2
  171. package/src/daemon/dev-cli-debug.ts +10 -1
  172. package/src/detection/cli-detector.ts +28 -9
  173. package/src/detection/ide-detector.ts +55 -16
  174. package/src/detection/win32-ide-version.ts +106 -0
  175. package/src/git/git-commands.ts +42 -12
  176. package/src/git/git-diff.ts +53 -0
  177. package/src/git/git-executor.ts +12 -0
  178. package/src/git/git-status.ts +408 -43
  179. package/src/git/git-types.ts +14 -62
  180. package/src/git/git-worktree.ts +8 -1
  181. package/src/index.ts +145 -11
  182. package/src/installer.d.ts +1 -1
  183. package/src/installer.ts +8 -6
  184. package/src/ipc/local-ipc-server.ts +278 -0
  185. package/src/launch.d.ts +1 -1
  186. package/src/launch.ts +37 -28
  187. package/src/logging/async-batch-writer.ts +55 -0
  188. package/src/logging/log-redactor.ts +100 -0
  189. package/src/logging/log-tail-reader.ts +220 -0
  190. package/src/logging/logger.ts +2 -1
  191. package/src/mesh/contracts.ts +329 -0
  192. package/src/mesh/coordinator-prompt.ts +234 -31
  193. package/src/mesh/coordinator-registry.ts +121 -0
  194. package/src/mesh/mesh-active-work.ts +469 -0
  195. package/src/mesh/mesh-delivery-policy.ts +315 -0
  196. package/src/mesh/mesh-events-coordinator.ts +2102 -0
  197. package/src/mesh/mesh-events-pending.ts +508 -0
  198. package/src/mesh/mesh-events-stale.ts +290 -0
  199. package/src/mesh/mesh-events-utils.ts +254 -0
  200. package/src/mesh/mesh-events.ts +30 -1035
  201. package/src/mesh/mesh-fast-forward.ts +839 -0
  202. package/src/mesh/mesh-host-ownership.ts +73 -0
  203. package/src/mesh/mesh-init.ts +260 -0
  204. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  205. package/src/mesh/mesh-ledger.ts +589 -102
  206. package/src/mesh/mesh-missions.ts +248 -0
  207. package/src/mesh/mesh-reconcile-loop.ts +496 -0
  208. package/src/mesh/mesh-refine-batch.ts +197 -0
  209. package/src/mesh/mesh-refine-status.ts +231 -0
  210. package/src/mesh/mesh-review-inbox.ts +307 -0
  211. package/src/mesh/mesh-routing.ts +291 -0
  212. package/src/mesh/mesh-runtime-store.ts +1578 -0
  213. package/src/mesh/mesh-task-stats.ts +154 -0
  214. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  215. package/src/mesh/mesh-work-queue.ts +663 -142
  216. package/src/mesh/preview-freshness.ts +118 -0
  217. package/src/mesh/refine-config.ts +403 -0
  218. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  219. package/src/providers/acp-provider-instance.ts +19 -4
  220. package/src/providers/approval-utils.d.ts +4 -0
  221. package/src/providers/approval-utils.ts +47 -5
  222. package/src/providers/chat-message-normalization.ts +4 -11
  223. package/src/providers/cli-provider-instance.ts +958 -91
  224. package/src/providers/contracts.d.ts +55 -0
  225. package/src/providers/contracts.ts +141 -6
  226. package/src/providers/extension-provider-instance.ts +5 -1
  227. package/src/providers/external-sources.ts +218 -0
  228. package/src/providers/ide-provider-instance.ts +25 -6
  229. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  230. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  231. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  232. package/src/providers/native-history/dispatcher.ts +340 -0
  233. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  234. package/src/providers/native-history/index.ts +30 -0
  235. package/src/providers/provider-instance-manager.ts +30 -0
  236. package/src/providers/provider-instance.ts +10 -1
  237. package/src/providers/provider-loader.ts +662 -50
  238. package/src/providers/provider-schema.ts +87 -14
  239. package/src/providers/provider-trust.ts +114 -0
  240. package/src/providers/read-chat-contract.ts +76 -16
  241. package/src/providers/sdk/README.md +49 -0
  242. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  243. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  244. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  245. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  246. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  247. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  248. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  249. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  250. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  251. package/src/providers/sdk/v1/index.ts +152 -0
  252. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  253. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  254. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  255. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  256. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  257. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  258. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  259. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  260. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  261. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  262. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  263. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  264. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  265. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  272. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  273. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  274. package/src/providers/sdk/v1/validators/index.ts +19 -0
  275. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  276. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  277. package/src/providers/spec/adapter.ts +168 -0
  278. package/src/providers/spec/cli-adapter.ts +986 -0
  279. package/src/providers/spec/evaluator.ts +345 -0
  280. package/src/providers/spec/fsm-driver.ts +909 -0
  281. package/src/providers/spec/fsm-evaluator.ts +255 -0
  282. package/src/providers/spec/fsm-loader.ts +112 -0
  283. package/src/providers/spec/fsm-types.ts +222 -0
  284. package/src/providers/spec/native-history-executor.ts +1136 -0
  285. package/src/providers/spec/pre-launch-trust.ts +104 -0
  286. package/src/providers/spec/route.ts +51 -0
  287. package/src/providers/spec/types.ts +226 -0
  288. package/src/providers/transcript-v2.ts +567 -0
  289. package/src/providers/types/interactive-prompt.ts +536 -0
  290. package/src/providers/version-archive.ts +64 -24
  291. package/src/providers/working-dir.ts +23 -0
  292. package/src/repo-mesh-types.ts +356 -13
  293. package/src/sessions/registry.ts +6 -0
  294. package/src/shared-types-extra.ts +2 -4
  295. package/src/shared-types.ts +45 -1
  296. package/src/status/builders.ts +26 -6
  297. package/src/status/normalize.ts +2 -0
  298. package/src/status/reporter.ts +15 -0
  299. package/src/status/snapshot.ts +84 -25
  300. package/src/system/host-memory.ts +29 -12
  301. package/src/types.ts +5 -0
  302. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  303. package/dist/mesh/mesh-sync.d.ts +0 -53
  304. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  305. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  306. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,909 @@
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 } 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, 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 }[] } | 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
+ }
127
+
128
+ export interface SpecDriverOpts {
129
+ specPath: string;
130
+ workingDir: string;
131
+ extraEnv?: Record<string, string>;
132
+ cols?: number;
133
+ rows?: number;
134
+ hotReload?: boolean;
135
+ emitTrace?: boolean;
136
+ transportFactory?: PtyTransportFactory;
137
+ extraCliArgs?: string[];
138
+ }
139
+
140
+ function countNewlines(s: string): number {
141
+ let n = 0;
142
+ for (let i = 0; i < s.length; i += 1) if (s.charCodeAt(i) === 10) n += 1;
143
+ return n;
144
+ }
145
+
146
+ const SUBMIT_DELAY_FLOOR_MS = 200;
147
+
148
+ export function resolveSubmitDelayMs(specBeforeSubmit: number | undefined, text: string): number {
149
+ const lines = countNewlines(text);
150
+ const linesBonus = Math.min(800, lines * 80);
151
+ const spec = typeof specBeforeSubmit === 'number' && specBeforeSubmit > 0 ? specBeforeSubmit : 0;
152
+ return Math.max(spec, SUBMIT_DELAY_FLOOR_MS + linesBonus);
153
+ }
154
+
155
+ export function guessExt(mime: string): string {
156
+ if (/png/i.test(mime)) return '.png';
157
+ if (/jpe?g/i.test(mime)) return '.jpg';
158
+ if (/gif/i.test(mime)) return '.gif';
159
+ if (/webp/i.test(mime)) return '.webp';
160
+ return '.bin';
161
+ }
162
+
163
+ // ─────────────────────────────────────────────────────────────────────────────
164
+
165
+ interface ModalSnapshot {
166
+ title: string | null;
167
+ buttons: { index: number; label: string; key: string }[];
168
+ }
169
+
170
+ interface VisibleControl {
171
+ id: string;
172
+ label: string;
173
+ actionType: 'send_keys' | 'open_picker' | 'attach_image';
174
+ }
175
+
176
+ type HistoryEntry = DriverHistoryEntry;
177
+
178
+ /** Per-state evaluation snapshot (mirrors v3 SpecEvaluation shape for the
179
+ * parts the cli-adapter / panel consume). */
180
+ interface CurrentEval {
181
+ state: { id: string; label: string; title: string | null; status: 'idle' | 'generating' | 'approval' };
182
+ modal: ModalSnapshot | null;
183
+ controls: VisibleControl[];
184
+ }
185
+
186
+ export class FsmDriver implements ISpecDriver {
187
+ private spec!: CliSpecV4;
188
+ private adapter: TerminalAdapter;
189
+ private listeners = new Set<(ev: DashboardEvent) => void>();
190
+
191
+ // ── The entire FSM state: which node we're in, and when we entered it.
192
+ private currentStateId = '';
193
+ private stateEnteredAt = 0;
194
+
195
+ // ── Clock bookkeeping for time conditions.
196
+ private startedAtMs = 0;
197
+ private prevScreenLines: string[] = [];
198
+ /** Per cursor_above region (key: cursor_above, -1 = whole screen) → last
199
+ * time that region's content changed. Drives stable_ms conditions. */
200
+ private regionLastChangedAt = new Map<number, number>();
201
+ /** Timer that re-runs evaluate() when a time-condition would flip true
202
+ * with no PTY frame to trigger it. */
203
+ private wakeTimer: ReturnType<typeof setTimeout> | null = null;
204
+
205
+ private currentEval: CurrentEval | null = null;
206
+ private stateHistory: HistoryEntry[] = [];
207
+ private prevStateAt = 0;
208
+
209
+ // ── send_message queueing until the machine first reaches a non-initial,
210
+ // non-busy ("ready") state — same contract as v3's idleSeenOnce.
211
+ private readySeenOnce = false;
212
+ private pendingSends: string[] = [];
213
+
214
+ private pickerInProgress: { control_id: string; spec: Control } | null = null;
215
+ private delegateTimers = new Map<string, ReturnType<typeof setTimeout>>();
216
+ private specWatcher: fs.FSWatcher | null = null;
217
+ /** Last full FSM evaluation, kept for the debugger. */
218
+ private lastFsmEval: ReturnType<typeof evaluateFsm> | null = null;
219
+ /** Ring buffer (max 20) of the full FSM evaluation captured at each
220
+ * transition — the rich pre-transition table that lastFsmEval only keeps
221
+ * for the single most recent evaluation. Separate from stateHistory. */
222
+ private fsmSnapshotHistory: FsmSnapshotEntry[] = [];
223
+
224
+ constructor(private readonly opts: SpecDriverOpts) {
225
+ this.loadSpecOrThrow();
226
+ this.adapter = new TerminalAdapter(
227
+ this.buildAdapterOpts(),
228
+ {
229
+ init: () => this.emitInitialState(),
230
+ on_pty_data: (chunk) => this.emit({ kind: 'pty_data', chunk }),
231
+ on_screen_changed: () => this.reevaluate(),
232
+ on_exit: ({ exitCode }) => this.handleExit(exitCode),
233
+ },
234
+ );
235
+ if (this.opts.hotReload !== false) this.armSpecWatcher();
236
+ }
237
+
238
+ subscribe(listener: (ev: DashboardEvent) => void): () => void {
239
+ this.listeners.add(listener);
240
+ return () => { this.listeners.delete(listener); };
241
+ }
242
+
243
+ start(): void {
244
+ const now = Date.now();
245
+ this.startedAtMs = now;
246
+ const init = initialState(this.spec);
247
+ this.currentStateId = init.id;
248
+ this.stateEnteredAt = now;
249
+ this.prevStateAt = now;
250
+ // Pre-trust the workspace before spawning so a first-run folder-trust
251
+ // prompt never appears (best-effort; failures fall back to the FSM's
252
+ // trust-modal detection). Only runs for specs that declare it.
253
+ if (this.spec.pre_launch_trust) {
254
+ applyPreLaunchTrust(this.spec.pre_launch_trust, this.opts.workingDir);
255
+ }
256
+ this.adapter.start();
257
+ // Prime focus-gated TUIs (see CliSpecV4.send_on_spawn). Written once,
258
+ // shortly after spawn, so the input stream is awake before the first
259
+ // delegated message — without this, a focus-event CLI like antigravity
260
+ // drops the first programmatic write until a manual keystroke.
261
+ this.scheduleSpawnPrime();
262
+ // The initial state may have a purely time-based exit (elapsed_ms);
263
+ // schedule a wake so we leave it even if the PTY goes quiet.
264
+ this.scheduleWakeForState();
265
+ }
266
+
267
+ private scheduleSpawnPrime(): void {
268
+ const seqs = this.spec.send_on_spawn;
269
+ if (!Array.isArray(seqs) || seqs.length === 0) return;
270
+ const delay = Math.max(0, this.spec.send_on_spawn_delay_ms ?? 250);
271
+ setTimeout(() => {
272
+ for (const seq of seqs) {
273
+ if (typeof seq === 'string' && seq.length > 0) this.adapter.send_keys(seq);
274
+ }
275
+ }, delay);
276
+ }
277
+
278
+ dispatch(cmd: DashboardCommand): void {
279
+ switch (cmd.kind) {
280
+ case 'send_message': this.handleSendMessage(cmd.text); return;
281
+ case 'pty_write': this.adapter.send_keys(cmd.data); return;
282
+ case 'click_control': this.handleClickControl(cmd.control_id, cmd.payload); return;
283
+ case 'click_modal_button': this.handleClickModalButton(cmd.index); return;
284
+ case 'attach_image': this.handleAttachImage(cmd.blob, cmd.mime); return;
285
+ case 'resize': this.adapter.resize(cmd.cols, cmd.rows); return;
286
+ case 'cancel': this.adapter.send_keys('\x03'); return;
287
+ case 'shutdown': this.shutdown(); return;
288
+ }
289
+ }
290
+
291
+ snapshot(): string { return this.adapter.snapshot(); }
292
+ getCursorPosition(): { row: number; col: number } { return this.adapter.getCursorPosition(); }
293
+ getScreen(): string { return this.adapter.snapshot(); }
294
+
295
+ /** Scrollback-inclusive screen as line array — used only for modal/button
296
+ * content extraction so a tall prompt's off-screen anchors stay matchable.
297
+ * Falls back to the viewport snapshot if scrollback read is unavailable. */
298
+ private scrollbackLines(): string[] {
299
+ let screen = '';
300
+ try {
301
+ screen = this.adapter.snapshotWithScrollback();
302
+ } catch { /* fall through to viewport */ }
303
+ if (!screen) screen = this.adapter.snapshot();
304
+ return screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
305
+ }
306
+ getSpecPath(): string { return this.opts.specPath; }
307
+
308
+ shutdown(): void {
309
+ for (const t of this.delegateTimers.values()) clearTimeout(t);
310
+ this.delegateTimers.clear();
311
+ if (this.wakeTimer) { clearTimeout(this.wakeTimer); this.wakeTimer = null; }
312
+ this.specWatcher?.close();
313
+ this.adapter.kill();
314
+ }
315
+
316
+ // ── Debug surface (the whole reason for the rewrite) ──────────────────
317
+ //
318
+ // getFsmDebug() answers, for the CURRENT instant: which state am I in,
319
+ // how long have I been here, and for every outgoing transition — does its
320
+ // guard pass right now, and if not, which sub-condition is blocking and
321
+ // how many ms until it would flip. No screenshots required.
322
+
323
+ getFsmDebug(): {
324
+ currentState: string;
325
+ label: string;
326
+ stateAgeMs: number;
327
+ status: string;
328
+ cursor: { row: number; col: number };
329
+ transitions: TransitionEval[];
330
+ } {
331
+ const now = Date.now();
332
+ const cursor = this.adapter.getCursorPosition();
333
+ const screen = this.adapter.snapshot();
334
+ const ev = this.evalFsmNow(screen, cursor, now);
335
+ const state = stateById(this.spec, this.currentStateId);
336
+ return {
337
+ currentState: this.currentStateId,
338
+ label: state?.label ?? this.currentStateId,
339
+ stateAgeMs: now - this.stateEnteredAt,
340
+ status: state ? statusForState(state) : 'idle',
341
+ cursor,
342
+ transitions: ev.transitions,
343
+ };
344
+ }
345
+
346
+ getStateHistory(): ReadonlyArray<HistoryEntry> { return this.stateHistory; }
347
+ getFsmSnapshotHistory(): ReadonlyArray<FsmSnapshotEntry> { return this.fsmSnapshotHistory; }
348
+ getSections(): Array<{ id: string; text: string }> | null {
349
+ try {
350
+ const screen = this.adapter.snapshot();
351
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
352
+ return resolveSections(this.spec.sections ?? {}, lines).map(s => ({ id: s.id, text: s.text }));
353
+ } catch { return null; }
354
+ }
355
+
356
+ /** v3-compat shims so the cli-adapter's existing debug snapshot keeps
357
+ * working without branching on driver type. */
358
+ getLastBusyAt(): number {
359
+ // Approximate: time we entered a generating-status state.
360
+ const st = stateById(this.spec, this.currentStateId);
361
+ return st && statusForState(st) === 'generating' ? this.stateEnteredAt : 0;
362
+ }
363
+ hasIdleHoldPending(): boolean {
364
+ // FSM has no separate idle-hold timer; min_hold_ms is the analog.
365
+ // Report true while any outgoing transition is hold-blocked.
366
+ return (this.lastFsmEval?.transitions ?? []).some(t => !t.holdSatisfied && t.condResult);
367
+ }
368
+ getCompletionIdleDebounceState(): { active: boolean; ageMs: number; holdMs: number; forceAfterMs: number } | null {
369
+ // Surface the busy→ready transition's stable countdown, if any, so the
370
+ // existing panel field stays meaningful.
371
+ const out = outgoingTransitions(this.spec, this.currentStateId);
372
+ const toReady = this.lastFsmEval?.transitions.find((t, i) => {
373
+ const st = stateById(this.spec, out[i]?.to ?? '');
374
+ return st && statusForState(st) === 'idle';
375
+ });
376
+ if (!toReady || !toReady.cond) return null;
377
+ const stable = findStable(toReady.cond);
378
+ if (!stable) return null;
379
+ return { active: true, ageMs: 0, holdMs: stable.totalMs, forceAfterMs: 0 };
380
+ }
381
+
382
+ // ────────────────────────────────────────────────────────────────────
383
+ // Loading & adapter wiring
384
+ // ────────────────────────────────────────────────────────────────────
385
+
386
+ private loadSpecOrThrow(): void {
387
+ const res = loadFsmSpec(this.opts.specPath);
388
+ if (!res.ok) throw new Error(`fsm spec invalid: ${res.errors.join('; ')}`);
389
+ this.spec = res.spec;
390
+ }
391
+
392
+ private buildAdapterOpts(): TerminalAdapterOpts {
393
+ // Single-source spawn resolution: route the spec's binary/args/env
394
+ // through the SAME planner the legacy ProviderCliAdapter uses
395
+ // (resolveCliSpawnPlanFromParts). This gives the spec/FSM path
396
+ // findBinary (PATH + npm-global / Node-dir fallback so an off-PATH
397
+ // `codex`/`claude` resolves), `{{workingDir}}` token substitution, shell
398
+ // wrapping for script-shims / non-absolute / non-native binaries, and a
399
+ // sanitized env with TERMINAL_CWD — none of which it had when it passed
400
+ // `this.spec.binary` straight to the PTY.
401
+ const cols = this.opts.cols ?? DEFAULT_SESSION_HOST_COLS;
402
+ const rows = this.opts.rows ?? DEFAULT_SESSION_HOST_ROWS;
403
+ const plan = resolveCliSpawnPlanFromParts({
404
+ command: this.spec.binary,
405
+ baseArgs: this.spec.spawn_args ?? [],
406
+ baseEnv: this.spec.env ?? {},
407
+ workingDir: this.opts.workingDir,
408
+ extraArgs: this.opts.extraCliArgs ?? [],
409
+ extraEnv: this.opts.extraEnv ?? {},
410
+ geometry: { cols, rows },
411
+ });
412
+ return {
413
+ binary: plan.shellCmd,
414
+ args: plan.shellArgs,
415
+ cwd: plan.ptyOptions.cwd,
416
+ // plan.ptyOptions.env is already a complete, sanitized environment —
417
+ // pass it verbatim, do not overlay process.env (see envIsComplete).
418
+ env: plan.ptyOptions.env,
419
+ envIsComplete: true,
420
+ cols,
421
+ rows,
422
+ transportFactory: this.opts.transportFactory,
423
+ };
424
+ }
425
+
426
+ private armSpecWatcher(): void {
427
+ try {
428
+ const dir = path.dirname(this.opts.specPath);
429
+ const base = path.basename(this.opts.specPath);
430
+ this.specWatcher = fs.watch(dir, { persistent: false }, (_event, filename) => {
431
+ if (filename && filename !== base) return;
432
+ const res = loadFsmSpec(this.opts.specPath);
433
+ if (!res.ok) {
434
+ this.emit({ kind: 'spec_error', errors: res.errors });
435
+ return;
436
+ }
437
+ this.spec = res.spec;
438
+ LOG.info('FsmDriver', `[${this.specTag()}] spec hot-reloaded`);
439
+ // Re-evaluate immediately with the new transitions.
440
+ this.reevaluate(true);
441
+ });
442
+ } catch { /* best-effort */ }
443
+ }
444
+
445
+ private emitInitialState(): void {
446
+ this.reevaluate(true);
447
+ }
448
+
449
+ // ────────────────────────────────────────────────────────────────────
450
+ // Core: evaluate the FSM and commit transitions
451
+ // ────────────────────────────────────────────────────────────────────
452
+
453
+ private buildClock(now: number): FsmClock {
454
+ return {
455
+ now,
456
+ stateEnteredAt: this.stateEnteredAt,
457
+ regionLastChangedAt: this.regionLastChangedAt,
458
+ };
459
+ }
460
+
461
+ private evalFsmNow(screen: string, cursor: { row: number; col: number }, now: number) {
462
+ const prev = this.prevScreenLines.length > 0 ? this.prevScreenLines : undefined;
463
+ return evaluateFsm(this.spec, this.currentStateId, screen, cursor, prev, this.buildClock(now));
464
+ }
465
+
466
+ private reevaluate(forceEmit = false): void {
467
+ const now = Date.now();
468
+ const screen = this.adapter.snapshot();
469
+ const cursor = this.adapter.getCursorPosition();
470
+ const currentLines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
471
+
472
+ // Track per-region change timestamps for stable_ms conditions BEFORE
473
+ // we overwrite prevScreenLines.
474
+ this.trackRegionChanges(currentLines, cursor, now);
475
+
476
+ const ev = this.evalFsmNow(screen, cursor, now);
477
+ this.lastFsmEval = ev;
478
+ this.prevScreenLines = currentLines;
479
+
480
+ if (ev.fired) {
481
+ this.commitTransition(ev.fired, now, ev);
482
+ // After a transition, immediately re-derive controls/modal for the
483
+ // new state and emit. Re-run once so a chain like approval→busy
484
+ // that's already satisfied doesn't wait for the next PTY frame.
485
+ this.emitStateChanged(forceEmit);
486
+ this.scheduleWakeForState();
487
+ // Drain queued sends on the SAME frame the machine reaches "ready".
488
+ // The first delegated message is queued in pendingSends until the
489
+ // FSM first enters a non-initial idle state (the prompt is drawn).
490
+ // That readiness is normally reached BY a transition (e.g.
491
+ // signing_in→idle / starting→idle) — and an idle state has no
492
+ // pending time-condition, so scheduleWakeForState() arms no timer
493
+ // and, agy being quiet at the prompt, no further PTY frame arrives.
494
+ // Without this call the queued first message would strand here
495
+ // forever (the "first input never processed" bug). maybeMarkReady is
496
+ // idempotent (guarded by readySeenOnce) so calling it on both
497
+ // branches is safe.
498
+ this.maybeMarkReady();
499
+ return;
500
+ }
501
+
502
+ // No transition — refresh modal/controls (content inside the same
503
+ // state can still change, e.g. modal title/buttons) and emit if changed.
504
+ this.emitStateChanged(forceEmit);
505
+ // Schedule a wake for the soonest pending time-condition.
506
+ this.scheduleWakeForState();
507
+ // Drain queued sends once we first reach a "ready" state.
508
+ this.maybeMarkReady();
509
+ }
510
+
511
+ private commitTransition(fired: TransitionEval, now: number, ev: FsmEvaluation): void {
512
+ const from = this.currentStateId;
513
+ // Capture the full pre-transition evaluation BEFORE we mutate state, so
514
+ // the snapshot records why this transition fired from `from`.
515
+ this.pushFsmSnapshot(from, fired, now, ev);
516
+ this.currentStateId = fired.to;
517
+ this.stateEnteredAt = now;
518
+ // Region change timestamps are relative to the previous state's
519
+ // activity; reset so stable_ms in the new state measures from entry.
520
+ this.regionLastChangedAt.clear();
521
+ this.pushHistory(fired.to, stateById(this.spec, fired.to)?.label ?? fired.to, {
522
+ reason: 'transition',
523
+ via: `${from}→${fired.to}`,
524
+ matchedRules: summarizeTransition(fired),
525
+ });
526
+ LOG.info('FsmDriver', `[${this.specTag()}] ${from} → ${fired.to} (${fired.label})`);
527
+ }
528
+
529
+ /** Snapshot the full FSM evaluation that produced a transition into the
530
+ * separate fsmSnapshotHistory ring buffer (max 20). The transitions[]
531
+ * table is captured by reference — it is freshly built per evaluation in
532
+ * evaluateFsm and never mutated after, so no clone is needed. */
533
+ private pushFsmSnapshot(from: string, fired: TransitionEval, now: number, ev: FsmEvaluation): void {
534
+ this.fsmSnapshotHistory.push({
535
+ stateFrom: from,
536
+ stateTo: fired.to,
537
+ at: now,
538
+ firedTo: fired.to,
539
+ firedLabel: fired.label,
540
+ reason: summarizeTransition(fired),
541
+ transitions: ev.transitions,
542
+ });
543
+ if (this.fsmSnapshotHistory.length > 20) this.fsmSnapshotHistory.shift();
544
+ }
545
+
546
+ /** Re-derive the visible modal + controls for the current state and emit a
547
+ * state_changed if anything differs from the last emit. */
548
+ private emitStateChanged(forceEmit: boolean): void {
549
+ const state = stateById(this.spec, this.currentStateId);
550
+ if (!state) return;
551
+ const screen = this.adapter.snapshot();
552
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
553
+ const sections = resolveSections(this.spec.sections ?? {}, lines);
554
+
555
+ // Modal states (approval / picker) extract their buttons + title from a
556
+ // SCROLLBACK-INCLUSIVE buffer: claude-cli renders an approval as a box,
557
+ // and when the prompt body (a big diff / long explanation) is tall the
558
+ // top of the box — including the `─────` separator that anchors the
559
+ // `modal` section — scrolls above the viewport. Matching only the
560
+ // viewport then yields < min_count buttons, deriveModal returns null,
561
+ // and auto-approve never fires (the "long prompts never auto-approve"
562
+ // bug). The viewport stays authoritative for transitions / cursor
563
+ // conditions; only this content-pattern extraction reads scrollback.
564
+ const modalLines = state.modal
565
+ ? this.scrollbackLines()
566
+ : lines;
567
+ const modalSections = state.modal
568
+ ? resolveSections(this.spec.sections ?? {}, modalLines)
569
+ : sections;
570
+ const modalFullScreen = modalLines.join('\n');
571
+
572
+ const modal = this.deriveModal(state, modalSections, modalFullScreen);
573
+ const controls = this.deriveControls(state.id);
574
+ const title = modal?.title ?? this.deriveTitle(state, modalSections, modalFullScreen);
575
+
576
+ const next: CurrentEval = {
577
+ // status is derived from the FSM state itself (statusForState), NOT from
578
+ // whether a modal was parsed this frame. A modal state whose buttons briefly
579
+ // fail to parse (PTY repaint → deriveModal returns null) must still report
580
+ // its authoritative status (e.g. 'approval'), so the adapter never collapses
581
+ // an approval/busy state to idle on a transient modal-parse miss.
582
+ state: { id: state.id, label: state.label, title, status: statusForState(state) },
583
+ modal,
584
+ controls,
585
+ };
586
+
587
+ const changed = forceEmit
588
+ || !this.currentEval
589
+ || this.currentEval.state.id !== next.state.id
590
+ || this.currentEval.state.title !== next.state.title
591
+ || !sameModal(this.currentEval.modal, next.modal)
592
+ || !sameControls(this.currentEval.controls, next.controls);
593
+
594
+ this.currentEval = next;
595
+ if (this.pickerInProgress) this.tryAdvancePicker(screen);
596
+
597
+ if (changed) {
598
+ this.emit({
599
+ kind: 'state_changed',
600
+ state: next.state,
601
+ modal: next.modal ? { title: next.modal.title, buttons: next.modal.buttons.map(b => ({ index: b.index, label: b.label })) } : null,
602
+ controls: next.controls.map(c => ({ id: c.id, label: c.label, action_type: c.actionType })),
603
+ });
604
+ this.fireNotifications(state.id, title);
605
+ this.armOrCancelDelegateTimers(state.id);
606
+ }
607
+ }
608
+
609
+ private deriveModal(state: FsmState, sections: ResolvedSection[], fullScreen: string): ModalSnapshot | null {
610
+ const rule = state.extract?.buttons;
611
+ if (!rule) return null;
612
+ const hay = sectionText(sections, rule.section, fullScreen);
613
+ const minCount = rule.min_count ?? 2;
614
+ const buttons = extractButtonsFromRule(rule, hay);
615
+ if (buttons.length < minCount) return null;
616
+ const title = this.deriveTitle(state, sections, fullScreen);
617
+ return { title, buttons };
618
+ }
619
+
620
+ private deriveTitle(state: FsmState, sections: ResolvedSection[], fullScreen: string): string | null {
621
+ const rule = state.extract?.title;
622
+ if (!rule) return null;
623
+ return extractTitle(rule, sections, fullScreen);
624
+ }
625
+
626
+ private deriveControls(stateId: string): VisibleControl[] {
627
+ const out: VisibleControl[] = [];
628
+ for (const c of this.spec.control_bar ?? []) {
629
+ if (c.visible_when_state && !c.visible_when_state.includes(stateId)) continue;
630
+ out.push({ id: c.id, label: c.label, actionType: c.action.type });
631
+ }
632
+ return out;
633
+ }
634
+
635
+ /** Track which cursor_above regions changed since the previous frame so
636
+ * stable_ms conditions can measure quiet time. We record every region
637
+ * size referenced by a stable_ms condition in the spec, plus the whole
638
+ * screen (-1). */
639
+ private trackRegionChanges(currentLines: string[], cursor: { row: number; col: number }, now: number): void {
640
+ if (this.prevScreenLines.length === 0) return;
641
+ const sizes = this.stableRegionSizes();
642
+ for (const size of sizes) {
643
+ let cur: string; let prev: string;
644
+ if (size < 0) {
645
+ cur = currentLines.join('\n');
646
+ prev = this.prevScreenLines.join('\n');
647
+ } else {
648
+ const start = Math.max(0, cursor.row - size);
649
+ cur = currentLines.slice(start, cursor.row).join('\n');
650
+ prev = this.prevScreenLines.slice(start, cursor.row).join('\n');
651
+ }
652
+ if (cur !== prev) this.regionLastChangedAt.set(size, now);
653
+ }
654
+ }
655
+
656
+ /** All cursor_above region sizes referenced by stable_ms conditions in the
657
+ * current state's outgoing transitions, plus whole-screen. Cached lazily
658
+ * per spec load would be nicer but the set is tiny. */
659
+ private stableRegionSizes(): Set<number> {
660
+ const sizes = new Set<number>([-1]);
661
+ for (const t of outgoingTransitions(this.spec, this.currentStateId)) {
662
+ collectStableSizes(t.when, sizes);
663
+ }
664
+ return sizes;
665
+ }
666
+
667
+ /** Schedule a re-evaluation for the soonest pending time-condition on any
668
+ * outgoing transition (elapsed_ms / stable_ms / min_hold_ms). Without
669
+ * this, a state whose only exit is time-based would never leave once the
670
+ * PTY goes quiet. */
671
+ private scheduleWakeForState(): void {
672
+ if (this.wakeTimer) { clearTimeout(this.wakeTimer); this.wakeTimer = null; }
673
+ const ev = this.lastFsmEval;
674
+ if (!ev) return;
675
+ let soonest = Infinity;
676
+ for (const t of ev.transitions) {
677
+ if (t.fires) continue;
678
+ if (!t.holdSatisfied) soonest = Math.min(soonest, t.holdRemainingMs);
679
+ const condRemain = t.cond ? t.cond.remainingMs ?? Infinity : Infinity;
680
+ // Only treat the cond countdown as a wake source when the rest of
681
+ // the guard (hold) is already or will be satisfied.
682
+ if (Number.isFinite(condRemain) && condRemain > 0) soonest = Math.min(soonest, condRemain);
683
+ }
684
+ if (!Number.isFinite(soonest)) return;
685
+ this.wakeTimer = setTimeout(() => { this.wakeTimer = null; this.reevaluate(); }, Math.max(soonest + 30, 50));
686
+ }
687
+
688
+ private maybeMarkReady(): void {
689
+ if (this.readySeenOnce) return;
690
+ const st = stateById(this.spec, this.currentStateId);
691
+ if (!st) return;
692
+ // "Ready" = a non-initial state whose status is idle (the prompt is up).
693
+ if (!st.initial && statusForState(st) === 'idle') {
694
+ this.readySeenOnce = true;
695
+ const queued = this.pendingSends.splice(0);
696
+ for (const text of queued) setTimeout(() => this.actuallySendMessage(text), 50);
697
+ }
698
+ }
699
+
700
+ // ────────────────────────────────────────────────────────────────────
701
+ // Notifications & delegates
702
+ // ────────────────────────────────────────────────────────────────────
703
+
704
+ private fireNotifications(stateId: string, title: string | null): void {
705
+ for (const n of this.spec.notifications ?? []) {
706
+ if (n.when_state !== stateId) continue;
707
+ const body = (n.body ?? '').replace(/\{state\.title\}/g, title ?? '');
708
+ this.emit({ kind: 'notification', id: n.id, title: n.title, body });
709
+ }
710
+ }
711
+
712
+ private armOrCancelDelegateTimers(currentStateId: string): void {
713
+ for (const d of this.spec.delegate ?? []) {
714
+ const armed = this.delegateTimers.has(d.id);
715
+ const shouldFire = d.when_state === currentStateId;
716
+ if (shouldFire && !armed) {
717
+ const delay = d.after_duration_ms ?? 0;
718
+ const t = setTimeout(() => { this.fireDelegate(d); this.delegateTimers.delete(d.id); }, delay);
719
+ this.delegateTimers.set(d.id, t);
720
+ } else if (!shouldFire && armed) {
721
+ clearTimeout(this.delegateTimers.get(d.id)!);
722
+ this.delegateTimers.delete(d.id);
723
+ }
724
+ }
725
+ }
726
+
727
+ private fireDelegate(d: DelegateTrigger): void {
728
+ const ev = this.currentEval;
729
+ const task = d.task_template
730
+ .replace(/\{node\}/g, os.hostname())
731
+ .replace(/\{state\.label\}/g, ev?.state.label ?? '')
732
+ .replace(/\{state\.title\}/g, ev?.state.title ?? '')
733
+ .replace(/\{duration_ms\}/g, String(d.after_duration_ms ?? 0));
734
+ this.emit({ kind: 'delegate', id: d.id, task });
735
+ }
736
+
737
+ // ────────────────────────────────────────────────────────────────────
738
+ // Dashboard commands (identical semantics to v3)
739
+ // ────────────────────────────────────────────────────────────────────
740
+
741
+ private handleSendMessage(text: string): void {
742
+ if (!this.readySeenOnce) { this.pendingSends.push(text); return; }
743
+ this.actuallySendMessage(text);
744
+ }
745
+
746
+ private actuallySendMessage(text: string): void {
747
+ const sm = this.spec.send_message;
748
+ const perChar = sm.delay_ms_per_char ?? 0;
749
+ const beforeSubmit = resolveSubmitDelayMs(sm.delay_ms_before_submit, text);
750
+ if (perChar === 0) {
751
+ this.adapter.send_keys(text);
752
+ if (beforeSubmit > 0) setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
753
+ else this.adapter.send_keys(sm.submit_key);
754
+ return;
755
+ }
756
+ let i = 0;
757
+ const iv = setInterval(() => {
758
+ if (i >= text.length) {
759
+ clearInterval(iv);
760
+ setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
761
+ return;
762
+ }
763
+ this.adapter.send_keys(text[i]);
764
+ i += 1;
765
+ }, perChar);
766
+ }
767
+
768
+ private handleClickControl(controlId: string, payload?: unknown): void {
769
+ const ctl = (this.spec.control_bar ?? []).find(c => c.id === controlId);
770
+ if (!ctl) return;
771
+ if (ctl.visible_when_state && !ctl.visible_when_state.includes(this.currentStateId)) return;
772
+ const a = ctl.action;
773
+ switch (a.type) {
774
+ case 'send_keys': this.adapter.send_keys(a.keys); return;
775
+ case 'open_picker':
776
+ // Some TUIs (e.g. codex) don't register a slash command if its
777
+ // text and the submitting Enter arrive in the same write — the
778
+ // composer needs a beat to recognise the command before the CR.
779
+ // Split a trailing CR/LF off the trigger and send it after a
780
+ // short delay, mirroring send_message's delay_ms_before_submit.
781
+ {
782
+ const m = /^([\s\S]*?)([\r\n]+)$/.exec(a.trigger_keys);
783
+ if (m && m[1]) {
784
+ this.adapter.send_keys(m[1]);
785
+ setTimeout(() => this.adapter.send_keys(m[2]), 200);
786
+ } else {
787
+ this.adapter.send_keys(a.trigger_keys);
788
+ }
789
+ }
790
+ this.pickerInProgress = { control_id: ctl.id, spec: ctl };
791
+ return;
792
+ case 'attach_image': {
793
+ const p = typeof payload === 'object' && payload && (payload as any).path;
794
+ if (typeof p === 'string') this.adapter.send_keys(a.keys_template.replace(/\{path\}/g, p));
795
+ return;
796
+ }
797
+ }
798
+ }
799
+
800
+ private handleClickModalButton(index: number): void {
801
+ const m = this.currentEval?.modal;
802
+ if (!m) return;
803
+ const btn = m.buttons.find(b => b.index === index);
804
+ if (!btn) return;
805
+ this.adapter.send_keys(btn.key);
806
+ }
807
+
808
+ private handleAttachImage(blob: string, mime: string): void {
809
+ const ctl = (this.spec.control_bar ?? []).find(c => c.action.type === 'attach_image');
810
+ if (!ctl || ctl.action.type !== 'attach_image') return;
811
+ const ext = guessExt(mime);
812
+ const tmp = path.join(os.tmpdir(), `adhdev-attach-${Date.now()}${ext}`);
813
+ try { fs.writeFileSync(tmp, Buffer.from(blob, 'base64')); } catch { return; }
814
+ this.adapter.send_keys(ctl.action.keys_template.replace(/\{path\}/g, tmp));
815
+ }
816
+
817
+ private tryAdvancePicker(screen: string): void {
818
+ const picker = this.pickerInProgress;
819
+ if (!picker) return;
820
+ const action = picker.spec.action;
821
+ if (action.type !== 'open_picker' || !action.wait_for.regex) return;
822
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
823
+ const sections = resolveSections(this.spec.sections ?? {}, lines);
824
+ const hay = sectionText(sections, action.wait_for.section, lines.join('\n'));
825
+ const re = new RegExp(action.wait_for.regex, action.wait_for.flags ?? 'i');
826
+ if (!re.test(hay)) return;
827
+ this.pickerInProgress = null;
828
+ }
829
+
830
+ private handleExit(exitCode: number): void {
831
+ this.emit({ kind: 'exit', exit_code: exitCode });
832
+ this.shutdown();
833
+ }
834
+
835
+ private pushHistory(stateId: string, label: string, meta: { reason: string; via?: string; matchedRules?: string[] }): void {
836
+ const now = Date.now();
837
+ const durationMs = this.prevStateAt > 0 ? now - this.prevStateAt : 0;
838
+ this.prevStateAt = now;
839
+ this.stateHistory.push({
840
+ stateId, label, at: now, durationMs,
841
+ reason: meta.reason,
842
+ ...(meta.via ? { via: meta.via } : {}),
843
+ ...(meta.matchedRules ? { matchedRules: meta.matchedRules } : {}),
844
+ });
845
+ if (this.stateHistory.length > 50) this.stateHistory.shift();
846
+ }
847
+
848
+ private specTag(): string {
849
+ return this.opts.specPath.split('/').slice(-3).join('/');
850
+ }
851
+
852
+ private emit(ev: DashboardEvent): void {
853
+ for (const l of this.listeners) {
854
+ try { l(ev); } catch { /* listener side */ }
855
+ }
856
+ }
857
+ }
858
+
859
+ // ── helpers ──────────────────────────────────────────────────────────────
860
+
861
+ function sameModal(a: ModalSnapshot | null, b: ModalSnapshot | null): boolean {
862
+ if (!a && !b) return true;
863
+ if (!a || !b) return false;
864
+ if (a.title !== b.title) return false;
865
+ if (a.buttons.length !== b.buttons.length) return false;
866
+ for (let i = 0; i < a.buttons.length; i += 1) {
867
+ if (a.buttons[i].label !== b.buttons[i].label) return false;
868
+ }
869
+ return true;
870
+ }
871
+
872
+ function sameControls(a: VisibleControl[], b: VisibleControl[]): boolean {
873
+ if (a.length !== b.length) return false;
874
+ for (let i = 0; i < a.length; i += 1) if (a[i].id !== b[i].id) return false;
875
+ return true;
876
+ }
877
+
878
+ /** A compact one-line-per-condition summary of why a transition fired. */
879
+ function summarizeTransition(t: TransitionEval): string[] {
880
+ const out: string[] = [`${t.label} fired`];
881
+ if (t.cond) flattenCond(t.cond, out, 1);
882
+ return out;
883
+ }
884
+
885
+ function flattenCond(c: import('./fsm-evaluator.js').CondResult, out: string[], depth: number): void {
886
+ out.push(`${' '.repeat(depth)}${c.kind} ${c.detail} = ${c.result}${c.remainingMs ? ` (${c.remainingMs}ms left)` : ''}`);
887
+ for (const child of c.children ?? []) flattenCond(child, out, depth + 1);
888
+ }
889
+
890
+ function findStable(c: import('./fsm-evaluator.js').CondResult): { totalMs: number } | null {
891
+ if (c.kind === 'stable') {
892
+ const m = /\/ (\d+)ms/.exec(c.detail);
893
+ return { totalMs: m ? Number(m[1]) : 0 };
894
+ }
895
+ for (const child of c.children ?? []) {
896
+ const r = findStable(child);
897
+ if (r) return r;
898
+ }
899
+ return null;
900
+ }
901
+
902
+ function collectStableSizes(when: FsmTransition['when'], sizes: Set<number>): void {
903
+ if (!when) return;
904
+ const w = when as any;
905
+ if ('stable_ms' in w) { sizes.add(w.cursor_above && w.cursor_above > 0 ? w.cursor_above : -1); return; }
906
+ if ('all' in w) { for (const c of w.all) collectStableSizes(c, sizes); return; }
907
+ if ('any' in w) { for (const c of w.any) collectStableSizes(c, sizes); return; }
908
+ if ('not' in w) { collectStableSizes(w.not, sizes); return; }
909
+ }