@adhdev/daemon-core 0.9.82-rc.32 → 0.9.82-rc.321

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 (306) 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 +115 -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 +38 -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 +229 -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 +72 -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/git-commands.d.ts +9 -1
  30. package/dist/git/git-diff.d.ts +6 -0
  31. package/dist/git/git-executor.d.ts +11 -0
  32. package/dist/git/git-status.d.ts +9 -0
  33. package/dist/git/git-types.d.ts +2 -50
  34. package/dist/index.d.ts +51 -12
  35. package/dist/index.js +35378 -11873
  36. package/dist/index.js.map +1 -1
  37. package/dist/index.mjs +38854 -15461
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/installer.d.ts +1 -4
  40. package/dist/ipc/local-ipc-server.d.ts +91 -0
  41. package/dist/launch.d.ts +1 -1
  42. package/dist/logging/async-batch-writer.d.ts +10 -0
  43. package/dist/logging/log-redactor.d.ts +24 -0
  44. package/dist/logging/log-tail-reader.d.ts +46 -0
  45. package/dist/mesh/contracts.d.ts +164 -0
  46. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  47. package/dist/mesh/coordinator-registry.d.ts +59 -0
  48. package/dist/mesh/mesh-active-work.d.ts +108 -0
  49. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  50. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  51. package/dist/mesh/mesh-events-pending.d.ts +45 -0
  52. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  53. package/dist/mesh/mesh-events-utils.d.ts +47 -0
  54. package/dist/mesh/mesh-events.d.ts +6 -49
  55. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  56. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  57. package/dist/mesh/mesh-init.d.ts +86 -0
  58. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  59. package/dist/mesh/mesh-ledger.d.ts +77 -1
  60. package/dist/mesh/mesh-missions.d.ts +116 -0
  61. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  62. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  63. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  64. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  65. package/dist/mesh/mesh-routing.d.ts +70 -0
  66. package/dist/mesh/mesh-runtime-store.d.ts +401 -0
  67. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  68. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  69. package/dist/mesh/mesh-work-queue.d.ts +204 -5
  70. package/dist/mesh/preview-freshness.d.ts +18 -0
  71. package/dist/mesh/refine-config.d.ts +215 -0
  72. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  73. package/dist/providers/acp-provider-instance.d.ts +2 -0
  74. package/dist/providers/approval-utils.d.ts +13 -0
  75. package/dist/providers/cli-provider-instance.d.ts +61 -3
  76. package/dist/providers/contracts.d.ts +130 -6
  77. package/dist/providers/external-sources.d.ts +71 -0
  78. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  79. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  80. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  81. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  82. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  83. package/dist/providers/native-history/index.d.ts +13 -0
  84. package/dist/providers/provider-instance-manager.d.ts +13 -0
  85. package/dist/providers/provider-instance.d.ts +13 -1
  86. package/dist/providers/provider-loader.d.ts +26 -4
  87. package/dist/providers/provider-trust.d.ts +31 -0
  88. package/dist/providers/read-chat-contract.d.ts +29 -0
  89. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  90. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  91. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  92. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  93. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  94. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  95. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  96. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  97. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  98. package/dist/providers/sdk/v1/index.d.ts +30 -0
  99. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  100. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  101. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  102. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  103. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  104. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  105. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  106. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  107. package/dist/providers/spec/adapter.d.ts +69 -0
  108. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  109. package/dist/providers/spec/evaluator.d.ts +23 -0
  110. package/dist/providers/spec/fsm-driver.d.ts +278 -0
  111. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  112. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  113. package/dist/providers/spec/fsm-types.d.ts +128 -0
  114. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  115. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  116. package/dist/providers/spec/route.d.ts +4 -0
  117. package/dist/providers/spec/types.d.ts +180 -0
  118. package/dist/providers/transcript-v2.d.ts +176 -0
  119. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  120. package/dist/providers/working-dir.d.ts +17 -0
  121. package/dist/repo-mesh-types.d.ts +277 -13
  122. package/dist/sessions/registry.d.ts +6 -0
  123. package/dist/shared-types-extra.d.ts +2 -4
  124. package/dist/shared-types.d.ts +42 -1
  125. package/dist/status/normalize.d.ts +1 -1
  126. package/dist/status/normalize.js +1 -0
  127. package/dist/status/normalize.js.map +1 -1
  128. package/dist/status/normalize.mjs +1 -0
  129. package/dist/status/normalize.mjs.map +1 -1
  130. package/dist/status/reporter.d.ts +2 -0
  131. package/dist/status/snapshot.d.ts +1 -0
  132. package/dist/types.d.ts +5 -0
  133. package/package.json +7 -3
  134. package/src/agent-stream/poller.ts +2 -3
  135. package/src/boot/daemon-lifecycle.ts +55 -12
  136. package/src/boot/process-hardening.ts +89 -0
  137. package/src/build-info.ts +73 -0
  138. package/src/chat/source-machine.ts +534 -0
  139. package/src/chat/source-resolver.ts +0 -0
  140. package/src/chat/subscription-updates.ts +20 -1
  141. package/src/cli-adapter-types.d.ts +1 -0
  142. package/src/cli-adapter-types.ts +47 -2
  143. package/src/cli-adapters/cli-script-runner.ts +421 -0
  144. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  145. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  146. package/src/cli-adapters/provider-cli-adapter.ts +710 -1140
  147. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  148. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  149. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  150. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  151. package/src/cli-adapters/provider-cli-shared.ts +85 -11
  152. package/src/cli-adapters/pty-transport.ts +2 -1
  153. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  154. package/src/cli-adapters/resolve-executable.ts +90 -0
  155. package/src/cli-adapters/session-host-transport.ts +2 -1
  156. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  157. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  158. package/src/cli-adapters/terminal-screen.ts +16 -81
  159. package/src/commands/chat-commands.ts +1822 -61
  160. package/src/commands/cli-manager.ts +286 -14
  161. package/src/commands/handler.ts +809 -2
  162. package/src/commands/mesh-coordinator.ts +332 -122
  163. package/src/commands/router.ts +6369 -704
  164. package/src/commands/stream-commands.ts +8 -0
  165. package/src/commands/upgrade-helper.ts +81 -30
  166. package/src/config/chat-history.ts +483 -24
  167. package/src/config/config.ts +12 -0
  168. package/src/config/mesh-config.ts +320 -4
  169. package/src/config/recent-activity.ts +8 -2
  170. package/src/daemon/dev-auto-implement.ts +3 -2
  171. package/src/daemon/dev-cli-debug.ts +10 -1
  172. package/src/detection/cli-detector.ts +28 -9
  173. package/src/detection/ide-detector.ts +55 -16
  174. package/src/detection/win32-ide-version.ts +106 -0
  175. package/src/git/git-commands.ts +42 -12
  176. package/src/git/git-diff.ts +53 -0
  177. package/src/git/git-executor.ts +12 -0
  178. package/src/git/git-status.ts +408 -43
  179. package/src/git/git-types.ts +14 -62
  180. package/src/git/git-worktree.ts +8 -1
  181. package/src/index.ts +145 -11
  182. package/src/installer.d.ts +1 -1
  183. package/src/installer.ts +8 -6
  184. package/src/ipc/local-ipc-server.ts +278 -0
  185. package/src/launch.d.ts +1 -1
  186. package/src/launch.ts +37 -28
  187. package/src/logging/async-batch-writer.ts +55 -0
  188. package/src/logging/log-redactor.ts +100 -0
  189. package/src/logging/log-tail-reader.ts +220 -0
  190. package/src/logging/logger.ts +2 -1
  191. package/src/mesh/contracts.ts +329 -0
  192. package/src/mesh/coordinator-prompt.ts +234 -31
  193. package/src/mesh/coordinator-registry.ts +121 -0
  194. package/src/mesh/mesh-active-work.ts +469 -0
  195. package/src/mesh/mesh-delivery-policy.ts +315 -0
  196. package/src/mesh/mesh-events-coordinator.ts +2102 -0
  197. package/src/mesh/mesh-events-pending.ts +508 -0
  198. package/src/mesh/mesh-events-stale.ts +290 -0
  199. package/src/mesh/mesh-events-utils.ts +254 -0
  200. package/src/mesh/mesh-events.ts +30 -1035
  201. package/src/mesh/mesh-fast-forward.ts +839 -0
  202. package/src/mesh/mesh-host-ownership.ts +73 -0
  203. package/src/mesh/mesh-init.ts +260 -0
  204. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  205. package/src/mesh/mesh-ledger.ts +589 -102
  206. package/src/mesh/mesh-missions.ts +248 -0
  207. package/src/mesh/mesh-reconcile-loop.ts +496 -0
  208. package/src/mesh/mesh-refine-batch.ts +197 -0
  209. package/src/mesh/mesh-refine-status.ts +231 -0
  210. package/src/mesh/mesh-review-inbox.ts +307 -0
  211. package/src/mesh/mesh-routing.ts +291 -0
  212. package/src/mesh/mesh-runtime-store.ts +1578 -0
  213. package/src/mesh/mesh-task-stats.ts +154 -0
  214. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  215. package/src/mesh/mesh-work-queue.ts +663 -142
  216. package/src/mesh/preview-freshness.ts +118 -0
  217. package/src/mesh/refine-config.ts +403 -0
  218. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  219. package/src/providers/acp-provider-instance.ts +19 -4
  220. package/src/providers/approval-utils.d.ts +4 -0
  221. package/src/providers/approval-utils.ts +47 -5
  222. package/src/providers/chat-message-normalization.ts +4 -11
  223. package/src/providers/cli-provider-instance.ts +958 -91
  224. package/src/providers/contracts.d.ts +55 -0
  225. package/src/providers/contracts.ts +141 -6
  226. package/src/providers/extension-provider-instance.ts +5 -1
  227. package/src/providers/external-sources.ts +218 -0
  228. package/src/providers/ide-provider-instance.ts +25 -6
  229. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  230. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  231. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  232. package/src/providers/native-history/dispatcher.ts +340 -0
  233. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  234. package/src/providers/native-history/index.ts +30 -0
  235. package/src/providers/provider-instance-manager.ts +30 -0
  236. package/src/providers/provider-instance.ts +10 -1
  237. package/src/providers/provider-loader.ts +662 -50
  238. package/src/providers/provider-schema.ts +87 -14
  239. package/src/providers/provider-trust.ts +114 -0
  240. package/src/providers/read-chat-contract.ts +76 -16
  241. package/src/providers/sdk/README.md +49 -0
  242. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  243. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  244. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  245. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  246. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  247. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  248. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  249. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  250. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  251. package/src/providers/sdk/v1/index.ts +152 -0
  252. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  253. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  254. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  255. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  256. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  257. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  258. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  259. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  260. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  261. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  262. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  263. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  264. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  265. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  272. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  273. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  274. package/src/providers/sdk/v1/validators/index.ts +19 -0
  275. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  276. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  277. package/src/providers/spec/adapter.ts +168 -0
  278. package/src/providers/spec/cli-adapter.ts +986 -0
  279. package/src/providers/spec/evaluator.ts +345 -0
  280. package/src/providers/spec/fsm-driver.ts +909 -0
  281. package/src/providers/spec/fsm-evaluator.ts +255 -0
  282. package/src/providers/spec/fsm-loader.ts +112 -0
  283. package/src/providers/spec/fsm-types.ts +222 -0
  284. package/src/providers/spec/native-history-executor.ts +1136 -0
  285. package/src/providers/spec/pre-launch-trust.ts +104 -0
  286. package/src/providers/spec/route.ts +51 -0
  287. package/src/providers/spec/types.ts +226 -0
  288. package/src/providers/transcript-v2.ts +567 -0
  289. package/src/providers/types/interactive-prompt.ts +536 -0
  290. package/src/providers/version-archive.ts +64 -24
  291. package/src/providers/working-dir.ts +23 -0
  292. package/src/repo-mesh-types.ts +356 -13
  293. package/src/sessions/registry.ts +6 -0
  294. package/src/shared-types-extra.ts +2 -4
  295. package/src/shared-types.ts +45 -1
  296. package/src/status/builders.ts +26 -6
  297. package/src/status/normalize.ts +2 -0
  298. package/src/status/reporter.ts +15 -0
  299. package/src/status/snapshot.ts +84 -25
  300. package/src/system/host-memory.ts +29 -12
  301. package/src/types.ts +5 -0
  302. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  303. package/dist/mesh/mesh-sync.d.ts +0 -53
  304. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  305. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  306. package/src/mesh/mesh-sync.ts +0 -111
