@adhdev/daemon-core 0.9.82-rc.31 → 0.9.82-rc.311

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