@adhdev/daemon-core 0.9.82-rc.18 → 0.9.82-rc.180

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 (223) 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 +8 -0
  16. package/dist/config/config.d.ts +5 -0
  17. package/dist/config/mesh-config.d.ts +72 -1
  18. package/dist/git/git-commands.d.ts +5 -1
  19. package/dist/index.d.ts +35 -8
  20. package/dist/index.js +19937 -4800
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +20357 -5290
  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 +97 -5
  34. package/dist/mesh/mesh-fast-forward.d.ts +41 -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 +54 -6
  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 +15 -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 +25 -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 +159 -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 +102 -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 +3495 -502
  117. package/src/config/chat-history.ts +91 -24
  118. package/src/config/config.ts +12 -0
  119. package/src/config/mesh-config.ts +280 -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 -7
  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 +486 -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 +982 -67
  139. package/src/mesh/mesh-fast-forward.ts +438 -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 +263 -159
  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 +598 -55
  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 +231 -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 +453 -0
  203. package/src/providers/spec/driver.ts +540 -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 +706 -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 +112 -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
  222. package/dist/mesh/mesh-sync.d.ts +0 -53
  223. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Thin generic terminal adapter.
3
+ *
4
+ * Spawns a PTY, feeds bytes into a headless xterm so a visible screen
5
+ * snapshot is always available, and exposes a small hook surface
6
+ * (init / tick / on_screen_changed / on_exit). Nothing in this module
7
+ * knows about agents, modals, or specs — it's just a terminal host.
8
+ *
9
+ * The Spec Driver is built on top of this adapter and consumes the
10
+ * hooks to drive its declarative state machine.
11
+ *
12
+ * Inbound from driver:
13
+ * send_keys(str) — raw bytes to PTY
14
+ * resize(c, r) — resize the PTY and the xterm
15
+ * kill() — terminate the child
16
+ *
17
+ * Outbound to driver:
18
+ * init({ pid })
19
+ * on_pty_data(chunk) — raw bytes for dashboard's terminal pane
20
+ * on_screen_changed(snapshot) — coalesced visible-screen change
21
+ * tick() — periodic timer (configurable interval)
22
+ * on_exit({ exitCode })
23
+ */
24
+ 'use strict';
25
+
26
+ // @xterm/headless ships as CJS only but stamps __esModule = true on its
27
+ // export object, so tsup's __toESM helper neither synthesizes a `default`
28
+ // property (it sees the __esModule marker and trusts it) nor preserves
29
+ // the named `Terminal` export through a plain ESM-style
30
+ // `import { Terminal } from '@xterm/headless'`. The first symptom we saw
31
+ // from this was the published `adhdev` CLI exploding with
32
+ // "Named export 'Terminal' not found" inside the mcp ipc bootstrap.
33
+ //
34
+ // Pull Terminal off the namespace import (which tsup compiles into a
35
+ // shim that *does* see the package's own Terminal property) instead.
36
+ // Type-only import keeps the .d.ts surface honest.
37
+ import type { Terminal as TerminalType } from '@xterm/headless';
38
+ import * as xtermHeadlessNs from '@xterm/headless';
39
+ const TerminalCtor: { new (...args: unknown[]): TerminalType } =
40
+ (xtermHeadlessNs as any).Terminal
41
+ ?? (xtermHeadlessNs as any).default?.Terminal;
42
+ import { NodePtyTransportFactory, type PtyRuntimeTransport, type PtyTransportFactory } from '../../cli-adapters/pty-transport.js';
43
+
44
+ export interface TerminalAdapterOpts {
45
+ binary: string;
46
+ args?: string[];
47
+ cwd: string;
48
+ env?: Record<string, string>;
49
+ cols?: number;
50
+ rows?: number;
51
+ /** Coalesce screen snapshots: emit on_screen_changed at most this often. */
52
+ screenChangeDebounceMs?: number;
53
+ /** tick() period. 0 disables ticks. */
54
+ tickIntervalMs?: number;
55
+ /**
56
+ * Optional PTY transport factory. When the daemon supplies a
57
+ * SessionHostPtyTransportFactory (standalone runs the PTY inside the
58
+ * session-host so the runtime/<sid>/snapshot endpoint can serve it),
59
+ * forward it here. Without it the PTY spawns locally inside the
60
+ * daemon process and the dashboard's terminal pane reports
61
+ * "Runtime terminal unavailable: Unknown session".
62
+ */
63
+ transportFactory?: PtyTransportFactory;
64
+ }
65
+
66
+ export interface TerminalAdapterHandlers {
67
+ init?(info: { pid: number }): void;
68
+ on_pty_data?(chunk: string): void;
69
+ on_screen_changed?(snapshot: string): void;
70
+ tick?(): void;
71
+ on_exit?(info: { exitCode: number }): void;
72
+ }
73
+
74
+ export class TerminalAdapter {
75
+ private term: TerminalType;
76
+ private pty: PtyRuntimeTransport | null = null;
77
+ private factory: PtyTransportFactory;
78
+ private cols: number;
79
+ private rows: number;
80
+ private screenDebounceMs: number;
81
+ private tickIntervalMs: number;
82
+ private screenTimer: ReturnType<typeof setTimeout> | null = null;
83
+ private tickTimer: ReturnType<typeof setInterval> | null = null;
84
+ private lastScreen = '';
85
+
86
+ constructor(
87
+ private readonly opts: TerminalAdapterOpts,
88
+ private readonly handlers: TerminalAdapterHandlers,
89
+ ) {
90
+ this.cols = opts.cols ?? 100;
91
+ this.rows = opts.rows ?? 30;
92
+ this.screenDebounceMs = opts.screenChangeDebounceMs ?? 80;
93
+ this.tickIntervalMs = opts.tickIntervalMs ?? 0;
94
+ this.factory = opts.transportFactory ?? new NodePtyTransportFactory();
95
+ this.term = new TerminalCtor({ cols: this.cols, rows: this.rows, allowProposedApi: true, scrollback: 1000 });
96
+ }
97
+
98
+ start(): void {
99
+ this.pty = this.factory.spawn(this.opts.binary, this.opts.args ?? [], {
100
+ cwd: this.opts.cwd,
101
+ env: { ...process.env, ...(this.opts.env ?? {}) } as Record<string, string>,
102
+ cols: this.cols,
103
+ rows: this.rows,
104
+ });
105
+ this.handlers.init?.({ pid: this.pty.pid });
106
+ this.pty.onData((chunk) => this.onChunk(chunk));
107
+ this.pty.onExit((info) => {
108
+ this.stopTimers();
109
+ this.handlers.on_exit?.({ exitCode: typeof info.exitCode === 'number' ? info.exitCode : 0 });
110
+ this.pty = null;
111
+ });
112
+ if (this.tickIntervalMs > 0) {
113
+ this.tickTimer = setInterval(() => this.handlers.tick?.(), this.tickIntervalMs);
114
+ }
115
+ }
116
+
117
+ send_keys(s: string): void {
118
+ this.pty?.write(s);
119
+ }
120
+
121
+ resize(cols: number, rows: number): void {
122
+ this.cols = cols; this.rows = rows;
123
+ this.pty?.resize(cols, rows);
124
+ this.term.resize(cols, rows);
125
+ }
126
+
127
+ snapshot(): string {
128
+ return this.lastScreen || this.computeScreen();
129
+ }
130
+
131
+ kill(): void {
132
+ this.stopTimers();
133
+ try { this.pty?.kill(); } catch { /* ignore */ }
134
+ this.pty = null;
135
+ this.term.dispose();
136
+ }
137
+
138
+ private onChunk(chunk: string): void {
139
+ try { this.handlers.on_pty_data?.(chunk); } catch { /* user side */ }
140
+ this.term.write(chunk);
141
+ // Coalesce snapshot emission — rapid bursts shouldn't fire 200x.
142
+ if (this.screenTimer) return;
143
+ this.screenTimer = setTimeout(() => {
144
+ this.screenTimer = null;
145
+ const snap = this.computeScreen();
146
+ if (snap === this.lastScreen) return;
147
+ this.lastScreen = snap;
148
+ try { this.handlers.on_screen_changed?.(snap); } catch { /* user side */ }
149
+ }, this.screenDebounceMs);
150
+ }
151
+
152
+ private computeScreen(): string {
153
+ const buf = this.term.buffer.active;
154
+ const out: string[] = [];
155
+ for (let y = 0; y < buf.length; y += 1) {
156
+ const line = buf.getLine(y);
157
+ if (!line) continue;
158
+ out.push(line.translateToString(true));
159
+ }
160
+ while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
161
+ return out.join('\n');
162
+ }
163
+
164
+ private stopTimers(): void {
165
+ if (this.screenTimer) { clearTimeout(this.screenTimer); this.screenTimer = null; }
166
+ if (this.tickTimer) { clearInterval(this.tickTimer); this.tickTimer = null; }
167
+ }
168
+ }
@@ -0,0 +1,453 @@
1
+ /**
2
+ * SpecCliAdapter — bridges SpecDriver into the daemon's CliAdapter
3
+ * interface so an existing CliProviderInstance can drive a spec-backed
4
+ * provider without rewriting the surrounding session machinery.
5
+ *
6
+ * Translation:
7
+ * spec state.id 'approval' (with modal_buttons that produced a modal)
8
+ * → CliAdapterStatus.status='waiting_approval', activeModal={...}
9
+ * spec state.id 'busy' / any non-decision state with a 'busy' label
10
+ * → status='generating'
11
+ * spec state.id 'idle' or default
12
+ * → status='idle'
13
+ *
14
+ * Methods that the round-3 spec model doesn't have an opinion on
15
+ * (transcript reading, slash commands, history, runtime metadata
16
+ * surfacing) are minimal stubs. They satisfy the daemon's call sites
17
+ * without pretending to implement anything.
18
+ */
19
+ 'use strict';
20
+
21
+ import { SpecDriver, type DashboardEvent } from './driver.js';
22
+ import { loadSpec } from './loader.js';
23
+ import type { CliSpec } from './types.js';
24
+ import type { CliAdapter, CliAdapterStatus } from '../../cli-adapter-types.js';
25
+ import type { ChatMessage } from '../../types.js';
26
+ import type { PtyTransportFactory } from '../../cli-adapters/pty-transport.js';
27
+ import { LOG } from '../../logging/logger.js';
28
+ import {
29
+ buildClaudeInteractiveTuiAnswerSteps,
30
+ buildClaudeInteractiveToolResult,
31
+ detectClaudeAskUserQuestionPromptFromJson,
32
+ detectClaudeAskUserQuestionPromptFromTuiPages,
33
+ type ClaudeInteractiveTuiPage,
34
+ type InteractivePrompt,
35
+ type InteractivePromptResponse,
36
+ } from '../types/interactive-prompt.js';
37
+
38
+ export class SpecCliAdapter implements CliAdapter {
39
+ readonly cliType: string;
40
+ readonly cliName: string;
41
+ readonly workingDir: string;
42
+ /**
43
+ * Marker the daemon's finalization gate checks: `getStatus()` returns
44
+ * `messages: []` by design here (chat history lives in the daemon's
45
+ * native-history pipeline, not the adapter). Without this flag,
46
+ * cli-provider-instance's `missing_final_assistant` gate would stall
47
+ * every turn until the 30s safety timeout because it expects the
48
+ * adapter to surface the final assistant message.
49
+ */
50
+ readonly chatMessagesOwnedExternally = true as const;
51
+
52
+ private driver: SpecDriver;
53
+ private spec: CliSpec;
54
+ private lastEvent: DashboardEvent | null = null;
55
+ private latestState: { id: string; label: string; title: string | null } | null = null;
56
+ private latestModal: { title: string | null; buttons: { index: number; label: string }[] } | null = null;
57
+ private statusCallback: (() => void) | null = null;
58
+ private ptyDataCallback: ((data: string) => void) | null = null;
59
+ private partialResponse = '';
60
+ private activeInteractivePrompt: InteractivePrompt | null = null;
61
+ private interactivePromptTransport: 'stream-json' | 'tui' | null = null;
62
+ private claudeTuiPromptCaptureInFlight = false;
63
+ private jsonLineTail = '';
64
+ private exited = false;
65
+ private spawned = false;
66
+ private providerSessionId: string | undefined;
67
+ /** Wall clock at the moment spawn() ran. Used as the cutoff for
68
+ * native-history file selection so a prior session's transcript
69
+ * can't leak into this session before the agent has written its
70
+ * own records. */
71
+ private spawnedAtMs = 0;
72
+ /** Env vars the daemon set on the spawned child. Mesh coordinator
73
+ * points hermes at a per-coordinator HERMES_HOME so the dashboard's
74
+ * native-history reader needs that override to find the right
75
+ * state.db; without it the reader sees ~/.hermes/state.db which
76
+ * the coordinator-launched hermes never writes to. The choice to
77
+ * redirect HERMES_HOME is a workaround for an unresolved hermes
78
+ * upstream feature gap (see hermes-agent#23130 — runtime-supplied
79
+ * MCP config), so this routing keeps the dashboard honest until
80
+ * hermes ships a runtime MCP override. */
81
+ private spawnedEnv: Record<string, string> = {};
82
+
83
+ constructor(
84
+ specPath: string,
85
+ workingDir: string,
86
+ cliArgs: string[],
87
+ extraEnv: Record<string, string>,
88
+ transportFactory?: PtyTransportFactory,
89
+ ) {
90
+ const res = loadSpec(specPath);
91
+ if (!res.ok) throw new Error(`spec invalid (${specPath}): ${res.errors.join('; ')}`);
92
+ this.spec = res.spec;
93
+ this.cliType = this.spec.id;
94
+ this.cliName = this.spec.name;
95
+ this.workingDir = workingDir;
96
+ this.spawnedEnv = { ...extraEnv };
97
+
98
+ // cli-manager.ts allocates providerSessionId per launch and threads
99
+ // it through resume.newSessionArgs as additional cliArgs (e.g.
100
+ // ["--session-id", "<uuid>"]). We must hand those to SpecDriver
101
+ // so the agent uses the daemon's id, otherwise (claude case) the
102
+ // agent generates its own id and the chat-history pipeline can't
103
+ // pair the on-disk transcript with the live session.
104
+ this.driver = new SpecDriver({
105
+ specPath,
106
+ workingDir,
107
+ extraEnv,
108
+ hotReload: true,
109
+ emitTrace: false,
110
+ transportFactory,
111
+ extraCliArgs: cliArgs,
112
+ });
113
+ this.driver.subscribe((ev) => this.handleEvent(ev));
114
+ }
115
+
116
+ async spawn(): Promise<void> {
117
+ if (this.spawned) return;
118
+ this.driver.start();
119
+ this.spawned = true;
120
+ this.spawnedAtMs = Date.now();
121
+ }
122
+
123
+ async sendMessage(text: string): Promise<void> {
124
+ // Content-free at info — the prompt body is user data.
125
+ LOG.info('SpecAdapter', `[${this.cliType}] sendMessage(len=${text.length})`);
126
+ LOG.debug('SpecAdapter', `[${this.cliType}] sendMessage body=${JSON.stringify(text.slice(0, 80))}${text.length > 80 ? '…' : ''}`);
127
+ this.driver.dispatch({ kind: 'send_message', text });
128
+ }
129
+
130
+ getStatus(): CliAdapterStatus {
131
+ if (this.exited) return { status: 'stopped', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt };
132
+ if (!this.spawned) return { status: 'starting', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt };
133
+
134
+ // Refresh native history lazily — the watch_path is cheap to stat,
135
+ // but parsing a full session.jsonl every call would be wasteful.
136
+ this.maybeRefreshNativeHistory();
137
+
138
+ const state = this.latestState;
139
+ if (!state) return { status: 'starting', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt };
140
+
141
+ const modal = this.latestModal;
142
+ const lc = state.id.toLowerCase();
143
+ if (modal) {
144
+ return {
145
+ status: 'waiting_approval',
146
+ messages: [],
147
+ activeModal: {
148
+ message: modal.title ?? state.label,
149
+ buttons: modal.buttons.map(b => b.label),
150
+ },
151
+ activeInteractivePrompt: this.activeInteractivePrompt,
152
+ };
153
+ }
154
+ if (lc === 'busy' || lc === 'generating') {
155
+ return { status: 'generating', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt };
156
+ }
157
+ return { status: 'idle', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt };
158
+ }
159
+
160
+ private maybeRefreshNativeHistory(): void {
161
+ // Native history is now sourced by daemon's chat-history pipeline
162
+ // (which calls provider.scripts.readNativeHistory wired by
163
+ // provider-loader). SpecCliAdapter no longer polls or caches.
164
+ }
165
+
166
+ getScriptParsedStatus(): unknown {
167
+ return this.getStatus();
168
+ }
169
+
170
+ getPartialResponse(): string {
171
+ return this.partialResponse;
172
+ }
173
+
174
+ shutdown(): void {
175
+ try { this.driver.dispatch({ kind: 'shutdown' }); } catch { /* ignore */ }
176
+ }
177
+
178
+ cancel(): void {
179
+ try { this.driver.dispatch({ kind: 'cancel' }); } catch { /* ignore */ }
180
+ }
181
+
182
+ isProcessing(): boolean {
183
+ return this.getStatus().status === 'generating';
184
+ }
185
+
186
+ isReady(): boolean {
187
+ return this.spawned && !this.exited;
188
+ }
189
+
190
+ setOnStatusChange(cb: () => void): void {
191
+ this.statusCallback = cb;
192
+ }
193
+
194
+ setOnPtyData(cb: (data: string) => void): void {
195
+ this.ptyDataCallback = cb;
196
+ }
197
+
198
+ writeRaw(data: string): void {
199
+ // Raw pty input — typed characters, escape codes, arrow keys —
200
+ // goes straight to the underlying terminal. send_message would
201
+ // append submit_key after every chunk, which is why typing in
202
+ // the dashboard terminal felt like "enter on every keystroke".
203
+ this.driver.dispatch({ kind: 'pty_write', data });
204
+ }
205
+
206
+ resize(cols: number, rows: number): void {
207
+ this.driver.dispatch({ kind: 'resize', cols, rows });
208
+ }
209
+
210
+ resolveModal(buttonIndex: number): void {
211
+ // CliAdapter buttonIndex is 0-based; spec buttons are 1-based.
212
+ this.driver.dispatch({ kind: 'click_modal_button', index: buttonIndex + 1 });
213
+ }
214
+
215
+ async resolveAction(data: unknown): Promise<void> {
216
+ const args = (data && typeof data === 'object') ? (data as any) : {};
217
+ const explicitIndex = typeof args.buttonIndex === 'number' ? args.buttonIndex : -1;
218
+ if (explicitIndex >= 0) { this.resolveModal(explicitIndex); return; }
219
+ const action = typeof args.action === 'string' ? args.action : 'approve';
220
+ const buttons = this.latestModal?.buttons ?? [];
221
+ if (buttons.length === 0) return;
222
+ let target = -1;
223
+ if (action === 'reject' || action === 'deny') {
224
+ target = buttons.findIndex(b => /^(no|deny|reject|cancel)\b/i.test(b.label));
225
+ if (target < 0) target = buttons.length - 1;
226
+ } else {
227
+ target = buttons.findIndex(b => /^(yes|allow|approve|accept|continue|proceed|update)\b/i.test(b.label));
228
+ if (target < 0) target = 0;
229
+ }
230
+ this.resolveModal(target);
231
+ }
232
+
233
+ async setInteractivePromptResponse(response: InteractivePromptResponse): Promise<void> {
234
+ const prompt = this.activeInteractivePrompt;
235
+ if (!prompt || prompt.promptId !== response.promptId) throw new Error('Interactive prompt response does not match active prompt');
236
+ if (this.cliType !== 'claude-cli') return;
237
+ if (this.interactivePromptTransport === 'tui') {
238
+ const steps = buildClaudeInteractiveTuiAnswerSteps(prompt, response);
239
+ for (const step of steps) {
240
+ this.driver.dispatch({ kind: 'pty_write', data: step });
241
+ await new Promise(resolve => setTimeout(resolve, 180));
242
+ }
243
+ } else {
244
+ this.driver.dispatch({ kind: 'pty_write', data: `${buildClaudeInteractiveToolResult(response)}\n` });
245
+ }
246
+ this.activeInteractivePrompt = null;
247
+ this.interactivePromptTransport = null;
248
+ this.statusCallback?.();
249
+ }
250
+
251
+ isApprovalRecentlyResolved(): boolean { return false; }
252
+ clearHistory(): void { /* no transcript buffer yet */ }
253
+ updateRuntimeSettings(): void { /* no runtime settings in spec model yet */ }
254
+ setServerConn(): void { /* server conn unused by SpecDriver */ }
255
+ /**
256
+ * Map an invokeScript(name, args) call onto a control_bar entry.
257
+ *
258
+ * scriptName is matched against control.id. The control's action.type
259
+ * drives the dispatch:
260
+ *
261
+ * send_keys → click_control (e.g. stop)
262
+ * open_picker → click_control then resolve when extract_choices
263
+ * surface; choice index comes from args.choiceIndex
264
+ * or args.choice (string label match), defaulting to 0
265
+ * attach_image → attach_image dispatch; expects args.blob (data url
266
+ * or base64) and args.mime
267
+ *
268
+ * Callers that pass an unknown control id get a { not_found } response.
269
+ * No control matched, no driver call — keeps the surface honest.
270
+ */
271
+ invokeScript(scriptName: string, args?: Record<string, unknown>): Promise<unknown> {
272
+ const controls = this.spec.control_bar ?? [];
273
+ const ctl = controls.find(c => c.id === scriptName);
274
+ if (!ctl) {
275
+ return Promise.resolve({ ok: false, error: `unknown control: ${scriptName}` });
276
+ }
277
+ // Args may arrive as either { blob, mime } (direct invocation) or
278
+ // { params: { blob, mime } } (when the dashboard wraps script args
279
+ // in a params bag). Look at both.
280
+ const flat: Record<string, unknown> = { ...(args || {}) };
281
+ if (args && typeof args.params === 'object' && args.params) {
282
+ Object.assign(flat, args.params as Record<string, unknown>);
283
+ }
284
+ const action = ctl.action;
285
+ if (action.type === 'attach_image') {
286
+ const blob = typeof flat.blob === 'string' ? flat.blob : '';
287
+ const mime = typeof flat.mime === 'string' ? flat.mime : 'image/png';
288
+ if (!blob) return Promise.resolve({ ok: false, error: 'attach_image requires args.blob (base64 or data URL)' });
289
+ this.driver.dispatch({ kind: 'attach_image', blob, mime });
290
+ return Promise.resolve({ ok: true, effects: [{ type: 'attached_image', controlId: ctl.id }] });
291
+ }
292
+ // send_keys + open_picker both route through click_control. For
293
+ // open_picker the dashboard sees the picker modal arrive via a
294
+ // state_changed event, then submits the choice using
295
+ // resolveModal/click_modal_button. invokeScript's synchronous
296
+ // return is just an acknowledgement that the trigger fired.
297
+ this.driver.dispatch({ kind: 'click_control', control_id: ctl.id, payload: flat });
298
+ const effects: { type: string; controlId: string }[] = [];
299
+ if (action.type === 'open_picker') effects.push({ type: 'opened_picker', controlId: ctl.id });
300
+ else if (action.type === 'send_keys') effects.push({ type: 'sent_keys', controlId: ctl.id });
301
+ return Promise.resolve({ ok: true, effects });
302
+ }
303
+ getDebugSnapshot(): unknown {
304
+ let screen = '';
305
+ let sections: Record<string, string> | undefined;
306
+ try {
307
+ screen = this.driver.snapshot();
308
+ const lines = screen.split('\n');
309
+ sections = {};
310
+ for (const sec of this.spec.layout?.sections ?? []) {
311
+ const from = (sec as any).from_top;
312
+ const fromBottom = (sec as any).from_bottom;
313
+ let start = 0;
314
+ let end = lines.length;
315
+ if (typeof from === 'number') start = Math.max(0, from);
316
+ else if (typeof fromBottom === 'number') start = Math.max(0, lines.length - fromBottom);
317
+ const until = (sec as any).until;
318
+ if (until && typeof until === 'object' && typeof until.section === 'string') {
319
+ const ref = (this.spec.layout?.sections ?? []).find((s: any) => s.id === until.section) as any;
320
+ if (ref && typeof ref.from_bottom === 'number') end = Math.max(start, lines.length - ref.from_bottom);
321
+ }
322
+ sections[(sec as any).id] = lines.slice(start, end).join('\n');
323
+ }
324
+ } catch { /* best-effort */ }
325
+ return {
326
+ cliType: this.cliType,
327
+ spec_id: this.spec.id,
328
+ current_state: this.latestState,
329
+ current_modal: this.latestModal,
330
+ activeInteractivePrompt: this.activeInteractivePrompt,
331
+ exited: this.exited,
332
+ screen,
333
+ sections,
334
+ };
335
+ }
336
+ getRuntimeMetadata(): unknown {
337
+ return {
338
+ runtimeId: this.spec.id,
339
+ runtimeKey: this.spec.id,
340
+ displayName: this.spec.name,
341
+ spawnedAtMs: this.spawnedAtMs,
342
+ spawnedEnv: this.spawnedEnv,
343
+ };
344
+ }
345
+ updateRuntimeMeta(meta?: Record<string, unknown>): void {
346
+ if (meta && typeof meta.providerSessionId === 'string') {
347
+ this.providerSessionId = meta.providerSessionId;
348
+ }
349
+ }
350
+ refreshProviderDefinition(): void { /* hot reload handled by SpecDriver fs.watch */ }
351
+
352
+ private handleEvent(ev: DashboardEvent): void {
353
+ this.lastEvent = ev;
354
+ switch (ev.kind) {
355
+ case 'state_changed':
356
+ this.latestState = ev.state;
357
+ this.latestModal = ev.modal;
358
+ // info-level keeps only spec-defined identifiers (state.id /
359
+ // state.label / button count). The extracted title can carry
360
+ // user data — file paths, command text, ticket titles — so
361
+ // it stays at debug.
362
+ LOG.info('SpecAdapter', `[${this.cliType}] state=${ev.state.id} (${ev.state.label}) modal=${ev.modal ? `${ev.modal.buttons.length}-buttons` : 'none'}`);
363
+ if (ev.state.title) {
364
+ LOG.debug('SpecAdapter', `[${this.cliType}] state.title=${JSON.stringify(ev.state.title)}`);
365
+ }
366
+ this.maybeCaptureClaudeTuiPrompt();
367
+ this.statusCallback?.();
368
+ return;
369
+ case 'pty_data':
370
+ this.detectInteractivePromptFromPtyChunk(ev.chunk);
371
+ this.maybeCaptureClaudeTuiPrompt();
372
+ try { this.ptyDataCallback?.(ev.chunk); } catch { /* ignore */ }
373
+ return;
374
+ case 'exit':
375
+ this.exited = true;
376
+ this.statusCallback?.();
377
+ return;
378
+ case 'spec_error':
379
+ LOG.warn('SpecAdapter', `[${this.cliType}] spec reload error: ${ev.errors.join('; ')}`);
380
+ return;
381
+ default:
382
+ return;
383
+ }
384
+ }
385
+
386
+ private detectInteractivePromptFromPtyChunk(chunk: string): void {
387
+ if (this.cliType !== 'claude-cli' || !chunk) return;
388
+ this.jsonLineTail += chunk;
389
+ if (this.jsonLineTail.length > 64 * 1024) this.jsonLineTail = this.jsonLineTail.slice(-64 * 1024);
390
+ const lines = this.jsonLineTail.split(/\r?\n/);
391
+ this.jsonLineTail = lines.pop() || '';
392
+ for (const line of lines) {
393
+ const trimmed = line.trim();
394
+ if (!trimmed.startsWith('{') || !trimmed.includes('AskUserQuestion')) continue;
395
+ try {
396
+ const parsed = JSON.parse(trimmed);
397
+ const prompt = detectClaudeAskUserQuestionPromptFromJson(parsed, this.cliType);
398
+ if (!prompt) continue;
399
+ this.activeInteractivePrompt = prompt;
400
+ this.interactivePromptTransport = 'stream-json';
401
+ this.statusCallback?.();
402
+ } catch {
403
+ // PTY output is not guaranteed to be machine JSON.
404
+ }
405
+ }
406
+ }
407
+
408
+ private maybeCaptureClaudeTuiPrompt(): void {
409
+ if (this.cliType !== 'claude-cli'
410
+ || this.activeInteractivePrompt
411
+ || this.claudeTuiPromptCaptureInFlight) return;
412
+ const screenText = this.driver.snapshot();
413
+ const headers = this.readClaudeTuiHeaders(screenText);
414
+ if (headers.length === 0 || !screenText.includes('Enter to select')) return;
415
+ this.claudeTuiPromptCaptureInFlight = true;
416
+ void this.captureClaudeTuiPrompt(screenText, headers).finally(() => {
417
+ this.claudeTuiPromptCaptureInFlight = false;
418
+ });
419
+ }
420
+
421
+ private readClaudeTuiHeaders(screenText: string): string[] {
422
+ const navLine = screenText.split(/\r?\n/).find(line => line.includes('✔ Submit') && /[☐☒]/.test(line));
423
+ if (!navLine) return [];
424
+ const headers: string[] = [];
425
+ for (const match of navLine.matchAll(/[☐☒]\s+(.+?)(?=\s+[☐☒]|\s+✔\s+Submit)/g)) {
426
+ const header = match[1]?.trim();
427
+ if (header) headers.push(header);
428
+ }
429
+ return headers;
430
+ }
431
+
432
+ private async captureClaudeTuiPrompt(firstScreen: string, headers: string[]): Promise<void> {
433
+ const pages: ClaudeInteractiveTuiPage[] = [{ screenText: firstScreen, header: headers[0] }];
434
+ for (let index = 1; index < headers.length; index += 1) {
435
+ this.driver.dispatch({ kind: 'pty_write', data: '\t' });
436
+ await new Promise(resolve => setTimeout(resolve, 120));
437
+ pages.push({ screenText: this.driver.snapshot(), header: headers[index] });
438
+ }
439
+ for (let index = headers.length - 1; index > 0; index -= 1) {
440
+ this.driver.dispatch({ kind: 'pty_write', data: '\x1b[Z' });
441
+ await new Promise(resolve => setTimeout(resolve, 80));
442
+ }
443
+
444
+ const prompt = detectClaudeAskUserQuestionPromptFromTuiPages(pages, {
445
+ promptId: `ask-user-${this.providerSessionId || 'claude'}-${Date.now()}`,
446
+ providerType: this.cliType,
447
+ });
448
+ if (!prompt) return;
449
+ this.activeInteractivePrompt = prompt;
450
+ this.interactivePromptTransport = 'tui';
451
+ this.statusCallback?.();
452
+ }
453
+ }