@adhdev/daemon-core 0.9.82-rc.21 → 0.9.82-rc.211

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 (269) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +1 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/chat/source-machine.d.ts +166 -0
  4. package/dist/chat/source-resolver.d.ts +104 -0
  5. package/dist/chat/subscription-updates.d.ts +1 -0
  6. package/dist/cli-adapter-types.d.ts +23 -2
  7. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  8. package/dist/cli-adapters/cli-state-engine.d.ts +178 -0
  9. package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
  10. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  11. package/dist/cli-adapters/provider-cli-shared.d.ts +29 -0
  12. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  13. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +3 -3
  14. package/dist/cli-adapters/terminal-backends/types.d.ts +1 -2
  15. package/dist/cli-adapters/terminal-screen.d.ts +2 -11
  16. package/dist/commands/cli-manager.d.ts +2 -1
  17. package/dist/commands/handler.d.ts +110 -0
  18. package/dist/commands/mesh-coordinator.d.ts +85 -1
  19. package/dist/commands/router.d.ts +32 -1
  20. package/dist/config/chat-history.d.ts +9 -0
  21. package/dist/config/config.d.ts +5 -0
  22. package/dist/config/mesh-config.d.ts +72 -1
  23. package/dist/git/git-commands.d.ts +9 -1
  24. package/dist/git/git-diff.d.ts +6 -0
  25. package/dist/git/git-types.d.ts +2 -0
  26. package/dist/index.d.ts +46 -11
  27. package/dist/index.js +35173 -15756
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +34880 -15556
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/installer.d.ts +1 -4
  32. package/dist/ipc/local-ipc-server.d.ts +91 -0
  33. package/dist/launch.d.ts +1 -1
  34. package/dist/logging/async-batch-writer.d.ts +10 -0
  35. package/dist/mesh/contracts.d.ts +164 -0
  36. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  37. package/dist/mesh/coordinator-registry.d.ts +59 -0
  38. package/dist/mesh/mesh-active-work.d.ts +90 -0
  39. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  40. package/dist/mesh/mesh-events-coordinator.d.ts +151 -0
  41. package/dist/mesh/mesh-events-pending.d.ts +33 -0
  42. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  43. package/dist/mesh/mesh-events-utils.d.ts +14 -0
  44. package/dist/mesh/mesh-events.d.ts +5 -40
  45. package/dist/mesh/mesh-fast-forward.d.ts +41 -0
  46. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  47. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  48. package/dist/mesh/mesh-ledger.d.ts +77 -1
  49. package/dist/mesh/mesh-missions.d.ts +58 -0
  50. package/dist/mesh/mesh-refine-status.d.ts +26 -0
  51. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  52. package/dist/mesh/mesh-runtime-store.d.ts +324 -0
  53. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  54. package/dist/mesh/mesh-work-queue.d.ts +137 -6
  55. package/dist/mesh/preview-freshness.d.ts +18 -0
  56. package/dist/mesh/refine-config.d.ts +215 -0
  57. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  58. package/dist/providers/acp-provider-instance.d.ts +2 -0
  59. package/dist/providers/approval-utils.d.ts +13 -0
  60. package/dist/providers/cli-provider-instance.d.ts +39 -3
  61. package/dist/providers/contracts.d.ts +130 -6
  62. package/dist/providers/external-sources.d.ts +71 -0
  63. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  64. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  65. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  66. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  67. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  68. package/dist/providers/native-history/index.d.ts +13 -0
  69. package/dist/providers/provider-instance-manager.d.ts +12 -0
  70. package/dist/providers/provider-instance.d.ts +13 -1
  71. package/dist/providers/provider-loader.d.ts +26 -4
  72. package/dist/providers/provider-trust.d.ts +31 -0
  73. package/dist/providers/read-chat-contract.d.ts +29 -0
  74. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  75. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  76. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  77. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  78. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  79. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  80. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  81. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  82. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  83. package/dist/providers/sdk/v1/index.d.ts +30 -0
  84. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  85. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  86. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  87. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  88. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  89. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  90. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  91. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  92. package/dist/providers/spec/adapter.d.ts +52 -0
  93. package/dist/providers/spec/cli-adapter.d.ts +101 -0
  94. package/dist/providers/spec/driver.d.ts +225 -0
  95. package/dist/providers/spec/evaluator.d.ts +54 -0
  96. package/dist/providers/spec/loader.d.ts +15 -0
  97. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  98. package/dist/providers/spec/route.d.ts +4 -0
  99. package/dist/providers/spec/schema.gen.d.ts +2025 -0
  100. package/dist/providers/spec/types.d.ts +302 -0
  101. package/dist/providers/transcript-v2.d.ts +176 -0
  102. package/dist/providers/types/interactive-prompt.d.ts +48 -0
  103. package/dist/repo-mesh-types.d.ts +109 -1
  104. package/dist/sessions/registry.d.ts +3 -0
  105. package/dist/shared-types-extra.d.ts +2 -4
  106. package/dist/shared-types.d.ts +42 -1
  107. package/dist/status/normalize.d.ts +1 -1
  108. package/dist/status/normalize.js +1 -0
  109. package/dist/status/normalize.js.map +1 -1
  110. package/dist/status/normalize.mjs +1 -0
  111. package/dist/status/normalize.mjs.map +1 -1
  112. package/dist/status/reporter.d.ts +2 -0
  113. package/dist/status/snapshot.d.ts +1 -0
  114. package/dist/types.d.ts +5 -0
  115. package/package.json +6 -3
  116. package/src/agent-stream/poller.ts +2 -3
  117. package/src/boot/daemon-lifecycle.ts +22 -10
  118. package/src/boot/process-hardening.ts +89 -0
  119. package/src/chat/source-machine.ts +534 -0
  120. package/src/chat/source-resolver.ts +0 -0
  121. package/src/chat/subscription-updates.ts +20 -1
  122. package/src/cli-adapter-types.d.ts +1 -0
  123. package/src/cli-adapter-types.ts +22 -2
  124. package/src/cli-adapters/cli-script-runner.ts +421 -0
  125. package/src/cli-adapters/cli-state-engine.ts +1138 -0
  126. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  127. package/src/cli-adapters/provider-cli-adapter.ts +673 -1139
  128. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  129. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  130. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  131. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  132. package/src/cli-adapters/provider-cli-shared.ts +59 -11
  133. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  134. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +35 -29
  135. package/src/cli-adapters/terminal-backends/types.ts +1 -3
  136. package/src/cli-adapters/terminal-screen.ts +11 -81
  137. package/src/commands/chat-commands.ts +1787 -60
  138. package/src/commands/cli-manager.ts +283 -14
  139. package/src/commands/handler.ts +809 -2
  140. package/src/commands/mesh-coordinator.ts +332 -122
  141. package/src/commands/router.ts +4198 -557
  142. package/src/config/chat-history.ts +95 -24
  143. package/src/config/config.ts +12 -0
  144. package/src/config/mesh-config.ts +280 -2
  145. package/src/config/recent-activity.ts +8 -2
  146. package/src/daemon/dev-auto-implement.ts +3 -2
  147. package/src/daemon/dev-cli-debug.ts +10 -1
  148. package/src/detection/ide-detector.ts +26 -16
  149. package/src/git/git-commands.ts +42 -12
  150. package/src/git/git-diff.ts +53 -0
  151. package/src/git/git-status.ts +35 -6
  152. package/src/git/git-types.ts +2 -0
  153. package/src/git/git-worktree.ts +8 -1
  154. package/src/index.ts +126 -10
  155. package/src/installer.d.ts +1 -1
  156. package/src/installer.ts +8 -6
  157. package/src/ipc/local-ipc-server.ts +278 -0
  158. package/src/launch.d.ts +1 -1
  159. package/src/launch.ts +37 -28
  160. package/src/logging/async-batch-writer.ts +55 -0
  161. package/src/logging/logger.ts +2 -1
  162. package/src/mesh/contracts.ts +329 -0
  163. package/src/mesh/coordinator-prompt.ts +218 -31
  164. package/src/mesh/coordinator-registry.ts +121 -0
  165. package/src/mesh/mesh-active-work.ts +437 -0
  166. package/src/mesh/mesh-delivery-policy.ts +315 -0
  167. package/src/mesh/mesh-events-coordinator.ts +1404 -0
  168. package/src/mesh/mesh-events-pending.ts +371 -0
  169. package/src/mesh/mesh-events-stale.ts +283 -0
  170. package/src/mesh/mesh-events-utils.ts +161 -0
  171. package/src/mesh/mesh-events.ts +24 -908
  172. package/src/mesh/mesh-fast-forward.ts +438 -0
  173. package/src/mesh/mesh-host-ownership.ts +73 -0
  174. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  175. package/src/mesh/mesh-ledger.ts +587 -102
  176. package/src/mesh/mesh-missions.ts +151 -0
  177. package/src/mesh/mesh-refine-status.ts +144 -0
  178. package/src/mesh/mesh-review-inbox.ts +307 -0
  179. package/src/mesh/mesh-runtime-store.ts +1305 -0
  180. package/src/mesh/mesh-task-stats.ts +154 -0
  181. package/src/mesh/mesh-work-queue.ts +490 -166
  182. package/src/mesh/preview-freshness.ts +118 -0
  183. package/src/mesh/refine-config.ts +403 -0
  184. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  185. package/src/providers/acp-provider-instance.ts +15 -1
  186. package/src/providers/approval-utils.d.ts +4 -0
  187. package/src/providers/approval-utils.ts +47 -5
  188. package/src/providers/chat-message-normalization.ts +4 -11
  189. package/src/providers/cli-provider-instance.ts +833 -64
  190. package/src/providers/contracts.d.ts +55 -0
  191. package/src/providers/contracts.ts +141 -6
  192. package/src/providers/external-sources.ts +218 -0
  193. package/src/providers/ide-provider-instance.ts +19 -5
  194. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  195. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  196. package/src/providers/native-history/codex-cli-transcript.ts +419 -0
  197. package/src/providers/native-history/dispatcher.ts +340 -0
  198. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  199. package/src/providers/native-history/index.ts +30 -0
  200. package/src/providers/provider-instance-manager.ts +30 -0
  201. package/src/providers/provider-instance.ts +10 -1
  202. package/src/providers/provider-loader.ts +582 -50
  203. package/src/providers/provider-schema.ts +87 -14
  204. package/src/providers/provider-trust.ts +114 -0
  205. package/src/providers/read-chat-contract.ts +76 -16
  206. package/src/providers/sdk/README.md +49 -0
  207. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  208. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  209. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  210. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  211. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  212. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  213. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  214. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  215. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  216. package/src/providers/sdk/v1/index.ts +152 -0
  217. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  218. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  219. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  220. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  221. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  222. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  223. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  224. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  225. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  226. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  227. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  228. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  229. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  230. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  231. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  232. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  233. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  234. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  235. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  236. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  237. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  238. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  239. package/src/providers/sdk/v1/validators/index.ts +19 -0
  240. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  241. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  242. package/src/providers/spec/adapter.ts +138 -0
  243. package/src/providers/spec/cli-adapter.ts +626 -0
  244. package/src/providers/spec/driver.ts +922 -0
  245. package/src/providers/spec/evaluator.ts +597 -0
  246. package/src/providers/spec/loader.ts +324 -0
  247. package/src/providers/spec/native-history-executor.ts +939 -0
  248. package/src/providers/spec/route.ts +51 -0
  249. package/src/providers/spec/schema.gen.ts +691 -0
  250. package/src/providers/spec/schema.json +341 -0
  251. package/src/providers/spec/types.ts +356 -0
  252. package/src/providers/transcript-v2.ts +567 -0
  253. package/src/providers/types/interactive-prompt.ts +425 -0
  254. package/src/providers/version-archive.ts +38 -20
  255. package/src/repo-mesh-types.ts +119 -1
  256. package/src/sessions/registry.ts +3 -0
  257. package/src/shared-types-extra.ts +2 -4
  258. package/src/shared-types.ts +45 -1
  259. package/src/status/builders.ts +24 -6
  260. package/src/status/normalize.ts +2 -0
  261. package/src/status/reporter.ts +15 -0
  262. package/src/status/snapshot.ts +84 -25
  263. package/src/system/host-memory.ts +29 -12
  264. package/src/types.ts +5 -0
  265. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  266. package/dist/mesh/mesh-sync.d.ts +0 -53
  267. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  268. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  269. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,922 @@
