@adhdev/daemon-core 0.9.82-rc.17 → 0.9.82-rc.170

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