@adhdev/daemon-core 0.9.82-rc.21 → 0.9.82-rc.210

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