@@ -13,19 +13,22 @@ import { createRequire } from 'node:module';
13
13
  import { normalizeInputEnvelope, type ProviderModule, flattenContent, type InputEnvelope, type InputPart } from './contracts.js';
14
14
  import { assertProviderSupportsDeclaredInput, getEffectiveMessageInputSupport } from './provider-input-support.js';
15
15
  import type { ProviderInstance, ProviderState, ProviderEvent, InstanceContext, ProviderErrorReason, HotChatSessionState, SessionModalState } from './provider-instance.js';
16
+ import { normalizeInteractivePrompt, normalizeInteractivePromptResponse, type InteractivePrompt } from './types/interactive-prompt.js';
16
17
  import { ProviderCliAdapter } from '../cli-adapters/provider-cli-adapter.js';
17
18
  import type { CliProviderModule } from '../cli-adapters/provider-cli-adapter.js';
19
+ import { createCliAdapter } from './spec/route.js';
18
20
  import type { PtyRuntimeMetadata, PtyTransportFactory } from '../cli-adapters/pty-transport.js';
19
21
  import { StatusMonitor } from './status-monitor.js';
20
22
  import { ChatHistoryWriter, isNativeSourceCanonicalHistory, materializeProviderNativeHistory, readChatHistory, readProviderChatHistory } from '../config/chat-history.js';
21
23
  import { LOG } from '../logging/logger.js';
22
24
  import type { ChatMessage } from '../types.js';
23
25
  import { buildPersistedProviderEffectMessage, normalizeProviderEffects } from './control-effects.js';
24
- import { formatAutoApprovalMessage, pickApprovalButton } from './approval-utils.js';
26
+ import { formatAutoApprovalMessage, pickApprovalButton, pickAutoApprovalButton, looksLikeActiveApprovalPromptText } from './approval-utils.js';
25
27
  import { getCliScriptCommand, parseCliScriptResult } from './cli-script-results.js';
26
28
  import { mergeProviderPatchState, resolveProviderStateSurface } from './provider-patch-state.js';
27
29
  import { normalizeProviderSessionId } from './provider-session-id.js';
28
30
  import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages } from './chat-message-normalization.js';
31
+ import { workingDirBasename } from './working-dir.js';
29
32
 
