@adhdev/daemon-core 0.9.82-rc.34 → 0.9.82-rc.340

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 (318) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +46 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +110 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +308 -1
  23. package/dist/commands/upgrade-helper.d.ts +12 -0
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +52 -13
  37. package/dist/index.js +39439 -14533
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +39000 -14215
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/mesh/contracts.d.ts +164 -0
  48. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  49. package/dist/mesh/coordinator-registry.d.ts +59 -0
  50. package/dist/mesh/mesh-active-work.d.ts +174 -0
  51. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  52. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  53. package/dist/mesh/mesh-events-pending.d.ts +45 -0
  54. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  55. package/dist/mesh/mesh-events-utils.d.ts +66 -0
  56. package/dist/mesh/mesh-events.d.ts +6 -49
  57. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  58. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  59. package/dist/mesh/mesh-init.d.ts +86 -0
  60. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  61. package/dist/mesh/mesh-ledger.d.ts +77 -1
  62. package/dist/mesh/mesh-missions.d.ts +116 -0
  63. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  64. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  65. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  66. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  67. package/dist/mesh/mesh-routing.d.ts +70 -0
  68. package/dist/mesh/mesh-runtime-store.d.ts +418 -0
  69. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  70. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  71. package/dist/mesh/mesh-work-queue.d.ts +208 -5
  72. package/dist/mesh/preview-freshness.d.ts +18 -0
  73. package/dist/mesh/refine-config.d.ts +216 -0
  74. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  75. package/dist/providers/acp-provider-instance.d.ts +2 -0
  76. package/dist/providers/approval-utils.d.ts +13 -0
  77. package/dist/providers/chat-message-normalization.d.ts +12 -0
  78. package/dist/providers/cli-provider-instance.d.ts +76 -3
  79. package/dist/providers/contracts.d.ts +139 -6
  80. package/dist/providers/external-sources.d.ts +71 -0
  81. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  82. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  83. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  84. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  85. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  86. package/dist/providers/native-history/index.d.ts +13 -0
  87. package/dist/providers/provider-instance-manager.d.ts +13 -0
  88. package/dist/providers/provider-instance.d.ts +13 -1
  89. package/dist/providers/provider-loader.d.ts +26 -4
  90. package/dist/providers/provider-trust.d.ts +31 -0
  91. package/dist/providers/read-chat-contract.d.ts +29 -0
  92. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  93. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  94. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  95. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  96. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  97. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  98. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  99. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  100. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  101. package/dist/providers/sdk/v1/index.d.ts +30 -0
  102. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  103. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  104. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  105. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  106. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  107. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  108. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  109. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  110. package/dist/providers/spec/adapter.d.ts +69 -0
  111. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  112. package/dist/providers/spec/evaluator.d.ts +23 -0
  113. package/dist/providers/spec/fsm-driver.d.ts +306 -0
  114. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  115. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  116. package/dist/providers/spec/fsm-types.d.ts +144 -0
  117. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  118. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  119. package/dist/providers/spec/route.d.ts +4 -0
  120. package/dist/providers/spec/types.d.ts +180 -0
  121. package/dist/providers/status-monitor.d.ts +7 -7
  122. package/dist/providers/transcript-v2.d.ts +176 -0
  123. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  124. package/dist/providers/working-dir.d.ts +17 -0
  125. package/dist/repo-mesh-types.d.ts +295 -13
  126. package/dist/sessions/registry.d.ts +6 -0
  127. package/dist/shared-types-extra.d.ts +2 -4
  128. package/dist/shared-types.d.ts +59 -2
  129. package/dist/status/normalize.d.ts +1 -1
  130. package/dist/status/normalize.js +1 -0
  131. package/dist/status/normalize.js.map +1 -1
  132. package/dist/status/normalize.mjs +1 -0
  133. package/dist/status/normalize.mjs.map +1 -1
  134. package/dist/status/reporter.d.ts +2 -0
  135. package/dist/status/snapshot.d.ts +26 -0
  136. package/dist/system/load-better-sqlite3.d.ts +21 -0
  137. package/dist/types.d.ts +5 -0
  138. package/package.json +7 -3
  139. package/src/agent-stream/poller.ts +2 -3
  140. package/src/agent-stream/provider-adapter.ts +1 -1
  141. package/src/boot/daemon-lifecycle.ts +55 -12
  142. package/src/boot/process-hardening.ts +89 -0
  143. package/src/build-info.ts +73 -0
  144. package/src/chat/source-machine.ts +534 -0
  145. package/src/chat/source-resolver.ts +0 -0
  146. package/src/chat/subscription-updates.ts +20 -1
  147. package/src/cli-adapter-types.d.ts +1 -0
  148. package/src/cli-adapter-types.ts +47 -2
  149. package/src/cli-adapters/cli-script-runner.ts +421 -0
  150. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  151. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  152. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  153. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  154. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  155. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  156. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  157. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  158. package/src/cli-adapters/pty-transport.ts +2 -1
  159. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  160. package/src/cli-adapters/resolve-executable.ts +90 -0
  161. package/src/cli-adapters/session-host-transport.ts +2 -1
  162. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  163. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  164. package/src/cli-adapters/terminal-screen.ts +16 -81
  165. package/src/commands/chat-commands.ts +1823 -62
  166. package/src/commands/cli-manager.ts +286 -14
  167. package/src/commands/handler.ts +809 -2
  168. package/src/commands/mesh-coordinator.ts +332 -122
  169. package/src/commands/router.ts +7433 -1317
  170. package/src/commands/stream-commands.ts +8 -0
  171. package/src/commands/upgrade-helper.ts +81 -30
  172. package/src/config/chat-history.ts +483 -24
  173. package/src/config/config.ts +12 -0
  174. package/src/config/mesh-config.ts +388 -6
  175. package/src/config/recent-activity.ts +8 -2
  176. package/src/daemon/dev-auto-implement.ts +3 -2
  177. package/src/daemon/dev-cli-debug.ts +10 -1
  178. package/src/detection/cli-detector.ts +28 -9
  179. package/src/detection/ide-detector.ts +55 -16
  180. package/src/detection/win32-ide-version.ts +106 -0
  181. package/src/git/change-impact-config.ts +354 -0
  182. package/src/git/git-commands.ts +55 -14
  183. package/src/git/git-diff.ts +53 -0
  184. package/src/git/git-executor.ts +12 -0
  185. package/src/git/git-status.ts +574 -43
  186. package/src/git/git-types.ts +14 -62
  187. package/src/git/git-worktree.ts +8 -1
  188. package/src/git/index.ts +16 -0
  189. package/src/index.ts +146 -12
  190. package/src/installer.d.ts +1 -1
  191. package/src/installer.ts +8 -6
  192. package/src/ipc/local-ipc-server.ts +278 -0
  193. package/src/launch.d.ts +1 -1
  194. package/src/launch.ts +37 -28
  195. package/src/logging/async-batch-writer.ts +55 -0
  196. package/src/logging/log-redactor.ts +100 -0
  197. package/src/logging/log-tail-reader.ts +220 -0
  198. package/src/logging/logger.ts +2 -1
  199. package/src/mesh/contracts.ts +329 -0
  200. package/src/mesh/coordinator-prompt.ts +234 -31
  201. package/src/mesh/coordinator-registry.ts +121 -0
  202. package/src/mesh/mesh-active-work.ts +623 -0
  203. package/src/mesh/mesh-delivery-policy.ts +315 -0
  204. package/src/mesh/mesh-events-coordinator.ts +2144 -0
  205. package/src/mesh/mesh-events-pending.ts +508 -0
  206. package/src/mesh/mesh-events-stale.ts +290 -0
  207. package/src/mesh/mesh-events-utils.ts +300 -0
  208. package/src/mesh/mesh-events.ts +30 -1035
  209. package/src/mesh/mesh-fast-forward.ts +839 -0
  210. package/src/mesh/mesh-host-ownership.ts +73 -0
  211. package/src/mesh/mesh-init.ts +260 -0
  212. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  213. package/src/mesh/mesh-ledger.ts +589 -102
  214. package/src/mesh/mesh-missions.ts +248 -0
  215. package/src/mesh/mesh-reconcile-loop.ts +822 -0
  216. package/src/mesh/mesh-refine-batch.ts +197 -0
  217. package/src/mesh/mesh-refine-status.ts +231 -0
  218. package/src/mesh/mesh-review-inbox.ts +307 -0
  219. package/src/mesh/mesh-routing.ts +291 -0
  220. package/src/mesh/mesh-runtime-store.ts +1626 -0
  221. package/src/mesh/mesh-task-stats.ts +154 -0
  222. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  223. package/src/mesh/mesh-work-queue.ts +888 -141
  224. package/src/mesh/preview-freshness.ts +118 -0
  225. package/src/mesh/refine-config.ts +423 -0
  226. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  227. package/src/providers/acp-provider-instance.ts +25 -9
  228. package/src/providers/approval-utils.d.ts +4 -0
  229. package/src/providers/approval-utils.ts +47 -5
  230. package/src/providers/chat-message-normalization.ts +45 -5
  231. package/src/providers/cli-provider-instance.ts +1038 -99
  232. package/src/providers/contracts.d.ts +55 -0
  233. package/src/providers/contracts.ts +150 -6
  234. package/src/providers/extension-provider-instance.ts +12 -7
  235. package/src/providers/external-sources.ts +218 -0
  236. package/src/providers/ide-provider-instance.ts +35 -12
  237. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  238. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  239. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  240. package/src/providers/native-history/dispatcher.ts +340 -0
  241. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  242. package/src/providers/native-history/index.ts +30 -0
  243. package/src/providers/provider-instance-manager.ts +30 -0
  244. package/src/providers/provider-instance.ts +10 -1
  245. package/src/providers/provider-loader.ts +670 -50
  246. package/src/providers/provider-schema.ts +87 -14
  247. package/src/providers/provider-trust.ts +114 -0
  248. package/src/providers/read-chat-contract.ts +76 -16
  249. package/src/providers/sdk/README.md +49 -0
  250. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  251. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  252. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  253. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  254. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  255. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  256. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  257. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  258. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  259. package/src/providers/sdk/v1/index.ts +152 -0
  260. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  261. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  262. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  263. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  264. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  265. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  272. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  279. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  280. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  281. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  282. package/src/providers/sdk/v1/validators/index.ts +19 -0
  283. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  284. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  285. package/src/providers/spec/adapter.ts +168 -0
  286. package/src/providers/spec/cli-adapter.ts +986 -0
  287. package/src/providers/spec/evaluator.ts +345 -0
  288. package/src/providers/spec/fsm-driver.ts +993 -0
  289. package/src/providers/spec/fsm-evaluator.ts +255 -0
  290. package/src/providers/spec/fsm-loader.ts +120 -0
  291. package/src/providers/spec/fsm-types.ts +238 -0
  292. package/src/providers/spec/native-history-executor.ts +1136 -0
  293. package/src/providers/spec/pre-launch-trust.ts +104 -0
  294. package/src/providers/spec/route.ts +51 -0
  295. package/src/providers/spec/types.ts +226 -0
  296. package/src/providers/status-monitor.d.ts +7 -7
  297. package/src/providers/status-monitor.ts +37 -22
  298. package/src/providers/transcript-v2.ts +567 -0
  299. package/src/providers/types/interactive-prompt.ts +536 -0
  300. package/src/providers/version-archive.ts +64 -24
  301. package/src/providers/working-dir.ts +23 -0
  302. package/src/repo-mesh-types.ts +378 -14
  303. package/src/sessions/registry.ts +6 -0
  304. package/src/shared-types-extra.ts +2 -4
  305. package/src/shared-types.d.ts +8 -0
  306. package/src/shared-types.ts +64 -1
  307. package/src/status/builders.ts +26 -6
  308. package/src/status/normalize.ts +2 -0
  309. package/src/status/reporter.ts +19 -1
  310. package/src/status/snapshot.ts +95 -26
  311. package/src/system/host-memory.ts +29 -12
  312. package/src/system/load-better-sqlite3.ts +68 -0
  313. package/src/types.ts +5 -0
  314. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  315. package/dist/mesh/mesh-sync.d.ts +0 -53
  316. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  317. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  318. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1215 @@