1
+ /**
2
+ * SpecDriver — the single fixed script that turns a CliSpec + a
3
+ * TerminalAdapter into the dashboard-facing wire protocol.
4
+ *
5
+ * Wire (dashboard ↔ daemon):
6
+ *
7
+ * dashboard → daemon:
8
+ * { kind: 'send_message', text }
9
+ * { kind: 'click_control', control_id, payload? }
10
+ * { kind: 'click_modal_button', index }
11
+ * { kind: 'attach_image', blob, mime }
12
+ * { kind: 'resize', cols, rows }
13
+ * { kind: 'cancel' }
14
+ * { kind: 'shutdown' }
15
+ *
16
+ * daemon → dashboard:
17
+ * { kind: 'pty_data', chunk }
18
+ * { kind: 'state_changed',
19
+ * state: { id, label, title },
20
+ * modal: null | { title, buttons: [{ index, label }] },
21
+ * controls: [{ id, label, action_type }] }
22
+ * { kind: 'notification', id, title, body }
23
+ * { kind: 'delegate', id, task }
24
+ * { kind: 'spec_trace', entries: [...] }
25
+ * { kind: 'exit', exit_code }
26
+ *
27
+ * Hot reload: spec.json is watched. A reload re-evaluates and emits a
28
+ * fresh state_changed; no PTY restart is required.
29
+ *
30
+ * Delegate timers: after_duration_ms is enforced here (the evaluator
31
+ * is stateless). A timer is armed when a delegate's when_state is
32
+ * entered and cancelled when it changes.
33
+ */
34
+ 'use strict';
35
+
36
+ import * as fs from 'node:fs';
37
+ import * as os from 'node:os';
38
+ import * as path from 'node:path';
39
+ import { TerminalAdapter, type TerminalAdapterOpts } from './adapter.js';
40
+ import type { PtyTransportFactory } from '../../cli-adapters/pty-transport.js';
41
+ import { DEFAULT_SESSION_HOST_COLS, DEFAULT_SESSION_HOST_ROWS } from '@adhdev/session-host-core';
42
+ import { evaluate, type SpecEvaluation, type TraceEntry } from './evaluator.js';
43
+ import { loadSpec } from './loader.js';
44
+ import type { CliSpec, Control, DelegateTrigger, SectionDef } from './types.js';
45
+ import { LOG } from '../../logging/logger.js';
46
+
47
+ export type DashboardEvent =
48
+ | { kind: 'pty_data'; chunk: string }
49
+ | { kind: 'state_changed'; state: { id: string; label: string; title: string | null };
50
+ modal: { title: string | null; buttons: { index: number; label: string }[] } | null;
51
+ controls: { id: string; label: string; action_type: string }[] }
52
+ | { kind: 'notification'; id: string; title: string; body: string }
53
+ | { kind: 'delegate'; id: string; task: string }
54
+ | { kind: 'spec_trace'; entries: TraceEntry[] }
55
+ | { kind: 'exit'; exit_code: number }
56
+ | { kind: 'spec_error'; errors: string[] };
57
+
58
+ export type DashboardCommand =
59
+ | { kind: 'send_message'; text: string }
60
+ | { kind: 'pty_write'; data: string }
61
+ | { kind: 'click_control'; control_id: string; payload?: unknown }
62
+ | { kind: 'click_modal_button'; index: number }
63
+ | { kind: 'attach_image'; blob: string; mime: string }
64
+ | { kind: 'resize'; cols: number; rows: number }
65
+ | { kind: 'cancel' }
66
+ | { kind: 'shutdown' };
67
+
68
+ export interface SpecDriverOpts {
69
+ specPath: string;
70
+ workingDir: string;
71
+ extraEnv?: Record<string, string>;
72
+ cols?: number;
73
+ rows?: number;
74
+ /** Set false to skip the spec.json fs.watch. */
75
+ hotReload?: boolean;
76
+ /** Set true to forward trace entries on every state_changed. */
77
+ emitTrace?: boolean;
78
+ /** Inject the daemon's PTY transport (typically SessionHostPtyTransportFactory). */
79
+ transportFactory?: PtyTransportFactory;
80
+ /**
81
+ * Extra CLI args appended to spec.spawn_args. Used by the daemon to
82
+ * pass per-launch arguments like `--session-id <uuid>` so the agent
83
+ * uses the daemon's providerSessionId instead of generating its own.
84
+ */
85
+ extraCliArgs?: string[];
86
+ }
87
+
88
+ /** How long after start() to ignore "idle" readings before treating one
89
+ * as a real prompt-ready signal. Most TUIs paint a banner + tool list +
90
+ * status line on startup that can briefly score as "no state matches →
91
+ * default idle"; firing a send_keys into that buffer gets the input
92
+ * wiped when the banner clears. 2s covers the slow agents (hermes,
93
+ * agy) without delaying snappy ones (claude/codex) by much. */
94
+ const STARTUP_GRACE_MS = 2500;
95
+
96
+ /** Min time to stay in busy after the evaluator last reports it. Most TUIs
97
+ * flicker their busy spinner on and off as layout reflows (claude streams
98
+ * body text in the same region where the spinner lives, so the spinner
99
+ * disappears mid-response and the footer-only frames score as idle). The
100
+ * hold turns short idle gaps inside a single turn into "still busy", at
101
+ * the cost of looking busy for a couple seconds after a turn actually
102
+ * ends. Pick something long enough to cover the longest claude streaming
103
+ * gap we've observed (~5s between spinner refreshes) without dragging
104
+ * the post-turn idle indication noticeably. */
105
+ const BUSY_HOLD_MS = 6000;
106
+
107
+ /** Minimum delay between the prompt body and the submit_key in send_message.
108
+ * Claude / antigravity specs ship without an explicit delay_ms_before_submit
109
+ * and their TUIs sometimes drop the `\r` event when it arrives in the same
110
+ * PTY chunk as the text body — the prompt sits visible in the input field
111
+ * but is never submitted until the user hits Enter manually. 200ms matches
112
+ * codex's explicit setting and is barely perceptible to a human caller. */
113
+ const SUBMIT_DELAY_FLOOR_MS = 200;
114
+
115
+ function countNewlines(s: string): number {
116
+ let n = 0;
117
+ for (let i = 0; i < s.length; i += 1) if (s.charCodeAt(i) === 10) n += 1;
118
+ return n;
119
+ }
120
+
121
+ /**
122
+ * Pick the effective delay (ms) to wait between writing the prompt body and
123
+ * writing the submit_key. Exported for tests; production callers go through
124
+ * actuallySendMessage. Floors to SUBMIT_DELAY_FLOOR_MS so specs that omit
125
+ * delay_ms_before_submit (e.g. claude, antigravity) still get baseline
126
+ * protection against the paste→submit race. Adds line-count bonus so
127
+ * multi-line prompts get more settling time on TUIs that re-render per
128
+ * embedded `\n`.
129
+ */
130
+ export function resolveSubmitDelayMs(specBeforeSubmit: number | undefined, text: string): number {
131
+ const lines = countNewlines(text);
132
+ const linesBonus = Math.min(800, lines * 80);
133
+ const spec = typeof specBeforeSubmit === 'number' && specBeforeSubmit > 0 ? specBeforeSubmit : 0;
134
+ return Math.max(spec, SUBMIT_DELAY_FLOOR_MS + linesBonus);
135
+ }
136
+
137
+ export function matchesCompletionIdleRule(spec: CliSpec, ev: SpecEvaluation, screen: string): string | null {
138
+ const rule = spec.debounce?.completion_idle_after;
139
+ if (!rule?.regex) return null;
140
+ const haystack = rule.section
141
+ ? ev.sections.find(section => section.id === rule.section)?.text ?? ''
142
+ : screen;
143
+ if (!haystack) return null;
144
+ try {
145
+ const regex = new RegExp(rule.regex, rule.flags || '');
146
+ const matched = regex.test(haystack);
147
+ // Return the regex pattern as the stable key rather than the match
148
+ // text. The match text often contains a live counter (e.g. "Compacted
149
+ // for 1m 6s") that changes every second, which would reset
150
+ // completionIdleFirstSeenAt on every PTY frame and prevent the hold
151
+ // window from ever expiring.
152
+ return matched ? rule.regex : null;
153
+ } catch {
154
+ return null;
155
+ }
156
+ }
157
+
158
+ export function matchesCompletionIdleTargetState(
159
+ spec: CliSpec,
160
+ ev: SpecEvaluation,
161
+ screen: string,
162
+ cursor?: { row: number; col: number },
163
+ ): boolean {
164
+ // Test whether the idle/default state's when-condition actually matches
165
+ // the current screen, WITHOUT the default fallback. We don't want to
166
+ // return true just because no other state matched (which is what
167
+ // evaluate() does via its default_state fallback).
168
+ const targetId = spec.default_state ?? 'idle';
169
+ const target = spec.states.find(state => state.id === targetId)
170
+ ?? spec.states.find(state => state.id === 'idle');
171
+ if (!target) return false;
172
+
173
+ // Re-use the resolved sections already computed by evaluate().
174
+ const sections = ev.sections;
175
+ const cleanScreen = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l).join('\n');
176
+
177
+ try {
178
+ // Import the condition evaluator — but we need it as a module-level fn.
179
+ // Instead, call evaluate() and check: if the evaluator chose the target
180
+ // via an *explicit* state match (not fallback), return true.
181
+ // We detect a fallback via trace: the fallback emits "(no state matched".
182
+ const result = evaluate(spec, screen, cursor);
183
+ const wasFallback = result.trace.some(t => t.text.startsWith('(no state matched'));
184
+ return result.state.id === targetId && !wasFallback;
185
+ } catch {
186
+ return false;
187
+ }
188
+ }
189
+
190
+ export class SpecDriver {
191
+ private spec!: CliSpec;
192
+ private adapter!: TerminalAdapter;
193
+ private listeners = new Set<(ev: DashboardEvent) => void>();
194
+ private currentStateId: string | null = null;
195
+ /** Have we ever seen the spec's idle state *after* the startup grace
196
+ * window? Until we do, the agent's startup banner may still be
197
+ * painting and any send_message we forward to the PTY will be wiped
198
+ * when the banner clears the screen. Queue + drain on first valid
199
+ * idle. */
200
+ private idleSeenOnce = false;
201
+ private startedAtMs = 0;
202
+ private pendingSends: string[] = [];
203
+ private currentEval: SpecEvaluation | null = null;
204
+ private pickerInProgress: { control_id: string; phase: 'waiting'; spec: Control } | null = null;
205
+ private delegateTimers = new Map<string, ReturnType<typeof setTimeout>>();
206
+ /** Timestamp of the last time the evaluator returned busy. Used to debounce
207
+ * the busy → idle transition (see reevaluate). */
208
+ private lastBusyAt = 0;
209
+ /** The exact busy state object we last saw — held alongside lastBusyAt so
210
+ * the hold can re-emit the same { id: 'busy', label, title } payload the
211
+ * dashboard already learned about. currentEval can't fill this role
212
+ * because the evaluator already moved past busy by the time the hold
213
+ * kicks in. */
214
+ private lastBusyState: SpecEvaluation['state'] | null = null;
215
+ /** Timestamp of the last time we entered a modal state (approval/picker or
216
+ * any non-busy non-idle state). Used to suppress brief busy blips that
217
+ * appear while the modal is still on screen — Claude Code streams body
218
+ * text that transiently shows a spinner even while an approval modal is
219
+ * visible, causing rapid approval→busy→approval flicker on the dashboard. */
220
+ private lastModalAt = 0;
221
+ /** The modal state snapshot held across busy blips. */
222
+ private lastModalState: SpecEvaluation['state'] | null = null;
223
+ /** Timestamp of when we last *exited* a modal state (approval/picker → idle
224
+ * or directly via completion_idle_after). Used to suppress completion_idle_after
225
+ * firings that were queued before the modal appeared and expire immediately
226
+ * after the modal is dismissed — without this the agent appears idle even
227
+ * though it is still generating. */
228
+ private lastModalExitAt = 0;
229
+ private completionIdleFirstSeenAt = 0;
230
+ private completionIdleKey = '';
231
+ /** Previous screen lines — passed to evaluate() for `changed` condition detection. */
232
+ private prevScreenLines: string[] = [];
233
+ /** Timer that re-runs evaluate() once the hold window expires. Needed
234
+ * because the PTY stops emitting once the agent finishes; without an
235
+ * explicit wake-up there's nothing to trigger the busy → idle
236
+ * downshift. */
237
+ private busyExpiryTimer: ReturnType<typeof setTimeout> | null = null;
238
+ /** Set true while reevaluate() is invoked from busyExpiryTimer callback. */
239
+ private busyExpiryFired = false;
240
+ /** Pending idle-commit timer. Armed when the evaluator first returns idle;
241
+ * fires after idle_hold_ms if no non-idle reading has cancelled it. */
242
+ private idleHoldTimer: ReturnType<typeof setTimeout> | null = null;
243
+ /** State snapshot captured when the idle hold was armed — emitted on commit. */
244
+ private pendingIdleState: SpecEvaluation['state'] | null = null;
245
+ private specWatcher: fs.FSWatcher | null = null;
246
+ /** Ring buffer of committed state transitions (max 50). */
247
+ private stateHistory: Array<{
248
+ stateId: string;
249
+ label: string;
250
+ at: number;
251
+ durationMs: number;
252
+ reason: string;
253
+ matchedStateId?: string;
254
+ matchedRules?: string[];
255
+ debounceKind?: string;
256
+ idleHoldMs?: number;
257
+ busyHoldMs?: number;
258
+ }> = [];
259
+ private prevStateAt = 0;
260
+
261
+ constructor(private readonly opts: SpecDriverOpts) {
262
+ this.loadSpecOrThrow();
263
+ this.adapter = new TerminalAdapter(
264
+ this.buildAdapterOpts(),
265
+ {
266
+ init: () => this.emitInitialState(),
267
+ on_pty_data: (chunk) => this.emit({ kind: 'pty_data', chunk }),
268
+ on_screen_changed: () => this.reevaluate(),
269
+ on_exit: ({ exitCode }) => this.handleExit(exitCode),
270
+ },
271
+ );
272
+ if (this.opts.hotReload !== false) this.armSpecWatcher();
273
+ }
274
+
275
+ /** Subscribe to outbound events. Returns an unsubscribe fn. */
276
+ subscribe(listener: (ev: DashboardEvent) => void): () => void {
277
+ this.listeners.add(listener);
278
+ return () => { this.listeners.delete(listener); };
279
+ }
280
+
281
+ start(): void {
282
+ this.startedAtMs = Date.now();
283
+ this.adapter.start();
284
+ // Make sure we always re-evaluate once the startup grace has
285
+ // expired. Without an explicit wake-up the PTY can go quiet
286
+ // immediately after the banner paints (agy: the screen stays at
287
+ // the input prompt forever), there's no on_screen_changed event
288
+ // to trigger reevaluate, and any send_message we queued during
289
+ // the grace window would never drain.
290
+ const graceMs = this.spec.debounce?.startup_grace_ms ?? STARTUP_GRACE_MS;
291
+ setTimeout(() => this.reevaluate(), graceMs + 100);
292
+ }
293
+
294
+ dispatch(cmd: DashboardCommand): void {
295
+ switch (cmd.kind) {
296
+ case 'send_message': this.handleSendMessage(cmd.text); return;
297
+ case 'pty_write': this.adapter.send_keys(cmd.data); return;
298
+ case 'click_control': this.handleClickControl(cmd.control_id, cmd.payload); return;
299
+ case 'click_modal_button': this.handleClickModalButton(cmd.index); return;
300
+ case 'attach_image': this.handleAttachImage(cmd.blob, cmd.mime); return;
301
+ case 'resize': this.adapter.resize(cmd.cols, cmd.rows); return;
302
+ case 'cancel': this.adapter.send_keys('\x03'); return;
303
+ case 'shutdown': this.shutdown(); return;
304
+ }
305
+ }
306
+
307
+ snapshot(): string {
308
+ return this.adapter.snapshot();
309
+ }
310
+
311
+ getCursorPosition(): { row: number; col: number } {
312
+ return this.adapter.getCursorPosition();
313
+ }
314
+
315
+ shutdown(): void {
316
+ for (const t of this.delegateTimers.values()) clearTimeout(t);
317
+ this.delegateTimers.clear();
318
+ this.cancelIdleHold();
319
+ if (this.busyExpiryTimer) { clearTimeout(this.busyExpiryTimer); this.busyExpiryTimer = null; }
320
+ this.specWatcher?.close();
321
+ this.adapter.kill();
322
+ }
323
+
324
+ private cancelIdleHold(): void {
325
+ if (this.idleHoldTimer) {
326
+ clearTimeout(this.idleHoldTimer);
327
+ this.idleHoldTimer = null;
328
+ // If the idle hold was armed by a completion_idle_after forced-idle,
329
+ // cancelling it means new activity arrived while we were waiting.
330
+ // Reset the completion tracker so the hold window restarts fresh
331
+ // when the marker reappears — otherwise the stale firstSeenAt makes
332
+ // the hold appear already-expired on the next PTY frame that matches.
333
+ this.completionIdleKey = '';
334
+ this.completionIdleFirstSeenAt = 0;
335
+ }
336
+ this.pendingIdleState = null;
337
+ }
338
+
339
+ private pushHistory(stateId: string, label: string, meta?: {
340
+ reason?: string;
341
+ matchedStateId?: string;
342
+ matchedRules?: string[];
343
+ debounceKind?: string;
344
+ idleHoldMs?: number;
345
+ busyHoldMs?: number;
346
+ }): void {
347
+ const now = Date.now();
348
+ const durationMs = this.prevStateAt > 0 ? now - this.prevStateAt : 0;
349
+ this.prevStateAt = now;
350
+ this.stateHistory.push({
351
+ stateId,
352
+ label,
353
+ at: now,
354
+ durationMs,
355
+ reason: meta?.reason ?? 'eval_match',
356
+ ...(meta?.matchedStateId !== undefined ? { matchedStateId: meta.matchedStateId } : {}),
357
+ ...(meta?.matchedRules !== undefined ? { matchedRules: meta.matchedRules } : {}),
358
+ ...(meta?.debounceKind !== undefined ? { debounceKind: meta.debounceKind } : {}),
359
+ ...(meta?.idleHoldMs !== undefined ? { idleHoldMs: meta.idleHoldMs } : {}),
360
+ ...(meta?.busyHoldMs !== undefined ? { busyHoldMs: meta.busyHoldMs } : {}),
361
+ });
362
+ if (this.stateHistory.length > 50) this.stateHistory.shift();
363
+ }
364
+
365
+ getStateHistory(): ReadonlyArray<{
366
+ stateId: string;
367
+ label: string;
368
+ at: number;
369
+ durationMs: number;
370
+ reason: string;
371
+ matchedStateId?: string;
372
+ matchedRules?: string[];
373
+ debounceKind?: string;
374
+ idleHoldMs?: number;
375
+ busyHoldMs?: number;
376
+ }> {
377
+ return this.stateHistory;
378
+ }
379
+
380
+ getLastBusyAt(): number { return this.lastBusyAt; }
381
+ hasIdleHoldPending(): boolean { return this.idleHoldTimer !== null; }
382
+ getSpecPath(): string { return this.opts.specPath; }
383
+ getCompletionIdleDebounceState(): { active: boolean; ageMs: number; holdMs: number; forceAfterMs: number } | null {
384
+ if (!this.completionIdleKey || !this.completionIdleFirstSeenAt) return null;
385
+ const rule = this.spec.debounce?.completion_idle_after;
386
+ if (!rule) return null;
387
+ return {
388
+ active: true,
389
+ ageMs: Date.now() - this.completionIdleFirstSeenAt,
390
+ holdMs: rule.hold_ms ?? 0,
391
+ forceAfterMs: typeof rule.force_after_ms === 'number' ? rule.force_after_ms : 0,
392
+ };
393
+ }
394
+ getScreen(): string { return this.adapter.snapshot(); }
395
+ getSections(): Array<{ id: string; text: string }> | null {
396
+ try {
397
+ const screen = this.adapter.snapshot();
398
+ const ev = evaluate(this.spec, screen, undefined);
399
+ return ev.sections.map(s => ({ id: s.id, text: s.text }));
400
+ } catch { return null; }
401
+ }
402
+
403
+ // ────────────────────────────────────────────────────────────────────
404
+ // Loading & adapter wiring
405
+ // ────────────────────────────────────────────────────────────────────
406
+
407
+ private loadSpecOrThrow(): void {
408
+ const res = loadSpec(this.opts.specPath);
409
+ if (!res.ok) throw new Error(`spec invalid: ${res.errors.join('; ')}`);
410
+ this.spec = res.spec;
411
+ }
412
+
413
+ private buildAdapterOpts(): TerminalAdapterOpts {
414
+ const baseArgs = this.spec.spawn_args ?? [];
415
+ const extra = this.opts.extraCliArgs ?? [];
416
+ return {
417
+ binary: this.spec.binary,
418
+ args: [...baseArgs, ...extra],
419
+ cwd: this.opts.workingDir,
420
+ env: { ...(this.spec.env ?? {}), ...(this.opts.extraEnv ?? {}) },
421
+ cols: this.opts.cols ?? DEFAULT_SESSION_HOST_COLS,
422
+ rows: this.opts.rows ?? DEFAULT_SESSION_HOST_ROWS,
423
+ transportFactory: this.opts.transportFactory,
424
+ };
425
+ }
426
+
427
+ private armSpecWatcher(): void {
428
+ try {
429
+ // Watch the parent directory so we catch atomic replacements
430
+ // (cp, install scripts) that create a new inode — a file-level
431
+ // watch misses those on macOS because the original inode is gone.
432
+ const dir = path.dirname(this.opts.specPath);
433
+ const base = path.basename(this.opts.specPath);
434
+ this.specWatcher = fs.watch(dir, { persistent: false }, (_event, filename) => {
435
+ if (filename && filename !== base) return;
436
+ const res = loadSpec(this.opts.specPath);
437
+ if (!res.ok) { this.emit({ kind: 'spec_error', errors: res.errors }); return; }
438
+ this.spec = res.spec;
439
+ this.reevaluate(/*forceEmit*/ true);
440
+ });
441
+ } catch { /* watch is best-effort */ }
442
+ }
443
+
444
+ // ────────────────────────────────────────────────────────────────────
445
+ // Evaluation pipeline
446
+ // ────────────────────────────────────────────────────────────────────
447
+
448
+ private emitInitialState(): void {
449
+ // Start with an empty-screen evaluation so the dashboard immediately
450
+ // knows about the default state.
451
+ this.reevaluate(true);
452
+ }
453
+
454
+ /** Re-arm the timer that wakes the driver up after BUSY_HOLD_MS so it
455
+ * can decide whether to downshift to idle. Always uses the most recent
456
+ * hold value so a spec hot-reload that shortens the hold takes effect
457
+ * on the next busy entry. Safe to call repeatedly; only the last call
458
+ * fires. */
459
+ private scheduleBusyExpiry(holdMs: number): void {
460
+ if (this.busyExpiryTimer) clearTimeout(this.busyExpiryTimer);
461
+ this.busyExpiryTimer = setTimeout(() => {
462
+ this.busyExpiryTimer = null;
463
+ LOG.debug('SpecDriver', `[${this.opts.specPath.split('/').slice(-3).join('/')}] busyExpiry fired holdMs=${holdMs}`);
464
+ this.busyExpiryFired = true;
465
+ this.reevaluate();
466
+ this.busyExpiryFired = false;
467
+ }, Math.max(holdMs + 50, 100));
468
+ }
469
+
470
+ private reevaluate(forceEmit = false): void {
471
+ const screen = this.adapter.snapshot();
472
+ const cursor = this.adapter.getCursorPosition();
473
+ const ev = evaluate(this.spec, screen, cursor, this.prevScreenLines.length > 0 ? this.prevScreenLines : undefined);
474
+ // Update prevScreenLines for next evaluation's `changed` condition detection.
475
+ this.prevScreenLines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
476
+
477
+ // Busy hold: many TUIs flicker between busy and idle every frame
478
+ // (claude in particular — its token counter appears and disappears
479
+ // as the layout reflows). Once we see busy, hold that state for
480
+ // BUSY_HOLD_MS before allowing a downshift to idle. Any state
481
+ // *other* than idle clears the hold immediately (approval is
482
+ // strictly more interesting than busy, so it shouldn't be held
483
+ // back). The hold lives on the driver, not the evaluator, so the
484
+ // spec author doesn't have to think about debouncing.
485
+ let evState = ev.state;
486
+ const busyHoldMs = this.spec.debounce?.busy_hold_ms ?? BUSY_HOLD_MS;
487
+ if (this.currentStateId === 'busy' && evState.id === 'idle') {
488
+ const ageMs = Date.now() - this.lastBusyAt;
489
+ if (ageMs < busyHoldMs) {
490
+ // Pin to the last seen busy state directly — currentEval can
491
+ // already be idle at this point (it tracks the previous tick,
492
+ // which during the flicker is just as likely to be idle as
493
+ // busy), so we can't rely on it to recover the busy label.
494
+ evState = this.lastBusyState ?? evState;
495
+ }
496
+ }
497
+ // Modal hold: when in a modal state (approval, picker, etc.) a brief
498
+ // busy reading should not interrupt the modal. Claude Code streams
499
+ // body content while the approval modal is visible, causing a spinner
500
+ // to appear transiently — without this hold, the dashboard sees a
501
+ // rapid modal→busy→modal flicker and the approval UI disappears and
502
+ // reappears every few seconds. Apply the same busy_hold_ms window:
503
+ // if the modal was entered recently and the evaluator now returns
504
+ // busy, stay in the modal state until the hold expires or a non-busy
505
+ // non-modal reading arrives.
506
+ const idleStateId = this.spec.default_state ?? 'idle';
507
+ const isModalState = (id: string | null) =>
508
+ id !== null && id !== 'busy' && id !== idleStateId;
509
+ if (isModalState(this.currentStateId) && evState.id === 'busy') {
510
+ const ageMs = Date.now() - this.lastModalAt;
511
+ if (ageMs < busyHoldMs && this.lastModalState) {
512
+ evState = this.lastModalState;
513
+ }
514
+ }
515
+ const completionIdleRule = this.spec.debounce?.completion_idle_after;
516
+ let busyWakeMs = busyHoldMs;
517
+ // Don't fire completion_idle_after while in a modal state (approval,
518
+ // picker, etc.) or within a grace period after leaving one. Two cases:
519
+ // 1. Modal still active: the hold window may have expired so evState
520
+ // resolves to busy, but the user is still looking at the approval screen.
521
+ // 2. Modal just dismissed: the timer may have been queued *before* the
522
+ // approval appeared and its hold expires immediately after dismissal,
523
+ // causing a false-idle even though the agent is still generating.
524
+ const postModalGraceMs = busyHoldMs;
525
+ const now = Date.now();
526
+ const recentlyInModal = isModalState(this.currentStateId) || (this.lastModalAt > 0 && now - this.lastModalAt < postModalGraceMs);
527
+ const recentlyLeftModal = !recentlyInModal && this.lastModalExitAt > 0 && now - this.lastModalExitAt < postModalGraceMs;
528
+ if (evState.id === 'busy' && completionIdleRule && !recentlyInModal && !recentlyLeftModal) {
529
+ const completionKey = matchesCompletionIdleRule(this.spec, ev, screen);
530
+ if (completionKey) {
531
+ const now = Date.now();
532
+ if (completionKey !== this.completionIdleKey) {
533
+ this.completionIdleKey = completionKey;
534
+ this.completionIdleFirstSeenAt = now;
535
+ LOG.debug('SpecDriver', `[${this.opts.specPath.split('/').slice(-3).join('/')}] completion_idle_after matched: key="${completionKey}"`);
536
+ }
537
+ const holdMs = Math.max(0, completionIdleRule.hold_ms || 0);
538
+ const forceAfterMs = typeof completionIdleRule.force_after_ms === 'number'
539
+ ? completionIdleRule.force_after_ms
540
+ : null;
541
+ const ageMs = now - this.completionIdleFirstSeenAt;
542
+ if (ageMs >= holdMs) {
543
+ const targetMatches = matchesCompletionIdleTargetState(this.spec, ev, screen, cursor);
544
+ const forced = !targetMatches && forceAfterMs !== null && ageMs >= holdMs + forceAfterMs;
545
+ LOG.debug('SpecDriver', `[${this.opts.specPath.split('/').slice(-3).join('/')}] completion_idle_after hold expired ageMs=${ageMs} targetState=${targetMatches} forced=${forced} screenTail="${screen.split(/\r?\n/).slice(-3).join('\\n').slice(-200)}"`);
546
+ if (targetMatches || forced) {
547
+ const idle = this.spec.states.find(state => state.id === this.spec.default_state)
548
+ ?? this.spec.states.find(state => state.id === 'idle');
549
+ evState = idle
550
+ ? { id: idle.id, label: idle.label, title: null }
551
+ : { id: 'idle', label: 'Ready', title: null };
552
+ } else {
553
+ busyWakeMs = Math.min(busyWakeMs, 1000);
554
+ }
555
+ } else {
556
+ busyWakeMs = Math.min(busyWakeMs, Math.max(holdMs - ageMs, 0));
557
+ }
558
+ } else {
559
+ this.completionIdleKey = '';
560
+ this.completionIdleFirstSeenAt = 0;
561
+ }
562
+ } else if (evState.id !== 'busy') {
563
+ this.completionIdleKey = '';
564
+ this.completionIdleFirstSeenAt = 0;
565
+ }
566
+
567
+ if (evState.id === 'busy') {
568
+ this.lastBusyAt = Date.now();
569
+ this.lastBusyState = evState;
570
+ // Cancel any pending idle commit — non-idle reading invalidates it.
571
+ this.cancelIdleHold();
572
+ // Reset completion_idle_after tracking only when the completion
573
+ // marker is NOT present. If the marker is on screen (key is set
574
+ // by the block above), clearing it here would restart the hold
575
+ // window on every PTY frame and the hold would never expire.
576
+ // Only reset when the marker disappeared (key is empty), meaning
577
+ // a new tool-output burst arrived that pushed the marker off
578
+ // screen — in that case the old firstSeenAt is stale and should
579
+ // restart when the marker reappears.
580
+ //
581
+ // Also reset on busy re-entry (transitioning back from a non-busy
582
+ // state). The previous generation may have set completionIdleKey
583
+ // and firstSeenAt; without this reset the hold window appears
584
+ // instantly expired on the new generation's first PTY frame that
585
+ // re-matches the same completion regex key, causing a false-idle
586
+ // before the new generation has a chance to run.
587
+ if (!this.completionIdleKey || this.currentStateId !== 'busy') {
588
+ this.completionIdleKey = '';
589
+ this.completionIdleFirstSeenAt = 0;
590
+ }
591
+ // Schedule a re-evaluation when the hold window expires. PTYs
592
+ // typically stop emitting once the agent stops printing (the
593
+ // footer settles), so without an explicit timer the driver
594
+ // never wakes up to downshift to idle and the dashboard sees
595
+ // status stuck at generating long after the turn ended.
596
+ this.scheduleBusyExpiry(busyWakeMs);
597
+ } else if (evState.id !== this.currentStateId && evState.id !== 'busy') {
598
+ // Non-busy modal states (approval, picker, signing_in) also cancel
599
+ // any in-flight idle hold — they are higher-priority than idle.
600
+ if (evState.id !== (this.spec.default_state ?? 'idle')) {
601
+ this.cancelIdleHold();
602
+ }
603
+ // Track the modal entry timestamp so the modal-hold above can
604
+ // suppress brief busy blips while the modal is still on screen.
605
+ if (isModalState(evState.id)) {
606
+ this.lastModalAt = Date.now();
607
+ this.lastModalState = evState;
608
+ } else {
609
+ // Leaving modal territory (going to idle) — clear the hold,
610
+ // but record the exit time so completion_idle_after can be
611
+ // suppressed during the grace period after dismissal.
612
+ if (this.lastModalAt > 0) this.lastModalExitAt = Date.now();
613
+ this.lastModalAt = 0;
614
+ this.lastModalState = null;
615
+ }
616
+ }
617
+
618
+ // Idle hold: if idle_hold_ms is set, don't commit idle immediately.
619
+ // Arm a timer; if a non-idle reading arrives before it fires, cancel.
620
+ const idleHoldMs = this.spec.debounce?.idle_hold_ms ?? 0;
621
+ const isIdleState = evState.id === (this.spec.default_state ?? 'idle');
622
+ if (isIdleState && idleHoldMs > 0 && this.currentStateId !== evState.id) {
623
+ if (!this.idleHoldTimer) {
624
+ this.pendingIdleState = evState;
625
+ const capturedEv = ev;
626
+ const capturedMatchedRules = extractMatchedRules(ev);
627
+ this.idleHoldTimer = setTimeout(() => {
628
+ this.idleHoldTimer = null;
629
+ const committed = this.pendingIdleState;
630
+ this.pendingIdleState = null;
631
+ if (!committed) return;
632
+ LOG.debug('SpecDriver', `[${this.opts.specPath.split('/').slice(-3).join('/')}] idleHold committed after ${idleHoldMs}ms`);
633
+ this.currentStateId = committed.id;
634
+ this.currentEval = capturedEv;
635
+ this.pushHistory(committed.id, committed.label, {
636
+ reason: 'idle_hold_committed',
637
+ matchedStateId: capturedEv.state.id,
638
+ matchedRules: capturedMatchedRules,
639
+ debounceKind: 'idle_hold',
640
+ idleHoldMs,
641
+ });
642
+ this.emit({
643
+ kind: 'state_changed',
644
+ state: committed,
645
+ modal: null,
646
+ controls: capturedEv.controls.map(c => ({ id: c.id, label: c.label, action_type: c.actionType })),
647
+ });
648
+ this.armOrCancelDelegateTimers(committed.id);
649
+ if (this.opts.emitTrace) this.emit({ kind: 'spec_trace', entries: capturedEv.trace });
650
+ }, idleHoldMs);
651
+ }
652
+ // Don't fall through to the normal changed/emit path for idle.
653
+ this.currentEval = ev;
654
+ const graceMs2 = this.spec.debounce?.startup_grace_ms ?? STARTUP_GRACE_MS;
655
+ if (!this.idleSeenOnce && Date.now() - this.startedAtMs >= graceMs2) {
656
+ this.idleSeenOnce = true;
657
+ const queued = this.pendingSends.splice(0);
658
+ for (const text of queued) setTimeout(() => this.actuallySendMessage(text), 50);
659
+ }
660
+ if (this.pickerInProgress) this.tryAdvancePicker(screen);
661
+ return;
662
+ }
663
+
664
+ const changed = forceEmit
665
+ || evState.id !== this.currentStateId
666
+ || !shallowSameModal(ev, this.currentEval)
667
+ || !shallowSameControls(ev, this.currentEval);
668
+
669
+ // Picker state tracking — if a picker is waiting for its
670
+ // wait_for cue and now sees it, complete the picker flow.
671
+ if (this.pickerInProgress) this.tryAdvancePicker(screen);
672
+
673
+ this.currentEval = ev;
674
+ // First time we ever see idle (or any non-busy non-startup state),
675
+ // flush any queued send_message calls that arrived before the
676
+ // agent finished painting its banner. Subsequent idle/busy
677
+ // toggles don't retrigger.
678
+ // Wait at least the spec's startup_grace_ms after start() so we
679
+ // don't treat a transient "matches no state, default idle"
680
+ // reading during the banner paint as a real idle. After that,
681
+ // the first non-busy observation is a real prompt-ready signal
682
+ // and we drain any queued send_message calls.
683
+ const graceMs = this.spec.debounce?.startup_grace_ms ?? STARTUP_GRACE_MS;
684
+ const sinceStart = Date.now() - this.startedAtMs;
685
+ if (!this.idleSeenOnce && evState.id !== 'busy' && sinceStart >= graceMs) {
686
+ this.idleSeenOnce = true;
687
+ const queued = this.pendingSends.splice(0);
688
+ for (const text of queued) {
689
+ setTimeout(() => this.actuallySendMessage(text), 50);
690
+ }
691
+ }
692
+ if (changed) {
693
+ this.currentStateId = evState.id;
694
+ const matchedRules = extractMatchedRules(ev);
695
+ // Determine reason and debounce kind for this transition
696
+ let transitionReason: string;
697
+ let debounceKind: string;
698
+ let transitionBusyHoldMs: number | undefined;
699
+ if (forceEmit) {
700
+ transitionReason = 'forceEmit';
701
+ debounceKind = 'none';
702
+ } else if (evState.id !== ev.state.id) {
703
+ // evState was overridden — completion_idle_after forced idle
704
+ transitionReason = 'completion_idle_after';
705
+ debounceKind = 'completion_idle_after';
706
+ } else if (this.busyExpiryFired) {
707
+ // busyExpiryTimer woke us up and hold has now expired
708
+ transitionReason = 'busy_hold_expired';
709
+ debounceKind = 'busy_hold';
710
+ transitionBusyHoldMs = busyHoldMs;
711
+ } else {
712
+ transitionReason = 'eval_match';
713
+ debounceKind = 'none';
714
+ }
715
+ this.pushHistory(evState.id, evState.label, {
716
+ reason: transitionReason,
717
+ matchedStateId: ev.state.id,
718
+ matchedRules,
719
+ debounceKind,
720
+ ...(transitionBusyHoldMs !== undefined ? { busyHoldMs: transitionBusyHoldMs } : {}),
721
+ });
722
+ this.emit({
723
+ kind: 'state_changed',
724
+ state: evState,
725
+ modal: ev.modal ? { title: ev.modal.title, buttons: ev.modal.buttons.map(b => ({ index: b.index, label: b.label })) } : null,
726
+ controls: ev.controls.map(c => ({ id: c.id, label: c.label, action_type: c.actionType })),
727
+ });
728
+ for (const n of ev.notifications) this.emit({ kind: 'notification', id: n.id, title: n.title, body: n.body });
729
+ this.armOrCancelDelegateTimers(evState.id);
730
+ if (this.opts.emitTrace) this.emit({ kind: 'spec_trace', entries: ev.trace });
731
+ }
732
+ }
733
+
734
+ private armOrCancelDelegateTimers(currentStateId: string): void {
735
+ for (const d of this.spec.delegate ?? []) {
736
+ const armed = this.delegateTimers.has(d.id);
737
+ const shouldFire = d.when_state === currentStateId;
738
+ if (shouldFire && !armed) {
739
+ const delay = d.after_duration_ms ?? 0;
740
+ const t = setTimeout(() => { this.fireDelegate(d); this.delegateTimers.delete(d.id); }, delay);
741
+ this.delegateTimers.set(d.id, t);
742
+ } else if (!shouldFire && armed) {
743
+ clearTimeout(this.delegateTimers.get(d.id)!);
744
+ this.delegateTimers.delete(d.id);
745
+ }
746
+ }
747
+ }
748
+
749
+ private fireDelegate(d: DelegateTrigger): void {
750
+ const ev = this.currentEval;
751
+ const task = (d.task_template)
752
+ .replace(/\{node\}/g, os.hostname())
753
+ .replace(/\{state\.label\}/g, ev?.state.label ?? '')
754
+ .replace(/\{state\.title\}/g, ev?.state.title ?? '')
755
+ .replace(/\{duration_ms\}/g, String(d.after_duration_ms ?? 0));
756
+ this.emit({ kind: 'delegate', id: d.id, task });
757
+ }
758
+
759
+ // ────────────────────────────────────────────────────────────────────
760
+ // Dashboard commands
761
+ // ────────────────────────────────────────────────────────────────────
762
+
763
+ private handleSendMessage(text: string): void {
764
+ if (!this.idleSeenOnce) {
765
+ // Agent is still drawing its startup banner. Queue and drain
766
+ // when we see idle so we don't fire keystrokes into a buffer
767
+ // that's about to be cleared.
768
+ this.pendingSends.push(text);
769
+ return;
770
+ }
771
+ this.actuallySendMessage(text);
772
+ }
773
+
774
+ private actuallySendMessage(text: string): void {
775
+ const sm = this.spec.send_message;
776
+ const perChar = sm.delay_ms_per_char ?? 0;
777
+ // Floor the gap between text and submit_key. Without this, claude /
778
+ // antigravity specs (which leave delay_ms_before_submit unset)
779
+ // race: text bytes and `\r` arrive back-to-back, the TUI processes
780
+ // the `\r` while still digesting the text input, and the prompt
781
+ // sits visible in the input field but never submits — the user has
782
+ // to press Enter manually. Scale with line count so multi-line
783
+ // pastes (which take longer for the TUI to render) get more
784
+ // settling time.
785
+ const beforeSubmit = resolveSubmitDelayMs(sm.delay_ms_before_submit, text);
786
+ if (perChar === 0) {
787
+ this.adapter.send_keys(text);
788
+ if (beforeSubmit > 0) setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
789
+ else this.adapter.send_keys(sm.submit_key);
790
+ return;
791
+ }
792
+ let i = 0;
793
+ const iv = setInterval(() => {
794
+ if (i >= text.length) {
795
+ clearInterval(iv);
796
+ setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
797
+ return;
798
+ }
799
+ this.adapter.send_keys(text[i]);
800
+ i += 1;
801
+ }, perChar);
802
+ }
803
+
804
+ private handleClickControl(controlId: string, payload?: unknown): void {
805
+ const ctl = (this.spec.control_bar ?? []).find(c => c.id === controlId);
806
+ if (!ctl) return;
807
+ // Reject controls that aren't currently visible.
808
+ const ev = this.currentEval;
809
+ if (ctl.visible_when_state && ev && !ctl.visible_when_state.includes(ev.state.id)) return;
810
+
811
+ const a = ctl.action;
812
+ switch (a.type) {
813
+ case 'send_keys':
814
+ this.adapter.send_keys(a.keys);
815
+ return;
816
+ case 'open_picker':
817
+ this.adapter.send_keys(a.trigger_keys);
818
+ this.pickerInProgress = { control_id: ctl.id, phase: 'waiting', spec: ctl };
819
+ return;
820
+ case 'attach_image': {
821
+ const p = typeof payload === 'object' && payload && (payload as any).path;
822
+ if (typeof p === 'string') {
823
+ const keys = a.keys_template.replace(/\{path\}/g, p);
824
+ this.adapter.send_keys(keys);
825
+ }
826
+ return;
827
+ }
828
+ }
829
+ }
830
+
831
+ private handleClickModalButton(index: number): void {
832
+ const m = this.currentEval?.modal;
833
+ if (!m) return;
834
+ const btn = m.buttons.find(b => b.index === index);
835
+ if (!btn) return;
836
+ this.adapter.send_keys(btn.key);
837
+ }
838
+
839
+ private handleAttachImage(blob: string, mime: string): void {
840
+ // tempfile_then_keys: write decoded bytes to a temp file, then
841
+ // fire the attach_image control_bar entry with that path.
842
+ const ctl = (this.spec.control_bar ?? []).find(c => c.action.type === 'attach_image');
843
+ if (!ctl || ctl.action.type !== 'attach_image') return;
844
+ const ext = guessExt(mime);
845
+ const tmp = path.join(os.tmpdir(), `adhdev-attach-${Date.now()}${ext}`);
846
+ try {
847
+ fs.writeFileSync(tmp, Buffer.from(blob, 'base64'));
848
+ } catch { return; }
849
+ const keys = ctl.action.keys_template.replace(/\{path\}/g, tmp);
850
+ this.adapter.send_keys(keys);
851
+ }
852
+
853
+ private tryAdvancePicker(screen: string): void {
854
+ const picker = this.pickerInProgress;
855
+ if (!picker) return;
856
+ const action = picker.spec.action;
857
+ if (action.type !== 'open_picker') return;
858
+ const hay = sectionTextFromSnapshot(this.spec, screen, action.wait_for.section) ?? screen;
859
+ if (!action.wait_for.regex) return;
860
+ const re = new RegExp(action.wait_for.regex, action.wait_for.flags ?? 'i');
861
+ if (!re.test(hay)) return;
862
+ // Cue arrived — the dashboard now sees the picker modal via
863
+ // state_changed. We do NOT auto-submit; the dashboard must call
864
+ // click_modal_button(index). After the modal closes the picker
865
+ // tracking naturally clears the next time the screen settles.
866
+ this.pickerInProgress = null;
867
+ }
868
+
869
+ private handleExit(exitCode: number): void {
870
+ this.emit({ kind: 'exit', exit_code: exitCode });
871
+ this.shutdown();
872
+ }
873
+
874
+ private emit(ev: DashboardEvent): void {
875
+ for (const l of this.listeners) {
876
+ try { l(ev); } catch { /* listener side */ }
877
+ }
878
+ }
879
+ }
880
+
881
+ function shallowSameModal(a: SpecEvaluation, b: SpecEvaluation | null): boolean {
882
+ if (!b) return false;
883
+ if (!a.modal && !b.modal) return true;
884
+ if (!a.modal || !b.modal) return false;
885
+ if (a.modal.title !== b.modal.title) return false;
886
+ if (a.modal.buttons.length !== b.modal.buttons.length) return false;
887
+ for (let i = 0; i < a.modal.buttons.length; i += 1) {
888
+ if (a.modal.buttons[i].label !== b.modal.buttons[i].label) return false;
889
+ }
890
+ return true;
891
+ }
892
+
893
+ function shallowSameControls(a: SpecEvaluation, b: SpecEvaluation | null): boolean {
894
+ if (!b) return false;
895
+ if (a.controls.length !== b.controls.length) return false;
896
+ for (let i = 0; i < a.controls.length; i += 1) {
897
+ if (a.controls[i].id !== b.controls[i].id) return false;
898
+ }
899
+ return true;
900
+ }
901
+
902
+ function sectionTextFromSnapshot(spec: CliSpec, screen: string, sectionId: string | undefined): string | null {
903
+ if (!sectionId) return null;
904
+ const ev = evaluate(spec, screen);
905
+ return ev.sections.find(s => s.id === sectionId)?.text ?? null;
906
+ }
907
+
908
+ function guessExt(mime: string): string {
909
+ if (/png/i.test(mime)) return '.png';
910
+ if (/jpe?g/i.test(mime)) return '.jpg';
911
+ if (/gif/i.test(mime)) return '.gif';
912
+ if (/webp/i.test(mime)) return '.webp';
913
+ return '.bin';
914
+ }
915
+
916
+ function extractMatchedRules(ev: SpecEvaluation): string[] {
917
+ if (!Array.isArray(ev.trace)) return [];
918
+ return ev.trace
919
+ .filter(t => t.kind === 'state_match')
920
+ .map(t => t.text)
921
+ .filter(Boolean);
922
+ }