@adhdev/daemon-core 0.9.82-rc.22 → 0.9.82-rc.220

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 (277) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +1 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/chat/source-machine.d.ts +166 -0
  4. package/dist/chat/source-resolver.d.ts +104 -0
  5. package/dist/chat/subscription-updates.d.ts +1 -0
  6. package/dist/cli-adapter-types.d.ts +23 -2
  7. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  8. package/dist/cli-adapters/cli-state-engine.d.ts +178 -0
  9. package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
  10. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  11. package/dist/cli-adapters/provider-cli-shared.d.ts +29 -0
  12. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  13. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +3 -3
  14. package/dist/cli-adapters/terminal-backends/types.d.ts +1 -2
  15. package/dist/cli-adapters/terminal-screen.d.ts +2 -11
  16. package/dist/commands/cli-manager.d.ts +2 -1
  17. package/dist/commands/handler.d.ts +110 -0
  18. package/dist/commands/mesh-coordinator.d.ts +85 -1
  19. package/dist/commands/router.d.ts +32 -1
  20. package/dist/config/chat-history.d.ts +9 -0
  21. package/dist/config/config.d.ts +5 -0
  22. package/dist/config/mesh-config.d.ts +72 -1
  23. package/dist/git/git-commands.d.ts +9 -1
  24. package/dist/git/git-diff.d.ts +6 -0
  25. package/dist/git/git-types.d.ts +2 -0
  26. package/dist/index.d.ts +46 -11
  27. package/dist/index.js +36322 -15614
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +36182 -15568
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/installer.d.ts +1 -4
  32. package/dist/ipc/local-ipc-server.d.ts +91 -0
  33. package/dist/launch.d.ts +1 -1
  34. package/dist/logging/async-batch-writer.d.ts +10 -0
  35. package/dist/mesh/contracts.d.ts +164 -0
  36. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  37. package/dist/mesh/coordinator-registry.d.ts +59 -0
  38. package/dist/mesh/mesh-active-work.d.ts +90 -0
  39. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  40. package/dist/mesh/mesh-events-coordinator.d.ts +151 -0
  41. package/dist/mesh/mesh-events-pending.d.ts +33 -0
  42. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  43. package/dist/mesh/mesh-events-utils.d.ts +14 -0
  44. package/dist/mesh/mesh-events.d.ts +5 -40
  45. package/dist/mesh/mesh-fast-forward.d.ts +41 -0
  46. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  47. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  48. package/dist/mesh/mesh-ledger.d.ts +77 -1
  49. package/dist/mesh/mesh-missions.d.ts +58 -0
  50. package/dist/mesh/mesh-refine-status.d.ts +26 -0
  51. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  52. package/dist/mesh/mesh-runtime-store.d.ts +324 -0
  53. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  54. package/dist/mesh/mesh-work-queue.d.ts +137 -6
  55. package/dist/mesh/preview-freshness.d.ts +18 -0
  56. package/dist/mesh/refine-config.d.ts +215 -0
  57. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  58. package/dist/providers/acp-provider-instance.d.ts +2 -0
  59. package/dist/providers/approval-utils.d.ts +13 -0
  60. package/dist/providers/cli-provider-instance.d.ts +39 -3
  61. package/dist/providers/contracts.d.ts +130 -6
  62. package/dist/providers/external-sources.d.ts +71 -0
  63. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  64. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  65. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  66. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  67. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  68. package/dist/providers/native-history/index.d.ts +13 -0
  69. package/dist/providers/provider-instance-manager.d.ts +12 -0
  70. package/dist/providers/provider-instance.d.ts +13 -1
  71. package/dist/providers/provider-loader.d.ts +26 -4
  72. package/dist/providers/provider-trust.d.ts +31 -0
  73. package/dist/providers/read-chat-contract.d.ts +29 -0
  74. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  75. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  76. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  77. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  78. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  79. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  80. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  81. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  82. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  83. package/dist/providers/sdk/v1/index.d.ts +30 -0
  84. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  85. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  86. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  87. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  88. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  89. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  90. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  91. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  92. package/dist/providers/spec/adapter.d.ts +52 -0
  93. package/dist/providers/spec/cli-adapter.d.ts +102 -0
  94. package/dist/providers/spec/driver.d.ts +287 -0
  95. package/dist/providers/spec/evaluator.d.ts +70 -0
  96. package/dist/providers/spec/fsm-driver.d.ts +110 -0
  97. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  98. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  99. package/dist/providers/spec/fsm-types.d.ts +91 -0
  100. package/dist/providers/spec/loader.d.ts +15 -0
  101. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  102. package/dist/providers/spec/route.d.ts +4 -0
  103. package/dist/providers/spec/schema.gen.d.ts +2039 -0
  104. package/dist/providers/spec/types.d.ts +311 -0
  105. package/dist/providers/transcript-v2.d.ts +176 -0
  106. package/dist/providers/types/interactive-prompt.d.ts +48 -0
  107. package/dist/repo-mesh-types.d.ts +126 -1
  108. package/dist/sessions/registry.d.ts +3 -0
  109. package/dist/shared-types-extra.d.ts +2 -4
  110. package/dist/shared-types.d.ts +42 -1
  111. package/dist/status/normalize.d.ts +1 -1
  112. package/dist/status/normalize.js +1 -0
  113. package/dist/status/normalize.js.map +1 -1
  114. package/dist/status/normalize.mjs +1 -0
  115. package/dist/status/normalize.mjs.map +1 -1
  116. package/dist/status/reporter.d.ts +2 -0
  117. package/dist/status/snapshot.d.ts +1 -0
  118. package/dist/types.d.ts +5 -0
  119. package/package.json +6 -3
  120. package/src/agent-stream/poller.ts +2 -3
  121. package/src/boot/daemon-lifecycle.ts +22 -10
  122. package/src/boot/process-hardening.ts +89 -0
  123. package/src/chat/source-machine.ts +534 -0
  124. package/src/chat/source-resolver.ts +0 -0
  125. package/src/chat/subscription-updates.ts +20 -1
  126. package/src/cli-adapter-types.d.ts +1 -0
  127. package/src/cli-adapter-types.ts +22 -2
  128. package/src/cli-adapters/cli-script-runner.ts +421 -0
  129. package/src/cli-adapters/cli-state-engine.ts +1162 -0
  130. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  131. package/src/cli-adapters/provider-cli-adapter.ts +673 -1139
  132. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  133. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  134. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  135. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  136. package/src/cli-adapters/provider-cli-shared.ts +59 -11
  137. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  138. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +35 -29
  139. package/src/cli-adapters/terminal-backends/types.ts +1 -3
  140. package/src/cli-adapters/terminal-screen.ts +11 -81
  141. package/src/commands/chat-commands.ts +1787 -60
  142. package/src/commands/cli-manager.ts +283 -14
  143. package/src/commands/handler.ts +809 -2
  144. package/src/commands/mesh-coordinator.ts +332 -122
  145. package/src/commands/router.ts +4369 -558
  146. package/src/config/chat-history.ts +95 -24
  147. package/src/config/config.ts +12 -0
  148. package/src/config/mesh-config.ts +303 -3
  149. package/src/config/recent-activity.ts +8 -2
  150. package/src/daemon/dev-auto-implement.ts +3 -2
  151. package/src/daemon/dev-cli-debug.ts +10 -1
  152. package/src/detection/ide-detector.ts +26 -16
  153. package/src/git/git-commands.ts +42 -12
  154. package/src/git/git-diff.ts +53 -0
  155. package/src/git/git-status.ts +35 -6
  156. package/src/git/git-types.ts +2 -0
  157. package/src/git/git-worktree.ts +8 -1
  158. package/src/index.ts +126 -10
  159. package/src/installer.d.ts +1 -1
  160. package/src/installer.ts +8 -6
  161. package/src/ipc/local-ipc-server.ts +278 -0
  162. package/src/launch.d.ts +1 -1
  163. package/src/launch.ts +37 -28
  164. package/src/logging/async-batch-writer.ts +55 -0
  165. package/src/logging/logger.ts +2 -1
  166. package/src/mesh/contracts.ts +329 -0
  167. package/src/mesh/coordinator-prompt.ts +218 -31
  168. package/src/mesh/coordinator-registry.ts +121 -0
  169. package/src/mesh/mesh-active-work.ts +437 -0
  170. package/src/mesh/mesh-delivery-policy.ts +315 -0
  171. package/src/mesh/mesh-events-coordinator.ts +1447 -0
  172. package/src/mesh/mesh-events-pending.ts +371 -0
  173. package/src/mesh/mesh-events-stale.ts +283 -0
  174. package/src/mesh/mesh-events-utils.ts +166 -0
  175. package/src/mesh/mesh-events.ts +24 -908
  176. package/src/mesh/mesh-fast-forward.ts +438 -0
  177. package/src/mesh/mesh-host-ownership.ts +73 -0
  178. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  179. package/src/mesh/mesh-ledger.ts +587 -102
  180. package/src/mesh/mesh-missions.ts +151 -0
  181. package/src/mesh/mesh-refine-status.ts +144 -0
  182. package/src/mesh/mesh-review-inbox.ts +307 -0
  183. package/src/mesh/mesh-runtime-store.ts +1305 -0
  184. package/src/mesh/mesh-task-stats.ts +154 -0
  185. package/src/mesh/mesh-work-queue.ts +490 -166
  186. package/src/mesh/preview-freshness.ts +118 -0
  187. package/src/mesh/refine-config.ts +403 -0
  188. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  189. package/src/providers/acp-provider-instance.ts +15 -1
  190. package/src/providers/approval-utils.d.ts +4 -0
  191. package/src/providers/approval-utils.ts +47 -5
  192. package/src/providers/chat-message-normalization.ts +4 -11
  193. package/src/providers/cli-provider-instance.ts +834 -64
  194. package/src/providers/contracts.d.ts +55 -0
  195. package/src/providers/contracts.ts +141 -6
  196. package/src/providers/external-sources.ts +218 -0
  197. package/src/providers/ide-provider-instance.ts +19 -5
  198. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  199. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  200. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  201. package/src/providers/native-history/dispatcher.ts +340 -0
  202. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  203. package/src/providers/native-history/index.ts +30 -0
  204. package/src/providers/provider-instance-manager.ts +30 -0
  205. package/src/providers/provider-instance.ts +10 -1
  206. package/src/providers/provider-loader.ts +592 -50
  207. package/src/providers/provider-schema.ts +87 -14
  208. package/src/providers/provider-trust.ts +114 -0
  209. package/src/providers/read-chat-contract.ts +76 -16
  210. package/src/providers/sdk/README.md +49 -0
  211. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  212. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  213. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  214. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  215. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  216. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  217. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  218. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  219. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  220. package/src/providers/sdk/v1/index.ts +152 -0
  221. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  222. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  223. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  224. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  225. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  226. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  227. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  228. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  229. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  230. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  231. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  232. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  233. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  234. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  235. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  236. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  237. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  238. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  239. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  240. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  241. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  242. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  243. package/src/providers/sdk/v1/validators/index.ts +19 -0
  244. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  245. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  246. package/src/providers/spec/adapter.ts +138 -0
  247. package/src/providers/spec/cli-adapter.ts +674 -0
  248. package/src/providers/spec/driver.ts +1082 -0
  249. package/src/providers/spec/evaluator.ts +604 -0
  250. package/src/providers/spec/fsm-driver.ts +663 -0
  251. package/src/providers/spec/fsm-evaluator.ts +255 -0
  252. package/src/providers/spec/fsm-loader.ts +102 -0
  253. package/src/providers/spec/fsm-types.ts +184 -0
  254. package/src/providers/spec/loader.ts +325 -0
  255. package/src/providers/spec/native-history-executor.ts +939 -0
  256. package/src/providers/spec/route.ts +51 -0
  257. package/src/providers/spec/schema.gen.ts +693 -0
  258. package/src/providers/spec/schema.json +342 -0
  259. package/src/providers/spec/types.ts +365 -0
  260. package/src/providers/transcript-v2.ts +567 -0
  261. package/src/providers/types/interactive-prompt.ts +425 -0
  262. package/src/providers/version-archive.ts +38 -20
  263. package/src/repo-mesh-types.ts +138 -1
  264. package/src/sessions/registry.ts +3 -0
  265. package/src/shared-types-extra.ts +2 -4
  266. package/src/shared-types.ts +45 -1
  267. package/src/status/builders.ts +24 -6
  268. package/src/status/normalize.ts +2 -0
  269. package/src/status/reporter.ts +15 -0
  270. package/src/status/snapshot.ts +84 -25
  271. package/src/system/host-memory.ts +29 -12
  272. package/src/types.ts +5 -0
  273. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  274. package/dist/mesh/mesh-sync.d.ts +0 -53
  275. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  276. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  277. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,674 @@
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, type ISpecDriver } from './driver.js';
22
+ import { FsmDriver } from './fsm-driver.js';
23
+ import { executeNativeHistory } from './native-history-executor.js';
24
+ import { loadSpec } from './loader.js';
25
+ import * as fs from 'node:fs';
26
+ import type { CliSpec } from './types.js';
27
+ import type { NativeHistoryConfig, Control } from './types.js';
28
+ import type { CliAdapter, CliAdapterStatus } from '../../cli-adapter-types.js';
29
+ import type { ChatMessage } from '../../types.js';
30
+ import type { PtyTransportFactory } from '../../cli-adapters/pty-transport.js';
31
+ import { LOG } from '../../logging/logger.js';
32
+ import {
33
+ buildClaudeInteractiveTuiAnswerSteps,
34
+ buildClaudeInteractiveToolResult,
35
+ detectClaudeAskUserQuestionPromptFromJson,
36
+ detectClaudeAskUserQuestionPromptFromTuiPages,
37
+ type ClaudeInteractiveTuiPage,
38
+ type InteractivePrompt,
39
+ type InteractivePromptResponse,
40
+ } from '../types/interactive-prompt.js';
41
+
42
+ /** Peek at the spec's $schema to choose the driver. Cheap header read. */
43
+ function detectV4Schema(specPath: string): boolean {
44
+ try {
45
+ const raw = JSON.parse(fs.readFileSync(specPath, 'utf8'));
46
+ return raw?.$schema === 'adhdev:cli/spec@4';
47
+ } catch { return false; }
48
+ }
49
+
50
+ function stripAnsi(text: string): string {
51
+ // eslint-disable-next-line no-control-regex
52
+ return String(text || '')
53
+ .replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, '')
54
+ .replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, '')
55
+ .replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, '');
56
+ }
57
+
58
+ export class SpecCliAdapter implements CliAdapter {
59
+ readonly cliType: string;
60
+ readonly cliName: string;
61
+ readonly workingDir: string;
62
+ /**
63
+ * Marker the daemon's finalization gate checks: `getStatus()` returns
64
+ * `messages: []` by design here (chat history lives in the daemon's
65
+ * native-history pipeline, not the adapter). Without this flag,
66
+ * cli-provider-instance's `missing_final_assistant` gate would stall
67
+ * every turn until the 30s safety timeout because it expects the
68
+ * adapter to surface the final assistant message.
69
+ */
70
+ readonly chatMessagesOwnedExternally = true as const;
71
+
72
+ private driver: ISpecDriver;
73
+ /** Common spec fields the adapter reads, present in both v3 and v4. */
74
+ private spec: {
75
+ id: string;
76
+ name: string;
77
+ control_bar?: Control[];
78
+ native_history?: NativeHistoryConfig;
79
+ };
80
+ private lastEvent: DashboardEvent | null = null;
81
+ private latestState: { id: string; label: string; title: string | null } | null = null;
82
+ private latestModal: { title: string | null; buttons: { index: number; label: string }[] } | null = null;
83
+ private statusCallback: (() => void) | null = null;
84
+ private ptyDataCallback: ((data: string) => void) | null = null;
85
+ private partialResponse = '';
86
+ private activeInteractivePrompt: InteractivePrompt | null = null;
87
+ private interactivePromptTransport: 'stream-json' | 'tui' | null = null;
88
+ private claudeTuiPromptCaptureInFlight = false;
89
+ private jsonLineTail = '';
90
+ private exited = false;
91
+ private spawned = false;
92
+ private providerSessionId: string | undefined;
93
+ /** Wall clock at the moment spawn() ran. Used as the cutoff for
94
+ * native-history file selection so a prior session's transcript
95
+ * can't leak into this session before the agent has written its
96
+ * own records. */
97
+ private spawnedAtMs = 0;
98
+ /** Env vars the daemon set on the spawned child. Mesh coordinator
99
+ * points hermes at a per-coordinator HERMES_HOME so the dashboard's
100
+ * native-history reader needs that override to find the right
101
+ * state.db; without it the reader sees ~/.hermes/state.db which
102
+ * the coordinator-launched hermes never writes to. The choice to
103
+ * redirect HERMES_HOME is a workaround for an unresolved hermes
104
+ * upstream feature gap (see hermes-agent#23130 — runtime-supplied
105
+ * MCP config), so this routing keeps the dashboard honest until
106
+ * hermes ships a runtime MCP override. */
107
+ private spawnedEnv: Record<string, string> = {};
108
+
109
+ constructor(
110
+ specPath: string,
111
+ workingDir: string,
112
+ cliArgs: string[],
113
+ extraEnv: Record<string, string>,
114
+ transportFactory?: PtyTransportFactory,
115
+ ) {
116
+ // Detect the spec schema version up front. v4 (FSM) and v3 (debounce)
117
+ // use different drivers behind the same ISpecDriver interface.
118
+ const isV4 = detectV4Schema(specPath);
119
+
120
+ if (isV4) {
121
+ // v4 loader runs inside FsmDriver; read the common header fields
122
+ // we need here directly from the parsed JSON.
123
+ const raw = JSON.parse(fs.readFileSync(specPath, 'utf8'));
124
+ this.spec = {
125
+ id: raw.id,
126
+ name: raw.name,
127
+ control_bar: raw.control_bar,
128
+ native_history: raw.native_history,
129
+ };
130
+ } else {
131
+ const res = loadSpec(specPath);
132
+ if (!res.ok) throw new Error(`spec invalid (${specPath}): ${res.errors.join('; ')}`);
133
+ this.spec = {
134
+ id: res.spec.id,
135
+ name: res.spec.name,
136
+ control_bar: res.spec.control_bar,
137
+ native_history: res.spec.native_history,
138
+ };
139
+ }
140
+ this.cliType = this.spec.id;
141
+ this.cliName = this.spec.name;
142
+ this.workingDir = workingDir;
143
+ this.spawnedEnv = { ...extraEnv };
144
+
145
+ // cli-manager.ts allocates providerSessionId per launch and threads
146
+ // it through resume.newSessionArgs as additional cliArgs (e.g.
147
+ // ["--session-id", "<uuid>"]). We must hand those to the driver
148
+ // so the agent uses the daemon's id, otherwise (claude case) the
149
+ // agent generates its own id and the chat-history pipeline can't
150
+ // pair the on-disk transcript with the live session.
151
+ const driverOpts = {
152
+ specPath,
153
+ workingDir,
154
+ extraEnv,
155
+ hotReload: true,
156
+ emitTrace: false,
157
+ transportFactory,
158
+ extraCliArgs: cliArgs,
159
+ };
160
+ this.driver = isV4 ? new FsmDriver(driverOpts) : new SpecDriver(driverOpts);
161
+ this.driver.subscribe((ev) => this.handleEvent(ev));
162
+ }
163
+
164
+ async spawn(): Promise<void> {
165
+ if (this.spawned) return;
166
+ this.driver.start();
167
+ this.spawned = true;
168
+ this.spawnedAtMs = Date.now();
169
+ }
170
+
171
+ async sendMessage(text: string): Promise<void> {
172
+ // Content-free at info — the prompt body is user data.
173
+ LOG.info('SpecAdapter', `[${this.cliType}] sendMessage(len=${text.length})`);
174
+ LOG.debug('SpecAdapter', `[${this.cliType}] sendMessage body=${JSON.stringify(text.slice(0, 80))}${text.length > 80 ? '…' : ''}`);
175
+ this.driver.dispatch({ kind: 'send_message', text });
176
+ }
177
+
178
+ getStatus(): CliAdapterStatus {
179
+ const sessionFields = this.providerSessionId ? { providerSessionId: this.providerSessionId } : {};
180
+ if (this.exited) return { status: 'stopped', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
181
+ if (!this.spawned) return { status: 'starting', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
182
+
183
+ // Refresh native history lazily — the watch_path is cheap to stat,
184
+ // but parsing a full session.jsonl every call would be wasteful.
185
+ this.maybeRefreshNativeHistory();
186
+
187
+ const state = this.latestState;
188
+ if (!state) return { status: 'starting', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
189
+
190
+ const modal = this.latestModal;
191
+ const lc = state.id.toLowerCase();
192
+ if (modal) {
193
+ return {
194
+ status: 'waiting_approval',
195
+ messages: [],
196
+ activeModal: {
197
+ message: modal.title ?? state.label,
198
+ buttons: modal.buttons.map(b => b.label),
199
+ },
200
+ activeInteractivePrompt: this.activeInteractivePrompt,
201
+ ...sessionFields,
202
+ };
203
+ }
204
+ if (lc === 'busy' || lc === 'generating') {
205
+ return { status: 'generating', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
206
+ }
207
+ return { status: 'idle', messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
208
+ }
209
+
210
+ private maybeRefreshNativeHistory(): void {
211
+ // Native history is now sourced by daemon's chat-history pipeline
212
+ // (which calls provider.scripts.readNativeHistory wired by
213
+ // provider-loader). SpecCliAdapter no longer polls or caches.
214
+ }
215
+
216
+ getScriptParsedStatus(): unknown {
217
+ const providerSessionId = this.extractProviderSessionIdFromScreen();
218
+ if (providerSessionId) this.providerSessionId = providerSessionId;
219
+ const status = this.getStatus();
220
+ return {
221
+ ...status,
222
+ messages: this.readClaudeScreenAssistantMessages(),
223
+ ...(this.providerSessionId ? { providerSessionId: this.providerSessionId } : {}),
224
+ };
225
+ }
226
+
227
+ getPartialResponse(): string {
228
+ return this.partialResponse;
229
+ }
230
+
231
+ shutdown(): void {
232
+ try { this.driver.dispatch({ kind: 'shutdown' }); } catch { /* ignore */ }
233
+ }
234
+
235
+ cancel(): void {
236
+ try { this.driver.dispatch({ kind: 'cancel' }); } catch { /* ignore */ }
237
+ }
238
+
239
+ isProcessing(): boolean {
240
+ return this.getStatus().status === 'generating';
241
+ }
242
+
243
+ isReady(): boolean {
244
+ return this.spawned && !this.exited;
245
+ }
246
+
247
+ setOnStatusChange(cb: () => void): void {
248
+ this.statusCallback = cb;
249
+ }
250
+
251
+ setOnPtyData(cb: (data: string) => void): void {
252
+ this.ptyDataCallback = cb;
253
+ }
254
+
255
+ writeRaw(data: string): void {
256
+ // Raw pty input — typed characters, escape codes, arrow keys —
257
+ // goes straight to the underlying terminal. send_message would
258
+ // append submit_key after every chunk, which is why typing in
259
+ // the dashboard terminal felt like "enter on every keystroke".
260
+ this.driver.dispatch({ kind: 'pty_write', data });
261
+ }
262
+
263
+ resize(cols: number, rows: number): void {
264
+ this.driver.dispatch({ kind: 'resize', cols, rows });
265
+ }
266
+
267
+ resolveModal(buttonIndex: number): void {
268
+ // CliAdapter buttonIndex is 0-based; spec buttons are 1-based.
269
+ this.driver.dispatch({ kind: 'click_modal_button', index: buttonIndex + 1 });
270
+ }
271
+
272
+ async resolveAction(data: unknown): Promise<void> {
273
+ const args = (data && typeof data === 'object') ? (data as any) : {};
274
+ const explicitIndex = typeof args.buttonIndex === 'number' ? args.buttonIndex : -1;
275
+ if (explicitIndex >= 0) { this.resolveModal(explicitIndex); return; }
276
+ const action = typeof args.action === 'string' ? args.action : 'approve';
277
+ const buttons = this.latestModal?.buttons ?? [];
278
+ if (buttons.length === 0) return;
279
+ let target = -1;
280
+ if (action === 'reject' || action === 'deny') {
281
+ target = buttons.findIndex(b => /^(no|deny|reject|cancel)\b/i.test(b.label));
282
+ if (target < 0) target = buttons.length - 1;
283
+ } else {
284
+ target = buttons.findIndex(b => /^(yes|allow|approve|accept|continue|proceed|update)\b/i.test(b.label));
285
+ if (target < 0) target = 0;
286
+ }
287
+ this.resolveModal(target);
288
+ }
289
+
290
+ async setInteractivePromptResponse(response: InteractivePromptResponse): Promise<void> {
291
+ const prompt = this.activeInteractivePrompt;
292
+ if (!prompt || prompt.promptId !== response.promptId) throw new Error('Interactive prompt response does not match active prompt');
293
+ if (this.cliType !== 'claude-cli') return;
294
+ if (this.interactivePromptTransport === 'tui') {
295
+ const steps = buildClaudeInteractiveTuiAnswerSteps(prompt, response);
296
+ for (const step of steps) {
297
+ this.driver.dispatch({ kind: 'pty_write', data: step });
298
+ await new Promise(resolve => setTimeout(resolve, 180));
299
+ }
300
+ } else {
301
+ this.driver.dispatch({ kind: 'pty_write', data: `${buildClaudeInteractiveToolResult(response)}\n` });
302
+ }
303
+ this.activeInteractivePrompt = null;
304
+ this.interactivePromptTransport = null;
305
+ this.statusCallback?.();
306
+ }
307
+
308
+ isApprovalRecentlyResolved(): boolean { return false; }
309
+ clearHistory(): void { /* no transcript buffer yet */ }
310
+ updateRuntimeSettings(): void { /* no runtime settings in spec model yet */ }
311
+ setServerConn(): void { /* server conn unused by SpecDriver */ }
312
+ /**
313
+ * Map an invokeScript(name, args) call onto a control_bar entry.
314
+ *
315
+ * scriptName is matched against control.id. The control's action.type
316
+ * drives the dispatch:
317
+ *
318
+ * send_keys → click_control (e.g. stop)
319
+ * open_picker → click_control then resolve when extract_choices
320
+ * surface; choice index comes from args.choiceIndex
321
+ * or args.choice (string label match), defaulting to 0
322
+ * attach_image → attach_image dispatch; expects args.blob (data url
323
+ * or base64) and args.mime
324
+ *
325
+ * Callers that pass an unknown control id get a { not_found } response.
326
+ * No control matched, no driver call — keeps the surface honest.
327
+ */
328
+ invokeScript(scriptName: string, args?: Record<string, unknown>): Promise<unknown> {
329
+ const controls = this.spec.control_bar ?? [];
330
+ const ctl = controls.find(c => c.id === scriptName);
331
+ if (!ctl) {
332
+ return Promise.resolve({ ok: false, error: `unknown control: ${scriptName}` });
333
+ }
334
+ // Args may arrive as either { blob, mime } (direct invocation) or
335
+ // { params: { blob, mime } } (when the dashboard wraps script args
336
+ // in a params bag). Look at both.
337
+ const flat: Record<string, unknown> = { ...(args || {}) };
338
+ if (args && typeof args.params === 'object' && args.params) {
339
+ Object.assign(flat, args.params as Record<string, unknown>);
340
+ }
341
+ const action = ctl.action;
342
+ if (action.type === 'attach_image') {
343
+ const blob = typeof flat.blob === 'string' ? flat.blob : '';
344
+ const mime = typeof flat.mime === 'string' ? flat.mime : 'image/png';
345
+ if (!blob) return Promise.resolve({ ok: false, error: 'attach_image requires args.blob (base64 or data URL)' });
346
+ this.driver.dispatch({ kind: 'attach_image', blob, mime });
347
+ return Promise.resolve({ ok: true, effects: [{ type: 'attached_image', controlId: ctl.id }] });
348
+ }
349
+ // send_keys + open_picker both route through click_control. For
350
+ // open_picker the dashboard sees the picker modal arrive via a
351
+ // state_changed event, then submits the choice using
352
+ // resolveModal/click_modal_button. invokeScript's synchronous
353
+ // return is just an acknowledgement that the trigger fired.
354
+ this.driver.dispatch({ kind: 'click_control', control_id: ctl.id, payload: flat });
355
+ const effects: { type: string; controlId: string }[] = [];
356
+ if (action.type === 'open_picker') effects.push({ type: 'opened_picker', controlId: ctl.id });
357
+ else if (action.type === 'send_keys') effects.push({ type: 'sent_keys', controlId: ctl.id });
358
+ return Promise.resolve({ ok: true, effects });
359
+ }
360
+ getDebugSnapshot(): unknown {
361
+ let screen = '';
362
+ let sections: Record<string, string> | undefined;
363
+ try {
364
+ screen = this.driver.snapshot();
365
+ const driverSections = this.driver.getSections?.();
366
+ if (driverSections) {
367
+ sections = Object.fromEntries(driverSections.map(s => [s.id, s.text]));
368
+ } else {
369
+ sections = this.readCurrentScreenSections(screen);
370
+ }
371
+ } catch { /* best-effort */ }
372
+ // Read native transcript messages for the debug snapshot
373
+ let messages: any[] = [];
374
+ if (this.spec.native_history?.source) {
375
+ try {
376
+ const nhResult = executeNativeHistory(this.spec.native_history, {
377
+ agentType: this.cliType,
378
+ providerSessionId: this.providerSessionId,
379
+ sessionStartedAtMs: this.spawnedAtMs,
380
+ envOverrides: this.spawnedEnv,
381
+ workspace: this.workingDir,
382
+ });
383
+ if (nhResult && Array.isArray(nhResult.messages)) messages = nhResult.messages;
384
+ } catch { /* best-effort */ }
385
+ } else {
386
+ messages = this.readClaudeScreenAssistantMessages();
387
+ }
388
+ return {
389
+ cliType: this.cliType,
390
+ spec_id: this.spec.id,
391
+ current_state: this.latestState,
392
+ current_modal: this.latestModal,
393
+ activeInteractivePrompt: this.activeInteractivePrompt,
394
+ exited: this.exited,
395
+ screen,
396
+ sections,
397
+ stateHistory: this.driver.getStateHistory(),
398
+ idleHoldPending: this.driver.hasIdleHoldPending(),
399
+ lastBusyAt: this.driver.getLastBusyAt(),
400
+ specPath: this.driver.getSpecPath(),
401
+ cursorPosition: this.driver.getCursorPosition(),
402
+ completionIdleDebounce: this.driver.getCompletionIdleDebounceState(),
403
+ // v4 FSM live transition table (null for v3 specs). Every outgoing
404
+ // transition from the current state with its per-condition match
405
+ // result + countdown — the canonical "why isn't it moving" answer.
406
+ fsm: this.driver.getFsmDebug?.() ?? null,
407
+ // Extended fields
408
+ name: this.cliName,
409
+ status: this.getStatus().status,
410
+ workingDir: this.workingDir,
411
+ spawnedAtMs: this.spawnedAtMs,
412
+ providerSessionId: this.providerSessionId ?? null,
413
+ messages,
414
+ committedMessages: messages,
415
+ };
416
+ }
417
+ getRuntimeMetadata(): unknown {
418
+ return {
419
+ runtimeId: this.spec.id,
420
+ runtimeKey: this.spec.id,
421
+ displayName: this.spec.name,
422
+ spawnedAtMs: this.spawnedAtMs,
423
+ spawnedEnv: this.spawnedEnv,
424
+ ...(this.providerSessionId ? { providerSessionId: this.providerSessionId } : {}),
425
+ };
426
+ }
427
+ updateRuntimeMeta(meta?: Record<string, unknown>): void {
428
+ if (meta && typeof meta.providerSessionId === 'string') {
429
+ this.providerSessionId = meta.providerSessionId;
430
+ }
431
+ }
432
+ refreshProviderDefinition(): void { /* hot reload handled by SpecDriver fs.watch */ }
433
+
434
+ private handleEvent(ev: DashboardEvent): void {
435
+ this.lastEvent = ev;
436
+ switch (ev.kind) {
437
+ case 'state_changed':
438
+ this.latestState = ev.state;
439
+ this.latestModal = ev.modal;
440
+ // info-level keeps only spec-defined identifiers (state.id /
441
+ // state.label / button count). The extracted title can carry
442
+ // user data — file paths, command text, ticket titles — so
443
+ // it stays at debug.
444
+ LOG.info('SpecAdapter', `[${this.cliType}] state=${ev.state.id} (${ev.state.label}) modal=${ev.modal ? `${ev.modal.buttons.length}-buttons` : 'none'}`);
445
+ if (ev.state.title) {
446
+ LOG.debug('SpecAdapter', `[${this.cliType}] state.title=${JSON.stringify(ev.state.title)}`);
447
+ }
448
+ this.maybeCaptureClaudeTuiPrompt();
449
+ this.statusCallback?.();
450
+ return;
451
+ case 'pty_data':
452
+ this.detectInteractivePromptFromPtyChunk(ev.chunk);
453
+ this.maybeCaptureClaudeTuiPrompt();
454
+ try { this.ptyDataCallback?.(ev.chunk); } catch { /* ignore */ }
455
+ return;
456
+ case 'exit':
457
+ this.exited = true;
458
+ this.statusCallback?.();
459
+ return;
460
+ case 'spec_error':
461
+ LOG.warn('SpecAdapter', `[${this.cliType}] spec reload error: ${ev.errors.join('; ')}`);
462
+ return;
463
+ default:
464
+ return;
465
+ }
466
+ }
467
+
468
+ private detectInteractivePromptFromPtyChunk(chunk: string): void {
469
+ if (this.cliType !== 'claude-cli' || !chunk) return;
470
+ this.jsonLineTail += chunk;
471
+ if (this.jsonLineTail.length > 64 * 1024) this.jsonLineTail = this.jsonLineTail.slice(-64 * 1024);
472
+ const lines = this.jsonLineTail.split(/\r?\n/);
473
+ this.jsonLineTail = lines.pop() || '';
474
+ for (const line of lines) {
475
+ const trimmed = line.trim();
476
+ if (!trimmed.startsWith('{') || !trimmed.includes('AskUserQuestion')) continue;
477
+ try {
478
+ const parsed = JSON.parse(trimmed);
479
+ const prompt = detectClaudeAskUserQuestionPromptFromJson(parsed, this.cliType);
480
+ if (!prompt) continue;
481
+ this.activeInteractivePrompt = prompt;
482
+ this.interactivePromptTransport = 'stream-json';
483
+ this.statusCallback?.();
484
+ } catch {
485
+ // PTY output is not guaranteed to be machine JSON.
486
+ }
487
+ }
488
+ }
489
+
490
+ private readCurrentScreenSections(_screenText: string): Record<string, string> {
491
+ try {
492
+ const sections = this.driver.getSections() ?? [];
493
+ return Object.fromEntries(sections.map(section => [section.id, section.text]));
494
+ } catch {
495
+ return {};
496
+ }
497
+ }
498
+
499
+ private extractProviderSessionIdFromScreen(): string | undefined {
500
+ if (this.cliType !== 'codex-cli') return this.providerSessionId;
501
+ let screenText = '';
502
+ try {
503
+ screenText = this.driver.snapshot();
504
+ } catch {
505
+ return this.providerSessionId;
506
+ }
507
+ const clean = stripAnsi(screenText);
508
+ const match = clean.match(/(?:gpt-|o\d|codex-)[^\n·]*·[^\n·]*·\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
509
+ return match?.[1] || this.providerSessionId;
510
+ }
511
+
512
+ private readClaudeScreenAssistantMessages(): ChatMessage[] {
513
+ if (this.cliType !== 'claude-cli') return [];
514
+ let screenText = '';
515
+ try {
516
+ screenText = this.driver.snapshot();
517
+ } catch {
518
+ return [];
519
+ }
520
+ const sections = this.readCurrentScreenSections(screenText);
521
+ const body = sections.body || screenText;
522
+ const messages: ChatMessage[] = [];
523
+ const seen = new Set<string>();
524
+ for (const line of body.split(/\r?\n/)) {
525
+ const match = line.match(/^\s*⏺\s+(.+?)\s*$/);
526
+ const content = match?.[1]?.trim();
527
+ if (!content || seen.has(content)) continue;
528
+ seen.add(content);
529
+ messages.push({
530
+ role: 'assistant',
531
+ kind: 'standard',
532
+ content,
533
+ source: 'assistant_text',
534
+ userFacing: true,
535
+ bubbleState: 'final',
536
+ });
537
+ }
538
+ return messages;
539
+ }
540
+
541
+ private maybeCaptureClaudeTuiPrompt(): void {
542
+ if (this.cliType !== 'claude-cli'
543
+ || this.activeInteractivePrompt
544
+ || this.claudeTuiPromptCaptureInFlight) return;
545
+ const screenText = this.driver.snapshot();
546
+ const headers = this.readClaudeTuiHeaders(screenText);
547
+ if (!screenText.includes('Enter to select')) return;
548
+ if (headers.length === 0) {
549
+ const prompt = detectClaudeAskUserQuestionPromptFromTuiPages([{ screenText }], {
550
+ promptId: `ask-user-${this.providerSessionId || 'claude'}-${Date.now()}`,
551
+ providerType: this.cliType,
552
+ });
553
+ if (!prompt) return;
554
+ this.activeInteractivePrompt = prompt;
555
+ this.interactivePromptTransport = 'tui';
556
+ this.statusCallback?.();
557
+ return;
558
+ }
559
+ this.claudeTuiPromptCaptureInFlight = true;
560
+ void this.captureClaudeTuiPrompt(screenText, headers).finally(() => {
561
+ this.claudeTuiPromptCaptureInFlight = false;
562
+ });
563
+ }
564
+
565
+ private readClaudeTuiHeaders(screenText: string): string[] {
566
+ const navLine = screenText.split(/\r?\n/).find(line => line.includes('✔ Submit') && /[☐☒]/.test(line));
567
+ if (!navLine) return [];
568
+ const headers: string[] = [];
569
+ for (const match of navLine.matchAll(/[☐☒]\s+(.+?)(?=\s+[☐☒]|\s+✔\s+Submit)/g)) {
570
+ const header = match[1]?.trim();
571
+ if (header) headers.push(header);
572
+ }
573
+ return headers;
574
+ }
575
+
576
+ private async captureClaudeTuiPrompt(firstScreen: string, headers: string[]): Promise<void> {
577
+ const pages: ClaudeInteractiveTuiPage[] = [{ screenText: firstScreen, header: headers[0] }];
578
+ for (let index = 1; index < headers.length; index += 1) {
579
+ this.driver.dispatch({ kind: 'pty_write', data: '\t' });
580
+ await new Promise(resolve => setTimeout(resolve, 120));
581
+ pages.push({ screenText: this.driver.snapshot(), header: headers[index] });
582
+ }
583
+ for (let index = headers.length - 1; index > 0; index -= 1) {
584
+ this.driver.dispatch({ kind: 'pty_write', data: '\x1b[Z' });
585
+ await new Promise(resolve => setTimeout(resolve, 80));
586
+ }
587
+
588
+ const prompt = detectClaudeAskUserQuestionPromptFromTuiPages(pages, {
589
+ promptId: `ask-user-${this.providerSessionId || 'claude'}-${Date.now()}`,
590
+ providerType: this.cliType,
591
+ });
592
+ if (!prompt) return;
593
+ this.activeInteractivePrompt = prompt;
594
+ this.interactivePromptTransport = 'tui';
595
+ this.statusCallback?.();
596
+ }
597
+
598
+ getDebugState(): Record<string, any> {
599
+ const screen = this.driver.getScreen?.() ?? '';
600
+ const history = this.driver.getStateHistory();
601
+ const status = this.getStatus();
602
+
603
+ let messages: any[] = [];
604
+ if (this.spec.native_history?.source) {
605
+ try {
606
+ const result = executeNativeHistory(this.spec.native_history, {
607
+ agentType: this.cliType,
608
+ providerSessionId: this.providerSessionId,
609
+ sessionStartedAtMs: this.spawnedAtMs,
610
+ envOverrides: this.spawnedEnv,
611
+ workspace: this.workingDir,
612
+ });
613
+ if (result && Array.isArray(result.messages)) {
614
+ messages = result.messages;
615
+ }
616
+ } catch (e) {
617
+ // Ignore native history read errors in debug state
618
+ }
619
+ } else {
620
+ messages = this.readClaudeScreenAssistantMessages();
621
+ }
622
+
623
+ const latestState = this.latestState;
624
+ const latestModal = this.latestModal;
625
+ return {
626
+ type: this.cliType,
627
+ name: this.cliName,
628
+ status: status.status,
629
+ rawStatus: status.status,
630
+ projectedStatus: status.status,
631
+ ready: this.spawned,
632
+ // Legacy snapshot-style fields for panels that read getDebugSnapshot shape
633
+ spec_id: this.spec.id,
634
+ current_state: latestState ?? null,
635
+ current_modal: latestModal ?? null,
636
+ exited: this.exited,
637
+ idleHoldPending: this.driver.hasIdleHoldPending?.() ?? false,
638
+ lastBusyAt: this.driver.getLastBusyAt?.() ?? 0,
639
+ screen: screen,
640
+ screenText: screen,
641
+ workingDir: this.workingDir,
642
+ spawnedAtMs: this.spawnedAtMs,
643
+ providerSessionId: this.providerSessionId ?? null,
644
+ sections: this.driver.getSections?.() ?? null,
645
+ stateHistory: history,
646
+ specPath: this.driver.getSpecPath?.() ?? null,
647
+ // v4 FSM live transition table — present only for FsmDriver. Lets
648
+ // the panel (and the daemon API) show, for the current instant,
649
+ // every outgoing transition with its per-condition match result
650
+ // and countdown. This is the canonical "why isn't it transitioning"
651
+ // answer — no screenshots needed.
652
+ fsm: this.driver.getFsmDebug?.() ?? null,
653
+ messages,
654
+ committedMessages: messages,
655
+ };
656
+ }
657
+
658
+ getTraceState(limit = 120): Record<string, any> {
659
+ const history = this.driver.getStateHistory();
660
+ return {
661
+ status: this.getStatus().status,
662
+ stateHistory: history.slice(-limit),
663
+ screenText: this.driver.getScreen?.() ?? '',
664
+ };
665
+ }
666
+
667
+ getProviderResolutionMeta(): Record<string, any> {
668
+ return {
669
+ type: this.cliType,
670
+ providerDir: null,
671
+ resolvedVersion: null,
672
+ };
673
+ }
674
+ }