1
+ /**
2
+ * CliStateEngine — CLI provider status state machine
3
+ *
4
+ * Owns all status-transition logic, timer management, and script-driven
5
+ * evaluation. Reads buffer state from the transport and writes to PTY via
6
+ * the transport interface — adapter stays as pure I/O layer.
7
+ */
8
+
9
+ import { LOG } from '../logging/logger.js';
10
+ import {
11
+ buildCliParseInput,
12
+ normalizeCliParsedMessages,
13
+ type TurnParseScope,
14
+ } from './provider-cli-parse.js';
15
+ import {
16
+ buildCliScreenSnapshot,
17
+ compactPromptText,
18
+ normalizePromptText,
19
+ promptLikelyVisible,
20
+ type CliChatMessage,
21
+ type CliProviderModule,
22
+ type CliSessionStatus,
23
+ type CliTraceEntry,
24
+ type ParsedSession,
25
+ } from './provider-cli-shared.js';
26
+ import type { CliScriptRunner } from './cli-script-runner.js';
27
+
28
+ // ─── Types ─────────────────────────────────────────────────────────────────
29
+
30
+ export interface CliBufferSnapshot {
31
+ accumulatedBuffer: string;
32
+ accumulatedRawBuffer: string;
33
+ recentOutputBuffer: string;
34
+ responseBuffer: string;
35
+ screenText: string;
36
+ parseScreenText: string;
37
+ workingDir: string;
38
+ providerSessionId: string | null;
39
+ runtimeSettings: Record<string, any>;
40
+ isWaitingForResponse: boolean;
41
+ currentTurnScope: TurnParseScope | null;
42
+ lastOutputAt: number;
43
+ lastNonEmptyOutputAt: number;
44
+ lastScreenChangeAt: number;
45
+ lastScreenSnapshot: string;
46
+ }
47
+
48
+ /** What the engine needs from the transport layer */
49
+ export interface CliTransportAccess {
50
+ getSnapshot(): CliBufferSnapshot;
51
+ writeRaw(data: string | Buffer): void;
52
+ getApprovalKeyForIndex(buttonIndex: number): string | undefined;
53
+ flushOutboundQueue(): void;
54
+ isAlive(): boolean;
55
+ /** Optional: override script dispatch (used by tests to mock detection) */
56
+ runDetectStatus?(text: string): string | null;
57
+ /** Optional: override script dispatch (used by tests to mock approval) */
58
+ runParseApproval?(tail: string): { message: string; buttons: string[] } | null;
59
+ /** Optional: override full session parse (used by tests to mock parsing) */
60
+ runParseSession?(): ParsedSession | null;
61
+ /** Optional: provider type override — used when tests patch the adapter's cliType */
62
+ cliType?: string;
63
+ }
64
+
65
+ export interface CliStateEngineCallbacks {
66
+ onStatusChange(): void;
67
+ onApplyParsedSession(session: ParsedSession): void;
68
+ onTurnCompleted(): void;
69
+ }
70
+
71
+ interface IdleFinishCandidate {
72
+ armedAt: number;
73
+ lastOutputAt: number;
74
+ lastScreenChangeAt: number;
75
+ responseEpoch: number;
76
+ assistantLength: number;
77
+ }
78
+
79
+ interface SettledEvalContext {
80
+ now: number;
81
+ modal: { message: string; buttons: string[] } | null;
82
+ status: string;
83
+ parsedMessages: CliChatMessage[];
84
+ lastParsedAssistant: CliChatMessage | undefined;
85
+ parsedStatus: string | null;
86
+ prevStatus: string;
87
+ }
88
+
89
+ // ─── Constants ─────────────────────────────────────────────────────────────
90
+
91
+ const SCRIPT_STATUS_DEBOUNCE_MS = 3000;
92
+ const MAX_FINISH_RETRIES = 2;
93
+ const FINISH_RETRY_DELAY_MS = 300;
94
+ const MAX_TRACE_ENTRIES = 250;
95
+ const APPROVAL_EXIT_TIMEOUT_MS = 60_000;
96
+ const IDLE_CONFIRMATION_GRACE_MS = 2_000;
97
+
98
+ // ─── Engine ────────────────────────────────────────────────────────────────
99
+
100
+ export class CliStateEngine {
101
+ // ── Status ───────────────────────────────────────
102
+ currentStatus: CliSessionStatus['status'] = 'starting';
103
+ isWaitingForResponse = false;
104
+ currentTurnScope: TurnParseScope | null = null;
105
+ activeModal: { message: string; buttons: string[] } | null = null;
106
+
107
+ // ── Approval ─────────────────────────────────────
108
+ lastApprovalResolvedAt = 0;
109
+ lastResolvedModalMessage = '';
110
+ /**
111
+ * Monotonic counter bumped every time the FSM *enters* waiting_approval
112
+ * with a freshly captured modal (see `applyWaitingApproval`). It is the
113
+ * single discriminator between "the same approval re-observed across TUI
114
+ * paint flaps" and "a genuinely new, distinct approval".
115
+ *
116
+ * The message-equality cooldown below (`lastResolvedModalMessage`) cannot
117
+ * tell these apart on its own: claude-cli routinely presents consecutive
118
+ * approvals whose modal message text is identical (e.g. two back-to-back
119
+ * Bash-command prompts). When that second approval arrived inside
120
+ * `approvalCooldown`, the message-equality guard silently swallowed the
121
+ * key write and the approval stuck forever — fatal under auto-approval.
122
+ *
123
+ * `approvalEntrySeq` increments on every fresh entry; `lastResolvedEntrySeq`
124
+ * records which entry the cooldown belongs to. We only short-circuit the
125
+ * write when we are still resolving *that same* entry — a new entry (new
126
+ * seq) is always a real, distinct approval and must be written.
127
+ */
128
+ approvalEntrySeq = 0;
129
+ private lastResolvedEntrySeq = -1;
130
+ /**
131
+ * When the engine previously held a modal but the latest parse failed
132
+ * to extract one, we record the timestamp here and only drop the modal
133
+ * after the configured `approvalCooldown` to avoid flapping between
134
+ * waiting_approval and generating on every Claude TUI redraw — that
135
+ * flapping is what fed auto-approve a fresh modal signature on each
136
+ * paint and made the engine type "1" repeatedly into the prompt.
137
+ */
138
+ modalLostAt = 0;
139
+ private approvalExitTimeout: NodeJS.Timeout | null = null;
140
+
141
+ // ── Response tracking ────────────────────────────
142
+ responseEpoch = 0;
143
+ submitPendingUntil = 0;
144
+ responseSettleIgnoreUntil = 0;
145
+ submitRetryUsed = false;
146
+ submitRetryPromptSnippet = '';
147
+ finishRetryCount = 0;
148
+ providerErrorMessage: string | null = null;
149
+ providerErrorReason: string | null = null;
150
+
151
+ // ── Timers ───────────────────────────────────────
152
+ private settleTimer: NodeJS.Timeout | null = null;
153
+ private idleTimeout: NodeJS.Timeout | null = null;
154
+ private finishRetryTimer: NodeJS.Timeout | null = null;
155
+ private providerErrorRetryTimer: NodeJS.Timeout | null = null;
156
+ private providerErrorRetryKey = '';
157
+
158
+ // ── Debounce ─────────────────────────────────────
159
+ pendingScriptStatus: 'generating' | 'waiting_approval' | null = null;
160
+ pendingScriptStatusSince = 0;
161
+ private pendingScriptStatusTimer: NodeJS.Timeout | null = null;
162
+
163
+ // ── Idle candidate ───────────────────────────────
164
+ private idleFinishCandidate: IdleFinishCandidate | null = null;
165
+
166
+ // ── Idle confirmation grace ──────────────────────
167
+ /**
168
+ * `finishResponse` produces the `generating → idle` transition that
169
+ * coordinators interpret as "task complete". Some providers (antigravity-
170
+ * cli observed in the wild) briefly paint a screen that looks like an
171
+ * idle prompt between tool result frames while still actively running,
172
+ * which fired `response_finished` and broke completion semantics.
173
+ * We defer the actual idle transition by IDLE_CONFIRMATION_GRACE_MS and
174
+ * cancel it if the scripted detection re-detects generating during that
175
+ * window — a true completion stays idle for many seconds, so a 2-second
176
+ * grace is sufficient to filter the paint blip.
177
+ */
178
+ private pendingIdleFinishTimer: NodeJS.Timeout | null = null;
179
+ private pendingIdleFinishAt = 0;
180
+
181
+ // ── Status history (debug) ───────────────────────
182
+ private statusHistory: { status: string; at: number; trigger?: string }[] = [];
183
+ private traceEntries: CliTraceEntry[] = [];
184
+ private traceSeq = 0;
185
+ private traceSessionId = '';
186
+
187
+ constructor(
188
+ private readonly provider: CliProviderModule,
189
+ private readonly runner: CliScriptRunner,
190
+ private readonly transport: CliTransportAccess,
191
+ private readonly callbacks: CliStateEngineCallbacks,
192
+ private readonly timeouts: Required<NonNullable<CliProviderModule['timeouts']>>,
193
+ ) {}
194
+
195
+ // ─── Public API ────────────────────────────────────────────────────────
196
+
197
+ setStatus(status: CliSessionStatus['status'], trigger?: string): void {
198
+ const prev = this.currentStatus;
199
+ if (prev === status) return;
200
+ this.currentStatus = status;
201
+ this.statusHistory.push({ status, at: Date.now(), trigger });
202
+ if (this.statusHistory.length > 50) this.statusHistory.shift();
203
+ this.recordTrace('status', { previousStatus: prev, trigger: trigger || null });
204
+ LOG.info('CLI', `[${this.provider.type}] status: ${prev} → ${status}${trigger ? ` (${trigger})` : ''}`);
205
+ }
206
+
207
+ scheduleSettle(): void {
208
+ if (this.settleTimer) clearTimeout(this.settleTimer);
209
+ const epoch = this.responseEpoch;
210
+ const delay = Math.max(
211
+ this.timeouts.outputSettle,
212
+ this.submitPendingUntil > Date.now()
213
+ ? (this.submitPendingUntil - Date.now()) + this.timeouts.outputSettle
214
+ : 0,
215
+ );
216
+ this.settleTimer = setTimeout(() => {
217
+ this.settleTimer = null;
218
+ if (epoch !== this.responseEpoch) return;
219
+ this.evaluateSettled(this.transport.getSnapshot());
220
+ }, delay);
221
+ }
222
+
223
+ /** Called from sendMessage in transport once a turn scope is established. */
224
+ onTurnStarted(turnScope: TurnParseScope): void {
225
+ this.isWaitingForResponse = true;
226
+ this.finishRetryCount = 0;
227
+ this.clearIdleFinishCandidate('send_message');
228
+ this.currentTurnScope = turnScope;
229
+ this.responseEpoch += 1;
230
+ }
231
+
232
+ /** Called when PTY exits */
233
+ onPtyExit(): void {
234
+ this.clearAllTimers();
235
+ this.setStatus('stopped', 'pty_exit');
236
+ }
237
+
238
+ /** Called when adapter starts up successfully */
239
+ onSpawnReady(): void {
240
+ this.setStatus('starting', 'pty_ready');
241
+ this.traceEntries = [];
242
+ this.traceSeq = 0;
243
+ this.traceSessionId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
244
+ this.recordTrace('session_start', { providerType: this.provider.type });
245
+ }
246
+
247
+ resolveModal(buttonIndex: number): void {
248
+ const snap = this.transport.getSnapshot();
249
+ const parseApproval = typeof this.transport.runParseApproval === 'function'
250
+ ? (s: CliBufferSnapshot) => this.transport.runParseApproval!(s.recentOutputBuffer.slice(-500))
251
+ : (s: CliBufferSnapshot) => this.runParseApproval(s);
252
+ let modal = this.activeModal ?? parseApproval(snap);
253
+
254
+ if (!modal && this.runner.hasParseSession()) {
255
+ try {
256
+ const parsed = this.runParseSession(snap) as any;
257
+ const parsedModal = parsed?.activeModal && Array.isArray(parsed.activeModal.buttons)
258
+ && parsed.activeModal.buttons.some((b: any) => typeof b === 'string' && b.trim())
259
+ ? parsed.activeModal : null;
260
+ if (parsed?.status === 'waiting_approval' && parsedModal) {
261
+ modal = parsedModal;
262
+ // No modal was held (`this.activeModal` was null above), so a
263
+ // freshly parsed approval here is a new entry by definition.
264
+ this.activeModal = parsedModal;
265
+ this.approvalEntrySeq++;
266
+ if (this.currentStatus !== 'waiting_approval') {
267
+ this.setStatus('waiting_approval', 'resolve_modal_parse');
268
+ this.callbacks.onStatusChange();
269
+ }
270
+ }
271
+ } catch { /* ignore parse failures */ }
272
+ }
273
+
274
+ if (!this.transport.isAlive()) return;
275
+ // (fix) Hard fail-safe: never write an approval key without a concrete
276
+ // modal that has buttons. The previous gate `currentStatus !== 'WA' &&
277
+ // !modal` let resolveModal proceed whenever status was still pinned to
278
+ // waiting_approval, even if parseApproval had returned null. Combined
279
+ // with auto-approve and Claude's modal flapping (status==WA but modal
280
+ // briefly null between paints) this typed "1" into the prompt over and
281
+ // over. Require a real modal with at least one button.
282
+ const buttonsValid = Array.isArray(modal?.buttons)
283
+ && modal.buttons.some((b: any) => typeof b === 'string' && b.trim());
284
+ if (!modal || !buttonsValid) return;
285
+
286
+ const currentModalMessage = typeof modal?.message === 'string' ? modal.message.trim() : '';
287
+ const inCooldown = !!this.lastApprovalResolvedAt
288
+ && (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown;
289
+ // (fix) Suppress the duplicate key-write ONLY when this is the *same*
290
+ // approval entry re-observed across TUI paint flaps — i.e. the FSM has
291
+ // not entered waiting_approval afresh since the last resolve
292
+ // (approvalEntrySeq unchanged). A new entry (bumped seq) is always a
293
+ // distinct approval and must be written, even within the cooldown
294
+ // window and even when its message text matches the previous one.
295
+ //
296
+ // Previously this gated on message equality alone, so consecutive
297
+ // claude-cli approvals that share message text (very common) had the
298
+ // second write swallowed — the approval stuck unresolved despite
299
+ // auto-approval being on.
300
+ const sameEntryReResolve = this.approvalEntrySeq === this.lastResolvedEntrySeq;
301
+ if (inCooldown && sameEntryReResolve && currentModalMessage === this.lastResolvedModalMessage) return;
302
+
303
+ this.clearIdleFinishCandidate('resolve_modal');
304
+ this.recordTrace('resolve_modal', { buttonIndex, activeModal: modal, approvalEntrySeq: this.approvalEntrySeq });
305
+ this.activeModal = null;
306
+ this.lastApprovalResolvedAt = Date.now();
307
+ this.lastResolvedModalMessage = currentModalMessage;
308
+ this.lastResolvedEntrySeq = this.approvalEntrySeq;
309
+ this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
310
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
311
+ this.setStatus('generating', 'approval_resolved');
312
+ this.callbacks.onStatusChange();
313
+
314
+ const approvalKey = this.transport.getApprovalKeyForIndex(buttonIndex);
315
+ if (approvalKey !== undefined) {
316
+ this.transport.writeRaw(approvalKey);
317
+ } else {
318
+ const DOWN = '\x1B[B';
319
+ const buttonCount = Array.isArray(modal?.buttons) ? modal.buttons.length : 0;
320
+ const clamped = buttonCount > 0
321
+ ? Math.min(Math.max(0, buttonIndex), buttonCount - 1)
322
+ : Math.max(0, buttonIndex);
323
+ this.transport.writeRaw(DOWN.repeat(clamped) + '\r');
324
+ }
325
+ }
326
+
327
+ isApprovalRecentlyResolved(): boolean {
328
+ return !!(this.lastApprovalResolvedAt
329
+ && (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown);
330
+ }
331
+
332
+ /**
333
+ * Called from sendMessage before starting a new turn.
334
+ * Clears stale idle response state when the terminal looks idle and no modal is active.
335
+ */
336
+ clearStaleIdleResponseGuard(reason: string, snap: CliBufferSnapshot): boolean {
337
+ const blockingModal = this.activeModal
338
+ ?? (typeof this.transport.runParseApproval === 'function'
339
+ ? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
340
+ : this.runParseApproval(snap));
341
+ const isIdle = (typeof this.transport.runDetectStatus === 'function'
342
+ ? this.transport.runDetectStatus(snap.recentOutputBuffer)
343
+ : this.runDetectStatus(snap)) === 'idle';
344
+ if (!this.isWaitingForResponse || this.currentStatus !== 'idle' || !isIdle || !!blockingModal) {
345
+ return false;
346
+ }
347
+ this.clearAllTimers();
348
+ this.clearIdleFinishCandidate(reason);
349
+ this.isWaitingForResponse = false;
350
+ this.responseSettleIgnoreUntil = 0;
351
+ this.submitRetryUsed = false;
352
+ this.submitRetryPromptSnippet = '';
353
+ this.finishRetryCount = 0;
354
+ this.currentTurnScope = null;
355
+ this.activeModal = null;
356
+ this.recordTrace('stale_idle_response_cleared', { reason });
357
+ this.callbacks.onTurnCompleted();
358
+ return true;
359
+ }
360
+
361
+ /**
362
+ * Called from sendMessage before starting a new turn.
363
+ * Clears stale idle response state when the parsed session confirms idle with a final assistant message.
364
+ */
365
+ clearParsedIdleResponseGuard(reason: string, parsedStatus: any, snap: CliBufferSnapshot): boolean {
366
+ const parsedRawStatus = typeof parsedStatus?.status === 'string' ? parsedStatus.status.trim() : '';
367
+ const parsedModal = parsedStatus?.activeModal ?? parsedStatus?.modal ?? null;
368
+ const blockingModal = this.activeModal
369
+ ?? (typeof this.transport.runParseApproval === 'function'
370
+ ? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
371
+ : this.runParseApproval(snap));
372
+ if (
373
+ !this.isWaitingForResponse
374
+ || parsedRawStatus !== 'idle'
375
+ || !!parsedModal
376
+ || !!blockingModal
377
+ || !this.parsedStatusHasFinalAssistantMessage(parsedStatus)
378
+ ) {
379
+ return false;
380
+ }
381
+ this.clearAllTimers();
382
+ this.clearIdleFinishCandidate(reason);
383
+ this.isWaitingForResponse = false;
384
+ this.responseSettleIgnoreUntil = 0;
385
+ this.submitRetryUsed = false;
386
+ this.submitRetryPromptSnippet = '';
387
+ this.finishRetryCount = 0;
388
+ this.currentTurnScope = null;
389
+ this.activeModal = null;
390
+ this.setStatus('idle', reason);
391
+ this.recordTrace('parsed_idle_response_cleared', {
392
+ reason,
393
+ parsedStatus: parsedRawStatus,
394
+ parsedMessageCount: Array.isArray(parsedStatus?.messages) ? parsedStatus.messages.length : 0,
395
+ });
396
+ this.callbacks.onTurnCompleted();
397
+ return true;
398
+ }
399
+
400
+ clearAllTimers(): void {
401
+ if (this.settleTimer) { clearTimeout(this.settleTimer); this.settleTimer = null; }
402
+ if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; }
403
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
404
+ if (this.finishRetryTimer) { clearTimeout(this.finishRetryTimer); this.finishRetryTimer = null; }
405
+ if (this.pendingScriptStatusTimer) { clearTimeout(this.pendingScriptStatusTimer); this.pendingScriptStatusTimer = null; }
406
+ if (this.providerErrorRetryTimer) { clearTimeout(this.providerErrorRetryTimer); this.providerErrorRetryTimer = null; }
407
+ if (this.pendingIdleFinishTimer) { clearTimeout(this.pendingIdleFinishTimer); this.pendingIdleFinishTimer = null; this.pendingIdleFinishAt = 0; }
408
+ this.providerErrorRetryKey = '';
409
+ }
410
+
411
+ resetActiveTurnState(): void {
412
+ this.clearAllTimers();
413
+ this.isWaitingForResponse = false;
414
+ this.responseSettleIgnoreUntil = 0;
415
+ this.submitRetryUsed = false;
416
+ this.submitRetryPromptSnippet = '';
417
+ this.finishRetryCount = 0;
418
+ this.currentTurnScope = null;
419
+ this.activeModal = null;
420
+ this.pendingScriptStatus = null;
421
+ this.pendingScriptStatusSince = 0;
422
+ }
423
+
424
+ clearIdleFinishCandidate(reason: string): void {
425
+ if (!this.idleFinishCandidate) return;
426
+ this.recordTrace('idle_candidate_reset', { reason, candidate: this.idleFinishCandidate });
427
+ this.idleFinishCandidate = null;
428
+ }
429
+
430
+ hasActionableApproval(startupModal?: { message: string; buttons: string[] } | null): boolean {
431
+ return !!(startupModal ?? this.activeModal);
432
+ }
433
+
434
+ getTraceEntries(): CliTraceEntry[] { return this.traceEntries; }
435
+ getStatusHistory(): { status: string; at: number; trigger?: string }[] { return this.statusHistory; }
436
+ getTraceSessionId(): string { return this.traceSessionId; }
437
+
438
+ /** Record a trace entry from the transport layer (e.g. output events in debug mode). */
439
+ recordExternalTrace(type: string, payload: Record<string, any> = {}): void {
440
+ this.recordTrace(type, payload);
441
+ }
442
+
443
+ // ─── Script dispatch (builds inputs from snapshot) ──────────────────────
444
+
445
+ runDetectStatus(snap: CliBufferSnapshot): string | null {
446
+ const tail = snap.recentOutputBuffer.slice(-500);
447
+ return this.runner.detectStatus({
448
+ tail,
449
+ screenText: snap.screenText,
450
+ rawBuffer: snap.accumulatedRawBuffer,
451
+ isWaitingForResponse: snap.isWaitingForResponse,
452
+ screen: buildCliScreenSnapshot(snap.screenText),
453
+ tailScreen: buildCliScreenSnapshot(tail),
454
+ });
455
+ }
456
+
457
+ runParseApproval(snap: CliBufferSnapshot): { message: string; buttons: string[] } | null {
458
+ const tail = snap.recentOutputBuffer.slice(-500);
459
+ const buffer = snap.screenText || snap.accumulatedBuffer;
460
+ return this.runner.parseApproval({
461
+ buffer,
462
+ screenText: snap.screenText,
463
+ rawBuffer: snap.accumulatedRawBuffer,
464
+ tail,
465
+ screen: buildCliScreenSnapshot(snap.screenText),
466
+ bufferScreen: buildCliScreenSnapshot(buffer),
467
+ tailScreen: buildCliScreenSnapshot(tail),
468
+ });
469
+ }
470
+
471
+ runParseSession(snap: CliBufferSnapshot): ParsedSession | null {
472
+ // Allow transport to override session parsing (enables test mocking)
473
+ if (typeof this.transport.runParseSession === 'function') {
474
+ const session = this.transport.runParseSession();
475
+ if (session && typeof session === 'object') {
476
+ this.callbacks.onApplyParsedSession(session);
477
+ }
478
+ return session;
479
+ }
480
+ const tail = snap.recentOutputBuffer.slice(-500);
481
+ const input = buildCliParseInput({
482
+ accumulatedBuffer: snap.accumulatedBuffer,
483
+ accumulatedRawBuffer: snap.accumulatedRawBuffer,
484
+ recentOutputBuffer: snap.recentOutputBuffer,
485
+ terminalScreenText: snap.parseScreenText,
486
+ workingDir: snap.workingDir,
487
+ providerSessionId: snap.providerSessionId || undefined,
488
+ historySessionId: snap.providerSessionId || undefined,
489
+ baseMessages: [],
490
+ partialResponse: snap.responseBuffer,
491
+ isWaitingForResponse: snap.isWaitingForResponse,
492
+ scope: snap.currentTurnScope,
493
+ runtimeSettings: snap.runtimeSettings,
494
+ });
495
+ const session = this.runner.parseSession({
496
+ ...input,
497
+ tail,
498
+ tailScreen: buildCliScreenSnapshot(tail),
499
+ });
500
+ if (session && typeof session === 'object') {
501
+ this.callbacks.onApplyParsedSession(session);
502
+ }
503
+ return session;
504
+ }
505
+
506
+ // ─── Core evaluation loop ───────────────────────────────────────────────
507
+
508
+ evaluateSettled(snap: CliBufferSnapshot): void {
509
+ const now = Date.now();
510
+ if (this.submitPendingUntil > now || this.responseSettleIgnoreUntil > now) {
511
+ const delayTime = Math.max(this.submitPendingUntil - now, this.responseSettleIgnoreUntil - now) + 50;
512
+ if (this.settleTimer) clearTimeout(this.settleTimer);
513
+ this.settleTimer = setTimeout(() => {
514
+ this.settleTimer = null;
515
+ this.evaluateSettled(this.transport.getSnapshot());
516
+ }, delayTime);
517
+ return;
518
+ }
519
+
520
+ if (!this.isWaitingForResponse && !this.currentTurnScope && !this.activeModal && !this.runner.parseErrorMessage) {
521
+ const tail = snap.recentOutputBuffer;
522
+ const modal = this.runParseApproval(snap);
523
+ const lightweightStatus = this.runner.hasDetectStatus() ? this.runDetectStatus(snap) : null;
524
+ if (!modal && lightweightStatus === 'idle' && this.currentStatus === 'idle') return;
525
+ }
526
+
527
+ const session = this.runParseSession(snap);
528
+ if (!session) return;
529
+
530
+ const { status, messages } = session;
531
+ const modal = (session as any).activeModal ?? session.modal ?? null;
532
+ const parsedStatus = (session as any).parsedStatus ?? null;
533
+ const parsedMessages = normalizeCliParsedMessages(messages, {
534
+ scope: null,
535
+ lastOutputAt: snap.lastOutputAt,
536
+ });
537
+
538
+ if (this.maybeCommitVisibleIdleTranscript(session, parsedMessages, snap)) return;
539
+
540
+ const lastParsedAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant');
541
+
542
+ if (
543
+ this.currentTurnScope
544
+ && !lastParsedAssistant
545
+ && !this.submitRetryUsed
546
+ && this.transport.isAlive()
547
+ && !this.hasActionableApproval()
548
+ && promptLikelyVisible(snap.screenText, normalizePromptText(this.submitRetryPromptSnippet || this.currentTurnScope?.prompt || ''))
549
+ && !this.hasMeaningfulResponseBuffer(snap, normalizePromptText(this.submitRetryPromptSnippet || this.currentTurnScope?.prompt || ''))
550
+ ) {
551
+ this.submitRetryUsed = true;
552
+ this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
553
+ LOG.info('CLI', `[${this.provider.type}] Retrying submit key from settled parser (no assistant yet)`);
554
+ this.transport.writeRaw('\r');
555
+ if (this.settleTimer) clearTimeout(this.settleTimer);
556
+ this.settleTimer = setTimeout(() => {
557
+ this.settleTimer = null;
558
+ this.evaluateSettled(this.transport.getSnapshot());
559
+ }, this.timeouts.outputSettle + 150);
560
+ return;
561
+ }
562
+
563
+ if (!status) return;
564
+
565
+ const prevStatus = this.currentStatus;
566
+ const ctx: SettledEvalContext = { now, modal, status, parsedMessages, lastParsedAssistant, parsedStatus: parsedStatus || null, prevStatus };
567
+
568
+ if (!this.applyPendingScriptStatusDebounce(ctx)) return;
569
+
570
+ const recentInteractiveActivity = this.hasRecentInteractiveActivity(snap, now);
571
+ LOG.debug(
572
+ 'CLI',
573
+ `[${this.provider.type}] settled diagnostics prompt=${JSON.stringify(this.currentTurnScope?.prompt || '').slice(0, 140)} status=${String(status || '')} parsedStatus=${String(parsedStatus || '')} parsedMsgCount=${parsedMessages.length} lastParsedAssistant=${JSON.stringify((lastParsedAssistant?.content || '').slice(0, 120)).slice(0, 160)} responseBuffer=${JSON.stringify((snap.responseBuffer || '').slice(0, 160)).slice(0, 220)} recentActivity=${recentInteractiveActivity}`
574
+ );
575
+
576
+ // recent_activity_hold protects an in-flight user turn from a false
577
+ // idle blip. It must NOT fire during startup — when the adapter has
578
+ // no currentTurnScope, there is no user turn to protect; the recent
579
+ // activity is just the CLI painting its welcome screen. Firing here
580
+ // produced the startup status flip the user reported
581
+ // (generating → idle → generating → idle within the first few seconds
582
+ // of claude-cli launch).
583
+ //
584
+ // When isWaitingForResponse=true and a currentTurnScope is alive, a
585
+ // PTY quiet period (>statusActivityHold ms without output) does NOT
586
+ // mean the response is done — claude-cli regularly pauses 2s+ between
587
+ // chunks during parsing/generation. recentInteractiveActivity going
588
+ // false during such a pause was the root cause of false-idle
589
+ // regressions. We hold generating whenever an active response turn is
590
+ // in flight (unconditionally, not just when there was recent output).
591
+ // The real completion gate is applyIdle's idleFinishCandidate +
592
+ // idleFinish timeout, which requires stable quiet AND a parsed
593
+ // assistant message.
594
+ //
595
+ // Fast-path exception: only release the hold if the parser shows a
596
+ // *current-turn* final standard assistant after the last user message,
597
+ // and it is not still streaming. Using !!lastParsedAssistant was too
598
+ // broad — it matched previous-turn assistant messages and caused
599
+ // false-idle between the first assistant text chunk and the first
600
+ // tool call (the agent outputs text, then immediately begins tool use;
601
+ // the gap between them hit this fast path and committed idle).
602
+ const hasFinalCurrentTurnAssistant = (() => {
603
+ if (parsedStatus !== 'idle') return false;
604
+ const msgs: any[] = Array.isArray(parsedMessages) ? parsedMessages : [];
605
+ let lastUserIdx = -1;
606
+ for (let i = msgs.length - 1; i >= 0; i--) {
607
+ if (msgs[i]?.role === 'user') { lastUserIdx = i; break; }
608
+ }
609
+ // No user message visible: fall back to any non-streaming standard assistant.
610
+ const searchSlice = lastUserIdx >= 0 ? msgs.slice(lastUserIdx + 1) : msgs;
611
+ return searchSlice.some((m: any) => {
612
+ if (!m || m.role !== 'assistant') return false;
613
+ if (typeof m.content !== 'string' || !m.content.trim()) return false;
614
+ const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
615
+ return kind === 'standard' && m.meta?.streaming !== true;
616
+ });
617
+ })();
618
+ const shouldHoldGenerating = status === 'idle'
619
+ && this.isWaitingForResponse
620
+ && !!this.currentTurnScope
621
+ && !modal
622
+ && !hasFinalCurrentTurnAssistant;
623
+
624
+ if (shouldHoldGenerating) { this.applyHoldGenerating(ctx); return; }
625
+ if (status === 'error') {
626
+ if (this.maybeScheduleProviderErrorRetry(ctx, session, snap)) return;
627
+ this.applyError(ctx, session);
628
+ return;
629
+ }
630
+ if (status === 'waiting_approval') { this.applyWaitingApproval(ctx); return; }
631
+ if (status === 'generating') { this.applyGenerating(ctx); return; }
632
+ if (status === 'idle') { this.applyIdle(ctx, snap, now); }
633
+ }
634
+
635
+ // ─── State transitions ──────────────────────────────────────────────────
636
+
637
+ private applyPendingScriptStatusDebounce(ctx: SettledEvalContext): boolean {
638
+ const { now, status, prevStatus } = ctx;
639
+ const shouldDebounce = prevStatus === 'idle' && !this.isWaitingForResponse
640
+ && !this.currentTurnScope && (status === 'generating' || status === 'waiting_approval');
641
+
642
+ if (!shouldDebounce) {
643
+ this.pendingScriptStatus = null;
644
+ this.pendingScriptStatusSince = 0;
645
+ if (this.pendingScriptStatusTimer) { clearTimeout(this.pendingScriptStatusTimer); this.pendingScriptStatusTimer = null; }
646
+ return true;
647
+ }
648
+
649
+ const armPending = (delayMs: number) => {
650
+ if (this.pendingScriptStatusTimer) clearTimeout(this.pendingScriptStatusTimer);
651
+ this.pendingScriptStatusTimer = setTimeout(() => {
652
+ this.pendingScriptStatusTimer = null;
653
+ this.evaluateSettled(this.transport.getSnapshot());
654
+ }, delayMs);
655
+ };
656
+
657
+ if (this.pendingScriptStatus !== status) {
658
+ this.pendingScriptStatus = status as 'generating' | 'waiting_approval';
659
+ this.pendingScriptStatusSince = now;
660
+ armPending(SCRIPT_STATUS_DEBOUNCE_MS);
661
+ return false;
662
+ }
663
+ const elapsed = now - this.pendingScriptStatusSince;
664
+ if (elapsed < SCRIPT_STATUS_DEBOUNCE_MS) { armPending(SCRIPT_STATUS_DEBOUNCE_MS - elapsed); return false; }
665
+ return true;
666
+ }
667
+
668
+ private applyHoldGenerating(ctx: SettledEvalContext): void {
669
+ this.clearIdleFinishCandidate('hold_generating_recent_activity');
670
+ this.setStatus('generating', 'recent_activity_hold');
671
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
672
+ this.idleTimeout = setTimeout(() => {
673
+ if (this.isWaitingForResponse && !this.hasActionableApproval()) {
674
+ if (this.shouldDeferIdleTimeoutFinish()) return;
675
+ this.finishResponse();
676
+ }
677
+ }, this.timeouts.generatingIdle);
678
+ this.callbacks.onStatusChange();
679
+ }
680
+
681
+ private applyWaitingApproval(ctx: SettledEvalContext): void {
682
+ const { modal } = ctx;
683
+ this.clearIdleFinishCandidate('waiting_approval');
684
+ const inCooldown = this.lastApprovalResolvedAt
685
+ && (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown;
686
+ if (inCooldown && !modal) {
687
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
688
+ this.activeModal = null;
689
+ const reason = inCooldown ? 'approval_cooldown_non_actionable' : 'approval_prompt_gone_non_actionable';
690
+ if (this.isWaitingForResponse) {
691
+ this.setStatus('idle', reason);
692
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
693
+ this.idleTimeout = setTimeout(() => {
694
+ if (this.isWaitingForResponse && !this.hasActionableApproval()) {
695
+ if (this.shouldDeferIdleTimeoutFinish()) return;
696
+ this.finishResponse();
697
+ }
698
+ }, this.timeouts.generatingIdle);
699
+ } else {
700
+ this.setStatus('idle', reason);
701
+ }
702
+ this.callbacks.onStatusChange();
703
+ return;
704
+ }
705
+ // (fix) A *real* modal with valid buttons surfacing during the cooldown
706
+ // window is a genuinely new approval, not a trailing repaint of the one
707
+ // we just resolved — resolveModal cleared activeModal and flipped status
708
+ // to generating, so detectStatus only re-reports waiting_approval with a
709
+ // concrete modal when the CLI actually presents the next prompt.
710
+ // Previously this case fell through BOTH the `inCooldown && !modal`
711
+ // branch above and the `!inCooldown` branch below, so the FSM silently
712
+ // ignored the second approval — leaving it stuck unresolved under
713
+ // auto-approval. Capture it like any fresh entry (the modal-message
714
+ // cooldown still de-dupes the same approval inside resolveModal, now
715
+ // keyed on approvalEntrySeq). The `!modal` flap case stays gated by
716
+ // cooldown above; only an actionable new modal breaks through here.
717
+ if (!inCooldown || modal) {
718
+ if (!modal) {
719
+ LOG.warn('CLI', `[${this.provider.type}] detectStatus=waiting_approval but parseApproval returned null; ignoring`);
720
+ // (fix) If we previously surfaced waiting_approval but the
721
+ // modal extraction is now failing, eventually drop the modal
722
+ // and fall back to generating so the dashboard doesn't show
723
+ // a "waiting" badge with no buttons. BUT defer the transition
724
+ // for a hysteresis window — Claude TUI re-renders parts of
725
+ // the approval frame multiple times per second and the
726
+ // intermediate parses occasionally lose buttons for a single
727
+ // pass. Flapping the engine status WA → generating → WA →
728
+ // generating between paints fed auto-approve a fresh modal
729
+ // signature each time, which typed the approval key
730
+ // ("1") into the prompt repeatedly. Wait for the modal to
731
+ // stay gone for `approvalCooldown` before clearing.
732
+ if (this.currentStatus === 'waiting_approval' && this.activeModal) {
733
+ const lostAt = this.modalLostAt || Date.now();
734
+ if (!this.modalLostAt) this.modalLostAt = lostAt;
735
+ if (Date.now() - lostAt >= this.timeouts.approvalCooldown) {
736
+ this.activeModal = null;
737
+ this.modalLostAt = 0;
738
+ this.setStatus('generating', 'approval_lost_modal');
739
+ this.callbacks.onStatusChange();
740
+ }
741
+ }
742
+ return;
743
+ }
744
+ this.modalLostAt = 0;
745
+ this.isWaitingForResponse = true;
746
+ this.setStatus('waiting_approval', 'script_detect');
747
+ // (fix) Don't overwrite an already-captured modal with a fresh
748
+ // re-parse on every evaluate — Claude TUI redraws option labels
749
+ // partially between paints (e.g. "Yes, and don't ask again for ..."
750
+ // is wider than the row and ships with a different trailing
751
+ // string each paint), which made the dashboard flap the modal
752
+ // signature continuously. Keep the first stable modal whose
753
+ // button count matches the latest parse; only swap when the
754
+ // shape clearly changed (different number of buttons → different
755
+ // approval).
756
+ const prev = this.activeModal;
757
+ const prevBtnCount = Array.isArray(prev?.buttons) ? prev!.buttons.length : 0;
758
+ const nextBtnCount = Array.isArray(modal.buttons) ? modal.buttons.length : 0;
759
+ if (!prev || prevBtnCount !== nextBtnCount) {
760
+ this.activeModal = modal;
761
+ // A fresh modal was captured (none held, or the button shape
762
+ // changed). This is a distinct approval entry — bump the seq so
763
+ // resolveModal's message-equality cooldown does not mistake it
764
+ // for a flap-repaint of the previously resolved approval.
765
+ this.approvalEntrySeq++;
766
+ this.callbacks.onStatusChange();
767
+ }
768
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
769
+ this.armApprovalExitTimeout();
770
+ }
771
+ }
772
+
773
+ private applyGenerating(ctx: SettledEvalContext): void {
774
+ const { modal, parsedMessages, lastParsedAssistant, parsedStatus, prevStatus } = ctx;
775
+ const noActiveTurn = !this.currentTurnScope;
776
+ // If the turn is already complete (isWaitingForResponse=false, no scope,
777
+ // no modal), PTY generating blips are just the CLI repainting its prompt.
778
+ // Check BEFORE cancelling the pending idle-finish timer — we don't want
779
+ // to cancel a scheduled idle transition just because the CLI blinked.
780
+ if (!this.isWaitingForResponse && noActiveTurn && !modal) return;
781
+ this.clearIdleFinishCandidate('generating');
782
+ // Cancel any pending grace-window idle transition. We have fresh
783
+ // evidence the provider is still generating; the previous
784
+ // finishResponse() was a paint blip, not a real completion.
785
+ this.cancelPendingIdleFinish('generating_signal_returned');
786
+ const snap = this.transport.getSnapshot();
787
+ const effectiveScreenText = snap.screenText || snap.accumulatedBuffer;
788
+ const looksIdleChrome = /(^|\n)\s*[❯›>]\s*(?:\n|$)/m.test(effectiveScreenText);
789
+ const parsedShowsLiveProgress = parsedStatus === 'generating' && !!lastParsedAssistant;
790
+ if (prevStatus === 'idle' && !this.isWaitingForResponse && noActiveTurn && !modal && looksIdleChrome && !parsedShowsLiveProgress) return;
791
+ if (prevStatus === 'waiting_approval') {
792
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
793
+ this.activeModal = null;
794
+ this.lastApprovalResolvedAt = Date.now();
795
+ }
796
+ if (!this.isWaitingForResponse) { this.isWaitingForResponse = true; }
797
+ this.setStatus('generating', 'script_detect');
798
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
799
+ this.idleTimeout = setTimeout(() => {
800
+ if (this.isWaitingForResponse) {
801
+ if (this.shouldDeferIdleTimeoutFinish()) return;
802
+ this.finishResponse();
803
+ }
804
+ }, this.timeouts.generatingIdle);
805
+ this.callbacks.onStatusChange();
806
+ }
807
+
808
+ private applyError(ctx: SettledEvalContext, session: ParsedSession): void {
809
+ this.clearIdleFinishCandidate('provider_error');
810
+ this.clearAllTimers();
811
+ this.isWaitingForResponse = false;
812
+ this.responseSettleIgnoreUntil = 0;
813
+ this.submitRetryUsed = false;
814
+ this.submitRetryPromptSnippet = '';
815
+ this.finishRetryCount = 0;
816
+ this.currentTurnScope = null;
817
+ this.activeModal = null;
818
+ this.providerErrorMessage = typeof session.errorMessage === 'string' && session.errorMessage.trim()
819
+ ? session.errorMessage.trim() : 'Provider reported an error';
820
+ this.providerErrorReason = typeof session.errorReason === 'string' && session.errorReason.trim()
821
+ ? session.errorReason.trim() : 'provider_error';
822
+ this.setStatus('error', this.providerErrorReason);
823
+ this.callbacks.onStatusChange();
824
+ }
825
+
826
+ private maybeScheduleProviderErrorRetry(ctx: SettledEvalContext, session: ParsedSession, snap: CliBufferSnapshot): boolean {
827
+ const retryPrompt = typeof (session as any).retryPrompt === 'string' ? String((session as any).retryPrompt).trim() : '';
828
+ const retryDelayMs = typeof (session as any).retryDelayMs === 'number' ? Number((session as any).retryDelayMs) : NaN;
829
+ if (!retryPrompt || !Number.isFinite(retryDelayMs) || retryDelayMs < 0 || !this.transport.isAlive()) return false;
830
+
831
+ const retryAttempt = typeof (session as any).retryAttempt === 'number' ? Number((session as any).retryAttempt) : 0;
832
+ const errorReason = typeof session.errorReason === 'string' && session.errorReason.trim() ? session.errorReason.trim() : 'provider_error';
833
+ const retryKey = `${errorReason}:${retryAttempt}:${retryPrompt}`;
834
+ if (this.providerErrorRetryTimer && this.providerErrorRetryKey === retryKey) return true;
835
+
836
+ if (this.providerErrorRetryTimer) clearTimeout(this.providerErrorRetryTimer);
837
+ this.providerErrorRetryKey = retryKey;
838
+ this.clearIdleFinishCandidate('provider_error_retry');
839
+ if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; }
840
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
841
+ this.providerErrorMessage = typeof session.errorMessage === 'string' && session.errorMessage.trim()
842
+ ? session.errorMessage.trim() : 'Provider reported an error';
843
+ this.providerErrorReason = errorReason;
844
+ this.activeModal = null;
845
+ this.responseSettleIgnoreUntil = Date.now() + retryDelayMs + this.timeouts.outputSettle + 400;
846
+ this.setStatus('generating', 'provider_error_retry_scheduled');
847
+ this.callbacks.onStatusChange();
848
+
849
+ this.providerErrorRetryTimer = setTimeout(() => {
850
+ this.providerErrorRetryTimer = null;
851
+ this.providerErrorRetryKey = '';
852
+ if (!this.transport.isAlive()) return;
853
+ this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
854
+ this.submitRetryUsed = false;
855
+ this.transport.writeRaw(`${retryPrompt}\r`);
856
+ if (this.settleTimer) clearTimeout(this.settleTimer);
857
+ this.settleTimer = setTimeout(() => {
858
+ this.settleTimer = null;
859
+ this.evaluateSettled(this.transport.getSnapshot());
860
+ }, this.timeouts.outputSettle + 150);
861
+ }, retryDelayMs);
862
+ return true;
863
+ }
864
+
865
+ private applyIdle(ctx: SettledEvalContext, snap: CliBufferSnapshot, now: number): void {
866
+ const { modal, lastParsedAssistant, prevStatus } = ctx;
867
+ if (prevStatus === 'waiting_approval') {
868
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
869
+ this.activeModal = null;
870
+ this.lastApprovalResolvedAt = Date.now();
871
+ this.setStatus('idle', 'approval_prompt_gone_script_idle');
872
+ }
873
+ if (!this.isWaitingForResponse) {
874
+ if (prevStatus !== 'idle') {
875
+ this.clearIdleFinishCandidate('idle_without_response');
876
+ this.setStatus('idle', 'script_detect');
877
+ this.callbacks.onStatusChange();
878
+ }
879
+ return;
880
+ }
881
+ const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
882
+ const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : 0;
883
+ const hasAssistantTurn = !!lastParsedAssistant;
884
+ const assistantLength = (lastParsedAssistant as any)?.content?.length || 0;
885
+ const idleFinishConfirmMs = this.timeouts.idleFinishConfirm;
886
+ const idleQuietThresholdMs = Math.max(idleFinishConfirmMs, this.timeouts.outputSettle);
887
+ const idleReady = !modal && hasAssistantTurn && quietForMs >= idleQuietThresholdMs && screenStableMs >= idleFinishConfirmMs;
888
+ const candidate = this.idleFinishCandidate;
889
+ const candidateQuiet = !!candidate && candidate.responseEpoch === this.responseEpoch
890
+ && candidate.lastOutputAt === snap.lastOutputAt
891
+ && candidate.lastScreenChangeAt === snap.lastScreenChangeAt
892
+ && assistantLength >= candidate.assistantLength
893
+ && (now - candidate.armedAt) >= idleFinishConfirmMs;
894
+
895
+ if (idleReady && candidateQuiet) {
896
+ this.clearIdleFinishCandidate('finish_response');
897
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
898
+ this.finishResponse();
899
+ return;
900
+ }
901
+
902
+ if (idleReady) {
903
+ if (!candidate) { this.armIdleFinishCandidate(snap, assistantLength); return; }
904
+ } else {
905
+ this.clearIdleFinishCandidate('idle_not_ready');
906
+ }
907
+
908
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
909
+ this.idleTimeout = setTimeout(() => {
910
+ if (this.isWaitingForResponse && !this.hasActionableApproval()) {
911
+ if (this.shouldDeferIdleTimeoutFinish()) return;
912
+ const parsed = this.runParseSession(this.transport.getSnapshot());
913
+ if (this.shouldDeferFinishForTranscript(parsed)) {
914
+ this.rescheduleTranscriptFinishCheck('transcript_idle_timeout_not_final');
915
+ return;
916
+ }
917
+ this.clearIdleFinishCandidate('idle_timeout_finish');
918
+ this.finishResponse();
919
+ }
920
+ }, this.timeouts.idleFinish);
921
+ }
922
+
923
+ finishResponse(): void {
924
+ if (this.submitPendingUntil > Date.now()) return;
925
+ if (this.responseSettleIgnoreUntil > Date.now()) return;
926
+ const snap = this.transport.getSnapshot();
927
+ const parsedBeforeFinish = this.runParseSession(snap);
928
+ if (this.shouldDeferFinishForTranscript(parsedBeforeFinish)) {
929
+ this.rescheduleTranscriptFinishCheck('transcript_finish_not_final');
930
+ return;
931
+ }
932
+ this.clearIdleFinishCandidate('finish_response_enter');
933
+ const commitResult = this.commitCurrentTranscript(snap);
934
+ if (this.shouldRetryFinishResponse(snap, commitResult)) {
935
+ this.finishRetryCount += 1;
936
+ if (this.finishRetryTimer) clearTimeout(this.finishRetryTimer);
937
+ this.finishRetryTimer = setTimeout(() => {
938
+ this.finishRetryTimer = null;
939
+ if (this.isWaitingForResponse && !this.hasActionableApproval()) this.finishResponse();
940
+ }, FINISH_RETRY_DELAY_MS);
941
+ return;
942
+ }
943
+ this.resetActiveTurnState();
944
+ this.callbacks.onTurnCompleted();
945
+ // Defer the actual `generating → idle` transition by a short grace
946
+ // window. If applyGenerating fires again before the grace expires —
947
+ // antigravity's tool-result paint blips do this — cancelPendingIdle
948
+ // Finish() drops the pending transition and we stay generating.
949
+ this.scheduleIdleFinish('response_finished');
950
+ this.transport.flushOutboundQueue();
951
+ }
952
+
953
+ private scheduleIdleFinish(reason: string): void {
954
+ // If we are already deferring, replace the schedule so the most
955
+ // recent finishResponse "wins". Reasons accumulate via the trigger.
956
+ if (this.pendingIdleFinishTimer) clearTimeout(this.pendingIdleFinishTimer);
957
+ this.pendingIdleFinishAt = Date.now() + IDLE_CONFIRMATION_GRACE_MS;
958
+ this.pendingIdleFinishTimer = setTimeout(() => {
959
+ this.pendingIdleFinishTimer = null;
960
+ this.pendingIdleFinishAt = 0;
961
+ // If a new user turn started during the grace window, we owe
962
+ // generating semantics to that turn — do not retroactively idle.
963
+ if (this.isWaitingForResponse) return;
964
+ // The timer firing without a cancelPendingIdleFinish call means
965
+ // no fresh applyGenerating happened during the grace window;
966
+ // the previous fake-blip is over. Commit the idle.
967
+ //
968
+ // Note: the previous "currentStatus === 'generating' → return"
969
+ // guard caused stuck-generating sessions — finishResponse leaves
970
+ // currentStatus='generating' on purpose (so the dashboard keeps
971
+ // the spinner during the 2s grace), and then the timer fired
972
+ // without cancellation but refused to commit because the very
973
+ // status we are about to transition out of was still set.
974
+ // Re-checking currentStatus there meant idle was unreachable.
975
+ this.setStatus('idle', reason);
976
+ this.callbacks.onStatusChange();
977
+ }, IDLE_CONFIRMATION_GRACE_MS);
978
+ }
979
+
980
+ private cancelPendingIdleFinish(reason: string): void {
981
+ if (!this.pendingIdleFinishTimer) return;
982
+ clearTimeout(this.pendingIdleFinishTimer);
983
+ this.pendingIdleFinishTimer = null;
984
+ this.pendingIdleFinishAt = 0;
985
+ this.recordTrace('idle_finish_cancelled', { trigger: reason });
986
+ }
987
+
988
+ // ─── Helpers ────────────────────────────────────────────────────────────
989
+
990
+ private armApprovalExitTimeout(): void {
991
+ if (this.approvalExitTimeout) clearTimeout(this.approvalExitTimeout);
992
+ this.approvalExitTimeout = setTimeout(() => {
993
+ if (!this.hasActionableApproval()) return;
994
+ const snap = this.transport.getSnapshot();
995
+ const modal = typeof this.transport.runParseApproval === 'function'
996
+ ? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
997
+ : this.runParseApproval(snap);
998
+ const detectStatus = typeof this.transport.runDetectStatus === 'function'
999
+ ? this.transport.runDetectStatus(snap.recentOutputBuffer)
1000
+ : this.runDetectStatus(snap);
1001
+ const stillWaiting = detectStatus === 'waiting_approval' || !!modal;
1002
+ if (stillWaiting) {
1003
+ if (!modal) {
1004
+ LOG.warn('CLI', `[${this.provider.type}] approval timeout: no actionable modal; keeping fail-closed`);
1005
+ this.activeModal = null;
1006
+ this.callbacks.onStatusChange();
1007
+ this.armApprovalExitTimeout();
1008
+ return;
1009
+ }
1010
+ this.activeModal = modal;
1011
+ this.callbacks.onStatusChange();
1012
+ this.armApprovalExitTimeout();
1013
+ return;
1014
+ }
1015
+ LOG.warn('CLI', `[${this.provider.type}] Approval timeout — auto-clearing`);
1016
+ this.activeModal = null;
1017
+ this.lastApprovalResolvedAt = Date.now();
1018
+ this.setStatus('idle', 'approval_timeout');
1019
+ this.callbacks.onStatusChange();
1020
+ }, APPROVAL_EXIT_TIMEOUT_MS);
1021
+ }
1022
+
1023
+ private armIdleFinishCandidate(snap: CliBufferSnapshot, assistantLength: number): void {
1024
+ const now = Date.now();
1025
+ this.idleFinishCandidate = {
1026
+ armedAt: now,
1027
+ lastOutputAt: snap.lastOutputAt,
1028
+ lastScreenChangeAt: snap.lastScreenChangeAt,
1029
+ responseEpoch: this.responseEpoch,
1030
+ assistantLength,
1031
+ };
1032
+ if (this.settleTimer) clearTimeout(this.settleTimer);
1033
+ this.settleTimer = setTimeout(() => {
1034
+ this.settleTimer = null;
1035
+ this.evaluateSettled(this.transport.getSnapshot());
1036
+ }, this.timeouts.idleFinishConfirm);
1037
+ }
1038
+
1039
+ private shouldDeferIdleTimeoutFinish(): boolean {
1040
+ if (!this.isWaitingForResponse || this.hasActionableApproval()) return false;
1041
+ const snap = this.transport.getSnapshot();
1042
+ const detectFn = typeof this.transport.runDetectStatus === 'function'
1043
+ ? () => this.transport.runDetectStatus!(snap.recentOutputBuffer)
1044
+ : () => this.runDetectStatus(snap);
1045
+ const latestStatus = detectFn() || this.currentStatus;
1046
+ if (latestStatus === 'generating') {
1047
+ this.evaluateSettled(snap);
1048
+ return true;
1049
+ }
1050
+ return false;
1051
+ }
1052
+
1053
+ private hasRecentInteractiveActivity(snap: CliBufferSnapshot, now: number): boolean {
1054
+ const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
1055
+ const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : Number.MAX_SAFE_INTEGER;
1056
+ return quietForMs < this.timeouts.statusActivityHold || screenStableMs < this.timeouts.statusActivityHold;
1057
+ }
1058
+
1059
+ private hasMeaningfulResponseBuffer(snap: CliBufferSnapshot, normalizedPromptSnippet: string): boolean {
1060
+ const raw = String(snap.responseBuffer || '').trim();
1061
+ if (!raw) return false;
1062
+ const normalizedPrompt = compactPromptText(normalizedPromptSnippet);
1063
+ if (!normalizedPrompt) return true;
1064
+ const normalizedBuffer = compactPromptText(raw);
1065
+ if (!normalizedBuffer) return false;
1066
+ if (normalizedBuffer === normalizedPrompt) return false;
1067
+ if (normalizedBuffer.startsWith(normalizedPrompt)) {
1068
+ const remainder = normalizedBuffer.slice(normalizedPrompt.length)
1069
+ .replace(/[─═\-]+/g, '')
1070
+ .replace(/⏵⏵accepteditson\([^)]*\)/gi, '')
1071
+ .replace(/esctointerrupt/gi, '')
1072
+ .replace(/❯/g, '')
1073
+ .replace(/^[\s\-–—:;,.!/?]+/, '')
1074
+ .trim();
1075
+ return remainder.length > 0;
1076
+ }
1077
+ return true;
1078
+ }
1079
+
1080
+ private shouldDeferFinishForTranscript(parsed: any): boolean {
1081
+ // Honor only the explicit manifest opt-in. We used to also hard-code
1082
+ // codex-cli here, but that left codex sessions wedged in `generating`
1083
+ // whenever the PTY parser or native transcript missed the final
1084
+ // assistant line — a much more common failure mode than the original
1085
+ // background-tool race this was meant to guard against. If a provider
1086
+ // really needs the gate, the manifest can set
1087
+ // `requiresFinalAssistantBeforeIdle: true`.
1088
+ const requiresFinalAssistant = !!this.provider.requiresFinalAssistantBeforeIdle;
1089
+ if (!requiresFinalAssistant) return false;
1090
+ if (!this.isWaitingForResponse || !this.currentTurnScope || this.hasActionableApproval()) return false;
1091
+ const parsedStatus = typeof parsed?.status === 'string' ? parsed.status.trim() : '';
1092
+ if (parsedStatus !== 'idle') return true;
1093
+ if (parsed?.activeModal || parsed?.modal) return true;
1094
+ // For providers that own their history externally (e.g. SpecCliAdapter
1095
+ // reading native JSONL), parsed.messages only reflects PTY-visible
1096
+ // content which may include previous-turn assistant messages. Gate on
1097
+ // whether the *current turn* has a final assistant: find the last user
1098
+ // in parsed.messages, and check there is an assistant after it.
1099
+ // If no user found at all (e.g. PTY hid it), defer — the native-history
1100
+ // completion gate in cli-provider-instance will confirm via JSONL read.
1101
+ // For providers that own their history externally (e.g. SpecCliAdapter
1102
+ // reading native JSONL), parsed.messages may include previous-turn
1103
+ // assistant messages. Only an assistant that appears *after* the last
1104
+ // user message counts as evidence the current turn finished.
1105
+ const messages: any[] = Array.isArray(parsed?.messages) ? parsed.messages : [];
1106
+ let lastUserIdx = -1;
1107
+ for (let i = messages.length - 1; i >= 0; i--) {
1108
+ if (messages[i]?.role === 'user') { lastUserIdx = i; break; }
1109
+ }
1110
+ if (lastUserIdx < 0) {
1111
+ // No user message visible in PTY parser. Two sub-cases:
1112
+ // (a) messages is non-empty — some content was parsed but no user
1113
+ // line was found. Use the any-assistant fallback.
1114
+ // (b) messages is empty — the provider owns history externally
1115
+ // (e.g. SpecCliAdapter always returns []) and PTY gives us
1116
+ // nothing to judge. Do NOT defer here: deferring with empty
1117
+ // messages causes an infinite reschedule loop because
1118
+ // parsedStatusHasFinalStandardAssistantMessage also returns
1119
+ // false on empty input. Let cli-provider-instance's native-
1120
+ // history gate handle this case.
1121
+ if (messages.length === 0) return false;
1122
+ return !this.parsedStatusHasFinalStandardAssistantMessage(parsed);
1123
+ }
1124
+ // Check for a final standard assistant after the last user
1125
+ const hasCurrentTurnAssistant = messages.slice(lastUserIdx + 1).some((m: any) => {
1126
+ if (!m || m.role !== 'assistant') return false;
1127
+ if (typeof m.content !== 'string' || !m.content.trim()) return false;
1128
+ const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
1129
+ return kind === 'standard' && m.meta?.streaming !== true;
1130
+ });
1131
+ return !hasCurrentTurnAssistant;
1132
+ }
1133
+
1134
+ private rescheduleTranscriptFinishCheck(reason: string): void {
1135
+ this.clearIdleFinishCandidate(reason);
1136
+ this.setStatus('generating', reason);
1137
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
1138
+ this.idleTimeout = setTimeout(() => {
1139
+ if (!this.isWaitingForResponse || this.hasActionableApproval()) return;
1140
+ this.evaluateSettled(this.transport.getSnapshot());
1141
+ }, this.timeouts.idleFinishConfirm);
1142
+ this.recordTrace('transcript_finish_deferred', { reason });
1143
+ }
1144
+
1145
+ private shouldRetryFinishResponse(snap: CliBufferSnapshot, commitResult: { hasAssistant: boolean; assistantContent: string }): boolean {
1146
+ if (!this.currentTurnScope) return false;
1147
+ if (this.hasActionableApproval()) return false;
1148
+ if (this.finishRetryCount >= MAX_FINISH_RETRIES) return false;
1149
+ if (commitResult.hasAssistant && commitResult.assistantContent.trim()) return false;
1150
+ if (this.runDetectStatus(snap) !== 'idle') return false;
1151
+ const now = Date.now();
1152
+ const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
1153
+ const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : 0;
1154
+ return quietForMs < 1200 || screenStableMs < 1200 || !commitResult.hasAssistant;
1155
+ }
1156
+
1157
+ private commitCurrentTranscript(snap: CliBufferSnapshot): { hasAssistant: boolean; assistantContent: string } {
1158
+ const parsed = this.runParseSession(snap);
1159
+ if (parsed && Array.isArray(parsed.messages)) {
1160
+ const parsedMessages = normalizeCliParsedMessages(parsed.messages, { scope: null, lastOutputAt: snap.lastOutputAt });
1161
+ const lastAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant');
1162
+ if (lastAssistant) return { hasAssistant: true, assistantContent: lastAssistant.content || '' };
1163
+ }
1164
+ return { hasAssistant: false, assistantContent: '' };
1165
+ }
1166
+
1167
+ private maybeCommitVisibleIdleTranscript(session: ParsedSession, parsedMessages: CliChatMessage[], snap: CliBufferSnapshot): boolean {
1168
+ if (!this.provider.allowInputDuringGeneration) return false;
1169
+ if (!session || session.status !== 'idle' || !this.isWaitingForResponse || !this.currentTurnScope || this.activeModal || session.modal) return false;
1170
+ const visibleAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant' && String(m.content || '').trim());
1171
+ if (!visibleAssistant) return false;
1172
+ this.resetActiveTurnState();
1173
+ this.callbacks.onTurnCompleted();
1174
+ this.setStatus('idle', 'script_idle_commit');
1175
+ this.callbacks.onStatusChange();
1176
+ this.transport.flushOutboundQueue();
1177
+ return true;
1178
+ }
1179
+
1180
+ private parsedStatusHasFinalAssistantMessage(parsed: any): boolean {
1181
+ const messages = Array.isArray(parsed?.messages) ? parsed.messages : [];
1182
+ const last = [...messages].reverse().find((m: any) => {
1183
+ if (!m || m.role !== 'assistant') return false;
1184
+ return typeof m.content === 'string' && m.content.trim().length > 0;
1185
+ });
1186
+ return !!last;
1187
+ }
1188
+
1189
+ private parsedStatusHasFinalStandardAssistantMessage(parsed: any): boolean {
1190
+ const messages = Array.isArray(parsed?.messages) ? parsed.messages : [];
1191
+ const last = [...messages].reverse().find((m: any) => {
1192
+ if (!m || m.role !== 'assistant') return false;
1193
+ if (typeof m.content !== 'string' || !m.content.trim()) return false;
1194
+ const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
1195
+ return kind === 'standard' && m.meta?.streaming !== true;
1196
+ });
1197
+ return !!last;
1198
+ }
1199
+
1200
+ private recordTrace(type: string, payload: Record<string, any> = {}): void {
1201
+ const entry: CliTraceEntry = {
1202
+ id: ++this.traceSeq,
1203
+ at: Date.now(),
1204
+ type,
1205
+ status: this.currentStatus,
1206
+ isWaitingForResponse: this.isWaitingForResponse,
1207
+ activeModal: this.activeModal ? { message: this.activeModal.message, buttons: [...this.activeModal.buttons] } : null,
1208
+ payload,
1209
+ };
1210
+ this.traceEntries.push(entry);
1211
+ if (this.traceEntries.length > MAX_TRACE_ENTRIES) {
1212
+ this.traceEntries.splice(0, this.traceEntries.length - MAX_TRACE_ENTRIES);
1213
+ }
1214
+ }
1215
+ }