30
33
  type PersistableCliHistoryMessage = {
31
34
  role: string;
@@ -35,17 +38,77 @@ type PersistableCliHistoryMessage = {
35
38
  receivedAt?: number;
36
39
  };
37
40
 
41
+ // Status snapshots only ever surface the newest messages: the cloud 'live'
42
+ // profile drops chat messages entirely (loaded lazily via read_chat on
43
+ // subscribe) and the 'full' profile caps activeChat.messages to the last 60
44
+ // (see status/normalize.ts). Unread/completion markers walk only the tail.
45
+ // So getState()'s saved-history hydration — which runs once per resume/manual
46
+ // CLI session on every status report — must read only a bounded tail, not the
47
+ // entire transcript. A full MAX_SAFE_INTEGER read here makes the initial
48
+ // status report O(transcript) × N(sessions), which is the real cold first-
49
+ // connection bottleneck on chat-heavy machines. The window comfortably exceeds
50
+ // the 60-message snapshot cap so dedup/collapse at the boundary stays stable.
51
+ const STATUS_HYDRATION_TAIL_LIMIT = 200;
52
+
38
53
  type CompletedDebouncePending = {
39
54
  chatTitle: string;
40
55
  duration: number;
41
56
  timestamp: number;
42
57
  firstObservedAt: number;
58
+ previousStatus: string;
43
59
  loggedBlockReason?: string;
60
+ loggedTranscriptProbe?: boolean;
61
+ transcriptProbeHistory?: ExternalTranscriptProbe[];
62
+ };
63
+
64
+ function isIdleStatus(value: unknown): boolean {
65
+ const status = typeof value === 'string' ? value.trim().toLowerCase() : '';
66
+ return !status || status === 'idle' || status === 'ready';
67
+ }
68
+
69
+
70
+ function getMessageTime(message: unknown): number {
71
+ if (!message || typeof message !== 'object') return 0;
72
+ const record = message as { receivedAt?: unknown; timestamp?: unknown };
73
+ const value = Number(record.receivedAt ?? record.timestamp ?? 0);
74
+ return Number.isFinite(value) ? value : 0;
75
+ }
76
+
77
+ type CompletedFinalizationBlock = {
78
+ reason: string;
79
+ terminal?: boolean;
80
+ allowTimeout?: boolean;
81
+ };
82
+
83
+ type CompletionFinalAssistantEvidence = {
84
+ present: boolean;
85
+ messages: unknown[];
86
+ source: 'parsed' | 'external-native' | 'unavailable';
87
+ };
88
+
89
+ type ExternalTranscriptProbe = {
90
+ readAt: number;
91
+ msgCount: number;
92
+ lastRole: string | null;
93
+ lastKind: string | null;
94
+ contentLen: number;
95
+ sourcePath: string | null;
96
+ sourceMtimeMs: number | null;
97
+ mtimeAgeMs: number | null;
44
98
  };
45
99
 
46
100
  const COMPLETED_FINALIZATION_RETRY_MS = 1000;
47
101
  const COMPLETED_FINALIZATION_MAX_WAIT_MS = 30_000;
48
102
 
103
+ /** Events that signal a dispatched mesh task has reached a terminal state.
104
+ * Detach the mesh assignment after emitting one of these so the worker's
105
+ * next unrelated turn doesn't impersonate another completion. */
106
+ const TERMINAL_MESH_EVENTS = new Set([
107
+ 'agent:generating_completed',
108
+ 'agent:stopped',
109
+ 'agent:ready',
110
+ ]);
111
+
49
112
  const IMAGE_MIME_EXTENSIONS: Record<string, string> = {
50
113
  'image/png': '.png',
51
114
  'image/jpeg': '.jpg',
@@ -300,6 +363,19 @@ export class CliProviderInstance implements ProviderInstance {
300
363
  readonly type: string;
301
364
  readonly category = 'cli' as const;
302
365
 
366
+ /**
367
+ * Quiet period an approval modal's signature must be stable before
368
+ * auto-approve sends the approve key. Guards against firing on a prompt
369
+ * that is still streaming into the PTY (the "resolves too fast" symptom):
370
+ * while the modal text/buttons are still changing, every frame yields a
371
+ * new signature and the settle clock restarts. Once the prompt finishes
372
+ * rendering the signature holds and the key is sent after this window.
373
+ * Bounded + small so genuine approvals stay timely. The FSM is already
374
+ * authoritative over the `waiting_approval` state; this only delays the
375
+ * keystroke until the modal *content* has settled.
376
+ */
377
+ private static readonly AUTO_APPROVE_SETTLE_MS = 600;
378
+
303
379
  private adapter: ProviderCliAdapter;
304
380
  private context: InstanceContext | null = null;
305
381
  private events: ProviderEvent[] = [];
@@ -309,15 +385,25 @@ export class CliProviderInstance implements ProviderInstance {
309
385
  private monitor: StatusMonitor;
310
386
  private generatingDebounceTimer: NodeJS.Timeout | null = null;
311
387
  private generatingDebouncePending: { chatTitle: string; timestamp: number } | null = null;
312
- private lastApprovalEventAt = 0;
388
+ private lastApprovalEventFingerprint = '';
313
389
  private autoApproveBusy = false;
314
390
  private autoApproveBusyTimer: NodeJS.Timeout | null = null;
391
+ private lastAutoApprovalSignature = '';
392
+ // Settle gate: the approval modal's signature + the wall-clock when this
393
+ // exact signature was first observed. Auto-approve only fires once the
394
+ // SAME signature has been stable for AUTO_APPROVE_SETTLE_MS, so a prompt
395
+ // still streaming into the PTY (its buttons/message changing frame to
396
+ // frame) keeps resetting the timer and is never approved half-rendered.
397
+ private pendingAutoApprovalSignature = '';
398
+ private pendingAutoApprovalSince = 0;
399
+ private autoApproveSettleTimer: NodeJS.Timeout | null = null;
315
400
  private controlValues: Record<string, string | number | boolean> = {};
316
401
  private summaryMetadata: unknown = undefined;
317
402
  private appliedEffectKeys = new Set<string>();
318
403
  private historyWriter: ChatHistoryWriter;
319
404
  private runtimeMessages: Array<{ key: string; message: ChatMessage }> = [];
320
405
  private lastPersistedHistoryMessages: PersistableCliHistoryMessage[] = [];
406
+ private lastAcknowledgedUserInputAt = 0;
321
407
  private lastNativeSourceCanonicalCheckAt = 0;
322
408
  private lastNativeSourceCanonicalCacheKey: string | undefined = undefined;
323
409
  private cachedSqliteDb: {
@@ -330,6 +416,7 @@ export class CliProviderInstance implements ProviderInstance {
330
416
  private suppressIdleHistoryReplay = false;
331
417
  private errorMessage: string | undefined = undefined;
332
418
  private errorReason: ProviderErrorReason | undefined = undefined;
419
+ private activeInteractivePrompt: InteractivePrompt | null = null;
333
420
 
334
421
  private presentationMode: 'terminal' | 'chat';
335
422
  private providerSessionId?: string;
@@ -370,7 +457,10 @@ export class CliProviderInstance implements ProviderInstance {
370
457
  this.providerSessionId = options?.providerSessionId;
371
458
  this.launchMode = options?.launchMode || 'new';
372
459
  this.onProviderSessionResolved = options?.onProviderSessionResolved;
373
- this.adapter = new ProviderCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory);
460
+ this.adapter = createCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory) as ProviderCliAdapter;
461
+ if (this.providerSessionId) {
462
+ this.adapter.updateRuntimeMeta({ providerSessionId: this.providerSessionId });
463
+ }
374
464
  this.monitor = new StatusMonitor();
375
465
  this.historyWriter = new ChatHistoryWriter();
376
466
  }
@@ -412,7 +502,7 @@ export class CliProviderInstance implements ProviderInstance {
412
502
  await this.adapter.spawn();
413
503
  await this.enforceFreshSessionLaunchIfNeeded();
414
504
  this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
415
- if (this.providerSessionId) {
505
+ if (this.providerSessionId && this.shouldHydrateExistingProviderHistory()) {
416
506
  this.restorePersistedHistoryFromCurrentSession();
417
507
  }
418
508
  if (this.providerSessionId && this.launchMode === 'resume') {
@@ -486,14 +576,38 @@ export class CliProviderInstance implements ProviderInstance {
486
576
  }
487
577
 
488
578
  getState(): ProviderState {
579
+ // TODO(phase5-sandbox): JS override scripts (detectStatus, parseApproval,
580
+ // parseSession) are currently invoked by CliScriptRunner.invoke() via direct
581
+ // function calls — the scripts run in the daemon process with full Node.js
582
+ // access and no resource limits.
583
+ //
584
+ // When Phase 5 lands, CliScriptRunner should route these calls through a
585
+ // SandboxedScriptRunner (see providers/sdk/v1/sandbox/script-runner.ts) so
586
+ // that each call gets a fresh isolated-vm context with a 50 ms CPU limit and
587
+ // a 32 MB memory cap. The execution path to change is:
588
+ // CliScriptRunner.invoke() → SandboxedScriptRunner.run(scriptSource, context)
589
+ //
590
+ // This getState() call-site is NOT where the change goes — the wiring belongs
591
+ // in cli-script-runner.ts (CliScriptRunner.detectStatus / parseApproval /
592
+ // parseSession), with provider-loader.ts updated to store script source strings
593
+ // alongside the loaded function references for extended-legacy providers.
489
594
  const adapterStatus = this.adapter.getStatus();
595
+ if (Object.prototype.hasOwnProperty.call(adapterStatus, 'activeInteractivePrompt')) {
596
+ this.activeInteractivePrompt = adapterStatus.activeInteractivePrompt ?? null;
597
+ }
490
598
  let parsedStatus: any = null;
491
599
  let parseErrorMessage: string | undefined;
492
600
  if (typeof this.adapter.getScriptParsedStatus === 'function') {
493
601
  try {
494
602
  parsedStatus = this.adapter.getScriptParsedStatus() || null;
495
- this.errorMessage = undefined;
496
- this.errorReason = undefined;
603
+ const parsedErrorMessage = typeof parsedStatus?.errorMessage === 'string' && parsedStatus.errorMessage.trim()
604
+ ? parsedStatus.errorMessage.trim()
605
+ : undefined;
606
+ const parsedErrorReason = typeof parsedStatus?.errorReason === 'string' && parsedStatus.errorReason.trim()
607
+ ? parsedStatus.errorReason.trim() as ProviderErrorReason
608
+ : undefined;
609
+ this.errorMessage = parsedErrorMessage;
610
+ this.errorReason = parsedErrorReason;
497
611
  } catch (error: any) {
498
612
  parseErrorMessage = error?.message || String(error);
499
613
  this.errorMessage = parseErrorMessage;
@@ -503,22 +617,53 @@ export class CliProviderInstance implements ProviderInstance {
503
617
  this.errorMessage = undefined;
504
618
  this.errorReason = undefined;
505
619
  }
506
- const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
507
- const visibleStatus = parseErrorMessage
508
- ? 'error'
509
- : (autoApproveActive ? 'generating' : adapterStatus.status);
510
- const parsedProviderSessionId = normalizeProviderSessionId(
620
+ const adapterProviderSessionId = normalizeProviderSessionId(
511
621
  this.provider,
512
- typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
622
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
513
623
  );
514
- if (parsedProviderSessionId) {
515
- this.promoteProviderSessionId(parsedProviderSessionId);
624
+ const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
625
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
626
+ let visibleStatus = parseErrorMessage || parsedStatus?.status === 'error'
627
+ ? 'error'
628
+ : (autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status);
629
+ // getState() must agree with the status the FSM-driven detectStatusTransition()
630
+ // already committed to lastStatus. The adapter's own status is authoritative; we do
631
+ // not second-guess it with native-transcript shape. Only reconcile a generating-like
632
+ // read down to idle when our own lastStatus has already flipped idle (avoids a
633
+ // perpetual dashboard spinner during the brief window before the next getStatus()).
634
+ if (isCliGeneratingLikeStatus(visibleStatus) && this.lastStatus === 'idle') {
635
+ visibleStatus = 'idle';
516
636
  }
517
637
  const runtime = this.adapter.getRuntimeMetadata();
518
638
  this.maybeAppendRuntimeRecoveryMessage(runtime);
519
639
  let parsedMessages = Array.isArray(parsedStatus?.messages)
520
640
  ? parsedStatus.messages
521
641
  : [];
642
+ const parsedProviderSessionId = normalizeProviderSessionId(
643
+ this.provider,
644
+ typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
645
+ );
646
+ const suppressFreshLaunchStartupReplay = this.shouldSuppressFreshLaunchStartupReplay(
647
+ parsedMessages,
648
+ parsedStatus,
649
+ adapterStatus,
650
+ parsedProviderSessionId,
651
+ );
652
+ if (adapterProviderSessionId && !suppressFreshLaunchStartupReplay) {
653
+ this.promoteProviderSessionId(adapterProviderSessionId);
654
+ }
655
+ if (parsedProviderSessionId && !suppressFreshLaunchStartupReplay) {
656
+ this.promoteProviderSessionId(parsedProviderSessionId);
657
+ }
658
+ if (suppressFreshLaunchStartupReplay) {
659
+ parsedMessages = [];
660
+ }
661
+ // Adapter runtime metadata is transport-owned and is not guaranteed to
662
+ // identify this conversation. Spec adapters historically exposed the
663
+ // provider spec id (for example "codex-cli") as runtimeId, which made
664
+ // concurrent sessions share one activeChat identity until their native
665
+ // provider session ids were discovered.
666
+ const activeChatId = this.providerSessionId || this.instanceId;
522
667
  const historyMessageCount = Number.isFinite(parsedStatus?.historyMessageCount)
523
668
  ? Math.max(0, Number(parsedStatus.historyMessageCount))
524
669
  : null;
@@ -528,9 +673,20 @@ export class CliProviderInstance implements ProviderInstance {
528
673
  : [];
529
674
  }
530
675
  const mergedMessages = this.mergeConversationMessages(parsedMessages);
531
- const canonicalBackedHistory = this.syncCanonicalSavedHistoryIfNeeded();
676
+ const canonicalBackedHistory = this.shouldHydrateExistingProviderHistory()
677
+ ? this.syncCanonicalSavedHistoryIfNeeded()
678
+ : false;
679
+ const statusMessages = canonicalBackedHistory && this.lastPersistedHistoryMessages.length > 0
680
+ ? this.lastPersistedHistoryMessages.map((message) => ({
681
+ role: message.role,
682
+ content: message.content,
683
+ kind: message.kind,
684
+ senderName: message.senderName,
685
+ receivedAt: message.receivedAt,
686
+ }))
687
+ : mergedMessages;
532
688
 
533
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
689
+ const dirName = workingDirBasename(this.workingDir);
534
690
  const parsedChatStatus = typeof parsedStatus?.status === 'string' && parsedStatus.status.trim()
535
691
  ? parsedStatus.status.trim()
536
692
  : undefined;
@@ -572,33 +728,48 @@ export class CliProviderInstance implements ProviderInstance {
572
728
  }
573
729
  }
574
730
 
575
- this.applyProviderResponse(parsedStatus, { phase: 'immediate' });
731
+ this.applyProviderResponse(
732
+ suppressFreshLaunchStartupReplay && parsedStatus && typeof parsedStatus === 'object'
733
+ ? { ...parsedStatus, providerSessionId: undefined }
734
+ : parsedStatus,
735
+ { phase: 'immediate' },
736
+ );
576
737
  const surface = resolveProviderStateSurface({
577
738
  summaryMetadata: this.summaryMetadata as any,
578
739
  controlValues: this.controlValues,
579
740
  });
580
741
  const activeChatStatus = parseErrorMessage
581
742
  ? 'error'
582
- : autoApproveActive && parsedStatus?.status === 'waiting_approval'
743
+ : (autoApproveActive && parsedStatus?.status === 'waiting_approval') || autoApproveHoldIdle
583
744
  ? 'generating'
584
745
  : (adapterStatus.status !== 'idle'
585
746
  ? visibleStatus
586
747
  : (suppressStaleParsedBusyStatus ? visibleStatus : (parsedChatStatus || visibleStatus)));
587
748
 
749
+ // If an AskUserQuestion prompt is awaiting user input, overlay status as
750
+ // waiting_choice. This is distinct from waiting_approval (tool-use consent)
751
+ // — the engine's isWaitingForResponse state is unchanged, so completion
752
+ // tracking continues normally once the user responds.
753
+ const hasInteractivePrompt = !!this.activeInteractivePrompt;
754
+ const finalStatus = hasInteractivePrompt ? 'waiting_choice' : visibleStatus;
755
+ const finalChatStatus = hasInteractivePrompt ? 'waiting_choice' : activeChatStatus;
756
+
588
757
  return {
589
758
  type: this.type,
590
759
  name: this.provider.name,
591
760
  category: 'cli',
592
- status: visibleStatus,
761
+ status: finalStatus,
593
762
  mode: this.presentationMode,
594
763
  activeChat: {
595
- id: `${this.type}_${this.workingDir}`,
764
+ id: activeChatId,
596
765
  title: parsedStatus?.title || dirName,
597
- status: activeChatStatus,
598
- messages: mergedMessages,
599
- activeModal: autoApproveActive ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
766
+ status: finalChatStatus,
767
+ messages: statusMessages,
768
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
769
+ activeInteractivePrompt: this.activeInteractivePrompt,
600
770
  inputContent: '',
601
771
  },
772
+ activeInteractivePrompt: this.activeInteractivePrompt,
602
773
  workspace: this.workingDir,
603
774
  instanceId: this.instanceId,
604
775
  providerSessionId: this.providerSessionId,
@@ -639,7 +810,8 @@ export class CliProviderInstance implements ProviderInstance {
639
810
  getHotChatSessionState(): HotChatSessionState {
640
811
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
641
812
  const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
642
- const visibleStatus = autoApproveActive ? 'generating' : adapterStatus.status;
813
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
814
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
643
815
  const runtime = this.adapter.getRuntimeMetadata();
644
816
  return {
645
817
  id: this.instanceId,
@@ -651,21 +823,46 @@ export class CliProviderInstance implements ProviderInstance {
651
823
  };
652
824
  }
653
825
 
654
- getSessionModalState(): SessionModalState {
655
- const adapterStatus = this.adapter.getStatus({ allowParse: false });
826
+ getSessionModalState(sessionId?: string): SessionModalState {
827
+ const adapterStatus = this.adapter.getStatus({ allowParse: true });
656
828
  const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
657
- const visibleStatus = autoApproveActive ? 'generating' : adapterStatus.status;
658
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
829
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
830
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
831
+ const dirName = workingDirBasename(this.workingDir);
659
832
  return {
660
- id: this.instanceId,
833
+ // Honor the caller-supplied sessionId — InstanceMgr rejects the
834
+ // projection when projected.id !== requested sessionId, and
835
+ // this.instanceId is the manager's internal key, not the public
836
+ // sessionId the dashboard subscribes by.
837
+ id: sessionId ?? this.instanceId,
661
838
  status: visibleStatus,
662
839
  title: dirName,
663
- activeModal: autoApproveActive ? null : adapterStatus.activeModal,
840
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : adapterStatus.activeModal,
664
841
  };
665
842
  }
666
843
 
667
844
  updateSettings(newSettings: Record<string, any>): void {
668
- this.settings = { ...newSettings };
845
+ // Merge semantics: a key omitted from newSettings preserves its existing
846
+ // value, a key present in newSettings (even as false) overrides it.
847
+ //
848
+ // This is required because updateSettings has two callers with opposite
849
+ // intent:
850
+ // 1. Full re-injection — the dashboard toggle path (handleSetProviderSetting
851
+ // → getSettings → updateInstanceSettings) sends the COMPLETE settings
852
+ // object, so an explicit autoApprove:false must win.
853
+ // 2. Partial stamp — the mesh relay-safety stamp (router.ts agent_command,
854
+ // buildMeshWorkerRelayStamp) sends ONLY {meshNodeFor, meshNodeId,
855
+ // meshCoordinatorDaemonId, launchedByCoordinator} on every coordinator
856
+ // re-dispatch. It carries no autoApprove, so a full replacement would
857
+ // wipe the launch-time autoApprove:true the worker was started with,
858
+ // silently dropping every later approval to a manual gate until the
859
+ // machine-page toggle re-injected the full settings.
860
+ //
861
+ // A plain merge satisfies both: undefined keys fall through to the existing
862
+ // value (preserving launch-stamp settings like autoApprove + the mesh routing
863
+ // keys), explicit keys override. This subsumes the previous mesh-key preserve
864
+ // list, which only protected the routing keys and not autoApprove.
865
+ this.settings = { ...this.settings, ...newSettings };
669
866
  this.adapter.updateRuntimeSettings?.(this.settings);
670
867
  this.monitor.updateConfig({
671
868
  approvalAlert: this.settings.approvalAlert !== false,
@@ -674,13 +871,53 @@ export class CliProviderInstance implements ProviderInstance {
674
871
  });
675
872
  }
676
873
 
874
+ /**
875
+ * Stamp a direct-dispatch mesh assignment on this instance.
876
+ * setupMeshEventForwarding reads settings.meshNodeFor + meshActiveTaskId to
877
+ * route generating_completed back to the originating coordinator. Without
878
+ * this stamp, mesh_send_task --direct targets a plain CLI session whose
879
+ * completion events silently drop because the forwarder has nothing to
880
+ * match against.
881
+ */
882
+ attachMeshAssignment(assignment: { meshId: string; nodeId?: string; taskId?: string; coordinatorDaemonId?: string }): void {
883
+ if (!assignment?.meshId) return;
884
+ this.settings = {
885
+ ...this.settings,
886
+ meshNodeFor: assignment.meshId,
887
+ ...(assignment.nodeId ? { meshNodeId: assignment.nodeId } : {}),
888
+ ...(assignment.taskId ? { meshActiveTaskId: assignment.taskId } : {}),
889
+ ...(assignment.coordinatorDaemonId ? { meshCoordinatorDaemonId: assignment.coordinatorDaemonId } : {}),
890
+ };
891
+ this.adapter.updateRuntimeSettings?.(this.settings);
892
+ }
893
+
894
+ /**
895
+ * Clear a previously-attached mesh assignment after the task reaches a
896
+ * terminal state. Leaving meshNodeFor pinned would route this session's
897
+ * subsequent unrelated turns (e.g. ad-hoc dashboard chats) to the
898
+ * coordinator as if they were task completions.
899
+ */
900
+ detachMeshAssignment(): void {
901
+ if (!this.settings.meshNodeFor && !this.settings.meshActiveTaskId && !this.settings.meshNodeId) return;
902
+ const { meshNodeFor, meshNodeId, meshActiveTaskId, ...rest } = this.settings;
903
+ void meshNodeFor; void meshNodeId; void meshActiveTaskId;
904
+ this.settings = rest;
905
+ this.adapter.updateRuntimeSettings?.(this.settings);
906
+ }
907
+
677
908
  onEvent(event: string, data?: any): void {
678
909
  if (event === 'send_message') {
679
910
  const input = normalizeInputEnvelope(data);
680
911
  assertProviderSupportsDeclaredInput(this.provider, input);
681
912
  const promptText = buildCliStructuredInputPrompt(input);
682
913
  if (promptText) {
683
- void this.adapter.sendMessage(promptText).catch((e: any) => {
914
+ // force:true bypasses the busy/generating send guard so terminal mesh
915
+ // events (completion/failure/bootstrap) land in a coordinator session that
916
+ // is itself parked in `generating` while awaiting that very event.
917
+ // Without it the message is queued and only flushed on the coordinator's
918
+ // own idle transition — which never happens until it receives the message.
919
+ const force = data?.force === true;
920
+ void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e: any) => {
684
921
  LOG.warn('CLI', `[${this.type}] send_message failed: ${e?.message || e}`);
685
922
  });
686
923
  }
@@ -690,14 +927,73 @@ export class CliProviderInstance implements ProviderInstance {
690
927
  void this.adapter.resolveAction(data).catch((e: any) => {
691
928
  LOG.warn('CLI', `[${this.type}] resolve_action failed: ${e?.message || e}`);
692
929
  });
930
+ } else if (event === 'interactive_prompt' && data) {
931
+ const prompt = normalizeInteractivePrompt(data);
932
+ if (prompt) {
933
+ this.activeInteractivePrompt = prompt;
934
+ this.events.push({
935
+ event: 'interactive_prompt',
936
+ timestamp: Date.now(),
937
+ promptId: prompt.promptId,
938
+ });
939
+ }
940
+ } else if (event === 'interactive_prompt_response' && data) {
941
+ try {
942
+ const response = normalizeInteractivePromptResponse(data);
943
+ if (this.activeInteractivePrompt?.promptId === response.promptId) {
944
+ this.activeInteractivePrompt = null;
945
+ }
946
+ if (typeof this.adapter.setInteractivePromptResponse !== 'function') {
947
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response ignored: adapter does not support interactive prompts`);
948
+ return;
949
+ }
950
+ void this.adapter.setInteractivePromptResponse(response).catch((e: any) => {
951
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response failed: ${e?.message || e}`);
952
+ });
953
+ } catch (e: any) {
954
+ LOG.warn('CLI', `[${this.type}] invalid interactive_prompt_response: ${e?.message || e}`);
955
+ }
693
956
  } else if (event === 'provider_state_patch' && data && typeof data === 'object') {
694
957
  this.applyProviderResponse(data, { phase: 'immediate' });
695
958
  }
696
959
  }
697
960
 
961
+ recordAcknowledgedUserInput(input: InputEnvelope | string): void {
962
+ const content = typeof input === 'string'
963
+ ? input.trim()
964
+ : buildCliStructuredInputPrompt(input).trim();
965
+ if (!content) return;
966
+
967
+ const receivedAt = Date.now();
968
+ this.lastAcknowledgedUserInputAt = receivedAt;
969
+ const dedupKey = `user_input_ack:${crypto
970
+ .createHash('sha256')
971
+ .update(`${this.instanceId}:${content}:${receivedAt}`)
972
+ .digest('hex')
973
+ .slice(0, 24)}`;
974
+ this.appendRuntimeMessage(buildChatMessage({
975
+ role: 'user',
976
+ senderName: 'User',
977
+ kind: 'standard',
978
+ content,
979
+ receivedAt,
980
+ timestamp: receivedAt,
981
+ source: 'runtime_input_ack',
982
+ meta: {
983
+ runtimeInputAck: true,
984
+ provider: this.type,
985
+ workspace: this.workingDir,
986
+ },
987
+ } as ChatMessage), dedupKey);
988
+ }
989
+
698
990
  dispose(): void {
699
991
  this.adapter.shutdown();
700
992
  this.monitor.reset();
993
+ // Cancel any armed auto-approve timers so a pending settle re-check
994
+ // can't fire resolveModal/detectStatusTransition against a dead adapter.
995
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
996
+ if (this.autoApproveBusyTimer) { clearTimeout(this.autoApproveBusyTimer); this.autoApproveBusyTimer = null; }
701
997
  this.appliedEffectKeys.clear();
702
998
  try { this.cachedSqliteDb?.close(); } catch { /* noop */ }
703
999
  this.cachedSqliteDb = null;
@@ -706,6 +1002,7 @@ export class CliProviderInstance implements ProviderInstance {
706
1002
 
707
1003
  private completedDebounceTimer: NodeJS.Timeout | null = null;
708
1004
  private completedDebouncePending: CompletedDebouncePending | null = null;
1005
+ private lastExternalCompletionProbe: ExternalTranscriptProbe | null = null;
709
1006
 
710
1007
  private async enforceFreshSessionLaunchIfNeeded(): Promise<void> {
711
1008
  const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
@@ -740,7 +1037,180 @@ export class CliProviderInstance implements ProviderInstance {
740
1037
  const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
741
1038
  const role = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : '';
742
1039
  const content = lastVisible ? flattenContent(lastVisible.content).trim() : '';
743
- return role === 'assistant' && !!content;
1040
+ if (role !== 'assistant' || !content) return false;
1041
+ // Guard: if the last assistant message looks like an active approval/input prompt,
1042
+ // it is not a real completion — the session is still awaiting user input.
1043
+ if (looksLikeActiveApprovalPromptText(content)) return false;
1044
+ return true;
1045
+ }
1046
+
1047
+ private buildExternalTranscriptProbe(messages: unknown[], sourcePath?: string, sourceMtimeMs?: number): ExternalTranscriptProbe {
1048
+ const visibleMessages = messages.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1049
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1050
+ const readAt = Date.now();
1051
+ const mtimeMs = Number(sourceMtimeMs) || 0;
1052
+ return {
1053
+ readAt,
1054
+ msgCount: messages.length,
1055
+ lastRole: typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null,
1056
+ lastKind: typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null,
1057
+ contentLen: lastVisible ? flattenContent(lastVisible.content).trim().length : 0,
1058
+ sourcePath: typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
1059
+ sourceMtimeMs: mtimeMs || null,
1060
+ mtimeAgeMs: mtimeMs ? Math.max(0, readAt - mtimeMs) : null,
1061
+ };
1062
+ }
1063
+
1064
+ private recordPendingTranscriptProbe(pending: CompletedDebouncePending): ExternalTranscriptProbe | null {
1065
+ const probe = this.lastExternalCompletionProbe;
1066
+ if (!probe) return null;
1067
+ const history = pending.transcriptProbeHistory || [];
1068
+ const last = history[history.length - 1];
1069
+ if (!last || last.readAt !== probe.readAt || last.msgCount !== probe.msgCount || last.lastRole !== probe.lastRole || last.contentLen !== probe.contentLen) {
1070
+ history.push(probe);
1071
+ pending.transcriptProbeHistory = history.slice(-5);
1072
+ }
1073
+ return probe;
1074
+ }
1075
+
1076
+ private readExternalCompletionMessages(): unknown[] | null {
1077
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1078
+ if (!adapterOwnsMessagesElsewhere) return null;
1079
+ if (!this.providerSessionId) return null;
1080
+ if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
1081
+
1082
+ if (this.lastExternalCompletionProbe?.sourcePath) {
1083
+ try { fs.statSync(this.lastExternalCompletionProbe.sourcePath); } catch { /* best-effort metadata refresh */ }
1084
+ }
1085
+ const restoredHistory = readProviderChatHistory(this.type, {
1086
+ canonicalHistory: this.provider.nativeHistory,
1087
+ historySessionId: this.providerSessionId,
1088
+ workspace: this.workingDir,
1089
+ offset: 0,
1090
+ limit: Number.MAX_SAFE_INTEGER,
1091
+ historyBehavior: this.provider.historyBehavior,
1092
+ scripts: this.provider.scripts as any,
1093
+ sessionStartedAtMs: this.startedAt,
1094
+ forceRefresh: true,
1095
+ });
1096
+ if (restoredHistory.source !== 'provider-native') {
1097
+ this.lastExternalCompletionProbe = null;
1098
+ return null;
1099
+ }
1100
+ this.lastExternalCompletionProbe = this.buildExternalTranscriptProbe(
1101
+ restoredHistory.messages,
1102
+ restoredHistory.sourcePath,
1103
+ restoredHistory.sourceMtimeMs,
1104
+ );
1105
+ return restoredHistory.messages;
1106
+ }
1107
+
1108
+ private completionFinalAssistantEvidence(parsedMessages: unknown): CompletionFinalAssistantEvidence {
1109
+ if (this.completionHasFinalAssistantMessage(parsedMessages)) {
1110
+ return {
1111
+ present: true,
1112
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1113
+ source: 'parsed',
1114
+ };
1115
+ }
1116
+
1117
+ const externalMessages = this.readExternalCompletionMessages();
1118
+ if (externalMessages) {
1119
+ return {
1120
+ present: this.completionHasFinalAssistantMessage(externalMessages),
1121
+ messages: externalMessages,
1122
+ source: 'external-native',
1123
+ };
1124
+ }
1125
+
1126
+ return {
1127
+ present: false,
1128
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1129
+ source: 'unavailable',
1130
+ };
1131
+ }
1132
+
1133
+ private completionFinalSummary(parsedMessages: unknown): string | undefined {
1134
+ // For native-source providers (claude-cli: chatMessagesOwnedExternally), the PTY
1135
+ // screen parse is NOT the source of truth for the final summary — the terminal
1136
+ // wraps/scrolls/clips text, so a screen-parsed assistant message is often a partial
1137
+ // prefix (e.g. 76 chars of a 112-char turn). The append-only native transcript holds
1138
+ // the complete turn. Prefer it whenever it yields a longer/complete summary; fall back
1139
+ // to the parsed screen only when the transcript is unavailable. This is the real cause
1140
+ // of the truncated finalSummary — independent of cloud vs standalone (it surfaces on
1141
+ // any short, fast-completing task where screen parse wins the race).
1142
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1143
+ const parsedSummary = extractFinalSummaryFromMessages(
1144
+ (this.completionHasFinalAssistantMessage(parsedMessages)
1145
+ ? (Array.isArray(parsedMessages) ? parsedMessages : [])
1146
+ : []) as any,
1147
+ );
1148
+ if (adapterOwnsMessagesElsewhere) {
1149
+ const externalMessages = this.readExternalCompletionMessages();
1150
+ const externalSummary = externalMessages
1151
+ ? extractFinalSummaryFromMessages(externalMessages as any)
1152
+ : '';
1153
+ // The transcript is authoritative for native-source providers. Use it unless it is
1154
+ // empty (not yet written) — only then fall back to whatever the screen parsed.
1155
+ if (externalSummary) return externalSummary;
1156
+ return parsedSummary || undefined;
1157
+ }
1158
+ return parsedSummary || undefined;
1159
+ }
1160
+
1161
+ private buildCompletedFinalizationDiagnostic(args: {
1162
+ blockReason: string;
1163
+ latestStatus?: any;
1164
+ latestVisibleStatus: string;
1165
+ waitedMs: number;
1166
+ pending: CompletedDebouncePending;
1167
+ emittedAfterFinalizationTimeout: boolean;
1168
+ }): Record<string, unknown> {
1169
+ let parsed: any = null;
1170
+ let parseError: string | undefined;
1171
+ try {
1172
+ parsed = this.adapter.getScriptParsedStatus();
1173
+ } catch (error: any) {
1174
+ parseError = error?.message || String(error);
1175
+ }
1176
+
1177
+ const evidence = this.completionFinalAssistantEvidence(parsed?.messages);
1178
+ if (evidence.source === 'external-native') {
1179
+ this.recordPendingTranscriptProbe(args.pending);
1180
+ }
1181
+ const visibleMessages = (Array.isArray(evidence.messages) ? evidence.messages : [])
1182
+ .filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1183
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1184
+ const lastVisibleRole = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null;
1185
+ const lastVisibleKind = typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null;
1186
+ const lastVisibleContentLength = lastVisible ? flattenContent(lastVisible.content).trim().length : 0;
1187
+
1188
+ return {
1189
+ providerType: this.type,
1190
+ sessionId: this.instanceId,
1191
+ providerSessionId: this.providerSessionId || null,
1192
+ workspace: this.workingDir,
1193
+ blockReason: args.blockReason,
1194
+ emittedAfterFinalizationTimeout: args.emittedAfterFinalizationTimeout,
1195
+ waitedMs: args.waitedMs,
1196
+ maxWaitMs: COMPLETED_FINALIZATION_MAX_WAIT_MS,
1197
+ adapterStatus: typeof args.latestStatus?.status === 'string' ? args.latestStatus.status : null,
1198
+ latestVisibleStatus: args.latestVisibleStatus,
1199
+ parsedStatus: typeof parsed?.status === 'string' ? parsed.status : (parseError ? 'parse_error' : 'unknown'),
1200
+ parseError: parseError || undefined,
1201
+ finalAssistantPresent: evidence.present,
1202
+ finalAssistantEvidenceSource: evidence.source,
1203
+ visibleMessageCount: visibleMessages.length,
1204
+ lastVisibleRole,
1205
+ lastVisibleKind,
1206
+ lastVisibleContentLength,
1207
+ pendingStartedAt: this.generatingStartedAt || null,
1208
+ pendingFirstObservedAt: args.pending.firstObservedAt,
1209
+ pendingTimestamp: args.pending.timestamp,
1210
+ pendingDurationSec: args.pending.duration,
1211
+ previousBlockReason: args.pending.loggedBlockReason || null,
1212
+ transcriptProbeHistory: args.pending.transcriptProbeHistory || [],
1213
+ };
744
1214
  }
745
1215
 
746
1216
  private hasAdapterPendingResponse(): boolean {
@@ -765,32 +1235,97 @@ export class CliProviderInstance implements ProviderInstance {
765
1235
  if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
766
1236
  if (adapterRawStatus !== 'idle') return false;
767
1237
  if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
768
- return !this.hasAdapterPendingResponse();
1238
+ if (this.hasAdapterPendingResponse()) return false;
1239
+ // Do not suppress when the adapter's raw response buffer is still non-empty.
1240
+ // This catches the case where isWaitingForResponse has already flipped to false
1241
+ // (so getPartialResponse() returns '') but the provider's native parser still
1242
+ // reports generating because it's parsing buffered content. Suppressing the
1243
+ // finalization block here would emit a false completion event while the provider
1244
+ // session is still actively processing its response stream.
1245
+ const adapterAny = this.adapter as any;
1246
+ if (typeof adapterAny?.responseBuffer === 'string' && adapterAny.responseBuffer.trim()) return false;
1247
+ return true;
769
1248
  }
770
1249
 
771
- private getCompletedFinalizationBlockReason(latestVisibleStatus: string): string | null {
772
- if (latestVisibleStatus !== 'idle') return `status:${latestVisibleStatus}`;
1250
+ private getCompletedFinalizationBlock(latestVisibleStatus: string, pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1251
+ if (latestVisibleStatus !== 'idle') return { reason: `status:${latestVisibleStatus}`, terminal: true };
773
1252
 
774
1253
  const adapterAny = this.adapter as any;
775
- if (adapterAny?.isWaitingForResponse === true) return 'adapter_waiting_for_response';
776
- if (adapterAny?.currentTurnScope) return 'adapter_turn_scope_active';
1254
+ const approvalResolvedIdle = pending.previousStatus === 'waiting_approval';
1255
+ if (!approvalResolvedIdle) {
1256
+ if (adapterAny?.isWaitingForResponse === true) return { reason: 'adapter_waiting_for_response', terminal: true };
1257
+ if (adapterAny?.currentTurnScope) return { reason: 'adapter_turn_scope_active', terminal: true };
1258
+ if (this.hasAdapterPendingResponse()) return { reason: 'adapter_pending_response', terminal: true };
1259
+ }
777
1260
 
778
1261
  const partial = typeof this.adapter.getPartialResponse === 'function'
779
1262
  ? this.adapter.getPartialResponse()
780
1263
  : '';
781
- if (typeof partial === 'string' && partial.trim()) return 'partial_response_pending';
1264
+ if (typeof partial === 'string' && partial.trim()) return { reason: 'partial_response_pending', terminal: true };
782
1265
 
783
1266
  let parsed: any;
784
1267
  try {
785
1268
  parsed = this.adapter.getScriptParsedStatus();
786
1269
  } catch (error: any) {
787
- return `parse_error:${error?.message || String(error)}`;
1270
+ return { reason: `parse_error:${error?.message || String(error)}` };
788
1271
  }
789
1272
 
790
1273
  const parsedStatus = typeof parsed?.status === 'string' ? parsed.status : 'unknown';
791
- if (parsedStatus !== 'idle') return `parsed_status:${parsedStatus}`;
792
- if (parsed?.activeModal || parsed?.modal) return 'parsed_modal_active';
793
- if (!this.completionHasFinalAssistantMessage(parsed?.messages)) return 'missing_final_assistant';
1274
+ if (parsedStatus !== 'idle') {
1275
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1276
+ if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
1277
+ return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
1278
+ }
1279
+ if (parsed?.activeModal || parsed?.modal) return { reason: 'parsed_modal_active', terminal: true };
1280
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1281
+ const finalAssistantEvidence = this.completionFinalAssistantEvidence(parsed?.messages);
1282
+ const allowMissingAssistantTimeout = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1283
+ LOG.debug('CLI', `[${this.type}] finalAssistantEvidence: present=${finalAssistantEvidence.present} source=${finalAssistantEvidence.source} adapterOwnsMessagesElsewhere=${adapterOwnsMessagesElsewhere} parsedStatus=${parsedStatus}`);
1284
+ if (!finalAssistantEvidence.present) {
1285
+ if (adapterOwnsMessagesElsewhere) {
1286
+ if (finalAssistantEvidence.source === 'external-native') {
1287
+ const probe = this.recordPendingTranscriptProbe(pending);
1288
+ if (probe && !pending.loggedTranscriptProbe) {
1289
+ LOG.info('CLI', `[${this.type}] external transcript probe: msgCount=${probe.msgCount} lastRole=${probe.lastRole || 'none'} lastKind=${probe.lastKind || 'none'} contentLen=${probe.contentLen} sourceMtime=${probe.sourceMtimeMs ?? 'unknown'} mtimeAge=${probe.mtimeAgeMs ?? 'unknown'}ms`);
1290
+ pending.loggedTranscriptProbe = true;
1291
+ }
1292
+ LOG.debug('CLI', `[${this.type}] external-native probe result: lastRole=${probe?.lastRole} contentLen=${probe?.contentLen}`);
1293
+ if (probe?.lastRole === 'assistant' && (probe.contentLen ?? 0) > 0) {
1294
+ return null;
1295
+ }
1296
+ if (this.type === 'antigravity-cli') {
1297
+ return null;
1298
+ }
1299
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1300
+ }
1301
+ if ((this.provider as any).requiresFinalAssistantBeforeIdle === true) {
1302
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1303
+ }
1304
+ } else {
1305
+ LOG.debug('CLI', `[${this.type}] missing_final_assistant (not ownsExternal) requiresFinalAssistant=${!!(this.provider as any).requiresFinalAssistantBeforeIdle}`);
1306
+ return {
1307
+ reason: 'missing_final_assistant',
1308
+ terminal: (this.provider as any).requiresFinalAssistantBeforeIdle === true,
1309
+ allowTimeout: allowMissingAssistantTimeout,
1310
+ };
1311
+ }
1312
+ }
1313
+
1314
+ // Guard: if the screen still shows an approval/choice prompt as the last visible text,
1315
+ // the turn is not complete even if the parsed status says idle and there is an assistant
1316
+ // message. This catches the case where waiting_approval→idle transitions occur before
1317
+ // the modal has been resolved (e.g. the PTY rendered the prompt but no button press fired).
1318
+ try {
1319
+ const screenText = typeof (this.adapter as any).getScreenText === 'function'
1320
+ ? String((this.adapter as any).getScreenText() || '')
1321
+ : '';
1322
+ if (screenText) {
1323
+ const tailLines = screenText.split(/\r?\n/).slice(-16).join('\n');
1324
+ if (looksLikeActiveApprovalPromptText(tailLines)) {
1325
+ return { reason: 'screen_shows_approval_prompt', terminal: approvalResolvedIdle };
1326
+ }
1327
+ }
1328
+ } catch { /* defensive: screen text read is best-effort */ }
794
1329
 
795
1330
  return null;
796
1331
  }
@@ -809,7 +1344,8 @@ export class CliProviderInstance implements ProviderInstance {
809
1344
 
810
1345
  const latestStatus = this.adapter.getStatus({ allowParse: false });
811
1346
  const latestAutoApproveActive = latestStatus.status === 'waiting_approval' && this.shouldAutoApprove();
812
- const latestVisibleStatus = latestAutoApproveActive ? 'generating' : latestStatus.status;
1347
+ const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? 'generating' : latestStatus.status;
1348
+ LOG.debug('CLI', `[${this.type}] flush attempt: adapterStatus=${latestStatus.status} latestVisible=${latestVisibleStatus} generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse} hasPartial=${!!this.adapter.getPartialResponse?.()}`);
813
1349
  if (latestVisibleStatus !== 'idle') {
814
1350
  LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
815
1351
  this.completedDebouncePending = null;
@@ -817,10 +1353,12 @@ export class CliProviderInstance implements ProviderInstance {
817
1353
  return;
818
1354
  }
819
1355
 
820
- const blockReason = this.getCompletedFinalizationBlockReason(latestVisibleStatus);
821
- if (blockReason) {
1356
+ const block = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
1357
+ if (block) {
1358
+ const blockReason = block.reason;
822
1359
  const waitedMs = Date.now() - pending.firstObservedAt;
823
- if (waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
1360
+ LOG.debug('CLI', `[${this.type}] finalization block: reason=${blockReason} terminal=${block.terminal} waitedMs=${waitedMs} maxWait=${COMPLETED_FINALIZATION_MAX_WAIT_MS}`);
1361
+ if ((block.terminal && !block.allowTimeout) || waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
824
1362
  if (pending.loggedBlockReason !== blockReason) {
825
1363
  LOG.info('CLI', `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
826
1364
  pending.loggedBlockReason = blockReason;
@@ -828,10 +1366,29 @@ export class CliProviderInstance implements ProviderInstance {
828
1366
  this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
829
1367
  return;
830
1368
  }
831
- LOG.warn('CLI', `[${this.type}] suppressed completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
1369
+ const completionDiagnostic = this.buildCompletedFinalizationDiagnostic({
1370
+ blockReason,
1371
+ latestStatus,
1372
+ latestVisibleStatus,
1373
+ waitedMs,
1374
+ pending,
1375
+ emittedAfterFinalizationTimeout: true,
1376
+ });
1377
+ LOG.warn('CLI', `[${this.type}] emitting completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
1378
+ this.pushEvent({
1379
+ event: 'agent:generating_completed',
1380
+ chatTitle: pending.chatTitle,
1381
+ duration: pending.duration,
1382
+ timestamp: pending.timestamp,
1383
+ finalSummary: blockReason.startsWith('parsed_status:')
1384
+ ? ''
1385
+ : this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
1386
+ completionDiagnostic,
1387
+ });
832
1388
  this.completedDebouncePending = null;
833
1389
  this.completedDebounceTimer = null;
834
1390
  this.generatingStartedAt = 0;
1391
+ this.lastApprovalEventFingerprint = '';
835
1392
  return;
836
1393
  }
837
1394
 
@@ -841,11 +1398,12 @@ export class CliProviderInstance implements ProviderInstance {
841
1398
  chatTitle: pending.chatTitle,
842
1399
  duration: pending.duration,
843
1400
  timestamp: pending.timestamp,
844
- finalSummary: extractFinalSummaryFromMessages(this.adapter?.getScriptParsedStatus()?.messages),
1401
+ finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
845
1402
  });
846
1403
  this.completedDebouncePending = null;
847
1404
  this.completedDebounceTimer = null;
848
1405
  this.generatingStartedAt = 0;
1406
+ this.lastApprovalEventFingerprint = '';
849
1407
  }
850
1408
 
851
1409
  private maybeAutoApproveStatus(adapterStatus: any, now = Date.now()): boolean {
@@ -853,34 +1411,138 @@ export class CliProviderInstance implements ProviderInstance {
853
1411
  // Guard re-entry: onStatusChange/getState can observe the same modal multiple
854
1412
  // times while the PTY absorbs the approval key. Without this flag, repeated
855
1413
  // snapshots would write stray keys into the input once the modal dismisses.
856
- if (autoApproveActive && !this.autoApproveBusy) {
857
- this.autoApproveBusy = true;
858
- if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
859
- this.autoApproveBusyTimer = setTimeout(() => {
860
- this.autoApproveBusy = false;
861
- this.autoApproveBusyTimer = null;
862
- }, 2000);
863
- const modal = adapterStatus.activeModal;
864
- const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(modal?.buttons, this.provider);
865
- this.recordAutoApproval(modal?.message, buttonLabel, now);
866
- setTimeout(() => {
867
- this.adapter.resolveModal(buttonIndex);
868
- }, 0);
1414
+ // However, Claude Code can present a second approval immediately after the
1415
+ // first. Resolve a changed modal signature even while the previous write is
1416
+ // still inside the short busy window.
1417
+ if (!autoApproveActive) {
1418
+ this.lastAutoApprovalSignature = '';
1419
+ // Clear the settle gate so the next approval starts its own quiet
1420
+ // window from scratch (a stale timestamp would let it fire instantly).
1421
+ this.pendingAutoApprovalSignature = '';
1422
+ this.pendingAutoApprovalSince = 0;
1423
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1424
+ return autoApproveActive;
1425
+ }
1426
+ const modal = adapterStatus.activeModal;
1427
+ // (fix) Do not auto-approve when no concrete modal/buttons are present.
1428
+ // Claude TUI flaps between paints; without this guard adapterStatus
1429
+ // could report status=waiting_approval with activeModal=null (or with
1430
+ // an empty buttons array briefly) and we'd still call
1431
+ // resolveModal(-1) — which used to type "1" into the prompt
1432
+ // repeatedly. Skip until a real modal is captured.
1433
+ const buttons = Array.isArray(modal?.buttons)
1434
+ ? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
1435
+ : [];
1436
+ if (!modal || buttons.length === 0) {
1437
+ return autoApproveActive;
869
1438
  }
1439
+ const { index: buttonIndex, label: buttonLabel } = pickAutoApprovalButton(buttons);
1440
+ if (buttonIndex < 0) {
1441
+ // No concrete button matched — don't pick a random index, just
1442
+ // surface the modal so the user can decide.
1443
+ return autoApproveActive;
1444
+ }
1445
+ // Include the FSM's approval entry seq: two distinct back-to-back
1446
+ // approvals can carry identical message/buttons (common with
1447
+ // claude-cli). Without the seq their signatures collide and the 5s
1448
+ // busy-window re-entry guard below swallows the second auto-approve,
1449
+ // leaving it stuck. The seq is bumped by the FSM on every fresh
1450
+ // waiting_approval entry, so a new approval always yields a new
1451
+ // signature and fires through.
1452
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
1453
+ ? adapterStatus.approvalEntrySeq
1454
+ : 0;
1455
+ const signature = [
1456
+ approvalEntrySeq,
1457
+ typeof modal?.message === 'string' ? modal.message.trim() : '',
1458
+ buttons.join('|'),
1459
+ buttonIndex,
1460
+ ].join('::');
1461
+ // Already fired for this exact modal and still inside the busy window —
1462
+ // nothing to do (re-entry guard for repeated snapshots of one modal).
1463
+ if (this.autoApproveBusy && signature === this.lastAutoApprovalSignature) {
1464
+ return autoApproveActive;
1465
+ }
1466
+
1467
+ // Settle gate: only fire once this exact signature has been stable for
1468
+ // AUTO_APPROVE_SETTLE_MS. A still-streaming prompt mutates its
1469
+ // message/buttons each frame → new signature → clock restarts, so we
1470
+ // never approve a half-rendered prompt (the "resolves too fast" bug).
1471
+ if (signature !== this.pendingAutoApprovalSignature) {
1472
+ this.pendingAutoApprovalSignature = signature;
1473
+ this.pendingAutoApprovalSince = now;
1474
+ }
1475
+ const settledForMs = now - this.pendingAutoApprovalSince;
1476
+ if (settledForMs < CliProviderInstance.AUTO_APPROVE_SETTLE_MS) {
1477
+ // Not yet settled. Arm a timer to re-check after the remaining quiet
1478
+ // window — the PTY may go silent once the prompt finishes painting,
1479
+ // so there is no guaranteed status-change frame to re-drive us.
1480
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1481
+ this.autoApproveSettleTimer = setTimeout(() => {
1482
+ this.autoApproveSettleTimer = null;
1483
+ this.recheckAutoApproveSettled();
1484
+ }, CliProviderInstance.AUTO_APPROVE_SETTLE_MS - settledForMs + 20);
1485
+ return autoApproveActive;
1486
+ }
1487
+
1488
+ // Settled — fire the approve key.
1489
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1490
+ this.autoApproveBusy = true;
1491
+ this.lastAutoApprovalSignature = signature;
1492
+ this.pendingAutoApprovalSignature = '';
1493
+ this.pendingAutoApprovalSince = 0;
1494
+ if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
1495
+ this.autoApproveBusyTimer = setTimeout(() => {
1496
+ this.autoApproveBusy = false;
1497
+ this.autoApproveBusyTimer = null;
1498
+ this.lastAutoApprovalSignature = '';
1499
+ }, 5000);
1500
+ this.recordAutoApproval(modal?.message, buttonLabel, now);
1501
+ setTimeout(() => {
1502
+ this.adapter.resolveModal(buttonIndex);
1503
+ }, 0);
870
1504
  return autoApproveActive;
871
1505
  }
872
1506
 
1507
+ /**
1508
+ * Re-drive the auto-approve check after the settle quiet window elapses.
1509
+ * The PTY may have gone silent once the approval prompt finished painting,
1510
+ * so no status-change frame is guaranteed to re-enter maybeAutoApproveStatus
1511
+ * — this timer-driven re-check picks up the now-settled modal and fires.
1512
+ * Deliberately lighter than detectStatusTransition(): it only re-evaluates
1513
+ * the approval decision; the next real PTY frame refreshes visible status.
1514
+ */
1515
+ private recheckAutoApproveSettled(): void {
1516
+ try {
1517
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1518
+ this.maybeAutoApproveStatus(adapterStatus, Date.now());
1519
+ } catch { /* adapter gone / transient — next frame retries */ }
1520
+ }
1521
+
873
1522
  private detectStatusTransition(): void {
874
1523
  const now = Date.now();
875
1524
  // Status-change handling is a hot path: PTY output can fire it many times
876
1525
  // during long-running CLI sessions. Keep this path on adapter-owned light
877
1526
  // state only; rich provider parsing is reserved for getState/read_chat.
878
1527
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
1528
+ const adapterProviderSessionId = normalizeProviderSessionId(
1529
+ this.provider,
1530
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
1531
+ );
1532
+ if (adapterProviderSessionId) {
1533
+ this.promoteProviderSessionId(adapterProviderSessionId);
1534
+ }
879
1535
  const parsedStatus = null;
880
1536
  const rawStatus = adapterStatus.status;
881
1537
  const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
882
- const newStatus = autoApproveActive ? 'generating' : rawStatus;
883
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
1538
+ // During the autoApproveBusy window (2s after firing approval key), the PTY
1539
+ // can briefly report 'idle' before the next generating phase starts. Treat that
1540
+ // transient idle as 'generating' to suppress a spurious agent:generating_completed
1541
+ // push notification. The adapter's status is otherwise authoritative — native
1542
+ // transcript shape does NOT override the FSM's busy/idle decision.
1543
+ const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === 'idle';
1544
+ const newStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : rawStatus;
1545
+ const dirName = workingDirBasename(this.workingDir);
884
1546
  const chatTitle = `${this.provider.name} · ${dirName}`;
885
1547
  const partial = this.adapter.getPartialResponse();
886
1548
  const progressFingerprint = newStatus === 'generating'
@@ -891,10 +1553,18 @@ export class CliProviderInstance implements ProviderInstance {
891
1553
  if (newStatus !== this.lastStatus) {
892
1554
  LOG.info('CLI', `[${this.type}] status: ${this.lastStatus} → ${newStatus}`);
893
1555
  if (this.lastStatus === 'idle' && newStatus === 'generating') {
1556
+ // If a completion event is already pending and the turn has ended
1557
+ // (generatingStartedAt===0), the PTY is painting its prompt area
1558
+ // after completing. Ignore this blip — do not cancel the pending
1559
+ // completion and do not advance lastStatus to generating.
1560
+ if (this.completedDebouncePending && this.generatingStartedAt === 0) {
1561
+ LOG.debug('CLI', `[${this.type}] ignoring post-completion PTY generating blip (generatingStartedAt=0)`);
1562
+ return;
1563
+ }
894
1564
  this.suppressIdleHistoryReplay = false;
895
1565
  // Cancel any pending completed event (multi-step: idle→generating resume)
896
1566
  if (this.completedDebouncePending) {
897
- LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating)`);
1567
+ LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating) generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse}`);
898
1568
  if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
899
1569
  this.completedDebouncePending = null;
900
1570
  }
@@ -926,10 +1596,29 @@ export class CliProviderInstance implements ProviderInstance {
926
1596
  if (!this.generatingStartedAt) this.generatingStartedAt = now;
927
1597
  const modal = adapterStatus.activeModal;
928
1598
  LOG.info('CLI', `[${this.type}] approval modal: "${modal?.message?.slice(0, 80) ?? 'none'}"`);
929
- // Only push event if not already in waiting_approval (prevent flood from rapid cycles)
930
- const approvalCooldown = 5000;
931
- if (this.lastStatus !== 'waiting_approval' && (!this.lastApprovalEventAt || now - this.lastApprovalEventAt > approvalCooldown)) {
932
- this.lastApprovalEventAt = now;
1599
+ // Include the FSM's approval entry seq, mirroring the auto-approve
1600
+ // path (maybeAutoApproveStatus) and resolveModal's sameEntryReResolve
1601
+ // guard. Two distinct back-to-back approvals can carry identical
1602
+ // message/buttons (very common with claude-cli's "Allow Bash
1603
+ // command?"). Without the seq their fingerprints collide and the dedup
1604
+ // below silently drops the second waiting_approval event — it is never
1605
+ // emitted, so it cannot even land in the pending inbox for a later
1606
+ // read_chat reconcile to recover. The seq is bumped by the FSM on every
1607
+ // fresh waiting_approval entry, so a new approval always yields a new
1608
+ // fingerprint and emits.
1609
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
1610
+ ? adapterStatus.approvalEntrySeq
1611
+ : 0;
1612
+ const approvalFingerprint = JSON.stringify({
1613
+ message: typeof modal?.message === 'string' ? modal.message.trim() : '',
1614
+ buttons: Array.isArray(modal?.buttons) ? modal.buttons.map((button: unknown) => String(button).trim()) : [],
1615
+ seq: approvalEntrySeq,
1616
+ });
1617
+ // PTY redraws repeat the same modal content; fingerprint dedup prevents duplicate events.
1618
+ // Do NOT also gate on lastStatus: consecutive approvals can arrive waiting_approval→waiting_approval
1619
+ // (e.g. antigravity-cli resolves one prompt and immediately shows the next) and would be silently dropped.
1620
+ if (approvalFingerprint !== this.lastApprovalEventFingerprint) {
1621
+ this.lastApprovalEventFingerprint = approvalFingerprint;
933
1622
  this.appendRuntimeSystemMessage(
934
1623
  this.formatApprovalRequestMessage(modal?.message, modal?.buttons),
935
1624
  `approval_request:${now}`,
@@ -941,22 +1630,113 @@ export class CliProviderInstance implements ProviderInstance {
941
1630
  modalButtons: modal?.buttons,
942
1631
  });
943
1632
  }
1633
+ } else if (newStatus === 'generating' && this.lastStatus === 'waiting_approval') {
1634
+ // Approval resolved and the agent resumed work. Defense-in-depth:
1635
+ // clear the approval emit fingerprint here too (not only on
1636
+ // completion at scheduleCompletedDebounceFlush). A subsequent
1637
+ // waiting_approval with the same modal content as the one just
1638
+ // resolved would otherwise collide with the stale fingerprint and be
1639
+ // dropped. The seq in the fingerprint already separates entries; this
1640
+ // reset is a belt-and-suspenders guard for the re-entry case.
1641
+ this.lastApprovalEventFingerprint = '';
944
1642
  } else if (newStatus === 'idle' && (this.lastStatus === 'generating' || this.lastStatus === 'waiting_approval')) {
945
1643
  const duration = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : 0;
946
- // If debounce still pending (generating lasted < 1s), cancel both events
1644
+ // Guard: if generatingStartedAt===0 and no debounce pending, the generating phase
1645
+ // was entered from 'starting' state (startup PTY noise), not from a real idle→generating
1646
+ // task dispatch. The idle→generating handler is the only code path that sets
1647
+ // generatingStartedAt and generatingDebouncePending, so both being absent means no
1648
+ // task was ever dispatched. Suppress the spurious completion event and fall through
1649
+ // to a simple lastStatus update.
1650
+ if (!this.generatingStartedAt && !this.generatingDebouncePending) {
1651
+ LOG.debug('CLI', `[${this.type}] suppressed startup-phase generating→idle blip (generatingStartedAt=0, no debounce pending)`);
1652
+ } else
1653
+ // If debounce still pending (generating lasted < 1s), cancel both UI events.
1654
+ // Still emit agent:generating_completed so mesh orchestration can record
1655
+ // task_completed for direct dispatches that complete faster than the debounce.
947
1656
  if (this.generatingDebouncePending) {
948
- LOG.info('CLI', `[${this.type}] suppressed short generating (${now - this.generatingStartedAt}ms)`);
1657
+ const shortDurationMs = this.generatingStartedAt ? now - this.generatingStartedAt : 0;
1658
+ LOG.info('CLI', `[${this.type}] suppressed short generating (${shortDurationMs}ms)`);
949
1659
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
1660
+ // Emit completion for mesh task association even though the UI generating
1661
+ // started/completed pair is suppressed (too short for visible UI update).
1662
+ let shortFinalSummary: string | undefined;
1663
+ let shortEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
1664
+ try {
1665
+ const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
1666
+ const evidence = this.completionFinalAssistantEvidence(parsedMessages);
1667
+ shortEvidenceSource = evidence.source;
1668
+ shortFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
1669
+ } catch { /* best-effort */ }
1670
+ // If a real response is confirmed, retroactively emit started so the chat
1671
+ // bubble appears even though the debounce suppressed the original event.
1672
+ if (shortFinalSummary) {
1673
+ this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now - shortDurationMs });
1674
+ }
950
1675
  this.generatingDebouncePending = null;
951
1676
  this.generatingStartedAt = 0;
1677
+ const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === 'external-native') && !shortFinalSummary;
1678
+ if (missingEvidence) {
1679
+ LOG.warn('CLI', `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
1680
+ }
1681
+ // When evidence is missing and there is no active mesh task context, suppress
1682
+ // the completion event. Providers with requiresFinalAssistantBeforeIdle or
1683
+ // external-native history must confirm a final assistant message before the
1684
+ // coordinator records task_completed. Only emit here if a mesh task is active
1685
+ // so the coordinator can apply its own timeout/retry logic.
1686
+ const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1687
+ if (missingEvidence && !hasMeshContext) {
1688
+ LOG.info('CLI', `[${this.type}] short completion suppressed: missing final assistant evidence, no mesh context (source=${shortEvidenceSource})`);
1689
+ // completedDebouncePending intentionally left null — the session is now idle
1690
+ // with no confirmed turn, matching the startup-blip suppression semantics.
1691
+ } else {
1692
+ this.pushEvent({
1693
+ event: 'agent:generating_completed',
1694
+ chatTitle,
1695
+ duration: 0,
1696
+ timestamp: now,
1697
+ finalSummary: shortFinalSummary,
1698
+ completionDiagnostic: {
1699
+ reason: 'short_generating_suppressed',
1700
+ shortDurationMs,
1701
+ finalAssistantEvidenceSource: shortEvidenceSource,
1702
+ ...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
1703
+ },
1704
+ });
1705
+ }
952
1706
  } else {
953
1707
  // Debounce completed, then require the rich transcript path that read_chat
954
1708
  // uses to show an idle turn whose last user-facing message is assistant.
955
- this.completedDebouncePending = { chatTitle, duration, timestamp: now, firstObservedAt: now };
956
- this.scheduleCompletedDebounceFlush(3000);
1709
+ this.completedDebouncePending = {
1710
+ chatTitle,
1711
+ duration,
1712
+ timestamp: now,
1713
+ firstObservedAt: now,
1714
+ previousStatus: this.lastStatus,
1715
+ };
1716
+ const ownsExternalHistory = !!(this.adapter as any)?.chatMessagesOwnedExternally;
1717
+ const flushDelay = ownsExternalHistory ? 0 : 3000;
1718
+ LOG.debug('CLI', `[${this.type}] set completedDebouncePending duration=${duration}s ownsExternalHistory=${ownsExternalHistory} flushDelay=${flushDelay}ms generatingStartedAt=${this.generatingStartedAt}`);
1719
+ this.scheduleCompletedDebounceFlush(flushDelay);
957
1720
  }
958
1721
  } else if (newStatus === 'idle' && this.lastStatus === 'starting') {
959
1722
  this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
1723
+ } else if (newStatus === 'error') {
1724
+ if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
1725
+ this.generatingDebouncePending = null;
1726
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
1727
+ this.completedDebouncePending = null;
1728
+ this.errorMessage = adapterStatus.errorMessage || this.errorMessage;
1729
+ this.errorReason = (adapterStatus.errorReason as ProviderErrorReason) || this.errorReason;
1730
+ this.pushEvent({
1731
+ event: 'agent:stopped',
1732
+ chatTitle,
1733
+ timestamp: now,
1734
+ finalSummary: adapterStatus.errorMessage || adapterStatus.errorReason || 'Provider reported an error',
1735
+ completionDiagnostic: {
1736
+ reason: adapterStatus.errorReason || 'provider_error',
1737
+ errorMessage: adapterStatus.errorMessage || undefined,
1738
+ },
1739
+ });
960
1740
  } else if (newStatus === 'stopped') {
961
1741
  // Cancel any pending debounce
962
1742
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
@@ -977,7 +1757,34 @@ export class CliProviderInstance implements ProviderInstance {
977
1757
  // Monitor check (cooldown based notification, IDE/CLI common)
978
1758
  const agentKey = `${this.type}:cli`;
979
1759
  const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint);
1760
+ const monitorParsedStatus: any = parsedStatus;
980
1761
  for (const me of monitorEvents) {
1762
+ if (
1763
+ me.type === 'monitor:long_generating'
1764
+ && this.completionHasFinalAssistantMessage(monitorParsedStatus?.messages)
1765
+ && !this.hasAdapterPendingResponse()
1766
+ && !hasNonEmptyCliModalButtons(monitorParsedStatus?.activeModal ?? monitorParsedStatus?.modal)
1767
+ ) {
1768
+ this.pushEvent({
1769
+ event: 'agent:generating_completed',
1770
+ chatTitle,
1771
+ duration: this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : undefined,
1772
+ timestamp: me.timestamp,
1773
+ finalSummary: extractFinalSummaryFromMessages(monitorParsedStatus?.messages),
1774
+ completionDiagnostic: {
1775
+ providerType: this.type,
1776
+ sessionId: this.instanceId,
1777
+ providerSessionId: this.providerSessionId || null,
1778
+ reconciliationReason: 'long_generating_monitor_final_summary',
1779
+ finalAssistantPresent: true,
1780
+ },
1781
+ });
1782
+ this.generatingStartedAt = 0;
1783
+ // Cancel any pending debounce flush — monitor already fired completion.
1784
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
1785
+ this.completedDebouncePending = null;
1786
+ continue;
1787
+ }
981
1788
  this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
982
1789
  }
983
1790
  }
@@ -1003,9 +1810,18 @@ export class CliProviderInstance implements ProviderInstance {
1003
1810
  };
1004
1811
  if (this.context?.emitProviderEvent) {
1005
1812
  this.context.emitProviderEvent(enrichedEvent);
1006
- return;
1813
+ } else {
1814
+ this.events.push(enrichedEvent);
1815
+ }
1816
+ // Auto-detach a direct-dispatch mesh assignment once the dispatched
1817
+ // task reaches a terminal state. Leaving meshNodeFor pinned would
1818
+ // route this session's next unrelated turn (a dashboard chat) into
1819
+ // the coordinator as if it were the completion of another task.
1820
+ // We schedule after the emit so the originating coordinator still
1821
+ // observes the completion event with its routing marker intact.
1822
+ if (TERMINAL_MESH_EVENTS.has(event.event) && this.settings.meshActiveTaskId) {
1823
+ try { this.detachMeshAssignment(); } catch { /* best-effort */ }
1007
1824
  }
1008
- this.events.push(enrichedEvent);
1009
1825
  }
1010
1826
 
1011
1827
  private flushEvents(): ProviderEvent[] {
@@ -1238,7 +2054,7 @@ export class CliProviderInstance implements ProviderInstance {
1238
2054
  receivedAt: normalizedMessage.receivedAt || normalizedMessage.timestamp,
1239
2055
  historyDedupKey: dedupKey,
1240
2056
  }],
1241
- this.adapter.getScriptParsedStatus?.()?.title || this.workingDir.split('/').filter(Boolean).pop() || 'session',
2057
+ this.adapter.getScriptParsedStatus?.()?.title || workingDirBasename(this.workingDir),
1242
2058
  this.instanceId,
1243
2059
  this.providerSessionId,
1244
2060
  );
@@ -1258,12 +2074,28 @@ export class CliProviderInstance implements ProviderInstance {
1258
2074
  index,
1259
2075
  source: 'parsed',
1260
2076
  }));
2077
+ const getRole = (message: ChatMessage): string => typeof message.role === 'string'
2078
+ ? message.role.trim().toLowerCase()
2079
+ : '';
1261
2080
  const runtimeEntries: MergeEntry[] = this.runtimeMessages.map((entry, index) => ({
1262
2081
  message: entry.message,
1263
2082
  index: parsedMessages.length + index,
1264
- source: 'runtime',
2083
+ source: 'runtime' as const,
1265
2084
  runtimeKey: entry.key,
1266
- }));
2085
+ })).filter((entry) => {
2086
+ const meta = entry.message.meta && typeof entry.message.meta === 'object' && !Array.isArray(entry.message.meta)
2087
+ ? entry.message.meta as Record<string, unknown>
2088
+ : {};
2089
+ if (meta.runtimeInputAck !== true) return true;
2090
+ const runtimeText = flattenContent(entry.message.content).replace(/\s+/g, ' ').trim();
2091
+ if (!runtimeText) return false;
2092
+ return !parsedEntries.some((parsedEntry) => {
2093
+ const parsedRole = getRole(parsedEntry.message);
2094
+ if (parsedRole !== 'user' && parsedRole !== 'human') return false;
2095
+ const parsedText = flattenContent(parsedEntry.message.content).replace(/\s+/g, ' ').trim();
2096
+ return parsedText === runtimeText;
2097
+ });
2098
+ });
1267
2099
  const getTime = (message: ChatMessage): number => {
1268
2100
  const value = typeof message.receivedAt === 'number'
1269
2101
  ? message.receivedAt
@@ -1273,9 +2105,6 @@ export class CliProviderInstance implements ProviderInstance {
1273
2105
  return Number.isFinite(value) && value > 0 ? value : 0;
1274
2106
  };
1275
2107
 
1276
- const getRole = (message: ChatMessage): string => typeof message.role === 'string'
1277
- ? message.role.trim().toLowerCase()
1278
- : '';
1279
2108
  const isRuntimeOverlay = (entry: MergeEntry): boolean => {
1280
2109
  if (entry.source !== 'runtime') return false;
1281
2110
  const key = typeof entry.runtimeKey === 'string' ? entry.runtimeKey.trim().toLowerCase() : '';
@@ -1341,7 +2170,9 @@ export class CliProviderInstance implements ProviderInstance {
1341
2170
  this.providerSessionId = nextSessionId;
1342
2171
  this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
1343
2172
  this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
1344
- this.restorePersistedHistoryFromCurrentSession();
2173
+ if (this.shouldHydrateExistingProviderHistory()) {
2174
+ this.restorePersistedHistoryFromCurrentSession();
2175
+ }
1345
2176
  this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
1346
2177
  this.onProviderSessionResolved?.({
1347
2178
  instanceId: this.instanceId,
@@ -1354,13 +2185,39 @@ export class CliProviderInstance implements ProviderInstance {
1354
2185
  LOG.info('CLI', `[${this.type}] discovered provider session id: ${nextSessionId}`);
1355
2186
  }
1356
2187
 
1357
- private syncCanonicalSavedHistoryIfNeeded(): boolean {
2188
+ private shouldHydrateExistingProviderHistory(): boolean {
2189
+ return this.launchMode === 'resume' || this.launchMode === 'manual';
2190
+ }
2191
+
2192
+ private shouldSuppressFreshLaunchStartupReplay(parsedMessages: unknown[], parsedStatus: any, adapterStatus: any, parsedProviderSessionId = ''): boolean {
2193
+ if (this.launchMode !== 'new') return false;
2194
+ if (this.providerSessionId) return false;
2195
+ if (!Array.isArray(parsedMessages) || parsedMessages.length === 0) return false;
2196
+ if (!isIdleStatus(adapterStatus?.status) || !isIdleStatus(parsedStatus?.status)) return false;
2197
+ if (parsedProviderSessionId) return true;
2198
+
2199
+ const newestMessageAt = parsedMessages.reduce<number>((newest, message) => Math.max(newest, getMessageTime(message)), 0);
2200
+
2201
+ // Untimestamped idle parser output during a fresh launch is usually the
2202
+ // provider's last workspace transcript before a new turn exists.
2203
+ return newestMessageAt === 0;
2204
+ }
2205
+
2206
+ private syncCanonicalSavedHistoryIfNeeded(options: { full?: boolean } = {}): boolean {
1358
2207
  if (!this.providerSessionId) return false;
1359
- const canonicalHistory = this.provider.canonicalHistory;
2208
+ const canonicalHistory = this.provider.nativeHistory;
1360
2209
  if (!canonicalHistory) return false;
1361
2210
 
2211
+ // Per-status-report hydration reads only a bounded tail (snapshot needs at
2212
+ // most the newest 60). The once-per-resume restore path passes full:true
2213
+ // because seedSessionHistory needs the COMPLETE transcript to seed dedup
2214
+ // state. The read-cache key encodes the window so the bounded and full
2215
+ // reads don't share/clobber each other's 2s cache entry.
2216
+ const limit = options.full ? Number.MAX_SAFE_INTEGER : STATUS_HYDRATION_TAIL_LIMIT;
2217
+ const windowTag = options.full ? 'full' : `tail:${STATUS_HYDRATION_TAIL_LIMIT}`;
2218
+
1362
2219
  if (isNativeSourceCanonicalHistory(canonicalHistory)) {
1363
- const cacheKey = [this.type, this.providerSessionId, this.workingDir].join('\0');
2220
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, windowTag].join('\0');
1364
2221
  const now = Date.now();
1365
2222
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1366
2223
  return true;
@@ -1373,7 +2230,7 @@ export class CliProviderInstance implements ProviderInstance {
1373
2230
  historySessionId: this.providerSessionId,
1374
2231
  workspace: this.workingDir,
1375
2232
  offset: 0,
1376
- limit: Number.MAX_SAFE_INTEGER,
2233
+ limit,
1377
2234
  historyBehavior: this.provider.historyBehavior,
1378
2235
  scripts: this.provider.scripts as any,
1379
2236
  });
@@ -1390,7 +2247,7 @@ export class CliProviderInstance implements ProviderInstance {
1390
2247
  }
1391
2248
 
1392
2249
  try {
1393
- const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror'].join('\0');
2250
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror', windowTag].join('\0');
1394
2251
  const now = Date.now();
1395
2252
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1396
2253
  return true;
@@ -1401,7 +2258,14 @@ export class CliProviderInstance implements ProviderInstance {
1401
2258
  if (!materializeProviderNativeHistory(this.type, canonicalHistory, this.providerSessionId, this.workingDir, this.provider.scripts as any)) {
1402
2259
  return false;
1403
2260
  }
1404
- const restoredHistory = readChatHistory(this.type, 0, Number.MAX_SAFE_INTEGER, this.providerSessionId, 0, this.provider.historyBehavior);
2261
+ // Bounded by default: the per-status-report path only needs the newest
2262
+ // STATUS_HYDRATION_TAIL_LIMIT messages because the snapshot caps
2263
+ // activeChat.messages to the last 60 (status/normalize.ts) and loads
2264
+ // the rest lazily via read_chat on subscribe. The once-per-resume
2265
+ // restore path passes full:true so seedSessionHistory still sees the
2266
+ // COMPLETE transcript for prefix-dedup seeding. readChatHistory serves
2267
+ // a bounded limit as an O(tail) read.
2268
+ const restoredHistory = readChatHistory(this.type, 0, limit, this.providerSessionId, 0, this.provider.historyBehavior);
1405
2269
  this.lastPersistedHistoryMessages = restoredHistory.messages.map((message) => ({
1406
2270
  role: message.role,
1407
2271
  content: message.content,
@@ -1417,10 +2281,13 @@ export class CliProviderInstance implements ProviderInstance {
1417
2281
 
1418
2282
  private restorePersistedHistoryFromCurrentSession(): void {
1419
2283
  if (!this.providerSessionId) return;
1420
- this.syncCanonicalSavedHistoryIfNeeded();
1421
- const restoredHistory = isNativeSourceCanonicalHistory(this.provider.canonicalHistory)
2284
+ // Restore is the once-per-resume seeding path: it needs the COMPLETE
2285
+ // transcript so seedSessionHistory can prime dedup state. Pass full so the
2286
+ // hydration read is unbounded here (and only here).
2287
+ this.syncCanonicalSavedHistoryIfNeeded({ full: true });
2288
+ const restoredHistory = isNativeSourceCanonicalHistory(this.provider.nativeHistory)
1422
2289
  ? readProviderChatHistory(this.type, {
1423
- canonicalHistory: this.provider.canonicalHistory,
2290
+ canonicalHistory: this.provider.nativeHistory,
1424
2291
  historySessionId: this.providerSessionId,
1425
2292
  workspace: this.workingDir,
1426
2293
  offset: 0,