@adhdev/daemon-core 0.9.82-rc.19 → 0.9.82-rc.191

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 (231) 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 +22 -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/commands/cli-manager.d.ts +2 -1
  14. package/dist/commands/handler.d.ts +110 -0
  15. package/dist/commands/mesh-coordinator.d.ts +85 -1
  16. package/dist/commands/router.d.ts +26 -1
  17. package/dist/config/chat-history.d.ts +9 -0
  18. package/dist/config/config.d.ts +5 -0
  19. package/dist/config/mesh-config.d.ts +72 -1
  20. package/dist/git/git-commands.d.ts +7 -1
  21. package/dist/git/git-types.d.ts +2 -0
  22. package/dist/index.d.ts +37 -10
  23. package/dist/index.js +32864 -16401
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.mjs +32584 -16191
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/installer.d.ts +1 -4
  28. package/dist/ipc/local-ipc-server.d.ts +91 -0
  29. package/dist/launch.d.ts +1 -1
  30. package/dist/logging/async-batch-writer.d.ts +10 -0
  31. package/dist/mesh/beads-db.d.ts +83 -0
  32. package/dist/mesh/contracts.d.ts +164 -0
  33. package/dist/mesh/coordinator-prompt.d.ts +30 -0
  34. package/dist/mesh/coordinator-registry.d.ts +59 -0
  35. package/dist/mesh/mesh-active-work.d.ts +90 -0
  36. package/dist/mesh/mesh-events.d.ts +143 -6
  37. package/dist/mesh/mesh-fast-forward.d.ts +41 -0
  38. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  39. package/dist/mesh/mesh-ledger.d.ts +58 -1
  40. package/dist/mesh/mesh-refine-status.d.ts +26 -0
  41. package/dist/mesh/mesh-work-queue.d.ts +55 -6
  42. package/dist/mesh/preview-freshness.d.ts +18 -0
  43. package/dist/mesh/refine-config.d.ts +193 -0
  44. package/dist/mesh/worktree-bootstrap-config.d.ts +113 -0
  45. package/dist/providers/approval-utils.d.ts +13 -0
  46. package/dist/providers/cli-provider-instance.d.ts +39 -3
  47. package/dist/providers/contracts.d.ts +130 -6
  48. package/dist/providers/external-sources.d.ts +71 -0
  49. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  50. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  51. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  52. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  53. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  54. package/dist/providers/native-history/index.d.ts +13 -0
  55. package/dist/providers/provider-instance-manager.d.ts +12 -0
  56. package/dist/providers/provider-instance.d.ts +12 -0
  57. package/dist/providers/provider-loader.d.ts +26 -4
  58. package/dist/providers/provider-trust.d.ts +31 -0
  59. package/dist/providers/read-chat-contract.d.ts +29 -0
  60. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  61. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  62. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  63. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  64. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  65. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  66. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  67. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  68. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  69. package/dist/providers/sdk/v1/index.d.ts +30 -0
  70. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  71. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  72. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  73. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  74. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  75. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  76. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  77. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  78. package/dist/providers/spec/adapter.d.ts +60 -0
  79. package/dist/providers/spec/cli-adapter.d.ts +98 -0
  80. package/dist/providers/spec/driver.d.ts +168 -0
  81. package/dist/providers/spec/evaluator.d.ts +55 -0
  82. package/dist/providers/spec/loader.d.ts +14 -0
  83. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  84. package/dist/providers/spec/route.d.ts +4 -0
  85. package/dist/providers/spec/schema.gen.d.ts +549 -0
  86. package/dist/providers/spec/types.d.ts +237 -0
  87. package/dist/providers/transcript-v2.d.ts +176 -0
  88. package/dist/providers/types/interactive-prompt.d.ts +48 -0
  89. package/dist/repo-mesh-types.d.ts +108 -1
  90. package/dist/sessions/registry.d.ts +3 -0
  91. package/dist/shared-types.d.ts +42 -1
  92. package/dist/status/reporter.d.ts +2 -0
  93. package/dist/status/snapshot.d.ts +1 -0
  94. package/dist/types.d.ts +5 -0
  95. package/package.json +7 -2
  96. package/src/agent-stream/poller.ts +2 -3
  97. package/src/boot/daemon-lifecycle.ts +19 -10
  98. package/src/boot/process-hardening.ts +89 -0
  99. package/src/chat/source-machine.ts +534 -0
  100. package/src/chat/source-resolver.ts +0 -0
  101. package/src/chat/subscription-updates.ts +20 -1
  102. package/src/cli-adapter-types.d.ts +1 -0
  103. package/src/cli-adapter-types.ts +21 -2
  104. package/src/cli-adapters/cli-script-runner.ts +421 -0
  105. package/src/cli-adapters/cli-state-engine.ts +1086 -0
  106. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  107. package/src/cli-adapters/provider-cli-adapter.ts +670 -1137
  108. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  109. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  110. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  111. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  112. package/src/cli-adapters/provider-cli-shared.ts +59 -11
  113. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  114. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +17 -1
  115. package/src/cli-adapters/terminal-backends/xterm-backend.ts +8 -1
  116. package/src/commands/chat-commands.ts +1787 -60
  117. package/src/commands/cli-manager.ts +283 -14
  118. package/src/commands/handler.ts +809 -2
  119. package/src/commands/mesh-coordinator.ts +331 -122
  120. package/src/commands/router.ts +3600 -510
  121. package/src/config/chat-history.ts +95 -24
  122. package/src/config/config.ts +12 -0
  123. package/src/config/mesh-config.ts +280 -2
  124. package/src/config/recent-activity.ts +8 -2
  125. package/src/daemon/dev-cli-debug.ts +10 -1
  126. package/src/detection/ide-detector.ts +26 -16
  127. package/src/git/git-commands.ts +37 -7
  128. package/src/git/git-status.ts +35 -6
  129. package/src/git/git-types.ts +2 -0
  130. package/src/git/git-worktree.ts +8 -1
  131. package/src/index.ts +115 -9
  132. package/src/installer.d.ts +1 -1
  133. package/src/installer.ts +8 -6
  134. package/src/ipc/local-ipc-server.ts +278 -0
  135. package/src/launch.d.ts +1 -1
  136. package/src/launch.ts +37 -28
  137. package/src/logging/async-batch-writer.ts +55 -0
  138. package/src/logging/logger.ts +2 -1
  139. package/src/mesh/beads-db.ts +527 -0
  140. package/src/mesh/contracts.ts +329 -0
  141. package/src/mesh/coordinator-prompt.ts +204 -30
  142. package/src/mesh/coordinator-registry.ts +121 -0
  143. package/src/mesh/mesh-active-work.ts +437 -0
  144. package/src/mesh/mesh-events.ts +1275 -108
  145. package/src/mesh/mesh-fast-forward.ts +438 -0
  146. package/src/mesh/mesh-host-ownership.ts +73 -0
  147. package/src/mesh/mesh-ledger.ts +457 -104
  148. package/src/mesh/mesh-refine-status.ts +144 -0
  149. package/src/mesh/mesh-work-queue.ts +267 -159
  150. package/src/mesh/preview-freshness.ts +118 -0
  151. package/src/mesh/refine-config.ts +366 -0
  152. package/src/mesh/worktree-bootstrap-config.ts +247 -0
  153. package/src/providers/approval-utils.d.ts +4 -0
  154. package/src/providers/approval-utils.ts +47 -5
  155. package/src/providers/chat-message-normalization.ts +4 -11
  156. package/src/providers/cli-provider-instance.ts +763 -60
  157. package/src/providers/contracts.d.ts +55 -0
  158. package/src/providers/contracts.ts +141 -6
  159. package/src/providers/external-sources.ts +218 -0
  160. package/src/providers/ide-provider-instance.ts +19 -5
  161. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  162. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  163. package/src/providers/native-history/codex-cli-transcript.ts +419 -0
  164. package/src/providers/native-history/dispatcher.ts +340 -0
  165. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  166. package/src/providers/native-history/index.ts +30 -0
  167. package/src/providers/provider-instance-manager.ts +30 -0
  168. package/src/providers/provider-instance.ts +9 -0
  169. package/src/providers/provider-loader.ts +582 -50
  170. package/src/providers/provider-schema.ts +87 -14
  171. package/src/providers/provider-trust.ts +114 -0
  172. package/src/providers/read-chat-contract.ts +76 -16
  173. package/src/providers/sdk/README.md +49 -0
  174. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  175. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  176. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  177. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  178. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  179. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  180. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  181. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  182. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  183. package/src/providers/sdk/v1/index.ts +152 -0
  184. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  185. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  186. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  187. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  188. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  189. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  190. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  191. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  192. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  193. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  194. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  195. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  196. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  197. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  198. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  199. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  200. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  201. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  202. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  203. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  204. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  205. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  206. package/src/providers/sdk/v1/validators/index.ts +19 -0
  207. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  208. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  209. package/src/providers/spec/adapter.ts +176 -0
  210. package/src/providers/spec/cli-adapter.ts +534 -0
  211. package/src/providers/spec/driver.ts +612 -0
  212. package/src/providers/spec/evaluator.ts +344 -0
  213. package/src/providers/spec/loader.ts +130 -0
  214. package/src/providers/spec/native-history-executor.ts +939 -0
  215. package/src/providers/spec/route.ts +51 -0
  216. package/src/providers/spec/schema.gen.ts +538 -0
  217. package/src/providers/spec/schema.json +235 -0
  218. package/src/providers/spec/types.ts +256 -0
  219. package/src/providers/transcript-v2.ts +567 -0
  220. package/src/providers/types/interactive-prompt.ts +408 -0
  221. package/src/providers/version-archive.ts +38 -20
  222. package/src/repo-mesh-types.ts +118 -1
  223. package/src/sessions/registry.ts +3 -0
  224. package/src/shared-types.ts +45 -1
  225. package/src/status/builders.ts +24 -6
  226. package/src/status/reporter.ts +15 -0
  227. package/src/status/snapshot.ts +84 -25
  228. package/src/system/host-memory.ts +29 -12
  229. package/src/types.ts +5 -0
  230. package/dist/mesh/mesh-sync.d.ts +0 -53
  231. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,612 @@
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 { evaluate, type SpecEvaluation, type TraceEntry } from './evaluator.js';
42
+ import { loadSpec } from './loader.js';
43
+ import type { CliSpec, Control, DelegateTrigger } from './types.js';
44
+
45
+ export type DashboardEvent =
46
+ | { kind: 'pty_data'; chunk: string }
47
+ | { kind: 'state_changed'; state: { id: string; label: string; title: string | null };
48
+ modal: { title: string | null; buttons: { index: number; label: string }[] } | null;
49
+ controls: { id: string; label: string; action_type: string }[] }
50
+ | { kind: 'notification'; id: string; title: string; body: string }
51
+ | { kind: 'delegate'; id: string; task: string }
52
+ | { kind: 'spec_trace'; entries: TraceEntry[] }
53
+ | { kind: 'exit'; exit_code: number }
54
+ | { kind: 'spec_error'; errors: string[] };
55
+
56
+ export type DashboardCommand =
57
+ | { kind: 'send_message'; text: string }
58
+ | { kind: 'pty_write'; data: string }
59
+ | { kind: 'click_control'; control_id: string; payload?: unknown }
60
+ | { kind: 'click_modal_button'; index: number }
61
+ | { kind: 'attach_image'; blob: string; mime: string }
62
+ | { kind: 'resize'; cols: number; rows: number }
63
+ | { kind: 'cancel' }
64
+ | { kind: 'shutdown' };
65
+
66
+ export interface SpecDriverOpts {
67
+ specPath: string;
68
+ workingDir: string;
69
+ extraEnv?: Record<string, string>;
70
+ cols?: number;
71
+ rows?: number;
72
+ /** Set false to skip the spec.json fs.watch. */
73
+ hotReload?: boolean;
74
+ /** Set true to forward trace entries on every state_changed. */
75
+ emitTrace?: boolean;
76
+ /** Inject the daemon's PTY transport (typically SessionHostPtyTransportFactory). */
77
+ transportFactory?: PtyTransportFactory;
78
+ /**
79
+ * Extra CLI args appended to spec.spawn_args. Used by the daemon to
80
+ * pass per-launch arguments like `--session-id <uuid>` so the agent
81
+ * uses the daemon's providerSessionId instead of generating its own.
82
+ */
83
+ extraCliArgs?: string[];
84
+ }
85
+
86
+ /** How long after start() to ignore "idle" readings before treating one
87
+ * as a real prompt-ready signal. Most TUIs paint a banner + tool list +
88
+ * status line on startup that can briefly score as "no state matches →
89
+ * default idle"; firing a send_keys into that buffer gets the input
90
+ * wiped when the banner clears. 2s covers the slow agents (hermes,
91
+ * agy) without delaying snappy ones (claude/codex) by much. */
92
+ const STARTUP_GRACE_MS = 2500;
93
+
94
+ /** Min time to stay in busy after the evaluator last reports it. Most TUIs
95
+ * flicker their busy spinner on and off as layout reflows (claude streams
96
+ * body text in the same region where the spinner lives, so the spinner
97
+ * disappears mid-response and the footer-only frames score as idle). The
98
+ * hold turns short idle gaps inside a single turn into "still busy", at
99
+ * the cost of looking busy for a couple seconds after a turn actually
100
+ * ends. Pick something long enough to cover the longest claude streaming
101
+ * gap we've observed (~5s between spinner refreshes) without dragging
102
+ * the post-turn idle indication noticeably. */
103
+ const BUSY_HOLD_MS = 6000;
104
+
105
+ /** Minimum delay between the prompt body and the submit_key in send_message.
106
+ * Claude / antigravity specs ship without an explicit delay_ms_before_submit
107
+ * and their TUIs sometimes drop the `\r` event when it arrives in the same
108
+ * PTY chunk as the text body — the prompt sits visible in the input field
109
+ * but is never submitted until the user hits Enter manually. 200ms matches
110
+ * codex's explicit setting and is barely perceptible to a human caller. */
111
+ const SUBMIT_DELAY_FLOOR_MS = 200;
112
+
113
+ function countNewlines(s: string): number {
114
+ let n = 0;
115
+ for (let i = 0; i < s.length; i += 1) if (s.charCodeAt(i) === 10) n += 1;
116
+ return n;
117
+ }
118
+
119
+ /**
120
+ * Pick the effective delay (ms) to wait between writing the prompt body and
121
+ * writing the submit_key. Exported for tests; production callers go through
122
+ * actuallySendMessage. Floors to SUBMIT_DELAY_FLOOR_MS so specs that omit
123
+ * delay_ms_before_submit (e.g. claude, antigravity) still get baseline
124
+ * protection against the paste→submit race. Adds line-count bonus so
125
+ * multi-line prompts get more settling time on TUIs that re-render per
126
+ * embedded `\n`.
127
+ */
128
+ export function resolveSubmitDelayMs(specBeforeSubmit: number | undefined, text: string): number {
129
+ const lines = countNewlines(text);
130
+ const linesBonus = Math.min(800, lines * 80);
131
+ const spec = typeof specBeforeSubmit === 'number' && specBeforeSubmit > 0 ? specBeforeSubmit : 0;
132
+ return Math.max(spec, SUBMIT_DELAY_FLOOR_MS + linesBonus);
133
+ }
134
+
135
+ export function matchesCompletionIdleRule(spec: CliSpec, ev: SpecEvaluation, screen: string): string | null {
136
+ const rule = spec.debounce?.completion_idle_after;
137
+ if (!rule?.regex) return null;
138
+ const haystack = rule.section
139
+ ? ev.sections.find(section => section.id === rule.section)?.text ?? ''
140
+ : screen;
141
+ if (!haystack) return null;
142
+ try {
143
+ const regex = new RegExp(rule.regex, rule.flags || '');
144
+ const match = haystack.match(regex);
145
+ return match?.[0] || null;
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+
151
+ export function matchesCompletionIdleTargetState(spec: CliSpec, ev: SpecEvaluation, screen: string): boolean {
152
+ const target = spec.states.find(state => state.id === spec.default_state)
153
+ ?? spec.states.find(state => state.id === 'idle');
154
+ if (!target?.when?.regex) return false;
155
+ const haystack = target.when.section
156
+ ? ev.sections.find(section => section.id === target.when.section)?.text ?? ''
157
+ : screen;
158
+ if (!haystack) return false;
159
+ try {
160
+ return new RegExp(target.when.regex, target.when.flags || 'i').test(haystack);
161
+ } catch {
162
+ return false;
163
+ }
164
+ }
165
+
166
+ export class SpecDriver {
167
+ private spec!: CliSpec;
168
+ private adapter!: TerminalAdapter;
169
+ private listeners = new Set<(ev: DashboardEvent) => void>();
170
+ private currentStateId: string | null = null;
171
+ /** Have we ever seen the spec's idle state *after* the startup grace
172
+ * window? Until we do, the agent's startup banner may still be
173
+ * painting and any send_message we forward to the PTY will be wiped
174
+ * when the banner clears the screen. Queue + drain on first valid
175
+ * idle. */
176
+ private idleSeenOnce = false;
177
+ private startedAtMs = 0;
178
+ private pendingSends: string[] = [];
179
+ private currentEval: SpecEvaluation | null = null;
180
+ private pickerInProgress: { control_id: string; phase: 'waiting'; spec: Control } | null = null;
181
+ private delegateTimers = new Map<string, ReturnType<typeof setTimeout>>();
182
+ /** Timestamp of the last time the evaluator returned busy. Used to debounce
183
+ * the busy → idle transition (see reevaluate). */
184
+ private lastBusyAt = 0;
185
+ /** The exact busy state object we last saw — held alongside lastBusyAt so
186
+ * the hold can re-emit the same { id: 'busy', label, title } payload the
187
+ * dashboard already learned about. currentEval can't fill this role
188
+ * because the evaluator already moved past busy by the time the hold
189
+ * kicks in. */
190
+ private lastBusyState: SpecEvaluation['state'] | null = null;
191
+ private completionIdleFirstSeenAt = 0;
192
+ private completionIdleKey = '';
193
+ /** Timer that re-runs evaluate() once the hold window expires. Needed
194
+ * because the PTY stops emitting once the agent finishes; without an
195
+ * explicit wake-up there's nothing to trigger the busy → idle
196
+ * downshift. */
197
+ private busyExpiryTimer: ReturnType<typeof setTimeout> | null = null;
198
+ private specWatcher: fs.FSWatcher | null = null;
199
+
200
+ constructor(private readonly opts: SpecDriverOpts) {
201
+ this.loadSpecOrThrow();
202
+ this.adapter = new TerminalAdapter(
203
+ this.buildAdapterOpts(),
204
+ {
205
+ init: () => this.emitInitialState(),
206
+ on_pty_data: (chunk) => this.emit({ kind: 'pty_data', chunk }),
207
+ on_screen_changed: () => this.reevaluate(),
208
+ on_exit: ({ exitCode }) => this.handleExit(exitCode),
209
+ },
210
+ );
211
+ if (this.opts.hotReload !== false) this.armSpecWatcher();
212
+ }
213
+
214
+ /** Subscribe to outbound events. Returns an unsubscribe fn. */
215
+ subscribe(listener: (ev: DashboardEvent) => void): () => void {
216
+ this.listeners.add(listener);
217
+ return () => { this.listeners.delete(listener); };
218
+ }
219
+
220
+ start(): void {
221
+ this.startedAtMs = Date.now();
222
+ this.adapter.start();
223
+ // Make sure we always re-evaluate once the startup grace has
224
+ // expired. Without an explicit wake-up the PTY can go quiet
225
+ // immediately after the banner paints (agy: the screen stays at
226
+ // the input prompt forever), there's no on_screen_changed event
227
+ // to trigger reevaluate, and any send_message we queued during
228
+ // the grace window would never drain.
229
+ const graceMs = this.spec.debounce?.startup_grace_ms ?? STARTUP_GRACE_MS;
230
+ setTimeout(() => this.reevaluate(), graceMs + 100);
231
+ }
232
+
233
+ dispatch(cmd: DashboardCommand): void {
234
+ switch (cmd.kind) {
235
+ case 'send_message': this.handleSendMessage(cmd.text); return;
236
+ case 'pty_write': this.adapter.send_keys(cmd.data); return;
237
+ case 'click_control': this.handleClickControl(cmd.control_id, cmd.payload); return;
238
+ case 'click_modal_button': this.handleClickModalButton(cmd.index); return;
239
+ case 'attach_image': this.handleAttachImage(cmd.blob, cmd.mime); return;
240
+ case 'resize': this.adapter.resize(cmd.cols, cmd.rows); return;
241
+ case 'cancel': this.adapter.send_keys('\x03'); return;
242
+ case 'shutdown': this.shutdown(); return;
243
+ }
244
+ }
245
+
246
+ snapshot(): string {
247
+ return this.adapter.snapshot();
248
+ }
249
+
250
+ getCursorPosition(): { row: number; col: number } {
251
+ return this.adapter.getCursorPosition();
252
+ }
253
+
254
+ shutdown(): void {
255
+ for (const t of this.delegateTimers.values()) clearTimeout(t);
256
+ this.delegateTimers.clear();
257
+ this.specWatcher?.close();
258
+ this.adapter.kill();
259
+ }
260
+
261
+ // ────────────────────────────────────────────────────────────────────
262
+ // Loading & adapter wiring
263
+ // ────────────────────────────────────────────────────────────────────
264
+
265
+ private loadSpecOrThrow(): void {
266
+ const res = loadSpec(this.opts.specPath);
267
+ if (!res.ok) throw new Error(`spec invalid: ${res.errors.join('; ')}`);
268
+ this.spec = res.spec;
269
+ }
270
+
271
+ private buildAdapterOpts(): TerminalAdapterOpts {
272
+ const baseArgs = this.spec.spawn_args ?? [];
273
+ const extra = this.opts.extraCliArgs ?? [];
274
+ return {
275
+ binary: this.spec.binary,
276
+ args: [...baseArgs, ...extra],
277
+ cwd: this.opts.workingDir,
278
+ env: { ...(this.spec.env ?? {}), ...(this.opts.extraEnv ?? {}) },
279
+ cols: this.opts.cols ?? 100,
280
+ rows: this.opts.rows ?? 30,
281
+ transportFactory: this.opts.transportFactory,
282
+ };
283
+ }
284
+
285
+ private armSpecWatcher(): void {
286
+ try {
287
+ this.specWatcher = fs.watch(this.opts.specPath, { persistent: false }, () => {
288
+ // Re-read; if it parses, replace and re-evaluate. Errors are
289
+ // surfaced to the dashboard so the spec author sees them live.
290
+ const res = loadSpec(this.opts.specPath);
291
+ if (!res.ok) { this.emit({ kind: 'spec_error', errors: res.errors }); return; }
292
+ this.spec = res.spec;
293
+ this.reevaluate(/*forceEmit*/ true);
294
+ });
295
+ } catch { /* watch is best-effort */ }
296
+ }
297
+
298
+ // ────────────────────────────────────────────────────────────────────
299
+ // Evaluation pipeline
300
+ // ────────────────────────────────────────────────────────────────────
301
+
302
+ private emitInitialState(): void {
303
+ // Start with an empty-screen evaluation so the dashboard immediately
304
+ // knows about the default state.
305
+ this.reevaluate(true);
306
+ }
307
+
308
+ /** Re-arm the timer that wakes the driver up after BUSY_HOLD_MS so it
309
+ * can decide whether to downshift to idle. Always uses the most recent
310
+ * hold value so a spec hot-reload that shortens the hold takes effect
311
+ * on the next busy entry. Safe to call repeatedly; only the last call
312
+ * fires. */
313
+ private scheduleBusyExpiry(holdMs: number): void {
314
+ if (this.busyExpiryTimer) clearTimeout(this.busyExpiryTimer);
315
+ this.busyExpiryTimer = setTimeout(() => {
316
+ this.busyExpiryTimer = null;
317
+ this.reevaluate();
318
+ }, Math.max(holdMs + 50, 100));
319
+ }
320
+
321
+ private reevaluate(forceEmit = false): void {
322
+ const screen = this.adapter.snapshot();
323
+ const cursor = this.adapter.getCursorPosition();
324
+ const ev = evaluate(this.spec, screen, cursor);
325
+
326
+ // Busy hold: many TUIs flicker between busy and idle every frame
327
+ // (claude in particular — its token counter appears and disappears
328
+ // as the layout reflows). Once we see busy, hold that state for
329
+ // BUSY_HOLD_MS before allowing a downshift to idle. Any state
330
+ // *other* than idle clears the hold immediately (approval is
331
+ // strictly more interesting than busy, so it shouldn't be held
332
+ // back). The hold lives on the driver, not the evaluator, so the
333
+ // spec author doesn't have to think about debouncing.
334
+ let evState = ev.state;
335
+ const busyHoldMs = this.spec.debounce?.busy_hold_ms ?? BUSY_HOLD_MS;
336
+ if (this.currentStateId === 'busy' && evState.id === 'idle') {
337
+ const ageMs = Date.now() - this.lastBusyAt;
338
+ if (ageMs < busyHoldMs) {
339
+ // Pin to the last seen busy state directly — currentEval can
340
+ // already be idle at this point (it tracks the previous tick,
341
+ // which during the flicker is just as likely to be idle as
342
+ // busy), so we can't rely on it to recover the busy label.
343
+ evState = this.lastBusyState ?? evState;
344
+ }
345
+ }
346
+ const completionIdleRule = this.spec.debounce?.completion_idle_after;
347
+ let busyWakeMs = busyHoldMs;
348
+ if (evState.id === 'busy' && completionIdleRule) {
349
+ const completionKey = matchesCompletionIdleRule(this.spec, ev, screen);
350
+ if (completionKey) {
351
+ const now = Date.now();
352
+ if (completionKey !== this.completionIdleKey) {
353
+ this.completionIdleKey = completionKey;
354
+ this.completionIdleFirstSeenAt = now;
355
+ }
356
+ const holdMs = Math.max(0, completionIdleRule.hold_ms || 0);
357
+ const ageMs = now - this.completionIdleFirstSeenAt;
358
+ if (ageMs >= holdMs) {
359
+ if (matchesCompletionIdleTargetState(this.spec, ev, screen)) {
360
+ const idle = this.spec.states.find(state => state.id === this.spec.default_state)
361
+ ?? this.spec.states.find(state => state.id === 'idle');
362
+ evState = idle
363
+ ? { id: idle.id, label: idle.label, title: null }
364
+ : { id: 'idle', label: 'Ready', title: null };
365
+ } else {
366
+ busyWakeMs = Math.min(busyWakeMs, 1000);
367
+ }
368
+ } else {
369
+ busyWakeMs = Math.min(busyWakeMs, Math.max(holdMs - ageMs, 0));
370
+ }
371
+ } else {
372
+ this.completionIdleKey = '';
373
+ this.completionIdleFirstSeenAt = 0;
374
+ }
375
+ } else if (evState.id !== 'busy') {
376
+ this.completionIdleKey = '';
377
+ this.completionIdleFirstSeenAt = 0;
378
+ }
379
+
380
+ if (evState.id === 'busy') {
381
+ this.lastBusyAt = Date.now();
382
+ this.lastBusyState = evState;
383
+ // Schedule a re-evaluation when the hold window expires. PTYs
384
+ // typically stop emitting once the agent stops printing (the
385
+ // footer settles), so without an explicit timer the driver
386
+ // never wakes up to downshift to idle and the dashboard sees
387
+ // status stuck at generating long after the turn ended.
388
+ this.scheduleBusyExpiry(busyWakeMs);
389
+ }
390
+
391
+ const changed = forceEmit
392
+ || evState.id !== this.currentStateId
393
+ || !shallowSameModal(ev, this.currentEval)
394
+ || !shallowSameControls(ev, this.currentEval);
395
+
396
+ // Picker state tracking — if a picker is waiting for its
397
+ // wait_for cue and now sees it, complete the picker flow.
398
+ if (this.pickerInProgress) this.tryAdvancePicker(screen);
399
+
400
+ this.currentEval = ev;
401
+ // First time we ever see idle (or any non-busy non-startup state),
402
+ // flush any queued send_message calls that arrived before the
403
+ // agent finished painting its banner. Subsequent idle/busy
404
+ // toggles don't retrigger.
405
+ // Wait at least the spec's startup_grace_ms after start() so we
406
+ // don't treat a transient "matches no state, default idle"
407
+ // reading during the banner paint as a real idle. After that,
408
+ // the first non-busy observation is a real prompt-ready signal
409
+ // and we drain any queued send_message calls.
410
+ const graceMs = this.spec.debounce?.startup_grace_ms ?? STARTUP_GRACE_MS;
411
+ const sinceStart = Date.now() - this.startedAtMs;
412
+ if (!this.idleSeenOnce && evState.id !== 'busy' && sinceStart >= graceMs) {
413
+ this.idleSeenOnce = true;
414
+ const queued = this.pendingSends.splice(0);
415
+ for (const text of queued) {
416
+ setTimeout(() => this.actuallySendMessage(text), 50);
417
+ }
418
+ }
419
+ if (changed) {
420
+ this.currentStateId = evState.id;
421
+ this.emit({
422
+ kind: 'state_changed',
423
+ state: evState,
424
+ modal: ev.modal ? { title: ev.modal.title, buttons: ev.modal.buttons.map(b => ({ index: b.index, label: b.label })) } : null,
425
+ controls: ev.controls.map(c => ({ id: c.id, label: c.label, action_type: c.actionType })),
426
+ });
427
+ for (const n of ev.notifications) this.emit({ kind: 'notification', id: n.id, title: n.title, body: n.body });
428
+ this.armOrCancelDelegateTimers(evState.id);
429
+ if (this.opts.emitTrace) this.emit({ kind: 'spec_trace', entries: ev.trace });
430
+ }
431
+ }
432
+
433
+ private armOrCancelDelegateTimers(currentStateId: string): void {
434
+ for (const d of this.spec.delegate ?? []) {
435
+ const armed = this.delegateTimers.has(d.id);
436
+ const shouldFire = d.when_state === currentStateId;
437
+ if (shouldFire && !armed) {
438
+ const delay = d.after_duration_ms ?? 0;
439
+ const t = setTimeout(() => { this.fireDelegate(d); this.delegateTimers.delete(d.id); }, delay);
440
+ this.delegateTimers.set(d.id, t);
441
+ } else if (!shouldFire && armed) {
442
+ clearTimeout(this.delegateTimers.get(d.id)!);
443
+ this.delegateTimers.delete(d.id);
444
+ }
445
+ }
446
+ }
447
+
448
+ private fireDelegate(d: DelegateTrigger): void {
449
+ const ev = this.currentEval;
450
+ const task = (d.task_template)
451
+ .replace(/\{node\}/g, os.hostname())
452
+ .replace(/\{state\.label\}/g, ev?.state.label ?? '')
453
+ .replace(/\{state\.title\}/g, ev?.state.title ?? '')
454
+ .replace(/\{duration_ms\}/g, String(d.after_duration_ms ?? 0));
455
+ this.emit({ kind: 'delegate', id: d.id, task });
456
+ }
457
+
458
+ // ────────────────────────────────────────────────────────────────────
459
+ // Dashboard commands
460
+ // ────────────────────────────────────────────────────────────────────
461
+
462
+ private handleSendMessage(text: string): void {
463
+ if (!this.idleSeenOnce) {
464
+ // Agent is still drawing its startup banner. Queue and drain
465
+ // when we see idle so we don't fire keystrokes into a buffer
466
+ // that's about to be cleared.
467
+ this.pendingSends.push(text);
468
+ return;
469
+ }
470
+ this.actuallySendMessage(text);
471
+ }
472
+
473
+ private actuallySendMessage(text: string): void {
474
+ const sm = this.spec.send_message;
475
+ const perChar = sm.delay_ms_per_char ?? 0;
476
+ // Floor the gap between text and submit_key. Without this, claude /
477
+ // antigravity specs (which leave delay_ms_before_submit unset)
478
+ // race: text bytes and `\r` arrive back-to-back, the TUI processes
479
+ // the `\r` while still digesting the text input, and the prompt
480
+ // sits visible in the input field but never submits — the user has
481
+ // to press Enter manually. Scale with line count so multi-line
482
+ // pastes (which take longer for the TUI to render) get more
483
+ // settling time.
484
+ const beforeSubmit = resolveSubmitDelayMs(sm.delay_ms_before_submit, text);
485
+ if (perChar === 0) {
486
+ this.adapter.send_keys(text);
487
+ if (beforeSubmit > 0) setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
488
+ else this.adapter.send_keys(sm.submit_key);
489
+ return;
490
+ }
491
+ let i = 0;
492
+ const iv = setInterval(() => {
493
+ if (i >= text.length) {
494
+ clearInterval(iv);
495
+ setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
496
+ return;
497
+ }
498
+ this.adapter.send_keys(text[i]);
499
+ i += 1;
500
+ }, perChar);
501
+ }
502
+
503
+ private handleClickControl(controlId: string, payload?: unknown): void {
504
+ const ctl = (this.spec.control_bar ?? []).find(c => c.id === controlId);
505
+ if (!ctl) return;
506
+ // Reject controls that aren't currently visible.
507
+ const ev = this.currentEval;
508
+ if (ctl.visible_when_state && ev && !ctl.visible_when_state.includes(ev.state.id)) return;
509
+
510
+ const a = ctl.action;
511
+ switch (a.type) {
512
+ case 'send_keys':
513
+ this.adapter.send_keys(a.keys);
514
+ return;
515
+ case 'open_picker':
516
+ this.adapter.send_keys(a.trigger_keys);
517
+ this.pickerInProgress = { control_id: ctl.id, phase: 'waiting', spec: ctl };
518
+ return;
519
+ case 'attach_image': {
520
+ const p = typeof payload === 'object' && payload && (payload as any).path;
521
+ if (typeof p === 'string') {
522
+ const keys = a.keys_template.replace(/\{path\}/g, p);
523
+ this.adapter.send_keys(keys);
524
+ }
525
+ return;
526
+ }
527
+ }
528
+ }
529
+
530
+ private handleClickModalButton(index: number): void {
531
+ const m = this.currentEval?.modal;
532
+ if (!m) return;
533
+ const btn = m.buttons.find(b => b.index === index);
534
+ if (!btn) return;
535
+ this.adapter.send_keys(btn.key);
536
+ }
537
+
538
+ private handleAttachImage(blob: string, mime: string): void {
539
+ // tempfile_then_keys: write decoded bytes to a temp file, then
540
+ // fire the attach_image control_bar entry with that path.
541
+ const ctl = (this.spec.control_bar ?? []).find(c => c.action.type === 'attach_image');
542
+ if (!ctl || ctl.action.type !== 'attach_image') return;
543
+ const ext = guessExt(mime);
544
+ const tmp = path.join(os.tmpdir(), `adhdev-attach-${Date.now()}${ext}`);
545
+ try {
546
+ fs.writeFileSync(tmp, Buffer.from(blob, 'base64'));
547
+ } catch { return; }
548
+ const keys = ctl.action.keys_template.replace(/\{path\}/g, tmp);
549
+ this.adapter.send_keys(keys);
550
+ }
551
+
552
+ private tryAdvancePicker(screen: string): void {
553
+ const picker = this.pickerInProgress;
554
+ if (!picker) return;
555
+ const action = picker.spec.action;
556
+ if (action.type !== 'open_picker') return;
557
+ const hay = sectionTextFromSnapshot(this.spec, screen, action.wait_for.section) ?? screen;
558
+ const re = new RegExp(action.wait_for.regex, action.wait_for.flags ?? 'i');
559
+ if (!re.test(hay)) return;
560
+ // Cue arrived — the dashboard now sees the picker modal via
561
+ // state_changed. We do NOT auto-submit; the dashboard must call
562
+ // click_modal_button(index). After the modal closes the picker
563
+ // tracking naturally clears the next time the screen settles.
564
+ this.pickerInProgress = null;
565
+ }
566
+
567
+ private handleExit(exitCode: number): void {
568
+ this.emit({ kind: 'exit', exit_code: exitCode });
569
+ this.shutdown();
570
+ }
571
+
572
+ private emit(ev: DashboardEvent): void {
573
+ for (const l of this.listeners) {
574
+ try { l(ev); } catch { /* listener side */ }
575
+ }
576
+ }
577
+ }
578
+
579
+ function shallowSameModal(a: SpecEvaluation, b: SpecEvaluation | null): boolean {
580
+ if (!b) return false;
581
+ if (!a.modal && !b.modal) return true;
582
+ if (!a.modal || !b.modal) return false;
583
+ if (a.modal.title !== b.modal.title) return false;
584
+ if (a.modal.buttons.length !== b.modal.buttons.length) return false;
585
+ for (let i = 0; i < a.modal.buttons.length; i += 1) {
586
+ if (a.modal.buttons[i].label !== b.modal.buttons[i].label) return false;
587
+ }
588
+ return true;
589
+ }
590
+
591
+ function shallowSameControls(a: SpecEvaluation, b: SpecEvaluation | null): boolean {
592
+ if (!b) return false;
593
+ if (a.controls.length !== b.controls.length) return false;
594
+ for (let i = 0; i < a.controls.length; i += 1) {
595
+ if (a.controls[i].id !== b.controls[i].id) return false;
596
+ }
597
+ return true;
598
+ }
599
+
600
+ function sectionTextFromSnapshot(spec: CliSpec, screen: string, sectionId: string | undefined): string | null {
601
+ if (!sectionId) return null;
602
+ const ev = evaluate(spec, screen);
603
+ return ev.sections.find(s => s.id === sectionId)?.text ?? null;
604
+ }
605
+
606
+ function guessExt(mime: string): string {
607
+ if (/png/i.test(mime)) return '.png';
608
+ if (/jpe?g/i.test(mime)) return '.jpg';
609
+ if (/gif/i.test(mime)) return '.gif';
610
+ if (/webp/i.test(mime)) return '.webp';
611
+ return '.bin';
612
+ }