@adhdev/daemon-core 0.9.82-rc.36 → 0.9.82-rc.360

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 (325) 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 +55 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +125 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +336 -1
  23. package/dist/commands/upgrade-helper.d.ts +41 -1
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +54 -13
  37. package/dist/index.js +44143 -17595
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +43858 -17438
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/logging/logger.d.ts +1 -1
  48. package/dist/mesh/contracts.d.ts +164 -0
  49. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  50. package/dist/mesh/coordinator-registry.d.ts +59 -0
  51. package/dist/mesh/mesh-active-work.d.ts +174 -0
  52. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  53. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  54. package/dist/mesh/mesh-events-coordinator.d.ts +170 -0
  55. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  56. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  57. package/dist/mesh/mesh-events-utils.d.ts +62 -0
  58. package/dist/mesh/mesh-events.d.ts +6 -49
  59. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  60. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  61. package/dist/mesh/mesh-init.d.ts +86 -0
  62. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  63. package/dist/mesh/mesh-ledger.d.ts +77 -1
  64. package/dist/mesh/mesh-missions.d.ts +164 -0
  65. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  66. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  67. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  68. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  69. package/dist/mesh/mesh-routing.d.ts +70 -0
  70. package/dist/mesh/mesh-runtime-store.d.ts +429 -0
  71. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  72. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  73. package/dist/mesh/mesh-work-queue.d.ts +246 -5
  74. package/dist/mesh/preview-freshness.d.ts +18 -0
  75. package/dist/mesh/refine-config.d.ts +216 -0
  76. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  77. package/dist/providers/acp-provider-instance.d.ts +5 -0
  78. package/dist/providers/approval-utils.d.ts +20 -0
  79. package/dist/providers/chat-message-normalization.d.ts +12 -0
  80. package/dist/providers/cli-provider-instance.d.ts +106 -3
  81. package/dist/providers/contracts.d.ts +139 -6
  82. package/dist/providers/external-sources.d.ts +71 -0
  83. package/dist/providers/manual-attendance.d.ts +63 -0
  84. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  85. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  86. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  87. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  88. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  89. package/dist/providers/native-history/index.d.ts +13 -0
  90. package/dist/providers/provider-instance-manager.d.ts +14 -0
  91. package/dist/providers/provider-instance.d.ts +23 -1
  92. package/dist/providers/provider-loader.d.ts +26 -4
  93. package/dist/providers/provider-trust.d.ts +31 -0
  94. package/dist/providers/read-chat-contract.d.ts +29 -0
  95. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  96. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  97. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  98. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  99. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  100. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  101. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  102. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  103. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  104. package/dist/providers/sdk/v1/index.d.ts +30 -0
  105. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  106. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  107. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  108. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  109. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  110. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  111. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  112. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  113. package/dist/providers/spec/adapter.d.ts +91 -0
  114. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  115. package/dist/providers/spec/evaluator.d.ts +45 -0
  116. package/dist/providers/spec/fsm-driver.d.ts +368 -0
  117. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  118. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  119. package/dist/providers/spec/fsm-types.d.ts +174 -0
  120. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  121. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  122. package/dist/providers/spec/route.d.ts +4 -0
  123. package/dist/providers/spec/types.d.ts +222 -0
  124. package/dist/providers/status-monitor.d.ts +7 -7
  125. package/dist/providers/transcript-v2.d.ts +176 -0
  126. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  127. package/dist/providers/working-dir.d.ts +17 -0
  128. package/dist/repo-mesh-types.d.ts +295 -13
  129. package/dist/sessions/registry.d.ts +6 -0
  130. package/dist/shared-types-extra.d.ts +2 -4
  131. package/dist/shared-types.d.ts +59 -2
  132. package/dist/status/normalize.d.ts +1 -1
  133. package/dist/status/normalize.js +1 -0
  134. package/dist/status/normalize.js.map +1 -1
  135. package/dist/status/normalize.mjs +1 -0
  136. package/dist/status/normalize.mjs.map +1 -1
  137. package/dist/status/reporter.d.ts +2 -0
  138. package/dist/status/snapshot.d.ts +26 -0
  139. package/dist/system/load-better-sqlite3.d.ts +21 -0
  140. package/dist/types.d.ts +5 -0
  141. package/package.json +7 -3
  142. package/src/agent-stream/poller.ts +2 -3
  143. package/src/agent-stream/provider-adapter.ts +1 -1
  144. package/src/boot/daemon-lifecycle.ts +55 -12
  145. package/src/boot/process-hardening.ts +89 -0
  146. package/src/build-info.ts +73 -0
  147. package/src/chat/source-machine.ts +534 -0
  148. package/src/chat/source-resolver.ts +0 -0
  149. package/src/chat/subscription-updates.ts +20 -1
  150. package/src/cli-adapter-types.d.ts +1 -0
  151. package/src/cli-adapter-types.ts +56 -2
  152. package/src/cli-adapters/cli-script-runner.ts +421 -0
  153. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  154. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  155. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  156. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  157. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  158. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  159. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  160. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  161. package/src/cli-adapters/pty-transport.ts +2 -1
  162. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  163. package/src/cli-adapters/resolve-executable.ts +90 -0
  164. package/src/cli-adapters/session-host-transport.ts +2 -1
  165. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  166. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  167. package/src/cli-adapters/terminal-screen.ts +16 -81
  168. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  169. package/src/commands/chat-commands.ts +1823 -62
  170. package/src/commands/cli-manager.ts +336 -19
  171. package/src/commands/handler.ts +841 -2
  172. package/src/commands/mesh-coordinator.ts +332 -122
  173. package/src/commands/router.ts +7624 -1312
  174. package/src/commands/stream-commands.ts +8 -0
  175. package/src/commands/upgrade-helper.ts +310 -45
  176. package/src/config/chat-history.ts +483 -24
  177. package/src/config/config.ts +12 -0
  178. package/src/config/mesh-config.ts +388 -6
  179. package/src/config/recent-activity.ts +8 -2
  180. package/src/daemon/dev-auto-implement.ts +3 -2
  181. package/src/daemon/dev-cli-debug.ts +10 -1
  182. package/src/detection/cli-detector.ts +28 -9
  183. package/src/detection/ide-detector.ts +55 -16
  184. package/src/detection/win32-ide-version.ts +106 -0
  185. package/src/git/change-impact-config.ts +354 -0
  186. package/src/git/git-commands.ts +55 -14
  187. package/src/git/git-diff.ts +81 -11
  188. package/src/git/git-executor.ts +12 -0
  189. package/src/git/git-status.ts +574 -43
  190. package/src/git/git-types.ts +14 -62
  191. package/src/git/git-worktree.ts +8 -1
  192. package/src/git/index.ts +16 -0
  193. package/src/index.ts +156 -12
  194. package/src/installer.d.ts +1 -1
  195. package/src/installer.ts +8 -6
  196. package/src/ipc/local-ipc-server.ts +278 -0
  197. package/src/launch.d.ts +1 -1
  198. package/src/launch.ts +37 -28
  199. package/src/logging/async-batch-writer.ts +55 -0
  200. package/src/logging/command-log.ts +7 -5
  201. package/src/logging/log-redactor.ts +100 -0
  202. package/src/logging/log-tail-reader.ts +220 -0
  203. package/src/logging/logger.ts +14 -7
  204. package/src/mesh/contracts.ts +329 -0
  205. package/src/mesh/coordinator-prompt.ts +234 -31
  206. package/src/mesh/coordinator-registry.ts +121 -0
  207. package/src/mesh/mesh-active-work.ts +667 -0
  208. package/src/mesh/mesh-delivery-policy.ts +315 -0
  209. package/src/mesh/mesh-event-trace.ts +67 -0
  210. package/src/mesh/mesh-events-coordinator.ts +2572 -0
  211. package/src/mesh/mesh-events-pending.ts +599 -0
  212. package/src/mesh/mesh-events-stale.ts +309 -0
  213. package/src/mesh/mesh-events-utils.ts +381 -0
  214. package/src/mesh/mesh-events.ts +30 -1035
  215. package/src/mesh/mesh-fast-forward.ts +839 -0
  216. package/src/mesh/mesh-host-ownership.ts +73 -0
  217. package/src/mesh/mesh-init.ts +260 -0
  218. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  219. package/src/mesh/mesh-ledger.ts +591 -102
  220. package/src/mesh/mesh-missions.ts +322 -0
  221. package/src/mesh/mesh-reconcile-loop.ts +1096 -0
  222. package/src/mesh/mesh-refine-batch.ts +197 -0
  223. package/src/mesh/mesh-refine-status.ts +231 -0
  224. package/src/mesh/mesh-review-inbox.ts +307 -0
  225. package/src/mesh/mesh-routing.ts +291 -0
  226. package/src/mesh/mesh-runtime-store.ts +1697 -0
  227. package/src/mesh/mesh-task-stats.ts +161 -0
  228. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  229. package/src/mesh/mesh-work-queue.ts +997 -141
  230. package/src/mesh/preview-freshness.ts +118 -0
  231. package/src/mesh/refine-config.ts +423 -0
  232. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  233. package/src/providers/acp-provider-instance.ts +43 -10
  234. package/src/providers/approval-utils.d.ts +5 -0
  235. package/src/providers/approval-utils.ts +57 -5
  236. package/src/providers/chat-message-normalization.ts +45 -5
  237. package/src/providers/cli-provider-instance.ts +1254 -101
  238. package/src/providers/contracts.d.ts +55 -0
  239. package/src/providers/contracts.ts +150 -6
  240. package/src/providers/extension-provider-instance.ts +12 -7
  241. package/src/providers/external-sources.ts +218 -0
  242. package/src/providers/ide-provider-instance.ts +35 -12
  243. package/src/providers/manual-attendance.ts +85 -0
  244. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  245. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  246. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  247. package/src/providers/native-history/dispatcher.ts +340 -0
  248. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  249. package/src/providers/native-history/index.ts +30 -0
  250. package/src/providers/provider-instance-manager.ts +30 -0
  251. package/src/providers/provider-instance.ts +19 -1
  252. package/src/providers/provider-loader.ts +670 -50
  253. package/src/providers/provider-schema.ts +87 -14
  254. package/src/providers/provider-trust.ts +114 -0
  255. package/src/providers/read-chat-contract.ts +76 -16
  256. package/src/providers/sdk/README.md +49 -0
  257. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  258. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  259. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  260. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  261. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  262. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  263. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  264. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  265. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  266. package/src/providers/sdk/v1/index.ts +152 -0
  267. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  268. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  269. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  270. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  271. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  272. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  279. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  280. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  281. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  282. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  283. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  284. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  285. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  286. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  287. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  288. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  289. package/src/providers/sdk/v1/validators/index.ts +19 -0
  290. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  291. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  292. package/src/providers/spec/adapter.ts +235 -0
  293. package/src/providers/spec/cli-adapter.ts +1051 -0
  294. package/src/providers/spec/evaluator.ts +407 -0
  295. package/src/providers/spec/fsm-driver.ts +1251 -0
  296. package/src/providers/spec/fsm-evaluator.ts +272 -0
  297. package/src/providers/spec/fsm-loader.ts +120 -0
  298. package/src/providers/spec/fsm-types.ts +273 -0
  299. package/src/providers/spec/native-history-executor.ts +1136 -0
  300. package/src/providers/spec/pre-launch-trust.ts +104 -0
  301. package/src/providers/spec/route.ts +51 -0
  302. package/src/providers/spec/types.ts +262 -0
  303. package/src/providers/status-monitor.d.ts +7 -7
  304. package/src/providers/status-monitor.ts +37 -22
  305. package/src/providers/transcript-v2.ts +567 -0
  306. package/src/providers/types/interactive-prompt.ts +536 -0
  307. package/src/providers/version-archive.ts +64 -24
  308. package/src/providers/working-dir.ts +23 -0
  309. package/src/repo-mesh-types.ts +378 -14
  310. package/src/sessions/registry.ts +6 -0
  311. package/src/shared-types-extra.ts +2 -4
  312. package/src/shared-types.d.ts +8 -0
  313. package/src/shared-types.ts +64 -1
  314. package/src/status/builders.ts +26 -6
  315. package/src/status/normalize.ts +2 -0
  316. package/src/status/reporter.ts +19 -1
  317. package/src/status/snapshot.ts +95 -26
  318. package/src/system/host-memory.ts +29 -12
  319. package/src/system/load-better-sqlite3.ts +68 -0
  320. package/src/types.ts +5 -0
  321. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  322. package/dist/mesh/mesh-sync.d.ts +0 -53
  323. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  324. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  325. package/src/mesh/mesh-sync.ts +0 -111
@@ -13,19 +13,24 @@ 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';
24
+ import { traceMeshEventStage, traceMeshEventDrop } from '../mesh/mesh-event-trace.js';
22
25
  import type { ChatMessage } from '../types.js';
23
26
  import { buildPersistedProviderEffectMessage, normalizeProviderEffects } from './control-effects.js';
24
- import { formatAutoApprovalMessage, pickApprovalButton } from './approval-utils.js';
27
+ import { formatAutoApprovalMessage, pickApprovalButton, hasNegativeApprovalOption, looksLikeActiveApprovalPromptText } from './approval-utils.js';
25
28
  import { getCliScriptCommand, parseCliScriptResult } from './cli-script-results.js';
26
29
  import { mergeProviderPatchState, resolveProviderStateSurface } from './provider-patch-state.js';
27
30
  import { normalizeProviderSessionId } from './provider-session-id.js';
28
31
  import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages } from './chat-message-normalization.js';
32
+ import { workingDirBasename } from './working-dir.js';
33
+ import { ManualAttendanceTracker } from './manual-attendance.js';
29
34
 
30
35
  type PersistableCliHistoryMessage = {
31
36
  role: string;
@@ -35,17 +40,77 @@ type PersistableCliHistoryMessage = {
35
40
  receivedAt?: number;
36
41
  };
37
42
 
43
+ // Status snapshots only ever surface the newest messages: the cloud 'live'
44
+ // profile drops chat messages entirely (loaded lazily via read_chat on
45
+ // subscribe) and the 'full' profile caps activeChat.messages to the last 60
46
+ // (see status/normalize.ts). Unread/completion markers walk only the tail.
47
+ // So getState()'s saved-history hydration — which runs once per resume/manual
48
+ // CLI session on every status report — must read only a bounded tail, not the
49
+ // entire transcript. A full MAX_SAFE_INTEGER read here makes the initial
50
+ // status report O(transcript) × N(sessions), which is the real cold first-
51
+ // connection bottleneck on chat-heavy machines. The window comfortably exceeds
52
+ // the 60-message snapshot cap so dedup/collapse at the boundary stays stable.
53
+ const STATUS_HYDRATION_TAIL_LIMIT = 200;
54
+
38
55
  type CompletedDebouncePending = {
39
56
  chatTitle: string;
40
57
  duration: number;
41
58
  timestamp: number;
42
59
  firstObservedAt: number;
60
+ previousStatus: string;
43
61
  loggedBlockReason?: string;
62
+ loggedTranscriptProbe?: boolean;
63
+ transcriptProbeHistory?: ExternalTranscriptProbe[];
64
+ };
65
+
66
+ function isIdleStatus(value: unknown): boolean {
67
+ const status = typeof value === 'string' ? value.trim().toLowerCase() : '';
68
+ return !status || status === 'idle' || status === 'ready';
69
+ }
70
+
71
+
72
+ function getMessageTime(message: unknown): number {
73
+ if (!message || typeof message !== 'object') return 0;
74
+ const record = message as { receivedAt?: unknown; timestamp?: unknown };
75
+ const value = Number(record.receivedAt ?? record.timestamp ?? 0);
76
+ return Number.isFinite(value) ? value : 0;
77
+ }
78
+
79
+ type CompletedFinalizationBlock = {
80
+ reason: string;
81
+ terminal?: boolean;
82
+ allowTimeout?: boolean;
83
+ };
84
+
85
+ type CompletionFinalAssistantEvidence = {
86
+ present: boolean;
87
+ messages: unknown[];
88
+ source: 'parsed' | 'external-native' | 'unavailable';
89
+ };
90
+
91
+ type ExternalTranscriptProbe = {
92
+ readAt: number;
93
+ msgCount: number;
94
+ lastRole: string | null;
95
+ lastKind: string | null;
96
+ contentLen: number;
97
+ sourcePath: string | null;
98
+ sourceMtimeMs: number | null;
99
+ mtimeAgeMs: number | null;
44
100
  };
45
101
 
46
102
  const COMPLETED_FINALIZATION_RETRY_MS = 1000;
47
103
  const COMPLETED_FINALIZATION_MAX_WAIT_MS = 30_000;
48
104
 
105
+ /** Events that signal a dispatched mesh task has reached a terminal state.
106
+ * Detach the mesh assignment after emitting one of these so the worker's
107
+ * next unrelated turn doesn't impersonate another completion. */
108
+ const TERMINAL_MESH_EVENTS = new Set([
109
+ 'agent:generating_completed',
110
+ 'agent:stopped',
111
+ 'agent:ready',
112
+ ]);
113
+
49
114
  const IMAGE_MIME_EXTENSIONS: Record<string, string> = {
50
115
  'image/png': '.png',
51
116
  'image/jpeg': '.jpg',
@@ -120,7 +185,7 @@ function hasNonEmptyCliModalButtons(activeModal: unknown): boolean {
120
185
  }
121
186
 
122
187
  function isCliGeneratingLikeStatus(status: unknown): boolean {
123
- return status === 'generating' || status === 'streaming' || status === 'long_generating' || status === 'starting';
188
+ return status === 'generating' || status === 'streaming' || status === 'no_progress' || status === 'long_generating' || status === 'starting';
124
189
  }
125
190
 
126
191
  export function buildCliStructuredInputPrompt(
@@ -300,6 +365,34 @@ export class CliProviderInstance implements ProviderInstance {
300
365
  readonly type: string;
301
366
  readonly category = 'cli' as const;
302
367
 
368
+ /**
369
+ * Quiet period an approval modal's signature must be stable before
370
+ * auto-approve sends the approve key. Guards against firing on a prompt
371
+ * that is still streaming into the PTY (the "resolves too fast" symptom):
372
+ * while the modal text/buttons are still changing, every frame yields a
373
+ * new signature and the settle clock restarts. Once the prompt finishes
374
+ * rendering the signature holds and the key is sent after this window.
375
+ * Bounded + small so genuine approvals stay timely. The FSM is already
376
+ * authoritative over the `waiting_approval` state; this only delays the
377
+ * keystroke until the modal *content* has settled.
378
+ */
379
+ private static readonly AUTO_APPROVE_SETTLE_MS = 600;
380
+
381
+ /**
382
+ * Busy-side hysteresis for the settle gate. A momentary `generating` flip
383
+ * while the SAME approval modal's button block is still on screen (its
384
+ * question line scrolled out of the captured frame, only the buttons + a
385
+ * residual `esc to interrupt` spinner remain) briefly reports
386
+ * status!=waiting_approval. Without hysteresis that flip wipes the settle
387
+ * clock, and the modal→generating→modal flap restarts the 600ms window
388
+ * every time so auto-approve never fires. We keep the in-progress settle
389
+ * gate warm across an inactive blip up to this bound; only once the modal
390
+ * has genuinely stayed gone this long (a real resolution → idle) is the
391
+ * gate cleared. Bounded so a genuinely new, later approval still re-settles
392
+ * from scratch rather than firing on a stale timestamp.
393
+ */
394
+ private static readonly AUTO_APPROVE_GATE_HYSTERESIS_MS = 1500;
395
+
303
396
  private adapter: ProviderCliAdapter;
304
397
  private context: InstanceContext | null = null;
305
398
  private events: ProviderEvent[] = [];
@@ -309,15 +402,34 @@ export class CliProviderInstance implements ProviderInstance {
309
402
  private monitor: StatusMonitor;
310
403
  private generatingDebounceTimer: NodeJS.Timeout | null = null;
311
404
  private generatingDebouncePending: { chatTitle: string; timestamp: number } | null = null;
312
- private lastApprovalEventAt = 0;
405
+ private lastApprovalEventFingerprint = '';
313
406
  private autoApproveBusy = false;
314
407
  private autoApproveBusyTimer: NodeJS.Timeout | null = null;
408
+ private lastAutoApprovalSignature = '';
409
+ // Settle gate: the approval modal's signature + the wall-clock when this
410
+ // exact signature was first observed. Auto-approve only fires once the
411
+ // SAME signature has been stable for AUTO_APPROVE_SETTLE_MS, so a prompt
412
+ // still streaming into the PTY (its buttons/message changing frame to
413
+ // frame) keeps resetting the timer and is never approved half-rendered.
414
+ private pendingAutoApprovalSignature = '';
415
+ private pendingAutoApprovalSince = 0;
416
+ private autoApproveSettleTimer: NodeJS.Timeout | null = null;
417
+ // Wall-clock when auto-approve first observed status!=waiting_approval while
418
+ // a settle gate was in progress. Drives AUTO_APPROVE_GATE_HYSTERESIS_MS so a
419
+ // brief generating flip does not immediately wipe the settle clock.
420
+ private autoApproveInactiveSince = 0;
421
+ // Provider-common manual-attendance signal: while a human is actively driving
422
+ // this session from the dashboard, auto-approve holds so they can take manual
423
+ // control. Background mesh workers are never attended → delegated auto-approve
424
+ // is unaffected.
425
+ private readonly manualAttendance = new ManualAttendanceTracker();
315
426
  private controlValues: Record<string, string | number | boolean> = {};
316
427
  private summaryMetadata: unknown = undefined;
317
428
  private appliedEffectKeys = new Set<string>();
318
429
  private historyWriter: ChatHistoryWriter;
319
430
  private runtimeMessages: Array<{ key: string; message: ChatMessage }> = [];
320
431
  private lastPersistedHistoryMessages: PersistableCliHistoryMessage[] = [];
432
+ private lastAcknowledgedUserInputAt = 0;
321
433
  private lastNativeSourceCanonicalCheckAt = 0;
322
434
  private lastNativeSourceCanonicalCacheKey: string | undefined = undefined;
323
435
  private cachedSqliteDb: {
@@ -330,6 +442,7 @@ export class CliProviderInstance implements ProviderInstance {
330
442
  private suppressIdleHistoryReplay = false;
331
443
  private errorMessage: string | undefined = undefined;
332
444
  private errorReason: ProviderErrorReason | undefined = undefined;
445
+ private activeInteractivePrompt: InteractivePrompt | null = null;
333
446
 
334
447
  private presentationMode: 'terminal' | 'chat';
335
448
  private providerSessionId?: string;
@@ -370,7 +483,10 @@ export class CliProviderInstance implements ProviderInstance {
370
483
  this.providerSessionId = options?.providerSessionId;
371
484
  this.launchMode = options?.launchMode || 'new';
372
485
  this.onProviderSessionResolved = options?.onProviderSessionResolved;
373
- this.adapter = new ProviderCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory);
486
+ this.adapter = createCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory) as ProviderCliAdapter;
487
+ if (this.providerSessionId) {
488
+ this.adapter.updateRuntimeMeta({ providerSessionId: this.providerSessionId });
489
+ }
374
490
  this.monitor = new StatusMonitor();
375
491
  this.historyWriter = new ChatHistoryWriter();
376
492
  }
@@ -389,8 +505,8 @@ export class CliProviderInstance implements ProviderInstance {
389
505
  this.adapter.updateRuntimeSettings?.(this.settings);
390
506
  this.monitor.updateConfig({
391
507
  approvalAlert: this.settings.approvalAlert !== false,
392
- longGeneratingAlert: this.settings.longGeneratingAlert !== false,
393
- longGeneratingThresholdSec: this.settings.longGeneratingThresholdSec || 180,
508
+ noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
509
+ noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
394
510
  });
395
511
 
396
512
  // Server connection
@@ -412,7 +528,7 @@ export class CliProviderInstance implements ProviderInstance {
412
528
  await this.adapter.spawn();
413
529
  await this.enforceFreshSessionLaunchIfNeeded();
414
530
  this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
415
- if (this.providerSessionId) {
531
+ if (this.providerSessionId && this.shouldHydrateExistingProviderHistory()) {
416
532
  this.restorePersistedHistoryFromCurrentSession();
417
533
  }
418
534
  if (this.providerSessionId && this.launchMode === 'resume') {
@@ -486,14 +602,38 @@ export class CliProviderInstance implements ProviderInstance {
486
602
  }
487
603
 
488
604
  getState(): ProviderState {
605
+ // TODO(phase5-sandbox): JS override scripts (detectStatus, parseApproval,
606
+ // parseSession) are currently invoked by CliScriptRunner.invoke() via direct
607
+ // function calls — the scripts run in the daemon process with full Node.js
608
+ // access and no resource limits.
609
+ //
610
+ // When Phase 5 lands, CliScriptRunner should route these calls through a
611
+ // SandboxedScriptRunner (see providers/sdk/v1/sandbox/script-runner.ts) so
612
+ // that each call gets a fresh isolated-vm context with a 50 ms CPU limit and
613
+ // a 32 MB memory cap. The execution path to change is:
614
+ // CliScriptRunner.invoke() → SandboxedScriptRunner.run(scriptSource, context)
615
+ //
616
+ // This getState() call-site is NOT where the change goes — the wiring belongs
617
+ // in cli-script-runner.ts (CliScriptRunner.detectStatus / parseApproval /
618
+ // parseSession), with provider-loader.ts updated to store script source strings
619
+ // alongside the loaded function references for extended-legacy providers.
489
620
  const adapterStatus = this.adapter.getStatus();
621
+ if (Object.prototype.hasOwnProperty.call(adapterStatus, 'activeInteractivePrompt')) {
622
+ this.activeInteractivePrompt = adapterStatus.activeInteractivePrompt ?? null;
623
+ }
490
624
  let parsedStatus: any = null;
491
625
  let parseErrorMessage: string | undefined;
492
626
  if (typeof this.adapter.getScriptParsedStatus === 'function') {
493
627
  try {
494
628
  parsedStatus = this.adapter.getScriptParsedStatus() || null;
495
- this.errorMessage = undefined;
496
- this.errorReason = undefined;
629
+ const parsedErrorMessage = typeof parsedStatus?.errorMessage === 'string' && parsedStatus.errorMessage.trim()
630
+ ? parsedStatus.errorMessage.trim()
631
+ : undefined;
632
+ const parsedErrorReason = typeof parsedStatus?.errorReason === 'string' && parsedStatus.errorReason.trim()
633
+ ? parsedStatus.errorReason.trim() as ProviderErrorReason
634
+ : undefined;
635
+ this.errorMessage = parsedErrorMessage;
636
+ this.errorReason = parsedErrorReason;
497
637
  } catch (error: any) {
498
638
  parseErrorMessage = error?.message || String(error);
499
639
  this.errorMessage = parseErrorMessage;
@@ -503,22 +643,53 @@ export class CliProviderInstance implements ProviderInstance {
503
643
  this.errorMessage = undefined;
504
644
  this.errorReason = undefined;
505
645
  }
506
- const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
507
- const visibleStatus = parseErrorMessage
508
- ? 'error'
509
- : (autoApproveActive ? 'generating' : adapterStatus.status);
510
- const parsedProviderSessionId = normalizeProviderSessionId(
646
+ const adapterProviderSessionId = normalizeProviderSessionId(
511
647
  this.provider,
512
- typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
648
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
513
649
  );
514
- if (parsedProviderSessionId) {
515
- this.promoteProviderSessionId(parsedProviderSessionId);
650
+ const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
651
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
652
+ let visibleStatus = parseErrorMessage || parsedStatus?.status === 'error'
653
+ ? 'error'
654
+ : (autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status);
655
+ // getState() must agree with the status the FSM-driven detectStatusTransition()
656
+ // already committed to lastStatus. The adapter's own status is authoritative; we do
657
+ // not second-guess it with native-transcript shape. Only reconcile a generating-like
658
+ // read down to idle when our own lastStatus has already flipped idle (avoids a
659
+ // perpetual dashboard spinner during the brief window before the next getStatus()).
660
+ if (isCliGeneratingLikeStatus(visibleStatus) && this.lastStatus === 'idle') {
661
+ visibleStatus = 'idle';
516
662
  }
517
663
  const runtime = this.adapter.getRuntimeMetadata();
518
664
  this.maybeAppendRuntimeRecoveryMessage(runtime);
519
665
  let parsedMessages = Array.isArray(parsedStatus?.messages)
520
666
  ? parsedStatus.messages
521
667
  : [];
668
+ const parsedProviderSessionId = normalizeProviderSessionId(
669
+ this.provider,
670
+ typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
671
+ );
672
+ const suppressFreshLaunchStartupReplay = this.shouldSuppressFreshLaunchStartupReplay(
673
+ parsedMessages,
674
+ parsedStatus,
675
+ adapterStatus,
676
+ parsedProviderSessionId,
677
+ );
678
+ if (adapterProviderSessionId && !suppressFreshLaunchStartupReplay) {
679
+ this.promoteProviderSessionId(adapterProviderSessionId);
680
+ }
681
+ if (parsedProviderSessionId && !suppressFreshLaunchStartupReplay) {
682
+ this.promoteProviderSessionId(parsedProviderSessionId);
683
+ }
684
+ if (suppressFreshLaunchStartupReplay) {
685
+ parsedMessages = [];
686
+ }
687
+ // Adapter runtime metadata is transport-owned and is not guaranteed to
688
+ // identify this conversation. Spec adapters historically exposed the
689
+ // provider spec id (for example "codex-cli") as runtimeId, which made
690
+ // concurrent sessions share one activeChat identity until their native
691
+ // provider session ids were discovered.
692
+ const activeChatId = this.providerSessionId || this.instanceId;
522
693
  const historyMessageCount = Number.isFinite(parsedStatus?.historyMessageCount)
523
694
  ? Math.max(0, Number(parsedStatus.historyMessageCount))
524
695
  : null;
@@ -528,9 +699,20 @@ export class CliProviderInstance implements ProviderInstance {
528
699
  : [];
529
700
  }
530
701
  const mergedMessages = this.mergeConversationMessages(parsedMessages);
531
- const canonicalBackedHistory = this.syncCanonicalSavedHistoryIfNeeded();
702
+ const canonicalBackedHistory = this.shouldHydrateExistingProviderHistory()
703
+ ? this.syncCanonicalSavedHistoryIfNeeded()
704
+ : false;
705
+ const statusMessages = canonicalBackedHistory && this.lastPersistedHistoryMessages.length > 0
706
+ ? this.lastPersistedHistoryMessages.map((message) => ({
707
+ role: message.role,
708
+ content: message.content,
709
+ kind: message.kind,
710
+ senderName: message.senderName,
711
+ receivedAt: message.receivedAt,
712
+ }))
713
+ : mergedMessages;
532
714
 
533
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
715
+ const dirName = workingDirBasename(this.workingDir);
534
716
  const parsedChatStatus = typeof parsedStatus?.status === 'string' && parsedStatus.status.trim()
535
717
  ? parsedStatus.status.trim()
536
718
  : undefined;
@@ -542,7 +724,7 @@ export class CliProviderInstance implements ProviderInstance {
542
724
  && adapterStatus.status === 'idle'
543
725
  && parsedStatus?.status === 'idle';
544
726
  let messagesToSave = parsedMessages;
545
- if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'long_generating')) {
727
+ if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'no_progress' || parsedChatStatus === 'long_generating')) {
546
728
  const lastIdx = messagesToSave.length - 1;
547
729
  if (lastIdx >= 0 && messagesToSave[lastIdx]?.role === 'assistant') {
548
730
  messagesToSave = messagesToSave.slice(0, lastIdx);
@@ -572,33 +754,48 @@ export class CliProviderInstance implements ProviderInstance {
572
754
  }
573
755
  }
574
756
 
575
- this.applyProviderResponse(parsedStatus, { phase: 'immediate' });
757
+ this.applyProviderResponse(
758
+ suppressFreshLaunchStartupReplay && parsedStatus && typeof parsedStatus === 'object'
759
+ ? { ...parsedStatus, providerSessionId: undefined }
760
+ : parsedStatus,
761
+ { phase: 'immediate' },
762
+ );
576
763
  const surface = resolveProviderStateSurface({
577
764
  summaryMetadata: this.summaryMetadata as any,
578
765
  controlValues: this.controlValues,
579
766
  });
580
767
  const activeChatStatus = parseErrorMessage
581
768
  ? 'error'
582
- : autoApproveActive && parsedStatus?.status === 'waiting_approval'
769
+ : (autoApproveActive && parsedStatus?.status === 'waiting_approval') || autoApproveHoldIdle
583
770
  ? 'generating'
584
771
  : (adapterStatus.status !== 'idle'
585
772
  ? visibleStatus
586
773
  : (suppressStaleParsedBusyStatus ? visibleStatus : (parsedChatStatus || visibleStatus)));
587
774
 
775
+ // If an AskUserQuestion prompt is awaiting user input, overlay status as
776
+ // waiting_choice. This is distinct from waiting_approval (tool-use consent)
777
+ // — the engine's isWaitingForResponse state is unchanged, so completion
778
+ // tracking continues normally once the user responds.
779
+ const hasInteractivePrompt = !!this.activeInteractivePrompt;
780
+ const finalStatus = hasInteractivePrompt ? 'waiting_choice' : visibleStatus;
781
+ const finalChatStatus = hasInteractivePrompt ? 'waiting_choice' : activeChatStatus;
782
+
588
783
  return {
589
784
  type: this.type,
590
785
  name: this.provider.name,
591
786
  category: 'cli',
592
- status: visibleStatus,
787
+ status: finalStatus,
593
788
  mode: this.presentationMode,
594
789
  activeChat: {
595
- id: `${this.type}_${this.workingDir}`,
790
+ id: activeChatId,
596
791
  title: parsedStatus?.title || dirName,
597
- status: activeChatStatus,
598
- messages: mergedMessages,
599
- activeModal: autoApproveActive ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
792
+ status: finalChatStatus,
793
+ messages: statusMessages,
794
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
795
+ activeInteractivePrompt: this.activeInteractivePrompt,
600
796
  inputContent: '',
601
797
  },
798
+ activeInteractivePrompt: this.activeInteractivePrompt,
602
799
  workspace: this.workingDir,
603
800
  instanceId: this.instanceId,
604
801
  providerSessionId: this.providerSessionId,
@@ -638,8 +835,9 @@ export class CliProviderInstance implements ProviderInstance {
638
835
 
639
836
  getHotChatSessionState(): HotChatSessionState {
640
837
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
641
- const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
642
- const visibleStatus = autoApproveActive ? 'generating' : adapterStatus.status;
838
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status);
839
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
840
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
643
841
  const runtime = this.adapter.getRuntimeMetadata();
644
842
  return {
645
843
  id: this.instanceId,
@@ -651,36 +849,152 @@ export class CliProviderInstance implements ProviderInstance {
651
849
  };
652
850
  }
653
851
 
654
- getSessionModalState(): SessionModalState {
655
- const adapterStatus = this.adapter.getStatus({ allowParse: false });
656
- 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';
852
+ getSessionModalState(sessionId?: string): SessionModalState {
853
+ const adapterStatus = this.adapter.getStatus({ allowParse: true });
854
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status);
855
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
856
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
857
+ const dirName = workingDirBasename(this.workingDir);
659
858
  return {
660
- id: this.instanceId,
859
+ // Honor the caller-supplied sessionId — InstanceMgr rejects the
860
+ // projection when projected.id !== requested sessionId, and
861
+ // this.instanceId is the manager's internal key, not the public
862
+ // sessionId the dashboard subscribes by.
863
+ id: sessionId ?? this.instanceId,
661
864
  status: visibleStatus,
662
865
  title: dirName,
663
- activeModal: autoApproveActive ? null : adapterStatus.activeModal,
866
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : adapterStatus.activeModal,
664
867
  };
665
868
  }
666
869
 
667
870
  updateSettings(newSettings: Record<string, any>): void {
668
- this.settings = { ...newSettings };
871
+ // Merge semantics: a key omitted from newSettings preserves its existing
872
+ // value, a key present in newSettings (even as false) overrides it.
873
+ //
874
+ // This is required because updateSettings has two callers with opposite
875
+ // intent:
876
+ // 1. Full re-injection — the dashboard toggle path (handleSetProviderSetting
877
+ // → getSettings → updateInstanceSettings) sends the COMPLETE settings
878
+ // object, so an explicit autoApprove:false must win.
879
+ // 2. Partial stamp — the mesh relay-safety stamp (router.ts agent_command,
880
+ // buildMeshWorkerRelayStamp) sends ONLY {meshNodeFor, meshNodeId,
881
+ // meshCoordinatorDaemonId, launchedByCoordinator} on every coordinator
882
+ // re-dispatch. It carries no autoApprove, so a full replacement would
883
+ // wipe the launch-time autoApprove:true the worker was started with,
884
+ // silently dropping every later approval to a manual gate until the
885
+ // machine-page toggle re-injected the full settings.
886
+ //
887
+ // A plain merge satisfies both: undefined keys fall through to the existing
888
+ // value (preserving launch-stamp settings like autoApprove + the mesh routing
889
+ // keys), explicit keys override. This subsumes the previous mesh-key preserve
890
+ // list, which only protected the routing keys and not autoApprove.
891
+ this.settings = { ...this.settings, ...newSettings };
669
892
  this.adapter.updateRuntimeSettings?.(this.settings);
670
893
  this.monitor.updateConfig({
671
894
  approvalAlert: this.settings.approvalAlert !== false,
672
- longGeneratingAlert: this.settings.longGeneratingAlert !== false,
673
- longGeneratingThresholdSec: this.settings.longGeneratingThresholdSec || 180,
895
+ noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
896
+ noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
674
897
  });
675
898
  }
676
899
 
900
+ /**
901
+ * Stamp a direct-dispatch mesh assignment on this instance.
902
+ * setupMeshEventForwarding reads settings.meshNodeFor + meshActiveTaskId to
903
+ * route generating_completed back to the originating coordinator. Without
904
+ * this stamp, mesh_send_task --direct targets a plain CLI session whose
905
+ * completion events silently drop because the forwarder has nothing to
906
+ * match against.
907
+ */
908
+ attachMeshAssignment(assignment: { meshId: string; nodeId?: string; taskId?: string; coordinatorDaemonId?: string; coordinatorSessionId?: string }): void {
909
+ if (!assignment?.meshId) return;
910
+ this.settings = {
911
+ ...this.settings,
912
+ meshNodeFor: assignment.meshId,
913
+ ...(assignment.nodeId ? { meshNodeId: assignment.nodeId } : {}),
914
+ ...(assignment.taskId ? { meshActiveTaskId: assignment.taskId } : {}),
915
+ ...(assignment.coordinatorDaemonId ? { meshCoordinatorDaemonId: assignment.coordinatorDaemonId } : {}),
916
+ // Session-level routing anchor: the originating coordinator session, so this
917
+ // worker's completion events route back to the exact session that dispatched it.
918
+ ...(assignment.coordinatorSessionId ? { meshCoordinatorSessionId: assignment.coordinatorSessionId } : {}),
919
+ };
920
+ this.adapter.updateRuntimeSettings?.(this.settings);
921
+ }
922
+
923
+ /**
924
+ * Clear a previously-attached mesh assignment after the task reaches a
925
+ * terminal state. Leaving meshNodeFor pinned would route this session's
926
+ * subsequent unrelated turns (e.g. ad-hoc dashboard chats) to the
927
+ * coordinator as if they were task completions.
928
+ */
929
+ detachMeshAssignment(): void {
930
+ if (!this.settings.meshNodeFor && !this.settings.meshActiveTaskId && !this.settings.meshNodeId) return;
931
+ const { meshNodeFor, meshNodeId, meshActiveTaskId, ...rest } = this.settings;
932
+ void meshNodeFor; void meshNodeId; void meshActiveTaskId;
933
+ this.settings = rest;
934
+ this.adapter.updateRuntimeSettings?.(this.settings);
935
+ }
936
+
937
+ /**
938
+ * The resolved modal-park status of this session, or null when it is not
939
+ * parked on a modal awaiting a human answer. Mirrors the overlay logic in
940
+ * getState(): an active AskUserQuestion interactive prompt resolves to
941
+ * waiting_choice; otherwise the adapter's waiting_approval (tool consent)
942
+ * counts — UNLESS auto-approve will dismiss it, in which case the session is
943
+ * effectively generating and is NOT modal-parked. This is the single signal
944
+ * the mesh force-inject guard consults, and the same status string the
945
+ * reconcile loop reads off get_status_metadata. Lowercase literals only —
946
+ * the SessionStatus enum is forked across modules and waiting_choice is
947
+ * absent from some of them.
948
+ */
949
+ resolveModalParkStatus(): 'waiting_choice' | 'waiting_approval' | null {
950
+ if (this.activeInteractivePrompt) return 'waiting_choice';
951
+ let adapterStatus: { status?: string };
952
+ try {
953
+ adapterStatus = this.adapter.getStatus({ allowParse: false });
954
+ } catch {
955
+ return null;
956
+ }
957
+ // A session whose auto-approve is held by manual attendance IS parked on a
958
+ // modal awaiting the human — autoApproveEffectivelyActive folds that in, so
959
+ // the mesh force-inject guard correctly treats it as modal-parked.
960
+ if (adapterStatus.status === 'waiting_approval' && !this.autoApproveEffectivelyActive(adapterStatus.status)) {
961
+ return 'waiting_approval';
962
+ }
963
+ return null;
964
+ }
965
+
966
+ /** True when this session is parked on a modal awaiting a human answer. */
967
+ isModalParked(): boolean {
968
+ return this.resolveModalParkStatus() !== null;
969
+ }
970
+
677
971
  onEvent(event: string, data?: any): void {
678
972
  if (event === 'send_message') {
679
973
  const input = normalizeInputEnvelope(data);
680
974
  assertProviderSupportsDeclaredInput(this.provider, input);
681
975
  const promptText = buildCliStructuredInputPrompt(input);
682
976
  if (promptText) {
683
- void this.adapter.sendMessage(promptText).catch((e: any) => {
977
+ // force:true bypasses the busy/generating send guard so terminal mesh
978
+ // events (completion/failure/bootstrap) land in a coordinator session that
979
+ // is itself parked in `generating` while awaiting that very event.
980
+ // Without it the message is queued and only flushed on the coordinator's
981
+ // own idle transition — which never happens until it receives the message.
982
+ const force = data?.force === true;
983
+ // Modal guard: a force-inject still writes raw keystrokes into the PTY,
984
+ // bypassing the busy send-guard. If the coordinator is parked on a
985
+ // harness modal (claude-cli AskUserQuestion → waiting_choice, or a
986
+ // tool-consent waiting_approval), those keystrokes are consumed by the
987
+ // modal's key handler and silently select a choice the user never made
988
+ // (data corruption). Hold the force-inject in that narrow window —
989
+ // the event stays queued and the reconcile loop redelivers it on the
990
+ // next tick once the modal is resolved. We ONLY hold for the two modal
991
+ // states; generating is still force-injected (that is the deadlock the
992
+ // force path exists to break — see mesh-events-coordinator).
993
+ if (force && this.isModalParked()) {
994
+ LOG.info('CLI', `[${this.type}] force send_message held — coordinator parked on modal (${this.resolveModalParkStatus()})`);
995
+ return;
996
+ }
997
+ void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e: any) => {
684
998
  LOG.warn('CLI', `[${this.type}] send_message failed: ${e?.message || e}`);
685
999
  });
686
1000
  }
@@ -690,14 +1004,73 @@ export class CliProviderInstance implements ProviderInstance {
690
1004
  void this.adapter.resolveAction(data).catch((e: any) => {
691
1005
  LOG.warn('CLI', `[${this.type}] resolve_action failed: ${e?.message || e}`);
692
1006
  });
1007
+ } else if (event === 'interactive_prompt' && data) {
1008
+ const prompt = normalizeInteractivePrompt(data);
1009
+ if (prompt) {
1010
+ this.activeInteractivePrompt = prompt;
1011
+ this.events.push({
1012
+ event: 'interactive_prompt',
1013
+ timestamp: Date.now(),
1014
+ promptId: prompt.promptId,
1015
+ });
1016
+ }
1017
+ } else if (event === 'interactive_prompt_response' && data) {
1018
+ try {
1019
+ const response = normalizeInteractivePromptResponse(data);
1020
+ if (this.activeInteractivePrompt?.promptId === response.promptId) {
1021
+ this.activeInteractivePrompt = null;
1022
+ }
1023
+ if (typeof this.adapter.setInteractivePromptResponse !== 'function') {
1024
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response ignored: adapter does not support interactive prompts`);
1025
+ return;
1026
+ }
1027
+ void this.adapter.setInteractivePromptResponse(response).catch((e: any) => {
1028
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response failed: ${e?.message || e}`);
1029
+ });
1030
+ } catch (e: any) {
1031
+ LOG.warn('CLI', `[${this.type}] invalid interactive_prompt_response: ${e?.message || e}`);
1032
+ }
693
1033
  } else if (event === 'provider_state_patch' && data && typeof data === 'object') {
694
1034
  this.applyProviderResponse(data, { phase: 'immediate' });
695
1035
  }
696
1036
  }
697
1037
 
1038
+ recordAcknowledgedUserInput(input: InputEnvelope | string): void {
1039
+ const content = typeof input === 'string'
1040
+ ? input.trim()
1041
+ : buildCliStructuredInputPrompt(input).trim();
1042
+ if (!content) return;
1043
+
1044
+ const receivedAt = Date.now();
1045
+ this.lastAcknowledgedUserInputAt = receivedAt;
1046
+ const dedupKey = `user_input_ack:${crypto
1047
+ .createHash('sha256')
1048
+ .update(`${this.instanceId}:${content}:${receivedAt}`)
1049
+ .digest('hex')
1050
+ .slice(0, 24)}`;
1051
+ this.appendRuntimeMessage(buildChatMessage({
1052
+ role: 'user',
1053
+ senderName: 'User',
1054
+ kind: 'standard',
1055
+ content,
1056
+ receivedAt,
1057
+ timestamp: receivedAt,
1058
+ source: 'runtime_input_ack',
1059
+ meta: {
1060
+ runtimeInputAck: true,
1061
+ provider: this.type,
1062
+ workspace: this.workingDir,
1063
+ },
1064
+ } as ChatMessage), dedupKey);
1065
+ }
1066
+
698
1067
  dispose(): void {
699
1068
  this.adapter.shutdown();
700
1069
  this.monitor.reset();
1070
+ // Cancel any armed auto-approve timers so a pending settle re-check
1071
+ // can't fire resolveModal/detectStatusTransition against a dead adapter.
1072
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1073
+ if (this.autoApproveBusyTimer) { clearTimeout(this.autoApproveBusyTimer); this.autoApproveBusyTimer = null; }
701
1074
  this.appliedEffectKeys.clear();
702
1075
  try { this.cachedSqliteDb?.close(); } catch { /* noop */ }
703
1076
  this.cachedSqliteDb = null;
@@ -706,6 +1079,7 @@ export class CliProviderInstance implements ProviderInstance {
706
1079
 
707
1080
  private completedDebounceTimer: NodeJS.Timeout | null = null;
708
1081
  private completedDebouncePending: CompletedDebouncePending | null = null;
1082
+ private lastExternalCompletionProbe: ExternalTranscriptProbe | null = null;
709
1083
 
710
1084
  private async enforceFreshSessionLaunchIfNeeded(): Promise<void> {
711
1085
  const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
@@ -740,7 +1114,180 @@ export class CliProviderInstance implements ProviderInstance {
740
1114
  const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
741
1115
  const role = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : '';
742
1116
  const content = lastVisible ? flattenContent(lastVisible.content).trim() : '';
743
- return role === 'assistant' && !!content;
1117
+ if (role !== 'assistant' || !content) return false;
1118
+ // Guard: if the last assistant message looks like an active approval/input prompt,
1119
+ // it is not a real completion — the session is still awaiting user input.
1120
+ if (looksLikeActiveApprovalPromptText(content)) return false;
1121
+ return true;
1122
+ }
1123
+
1124
+ private buildExternalTranscriptProbe(messages: unknown[], sourcePath?: string, sourceMtimeMs?: number): ExternalTranscriptProbe {
1125
+ const visibleMessages = messages.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1126
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1127
+ const readAt = Date.now();
1128
+ const mtimeMs = Number(sourceMtimeMs) || 0;
1129
+ return {
1130
+ readAt,
1131
+ msgCount: messages.length,
1132
+ lastRole: typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null,
1133
+ lastKind: typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null,
1134
+ contentLen: lastVisible ? flattenContent(lastVisible.content).trim().length : 0,
1135
+ sourcePath: typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
1136
+ sourceMtimeMs: mtimeMs || null,
1137
+ mtimeAgeMs: mtimeMs ? Math.max(0, readAt - mtimeMs) : null,
1138
+ };
1139
+ }
1140
+
1141
+ private recordPendingTranscriptProbe(pending: CompletedDebouncePending): ExternalTranscriptProbe | null {
1142
+ const probe = this.lastExternalCompletionProbe;
1143
+ if (!probe) return null;
1144
+ const history = pending.transcriptProbeHistory || [];
1145
+ const last = history[history.length - 1];
1146
+ if (!last || last.readAt !== probe.readAt || last.msgCount !== probe.msgCount || last.lastRole !== probe.lastRole || last.contentLen !== probe.contentLen) {
1147
+ history.push(probe);
1148
+ pending.transcriptProbeHistory = history.slice(-5);
1149
+ }
1150
+ return probe;
1151
+ }
1152
+
1153
+ private readExternalCompletionMessages(): unknown[] | null {
1154
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1155
+ if (!adapterOwnsMessagesElsewhere) return null;
1156
+ if (!this.providerSessionId) return null;
1157
+ if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
1158
+
1159
+ if (this.lastExternalCompletionProbe?.sourcePath) {
1160
+ try { fs.statSync(this.lastExternalCompletionProbe.sourcePath); } catch { /* best-effort metadata refresh */ }
1161
+ }
1162
+ const restoredHistory = readProviderChatHistory(this.type, {
1163
+ canonicalHistory: this.provider.nativeHistory,
1164
+ historySessionId: this.providerSessionId,
1165
+ workspace: this.workingDir,
1166
+ offset: 0,
1167
+ limit: Number.MAX_SAFE_INTEGER,
1168
+ historyBehavior: this.provider.historyBehavior,
1169
+ scripts: this.provider.scripts as any,
1170
+ sessionStartedAtMs: this.startedAt,
1171
+ forceRefresh: true,
1172
+ });
1173
+ if (restoredHistory.source !== 'provider-native') {
1174
+ this.lastExternalCompletionProbe = null;
1175
+ return null;
1176
+ }
1177
+ this.lastExternalCompletionProbe = this.buildExternalTranscriptProbe(
1178
+ restoredHistory.messages,
1179
+ restoredHistory.sourcePath,
1180
+ restoredHistory.sourceMtimeMs,
1181
+ );
1182
+ return restoredHistory.messages;
1183
+ }
1184
+
1185
+ private completionFinalAssistantEvidence(parsedMessages: unknown): CompletionFinalAssistantEvidence {
1186
+ if (this.completionHasFinalAssistantMessage(parsedMessages)) {
1187
+ return {
1188
+ present: true,
1189
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1190
+ source: 'parsed',
1191
+ };
1192
+ }
1193
+
1194
+ const externalMessages = this.readExternalCompletionMessages();
1195
+ if (externalMessages) {
1196
+ return {
1197
+ present: this.completionHasFinalAssistantMessage(externalMessages),
1198
+ messages: externalMessages,
1199
+ source: 'external-native',
1200
+ };
1201
+ }
1202
+
1203
+ return {
1204
+ present: false,
1205
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1206
+ source: 'unavailable',
1207
+ };
1208
+ }
1209
+
1210
+ private completionFinalSummary(parsedMessages: unknown): string | undefined {
1211
+ // For native-source providers (claude-cli: chatMessagesOwnedExternally), the PTY
1212
+ // screen parse is NOT the source of truth for the final summary — the terminal
1213
+ // wraps/scrolls/clips text, so a screen-parsed assistant message is often a partial
1214
+ // prefix (e.g. 76 chars of a 112-char turn). The append-only native transcript holds
1215
+ // the complete turn. Prefer it whenever it yields a longer/complete summary; fall back
1216
+ // to the parsed screen only when the transcript is unavailable. This is the real cause
1217
+ // of the truncated finalSummary — independent of cloud vs standalone (it surfaces on
1218
+ // any short, fast-completing task where screen parse wins the race).
1219
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1220
+ const parsedSummary = extractFinalSummaryFromMessages(
1221
+ (this.completionHasFinalAssistantMessage(parsedMessages)
1222
+ ? (Array.isArray(parsedMessages) ? parsedMessages : [])
1223
+ : []) as any,
1224
+ );
1225
+ if (adapterOwnsMessagesElsewhere) {
1226
+ const externalMessages = this.readExternalCompletionMessages();
1227
+ const externalSummary = externalMessages
1228
+ ? extractFinalSummaryFromMessages(externalMessages as any)
1229
+ : '';
1230
+ // The transcript is authoritative for native-source providers. Use it unless it is
1231
+ // empty (not yet written) — only then fall back to whatever the screen parsed.
1232
+ if (externalSummary) return externalSummary;
1233
+ return parsedSummary || undefined;
1234
+ }
1235
+ return parsedSummary || undefined;
1236
+ }
1237
+
1238
+ private buildCompletedFinalizationDiagnostic(args: {
1239
+ blockReason: string;
1240
+ latestStatus?: any;
1241
+ latestVisibleStatus: string;
1242
+ waitedMs: number;
1243
+ pending: CompletedDebouncePending;
1244
+ emittedAfterFinalizationTimeout: boolean;
1245
+ }): Record<string, unknown> {
1246
+ let parsed: any = null;
1247
+ let parseError: string | undefined;
1248
+ try {
1249
+ parsed = this.adapter.getScriptParsedStatus();
1250
+ } catch (error: any) {
1251
+ parseError = error?.message || String(error);
1252
+ }
1253
+
1254
+ const evidence = this.completionFinalAssistantEvidence(parsed?.messages);
1255
+ if (evidence.source === 'external-native') {
1256
+ this.recordPendingTranscriptProbe(args.pending);
1257
+ }
1258
+ const visibleMessages = (Array.isArray(evidence.messages) ? evidence.messages : [])
1259
+ .filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1260
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1261
+ const lastVisibleRole = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null;
1262
+ const lastVisibleKind = typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null;
1263
+ const lastVisibleContentLength = lastVisible ? flattenContent(lastVisible.content).trim().length : 0;
1264
+
1265
+ return {
1266
+ providerType: this.type,
1267
+ sessionId: this.instanceId,
1268
+ providerSessionId: this.providerSessionId || null,
1269
+ workspace: this.workingDir,
1270
+ blockReason: args.blockReason,
1271
+ emittedAfterFinalizationTimeout: args.emittedAfterFinalizationTimeout,
1272
+ waitedMs: args.waitedMs,
1273
+ maxWaitMs: COMPLETED_FINALIZATION_MAX_WAIT_MS,
1274
+ adapterStatus: typeof args.latestStatus?.status === 'string' ? args.latestStatus.status : null,
1275
+ latestVisibleStatus: args.latestVisibleStatus,
1276
+ parsedStatus: typeof parsed?.status === 'string' ? parsed.status : (parseError ? 'parse_error' : 'unknown'),
1277
+ parseError: parseError || undefined,
1278
+ finalAssistantPresent: evidence.present,
1279
+ finalAssistantEvidenceSource: evidence.source,
1280
+ visibleMessageCount: visibleMessages.length,
1281
+ lastVisibleRole,
1282
+ lastVisibleKind,
1283
+ lastVisibleContentLength,
1284
+ pendingStartedAt: this.generatingStartedAt || null,
1285
+ pendingFirstObservedAt: args.pending.firstObservedAt,
1286
+ pendingTimestamp: args.pending.timestamp,
1287
+ pendingDurationSec: args.pending.duration,
1288
+ previousBlockReason: args.pending.loggedBlockReason || null,
1289
+ transcriptProbeHistory: args.pending.transcriptProbeHistory || [],
1290
+ };
744
1291
  }
745
1292
 
746
1293
  private hasAdapterPendingResponse(): boolean {
@@ -765,32 +1312,97 @@ export class CliProviderInstance implements ProviderInstance {
765
1312
  if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
766
1313
  if (adapterRawStatus !== 'idle') return false;
767
1314
  if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
768
- return !this.hasAdapterPendingResponse();
1315
+ if (this.hasAdapterPendingResponse()) return false;
1316
+ // Do not suppress when the adapter's raw response buffer is still non-empty.
1317
+ // This catches the case where isWaitingForResponse has already flipped to false
1318
+ // (so getPartialResponse() returns '') but the provider's native parser still
1319
+ // reports generating because it's parsing buffered content. Suppressing the
1320
+ // finalization block here would emit a false completion event while the provider
1321
+ // session is still actively processing its response stream.
1322
+ const adapterAny = this.adapter as any;
1323
+ if (typeof adapterAny?.responseBuffer === 'string' && adapterAny.responseBuffer.trim()) return false;
1324
+ return true;
769
1325
  }
770
1326
 
771
- private getCompletedFinalizationBlockReason(latestVisibleStatus: string): string | null {
772
- if (latestVisibleStatus !== 'idle') return `status:${latestVisibleStatus}`;
1327
+ private getCompletedFinalizationBlock(latestVisibleStatus: string, pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1328
+ if (latestVisibleStatus !== 'idle') return { reason: `status:${latestVisibleStatus}`, terminal: true };
773
1329
 
774
1330
  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';
1331
+ const approvalResolvedIdle = pending.previousStatus === 'waiting_approval';
1332
+ if (!approvalResolvedIdle) {
1333
+ if (adapterAny?.isWaitingForResponse === true) return { reason: 'adapter_waiting_for_response', terminal: true };
1334
+ if (adapterAny?.currentTurnScope) return { reason: 'adapter_turn_scope_active', terminal: true };
1335
+ if (this.hasAdapterPendingResponse()) return { reason: 'adapter_pending_response', terminal: true };
1336
+ }
777
1337
 
778
1338
  const partial = typeof this.adapter.getPartialResponse === 'function'
779
1339
  ? this.adapter.getPartialResponse()
780
1340
  : '';
781
- if (typeof partial === 'string' && partial.trim()) return 'partial_response_pending';
1341
+ if (typeof partial === 'string' && partial.trim()) return { reason: 'partial_response_pending', terminal: true };
782
1342
 
783
1343
  let parsed: any;
784
1344
  try {
785
1345
  parsed = this.adapter.getScriptParsedStatus();
786
1346
  } catch (error: any) {
787
- return `parse_error:${error?.message || String(error)}`;
1347
+ return { reason: `parse_error:${error?.message || String(error)}` };
788
1348
  }
789
1349
 
790
1350
  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';
1351
+ if (parsedStatus !== 'idle') {
1352
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1353
+ if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
1354
+ return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
1355
+ }
1356
+ if (parsed?.activeModal || parsed?.modal) return { reason: 'parsed_modal_active', terminal: true };
1357
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1358
+ const finalAssistantEvidence = this.completionFinalAssistantEvidence(parsed?.messages);
1359
+ const allowMissingAssistantTimeout = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1360
+ LOG.debug('CLI', `[${this.type}] finalAssistantEvidence: present=${finalAssistantEvidence.present} source=${finalAssistantEvidence.source} adapterOwnsMessagesElsewhere=${adapterOwnsMessagesElsewhere} parsedStatus=${parsedStatus}`);
1361
+ if (!finalAssistantEvidence.present) {
1362
+ if (adapterOwnsMessagesElsewhere) {
1363
+ if (finalAssistantEvidence.source === 'external-native') {
1364
+ const probe = this.recordPendingTranscriptProbe(pending);
1365
+ if (probe && !pending.loggedTranscriptProbe) {
1366
+ 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`);
1367
+ pending.loggedTranscriptProbe = true;
1368
+ }
1369
+ LOG.debug('CLI', `[${this.type}] external-native probe result: lastRole=${probe?.lastRole} contentLen=${probe?.contentLen}`);
1370
+ if (probe?.lastRole === 'assistant' && (probe.contentLen ?? 0) > 0) {
1371
+ return null;
1372
+ }
1373
+ if (this.type === 'antigravity-cli') {
1374
+ return null;
1375
+ }
1376
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1377
+ }
1378
+ if ((this.provider as any).requiresFinalAssistantBeforeIdle === true) {
1379
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1380
+ }
1381
+ } else {
1382
+ LOG.debug('CLI', `[${this.type}] missing_final_assistant (not ownsExternal) requiresFinalAssistant=${!!(this.provider as any).requiresFinalAssistantBeforeIdle}`);
1383
+ return {
1384
+ reason: 'missing_final_assistant',
1385
+ terminal: (this.provider as any).requiresFinalAssistantBeforeIdle === true,
1386
+ allowTimeout: allowMissingAssistantTimeout,
1387
+ };
1388
+ }
1389
+ }
1390
+
1391
+ // Guard: if the screen still shows an approval/choice prompt as the last visible text,
1392
+ // the turn is not complete even if the parsed status says idle and there is an assistant
1393
+ // message. This catches the case where waiting_approval→idle transitions occur before
1394
+ // the modal has been resolved (e.g. the PTY rendered the prompt but no button press fired).
1395
+ try {
1396
+ const screenText = typeof (this.adapter as any).getScreenText === 'function'
1397
+ ? String((this.adapter as any).getScreenText() || '')
1398
+ : '';
1399
+ if (screenText) {
1400
+ const tailLines = screenText.split(/\r?\n/).slice(-16).join('\n');
1401
+ if (looksLikeActiveApprovalPromptText(tailLines)) {
1402
+ return { reason: 'screen_shows_approval_prompt', terminal: approvalResolvedIdle };
1403
+ }
1404
+ }
1405
+ } catch { /* defensive: screen text read is best-effort */ }
794
1406
 
795
1407
  return null;
796
1408
  }
@@ -800,6 +1412,26 @@ export class CliProviderInstance implements ProviderInstance {
800
1412
  this.completedDebounceTimer = setTimeout(() => this.flushCompletedDebounceIfFinalized(), delayMs);
801
1413
  }
802
1414
 
1415
+ // EVTTRACE (observation-only): is this a mesh worker session whose completion
1416
+ // events must route to a coordinator? Used purely to gate trace logging so a
1417
+ // non-mesh CLI session's completions don't add EvtTrace noise. No decision logic.
1418
+ private isMeshWorkerSession(): boolean {
1419
+ return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId
1420
+ || this.settings.meshNodeId || this.settings.launchedByCoordinator);
1421
+ }
1422
+
1423
+ // EVTTRACE correlation context for this session's completion lifecycle. taskId is
1424
+ // the primary grep anchor; instanceId is the session fallback.
1425
+ private meshTraceCtx(event = 'agent:generating_completed'): Record<string, unknown> {
1426
+ return {
1427
+ taskId: this.settings.meshActiveTaskId,
1428
+ sessionId: this.instanceId,
1429
+ nodeId: this.settings.meshNodeId,
1430
+ meshId: this.settings.meshNodeFor,
1431
+ event,
1432
+ };
1433
+ }
1434
+
803
1435
  private flushCompletedDebounceIfFinalized(): void {
804
1436
  const pending = this.completedDebouncePending;
805
1437
  if (!pending) {
@@ -809,7 +1441,8 @@ export class CliProviderInstance implements ProviderInstance {
809
1441
 
810
1442
  const latestStatus = this.adapter.getStatus({ allowParse: false });
811
1443
  const latestAutoApproveActive = latestStatus.status === 'waiting_approval' && this.shouldAutoApprove();
812
- const latestVisibleStatus = latestAutoApproveActive ? 'generating' : latestStatus.status;
1444
+ const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? 'generating' : latestStatus.status;
1445
+ 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
1446
  if (latestVisibleStatus !== 'idle') {
814
1447
  LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
815
1448
  this.completedDebouncePending = null;
@@ -817,84 +1450,350 @@ export class CliProviderInstance implements ProviderInstance {
817
1450
  return;
818
1451
  }
819
1452
 
820
- const blockReason = this.getCompletedFinalizationBlockReason(latestVisibleStatus);
821
- if (blockReason) {
1453
+ const block = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
1454
+ if (block) {
1455
+ const blockReason = block.reason;
822
1456
  const waitedMs = Date.now() - pending.firstObservedAt;
823
- if (waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
1457
+ // CANON-C (completion-gate decouple): a block carrying `allowTimeout` is the
1458
+ // transcript-evidence gate — the worker FSM has ALREADY reached idle and the only
1459
+ // thing missing is the append-only transcript's final assistant turn (a native-source
1460
+ // race: claude-cli owns its history externally and the file write trails the idle
1461
+ // transition). `allowTimeout` is set ONLY on the missing_final_assistant block, and
1462
+ // ONLY for mesh worker sessions (meshNodeFor / meshActiveTaskId / launchedByCoordinator).
1463
+ // The coordinator's sole path to learn this session is idle is agent:generating_completed,
1464
+ // so holding it up to COMPLETED_FINALIZATION_MAX_WAIT_MS (30s) leaves the coordinator
1465
+ // false-generating while the worker is done. Decouple the idle NOTIFICATION from the
1466
+ // transcript evidence: emit the completion immediately, marked weak
1467
+ // (completionDiagnostic.blockReason=missing_final_assistant, finalAssistantPresent=false).
1468
+ // The finalSummary is enriched on a SEPARATE path — the mesh reconcile loop reads the
1469
+ // transcript once written and re-emits a GENUINE completion (CANON-B weak→genuine
1470
+ // upgrade; buildPendingEventFingerprint keeps weak and genuine distinct so the enriched
1471
+ // one still surfaces, and isFalseIdleCompletion keeps the direct dispatch active until
1472
+ // then). All OTHER blocks (genuinely-busy adapter/partial/parsed states, transient
1473
+ // parse_error) keep the existing terminal-hold / 30s-retry behavior unchanged.
1474
+ const isTranscriptEvidenceGate = block.allowTimeout === true;
1475
+ LOG.debug('CLI', `[${this.type}] finalization block: reason=${blockReason} terminal=${block.terminal} allowTimeout=${isTranscriptEvidenceGate} waitedMs=${waitedMs} maxWait=${COMPLETED_FINALIZATION_MAX_WAIT_MS}`);
1476
+ if (!isTranscriptEvidenceGate && (block.terminal || waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS)) {
824
1477
  if (pending.loggedBlockReason !== blockReason) {
825
1478
  LOG.info('CLI', `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
1479
+ // EVTTRACE: completion held by the finalization gate (CANON-C). Observation
1480
+ // only — does not change the hold decision above.
1481
+ if (this.isMeshWorkerSession()) {
1482
+ traceMeshEventDrop('completion_gate_hold', this.meshTraceCtx(), `${blockReason} waited=${waitedMs}ms`);
1483
+ }
826
1484
  pending.loggedBlockReason = blockReason;
827
1485
  }
828
1486
  this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
829
1487
  return;
830
1488
  }
831
- LOG.warn('CLI', `[${this.type}] suppressed completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
1489
+ const emittedAfterFinalizationTimeout = waitedMs >= COMPLETED_FINALIZATION_MAX_WAIT_MS;
1490
+ const completionDiagnostic = this.buildCompletedFinalizationDiagnostic({
1491
+ blockReason,
1492
+ latestStatus,
1493
+ latestVisibleStatus,
1494
+ waitedMs,
1495
+ pending,
1496
+ emittedAfterFinalizationTimeout,
1497
+ });
1498
+ // Surface the CANON-C immediate-emit path distinctly so a delegated worker's idle
1499
+ // notification (transcript still pending) is not mistaken for a 30s-timeout fallback.
1500
+ (completionDiagnostic as Record<string, unknown>).decoupledImmediateEmit = isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout;
1501
+ LOG.warn('CLI', `[${this.type}] emitting completed event (${isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout ? 'CANON-C decoupled-immediate, transcript pending' : `after ${waitedMs}ms`}) without finalized assistant turn (${blockReason})`);
1502
+ // EVTTRACE: completion fired (forced past the finalization timeout / CANON-C decoupled-immediate).
1503
+ if (this.isMeshWorkerSession()) {
1504
+ traceMeshEventStage('fired', this.meshTraceCtx(), `forced after ${waitedMs}ms (${blockReason})`);
1505
+ }
1506
+ this.pushEvent({
1507
+ event: 'agent:generating_completed',
1508
+ chatTitle: pending.chatTitle,
1509
+ duration: pending.duration,
1510
+ timestamp: pending.timestamp,
1511
+ // When finalization is forced past the timeout on a `parsed_status:` block
1512
+ // (the parser never confirmed a final assistant turn) we previously rode an
1513
+ // empty `finalSummary` unconditionally. That empty value propagates to the
1514
+ // mesh coordinator's mirror preview (meshSessionLastMessagePreview), leaving a
1515
+ // delegated session's inbox preview blank — or, for a LOCAL worktree session,
1516
+ // stuck on the dispatched user task. If the parser DID surface assistant text,
1517
+ // prefer it; only fall back to '' when no assistant summary can be derived.
1518
+ finalSummary: blockReason.startsWith('parsed_status:')
1519
+ ? (this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages) ?? '')
1520
+ : this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
1521
+ completionDiagnostic,
1522
+ });
832
1523
  this.completedDebouncePending = null;
833
1524
  this.completedDebounceTimer = null;
834
1525
  this.generatingStartedAt = 0;
1526
+ this.lastApprovalEventFingerprint = '';
835
1527
  return;
836
1528
  }
837
1529
 
838
1530
  LOG.info('CLI', `[${this.type}] completed in ${pending.duration}s`);
1531
+ // EVTTRACE: completion fired (transcript finalized cleanly).
1532
+ if (this.isMeshWorkerSession()) {
1533
+ traceMeshEventStage('fired', this.meshTraceCtx(), `duration=${pending.duration}s`);
1534
+ }
839
1535
  this.pushEvent({
840
1536
  event: 'agent:generating_completed',
841
1537
  chatTitle: pending.chatTitle,
842
1538
  duration: pending.duration,
843
1539
  timestamp: pending.timestamp,
844
- finalSummary: extractFinalSummaryFromMessages(this.adapter?.getScriptParsedStatus()?.messages),
1540
+ finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
845
1541
  });
846
1542
  this.completedDebouncePending = null;
847
1543
  this.completedDebounceTimer = null;
848
1544
  this.generatingStartedAt = 0;
1545
+ this.lastApprovalEventFingerprint = '';
849
1546
  }
850
1547
 
851
1548
  private maybeAutoApproveStatus(adapterStatus: any, now = Date.now()): boolean {
1549
+ // Manual-attendance suppression (provider-common): when a human is
1550
+ // actively driving this session from the dashboard, hold auto-approve so
1551
+ // the modal stays visible and they can pick a button / use the controlbar
1552
+ // themselves. Return false (NOT auto-approving) so getState keeps the
1553
+ // modal surfaced. Clear any in-progress settle gate — a genuine fire
1554
+ // after the window lapses must re-settle from scratch — and arm a
1555
+ // re-check for the lapse moment, because the PTY may have gone silent and
1556
+ // would otherwise never re-drive this decision. Background mesh workers
1557
+ // are never attended, so their delegated auto-approve is untouched.
1558
+ if (adapterStatus?.status === 'waiting_approval'
1559
+ && this.shouldAutoApprove()
1560
+ && this.manualAttendance.isAttended(now)) {
1561
+ this.lastAutoApprovalSignature = '';
1562
+ this.pendingAutoApprovalSignature = '';
1563
+ this.pendingAutoApprovalSince = 0;
1564
+ this.autoApproveInactiveSince = 0;
1565
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1566
+ this.autoApproveSettleTimer = setTimeout(() => {
1567
+ this.autoApproveSettleTimer = null;
1568
+ this.recheckAutoApproveSettled();
1569
+ }, this.manualAttendance.remainingMs(now) + 20);
1570
+ return false;
1571
+ }
852
1572
  const autoApproveActive = adapterStatus?.status === 'waiting_approval' && this.shouldAutoApprove();
853
1573
  // Guard re-entry: onStatusChange/getState can observe the same modal multiple
854
1574
  // times while the PTY absorbs the approval key. Without this flag, repeated
855
1575
  // 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);
1576
+ // However, Claude Code can present a second approval immediately after the
1577
+ // first. Resolve a changed modal signature even while the previous write is
1578
+ // still inside the short busy window.
1579
+ if (!autoApproveActive) {
1580
+ this.lastAutoApprovalSignature = '';
1581
+ // Hysteresis: if a settle gate is mid-progress, a momentary
1582
+ // status!=waiting_approval blip (a generating flip while the same
1583
+ // modal's button block is still on screen) must NOT wipe the settle
1584
+ // clock otherwise the modal→generating→modal flap restarts the
1585
+ // 600ms window every time and auto-approve never fires. Keep the
1586
+ // gate warm for AUTO_APPROVE_GATE_HYSTERESIS_MS; re-arm a timer so
1587
+ // that if the modal does NOT come back the gate is cleared on the
1588
+ // re-check (a genuine resolution → idle frees the gate normally).
1589
+ if (this.pendingAutoApprovalSince) {
1590
+ if (!this.autoApproveInactiveSince) this.autoApproveInactiveSince = now;
1591
+ const goneForMs = now - this.autoApproveInactiveSince;
1592
+ if (goneForMs < CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS) {
1593
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1594
+ this.autoApproveSettleTimer = setTimeout(() => {
1595
+ this.autoApproveSettleTimer = null;
1596
+ this.recheckAutoApproveSettled();
1597
+ }, CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS - goneForMs + 20);
1598
+ return autoApproveActive;
1599
+ }
1600
+ }
1601
+ // Clear the settle gate so the next approval starts its own quiet
1602
+ // window from scratch (a stale timestamp would let it fire instantly).
1603
+ this.pendingAutoApprovalSignature = '';
1604
+ this.pendingAutoApprovalSince = 0;
1605
+ this.autoApproveInactiveSince = 0;
1606
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1607
+ return autoApproveActive;
1608
+ }
1609
+ // Active approval observed — reset the inactivity tracker so a later
1610
+ // blip starts its hysteresis window fresh.
1611
+ this.autoApproveInactiveSince = 0;
1612
+ const modal = adapterStatus.activeModal;
1613
+ // (fix) Do not auto-approve when no concrete modal/buttons are present.
1614
+ // Claude TUI flaps between paints; without this guard adapterStatus
1615
+ // could report status=waiting_approval with activeModal=null (or with
1616
+ // an empty buttons array briefly) and we'd still call
1617
+ // resolveModal(-1) — which used to type "1" into the prompt
1618
+ // repeatedly. Skip until a real modal is captured.
1619
+ const buttons = Array.isArray(modal?.buttons)
1620
+ ? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
1621
+ : [];
1622
+ if (!modal || buttons.length === 0) {
1623
+ return autoApproveActive;
1624
+ }
1625
+ // Picker/confirm exclusion (provider-common). A /model or /mode picker is
1626
+ // surfaced with status=waiting_approval so the dashboard shows it, but it
1627
+ // has no "correct" answer to auto-pick — blindly selecting the first
1628
+ // option silently switches the model (the "always Opus, before I even
1629
+ // choose" bug). Two independent gates, BOTH must pass to fire:
1630
+ //
1631
+ // (1) modal_kind — the spec/FSM tells us this is an 'approval' modal,
1632
+ // not a 'picker'/'confirm'. A modal whose kind is unknown (legacy
1633
+ // adapter, or a spec that predates modal_kind) reads as 'approval'
1634
+ // so genuine approvals keep auto-approving; only an explicit
1635
+ // 'picker'/'confirm' is excluded here.
1636
+ // (2) structural anchor — a real approval offers an affirmative AND a
1637
+ // decline option (pickApprovalButton finds a positive that isn't a
1638
+ // decline, and hasNegativeApprovalOption confirms a No/Cancel/Deny
1639
+ // is present). A model picker ("1. Default 2. Opus 3. Sonnet")
1640
+ // has no decline, so even an un-migrated picker is caught here.
1641
+ //
1642
+ // Mirrors the SDK v1 detect-status approval heuristic (detect-status.ts).
1643
+ const modalKind = typeof modal?.kind === 'string' ? modal.kind : 'approval';
1644
+ if (modalKind !== 'approval') {
1645
+ // Picker/confirm — leave it for the user; keep the modal surfaced.
1646
+ return autoApproveActive;
869
1647
  }
1648
+ const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(buttons, this.provider);
1649
+ if (buttonIndex < 0 || !hasNegativeApprovalOption(buttons)) {
1650
+ // No affirmative matched, or no decline option present (→ not a real
1651
+ // consent prompt, e.g. a picker that slipped past the kind gate).
1652
+ // Surface the modal so the user decides; never pick blindly.
1653
+ return autoApproveActive;
1654
+ }
1655
+ // Modal *identity* signature — the question/button set only, NO volatile
1656
+ // counters. This is what the settle gate tracks: the FSM bumps
1657
+ // approvalEntrySeq on every fresh waiting_approval entry, and a
1658
+ // modal→generating→modal flap (the question line scrolled out of the
1659
+ // captured frame while the button block stays) re-enters and bumps it
1660
+ // again. Folding that seq into the settle signature made the 600ms
1661
+ // settle clock restart on every flap, so the modal never stayed stable
1662
+ // long enough to fire — the gate was never satisfied. Identity excludes
1663
+ // the seq so button/seq flap of the SAME modal keeps one settle clock.
1664
+ const modalSignature = [
1665
+ typeof modal?.message === 'string' ? modal.message.trim() : '',
1666
+ buttons.join('|'),
1667
+ buttonIndex,
1668
+ ].join('::');
1669
+ // Busy-window re-entry guard still needs the seq: two DISTINCT
1670
+ // back-to-back approvals can carry identical message/buttons (common
1671
+ // with claude-cli). Without the seq their busy signatures collide and
1672
+ // the 5s busy-window guard below would swallow the second auto-approve,
1673
+ // leaving it stuck. The seq is bumped by the FSM on every fresh
1674
+ // waiting_approval entry, so a new approval always yields a new busy
1675
+ // signature and fires through.
1676
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
1677
+ ? adapterStatus.approvalEntrySeq
1678
+ : 0;
1679
+ const busySignature = `${approvalEntrySeq}::${modalSignature}`;
1680
+ // Already fired for this exact modal entry and still inside the busy
1681
+ // window — nothing to do (re-entry guard for repeated snapshots of one
1682
+ // modal).
1683
+ if (this.autoApproveBusy && busySignature === this.lastAutoApprovalSignature) {
1684
+ return autoApproveActive;
1685
+ }
1686
+
1687
+ // Settle gate: only fire once this modal identity has been stable for
1688
+ // AUTO_APPROVE_SETTLE_MS. A still-streaming prompt mutates its
1689
+ // message/buttons each frame → new identity → clock restarts, so we
1690
+ // never approve a half-rendered prompt (the "resolves too fast" bug).
1691
+ if (modalSignature !== this.pendingAutoApprovalSignature) {
1692
+ this.pendingAutoApprovalSignature = modalSignature;
1693
+ this.pendingAutoApprovalSince = now;
1694
+ }
1695
+ const settledForMs = now - this.pendingAutoApprovalSince;
1696
+ if (settledForMs < CliProviderInstance.AUTO_APPROVE_SETTLE_MS) {
1697
+ // Not yet settled. Arm a timer to re-check after the remaining quiet
1698
+ // window — the PTY may go silent once the prompt finishes painting,
1699
+ // so there is no guaranteed status-change frame to re-drive us.
1700
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1701
+ this.autoApproveSettleTimer = setTimeout(() => {
1702
+ this.autoApproveSettleTimer = null;
1703
+ this.recheckAutoApproveSettled();
1704
+ }, CliProviderInstance.AUTO_APPROVE_SETTLE_MS - settledForMs + 20);
1705
+ return autoApproveActive;
1706
+ }
1707
+
1708
+ // Settled — fire the approve key.
1709
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1710
+ this.autoApproveBusy = true;
1711
+ this.lastAutoApprovalSignature = busySignature;
1712
+ this.pendingAutoApprovalSignature = '';
1713
+ this.pendingAutoApprovalSince = 0;
1714
+ this.autoApproveInactiveSince = 0;
1715
+ if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
1716
+ this.autoApproveBusyTimer = setTimeout(() => {
1717
+ this.autoApproveBusy = false;
1718
+ this.autoApproveBusyTimer = null;
1719
+ this.lastAutoApprovalSignature = '';
1720
+ }, 5000);
1721
+ this.recordAutoApproval(modal?.message, buttonLabel, now);
1722
+ setTimeout(() => {
1723
+ this.adapter.resolveModal(buttonIndex);
1724
+ }, 0);
870
1725
  return autoApproveActive;
871
1726
  }
872
1727
 
1728
+ /**
1729
+ * Re-drive the auto-approve check after the settle quiet window elapses.
1730
+ * The PTY may have gone silent once the approval prompt finished painting,
1731
+ * so no status-change frame is guaranteed to re-enter maybeAutoApproveStatus
1732
+ * — this timer-driven re-check picks up the now-settled modal and fires.
1733
+ * Deliberately lighter than detectStatusTransition(): it only re-evaluates
1734
+ * the approval decision; the next real PTY frame refreshes visible status.
1735
+ */
1736
+ private recheckAutoApproveSettled(): void {
1737
+ try {
1738
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1739
+ this.maybeAutoApproveStatus(adapterStatus, Date.now());
1740
+ } catch { /* adapter gone / transient — next frame retries */ }
1741
+ }
1742
+
873
1743
  private detectStatusTransition(): void {
874
1744
  const now = Date.now();
875
1745
  // Status-change handling is a hot path: PTY output can fire it many times
876
1746
  // during long-running CLI sessions. Keep this path on adapter-owned light
877
1747
  // state only; rich provider parsing is reserved for getState/read_chat.
878
1748
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
1749
+ const adapterProviderSessionId = normalizeProviderSessionId(
1750
+ this.provider,
1751
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
1752
+ );
1753
+ if (adapterProviderSessionId) {
1754
+ this.promoteProviderSessionId(adapterProviderSessionId);
1755
+ }
879
1756
  const parsedStatus = null;
880
1757
  const rawStatus = adapterStatus.status;
881
1758
  const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
882
- const newStatus = autoApproveActive ? 'generating' : rawStatus;
883
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
1759
+ // During the autoApproveBusy window (2s after firing approval key), the PTY
1760
+ // can briefly report 'idle' before the next generating phase starts. Treat that
1761
+ // transient idle as 'generating' to suppress a spurious agent:generating_completed
1762
+ // push notification. The adapter's status is otherwise authoritative — native
1763
+ // transcript shape does NOT override the FSM's busy/idle decision.
1764
+ const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === 'idle';
1765
+ const newStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : rawStatus;
1766
+ const dirName = workingDirBasename(this.workingDir);
884
1767
  const chatTitle = `${this.provider.name} · ${dirName}`;
885
1768
  const partial = this.adapter.getPartialResponse();
1769
+ // Liveness fingerprint for the no-progress watchdog. The parsed
1770
+ // assistant buffer (`partial`) alone goes static while a tool/build runs
1771
+ // — the assistant emits no tokens even though the PTY is actively
1772
+ // printing tool output — which made the watchdog false-fire a "stuck"
1773
+ // alert mid-turn. Fold in the adapter's raw-activity timestamps so any
1774
+ // visible terminal progress (lastScreenChangeAt) or raw PTY byte
1775
+ // (lastOutputAt) keeps the fingerprint moving. The watchdog then only
1776
+ // survives a genuine stall where nothing at all is happening.
886
1777
  const progressFingerprint = newStatus === 'generating'
887
- ? `${partial || ''}`.slice(-2000)
1778
+ ? `${`${partial || ''}`.slice(-2000)}::scr=${adapterStatus.lastScreenChangeAt ?? 0}::out=${adapterStatus.lastOutputAt ?? 0}`
888
1779
  : undefined;
889
1780
 
890
1781
  const previousStatus = this.lastStatus;
891
1782
  if (newStatus !== this.lastStatus) {
892
1783
  LOG.info('CLI', `[${this.type}] status: ${this.lastStatus} → ${newStatus}`);
893
1784
  if (this.lastStatus === 'idle' && newStatus === 'generating') {
1785
+ // If a completion event is already pending and the turn has ended
1786
+ // (generatingStartedAt===0), the PTY is painting its prompt area
1787
+ // after completing. Ignore this blip — do not cancel the pending
1788
+ // completion and do not advance lastStatus to generating.
1789
+ if (this.completedDebouncePending && this.generatingStartedAt === 0) {
1790
+ LOG.debug('CLI', `[${this.type}] ignoring post-completion PTY generating blip (generatingStartedAt=0)`);
1791
+ return;
1792
+ }
894
1793
  this.suppressIdleHistoryReplay = false;
895
1794
  // Cancel any pending completed event (multi-step: idle→generating resume)
896
1795
  if (this.completedDebouncePending) {
897
- LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating)`);
1796
+ LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating) generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse}`);
898
1797
  if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
899
1798
  this.completedDebouncePending = null;
900
1799
  }
@@ -926,10 +1825,29 @@ export class CliProviderInstance implements ProviderInstance {
926
1825
  if (!this.generatingStartedAt) this.generatingStartedAt = now;
927
1826
  const modal = adapterStatus.activeModal;
928
1827
  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;
1828
+ // Include the FSM's approval entry seq, mirroring the auto-approve
1829
+ // path (maybeAutoApproveStatus) and resolveModal's sameEntryReResolve
1830
+ // guard. Two distinct back-to-back approvals can carry identical
1831
+ // message/buttons (very common with claude-cli's "Allow Bash
1832
+ // command?"). Without the seq their fingerprints collide and the dedup
1833
+ // below silently drops the second waiting_approval event — it is never
1834
+ // emitted, so it cannot even land in the pending inbox for a later
1835
+ // read_chat reconcile to recover. The seq is bumped by the FSM on every
1836
+ // fresh waiting_approval entry, so a new approval always yields a new
1837
+ // fingerprint and emits.
1838
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
1839
+ ? adapterStatus.approvalEntrySeq
1840
+ : 0;
1841
+ const approvalFingerprint = JSON.stringify({
1842
+ message: typeof modal?.message === 'string' ? modal.message.trim() : '',
1843
+ buttons: Array.isArray(modal?.buttons) ? modal.buttons.map((button: unknown) => String(button).trim()) : [],
1844
+ seq: approvalEntrySeq,
1845
+ });
1846
+ // PTY redraws repeat the same modal content; fingerprint dedup prevents duplicate events.
1847
+ // Do NOT also gate on lastStatus: consecutive approvals can arrive waiting_approval→waiting_approval
1848
+ // (e.g. antigravity-cli resolves one prompt and immediately shows the next) and would be silently dropped.
1849
+ if (approvalFingerprint !== this.lastApprovalEventFingerprint) {
1850
+ this.lastApprovalEventFingerprint = approvalFingerprint;
933
1851
  this.appendRuntimeSystemMessage(
934
1852
  this.formatApprovalRequestMessage(modal?.message, modal?.buttons),
935
1853
  `approval_request:${now}`,
@@ -941,22 +1859,118 @@ export class CliProviderInstance implements ProviderInstance {
941
1859
  modalButtons: modal?.buttons,
942
1860
  });
943
1861
  }
1862
+ } else if (newStatus === 'generating' && this.lastStatus === 'waiting_approval') {
1863
+ // Approval resolved and the agent resumed work. Defense-in-depth:
1864
+ // clear the approval emit fingerprint here too (not only on
1865
+ // completion at scheduleCompletedDebounceFlush). A subsequent
1866
+ // waiting_approval with the same modal content as the one just
1867
+ // resolved would otherwise collide with the stale fingerprint and be
1868
+ // dropped. The seq in the fingerprint already separates entries; this
1869
+ // reset is a belt-and-suspenders guard for the re-entry case.
1870
+ this.lastApprovalEventFingerprint = '';
944
1871
  } else if (newStatus === 'idle' && (this.lastStatus === 'generating' || this.lastStatus === 'waiting_approval')) {
945
1872
  const duration = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : 0;
946
- // If debounce still pending (generating lasted < 1s), cancel both events
1873
+ // Guard: if generatingStartedAt===0 and no debounce pending, the generating phase
1874
+ // was entered from 'starting' state (startup PTY noise), not from a real idle→generating
1875
+ // task dispatch. The idle→generating handler is the only code path that sets
1876
+ // generatingStartedAt and generatingDebouncePending, so both being absent means no
1877
+ // task was ever dispatched. Suppress the spurious completion event and fall through
1878
+ // to a simple lastStatus update.
1879
+ if (!this.generatingStartedAt && !this.generatingDebouncePending) {
1880
+ LOG.debug('CLI', `[${this.type}] suppressed startup-phase generating→idle blip (generatingStartedAt=0, no debounce pending)`);
1881
+ } else
1882
+ // If debounce still pending (generating lasted < 1s), cancel both UI events.
1883
+ // Still emit agent:generating_completed so mesh orchestration can record
1884
+ // task_completed for direct dispatches that complete faster than the debounce.
947
1885
  if (this.generatingDebouncePending) {
948
- LOG.info('CLI', `[${this.type}] suppressed short generating (${now - this.generatingStartedAt}ms)`);
1886
+ const shortDurationMs = this.generatingStartedAt ? now - this.generatingStartedAt : 0;
1887
+ LOG.info('CLI', `[${this.type}] suppressed short generating (${shortDurationMs}ms)`);
949
1888
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
1889
+ // Emit completion for mesh task association even though the UI generating
1890
+ // started/completed pair is suppressed (too short for visible UI update).
1891
+ let shortFinalSummary: string | undefined;
1892
+ let shortEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
1893
+ try {
1894
+ const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
1895
+ const evidence = this.completionFinalAssistantEvidence(parsedMessages);
1896
+ shortEvidenceSource = evidence.source;
1897
+ shortFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
1898
+ } catch { /* best-effort */ }
1899
+ // If a real response is confirmed, retroactively emit started so the chat
1900
+ // bubble appears even though the debounce suppressed the original event.
1901
+ if (shortFinalSummary) {
1902
+ this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now - shortDurationMs });
1903
+ }
950
1904
  this.generatingDebouncePending = null;
951
1905
  this.generatingStartedAt = 0;
1906
+ const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === 'external-native') && !shortFinalSummary;
1907
+ if (missingEvidence) {
1908
+ LOG.warn('CLI', `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
1909
+ }
1910
+ // When evidence is missing and there is no active mesh task context, suppress
1911
+ // the completion event. Providers with requiresFinalAssistantBeforeIdle or
1912
+ // external-native history must confirm a final assistant message before the
1913
+ // coordinator records task_completed. Only emit here if a mesh task is active
1914
+ // so the coordinator can apply its own timeout/retry logic.
1915
+ const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1916
+ if (missingEvidence && !hasMeshContext) {
1917
+ LOG.info('CLI', `[${this.type}] short completion suppressed: missing final assistant evidence, no mesh context (source=${shortEvidenceSource})`);
1918
+ // completedDebouncePending intentionally left null — the session is now idle
1919
+ // with no confirmed turn, matching the startup-blip suppression semantics.
1920
+ // (No EvtTrace: not a mesh session, so nothing routes to a coordinator.)
1921
+ } else {
1922
+ // EVTTRACE: completion fired (short-generating idle path).
1923
+ if (this.isMeshWorkerSession()) {
1924
+ traceMeshEventStage('fired', this.meshTraceCtx(), `short-generating idle (source=${shortEvidenceSource})`);
1925
+ }
1926
+ this.pushEvent({
1927
+ event: 'agent:generating_completed',
1928
+ chatTitle,
1929
+ duration: 0,
1930
+ timestamp: now,
1931
+ finalSummary: shortFinalSummary,
1932
+ completionDiagnostic: {
1933
+ reason: 'short_generating_suppressed',
1934
+ shortDurationMs,
1935
+ finalAssistantEvidenceSource: shortEvidenceSource,
1936
+ ...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
1937
+ },
1938
+ });
1939
+ }
952
1940
  } else {
953
1941
  // Debounce completed, then require the rich transcript path that read_chat
954
1942
  // 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);
1943
+ this.completedDebouncePending = {
1944
+ chatTitle,
1945
+ duration,
1946
+ timestamp: now,
1947
+ firstObservedAt: now,
1948
+ previousStatus: this.lastStatus,
1949
+ };
1950
+ const ownsExternalHistory = !!(this.adapter as any)?.chatMessagesOwnedExternally;
1951
+ const flushDelay = ownsExternalHistory ? 0 : 3000;
1952
+ LOG.debug('CLI', `[${this.type}] set completedDebouncePending duration=${duration}s ownsExternalHistory=${ownsExternalHistory} flushDelay=${flushDelay}ms generatingStartedAt=${this.generatingStartedAt}`);
1953
+ this.scheduleCompletedDebounceFlush(flushDelay);
957
1954
  }
958
1955
  } else if (newStatus === 'idle' && this.lastStatus === 'starting') {
959
1956
  this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
1957
+ } else if (newStatus === 'error') {
1958
+ if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
1959
+ this.generatingDebouncePending = null;
1960
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
1961
+ this.completedDebouncePending = null;
1962
+ this.errorMessage = adapterStatus.errorMessage || this.errorMessage;
1963
+ this.errorReason = (adapterStatus.errorReason as ProviderErrorReason) || this.errorReason;
1964
+ this.pushEvent({
1965
+ event: 'agent:stopped',
1966
+ chatTitle,
1967
+ timestamp: now,
1968
+ finalSummary: adapterStatus.errorMessage || adapterStatus.errorReason || 'Provider reported an error',
1969
+ completionDiagnostic: {
1970
+ reason: adapterStatus.errorReason || 'provider_error',
1971
+ errorMessage: adapterStatus.errorMessage || undefined,
1972
+ },
1973
+ });
960
1974
  } else if (newStatus === 'stopped') {
961
1975
  // Cancel any pending debounce
962
1976
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
@@ -976,8 +1990,43 @@ export class CliProviderInstance implements ProviderInstance {
976
1990
 
977
1991
  // Monitor check (cooldown based notification, IDE/CLI common)
978
1992
  const agentKey = `${this.type}:cli`;
979
- const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint);
1993
+ // Approval pending is detected from the raw adapter status, not `newStatus`:
1994
+ // auto-approve synthesizes `waiting_approval` → 'generating', which would
1995
+ // otherwise let the no-progress watchdog accumulate the approval wait.
1996
+ const approvalPending = rawStatus === 'waiting_approval';
1997
+ const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint, approvalPending);
1998
+ const monitorParsedStatus: any = parsedStatus;
980
1999
  for (const me of monitorEvents) {
2000
+ if (
2001
+ me.type === 'monitor:no_progress'
2002
+ && this.completionHasFinalAssistantMessage(monitorParsedStatus?.messages)
2003
+ && !this.hasAdapterPendingResponse()
2004
+ && !hasNonEmptyCliModalButtons(monitorParsedStatus?.activeModal ?? monitorParsedStatus?.modal)
2005
+ ) {
2006
+ // EVTTRACE: completion fired (no-progress monitor reconciled to completion).
2007
+ if (this.isMeshWorkerSession()) {
2008
+ traceMeshEventStage('fired', this.meshTraceCtx(), 'no_progress_monitor_final_summary');
2009
+ }
2010
+ this.pushEvent({
2011
+ event: 'agent:generating_completed',
2012
+ chatTitle,
2013
+ duration: this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : undefined,
2014
+ timestamp: me.timestamp,
2015
+ finalSummary: extractFinalSummaryFromMessages(monitorParsedStatus?.messages),
2016
+ completionDiagnostic: {
2017
+ providerType: this.type,
2018
+ sessionId: this.instanceId,
2019
+ providerSessionId: this.providerSessionId || null,
2020
+ reconciliationReason: 'no_progress_monitor_final_summary',
2021
+ finalAssistantPresent: true,
2022
+ },
2023
+ });
2024
+ this.generatingStartedAt = 0;
2025
+ // Cancel any pending debounce flush — monitor already fired completion.
2026
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
2027
+ this.completedDebouncePending = null;
2028
+ continue;
2029
+ }
981
2030
  this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
982
2031
  }
983
2032
  }
@@ -997,15 +2046,49 @@ export class CliProviderInstance implements ProviderInstance {
997
2046
  workspaceName: typeof event.workspaceName === 'string' && event.workspaceName.trim()
998
2047
  ? event.workspaceName
999
2048
  : this.workingDir,
2049
+ // Carry the workspace under BOTH `workspace` and `workspaceName` so the
2050
+ // downstream mesh forward/merge path — which reads `workspace` — can
2051
+ // propagate it to the coordinator snapshot. Without `workspace` the live
2052
+ // event path delivers an empty workspace and the dashboard falls back to
2053
+ // the generic "Terminal (Mesh Node)" title.
2054
+ workspace: typeof event.workspace === 'string' && event.workspace.trim()
2055
+ ? event.workspace
2056
+ : this.workingDir,
1000
2057
  providerSessionId: typeof event.providerSessionId === 'string' && event.providerSessionId.trim()
1001
2058
  ? event.providerSessionId
1002
2059
  : this.providerSessionId,
1003
2060
  };
2061
+ // TASKIDLESS: stamp the mesh task primary key on lifecycle events emitted by
2062
+ // a mesh worker session. The consumer (updateDirectDispatchStatus) was switched
2063
+ // to key on task_id (CANON-B), but the producer never carried it — so every
2064
+ // forwarded metadataEvent.taskId arrived undefined and the coordinator fell back
2065
+ // to a session_id match, which can flip a sibling dispatch row. The session
2066
+ // already knows its own taskId via attachMeshAssignment (settings.meshActiveTaskId);
2067
+ // surface it here so updateDirectDispatchStatus hits the exact PK row and the
2068
+ // session_id fallback is never exercised. Non-mesh sessions get no taskId
2069
+ // (regression guard) — isMeshWorkerSession() gates the injection.
2070
+ if (this.isMeshWorkerSession() && this.settings.meshActiveTaskId) {
2071
+ const existingTaskId = typeof enrichedEvent.taskId === 'string' && enrichedEvent.taskId.trim()
2072
+ ? enrichedEvent.taskId
2073
+ : undefined;
2074
+ if (!existingTaskId) {
2075
+ enrichedEvent.taskId = this.settings.meshActiveTaskId;
2076
+ }
2077
+ }
1004
2078
  if (this.context?.emitProviderEvent) {
1005
2079
  this.context.emitProviderEvent(enrichedEvent);
1006
- return;
2080
+ } else {
2081
+ this.events.push(enrichedEvent);
2082
+ }
2083
+ // Auto-detach a direct-dispatch mesh assignment once the dispatched
2084
+ // task reaches a terminal state. Leaving meshNodeFor pinned would
2085
+ // route this session's next unrelated turn (a dashboard chat) into
2086
+ // the coordinator as if it were the completion of another task.
2087
+ // We schedule after the emit so the originating coordinator still
2088
+ // observes the completion event with its routing marker intact.
2089
+ if (TERMINAL_MESH_EVENTS.has(event.event) && this.settings.meshActiveTaskId) {
2090
+ try { this.detachMeshAssignment(); } catch { /* best-effort */ }
1007
2091
  }
1008
- this.events.push(enrichedEvent);
1009
2092
  }
1010
2093
 
1011
2094
  private flushEvents(): ProviderEvent[] {
@@ -1151,6 +2234,25 @@ export class CliProviderInstance implements ProviderInstance {
1151
2234
  return false;
1152
2235
  }
1153
2236
 
2237
+ /** @see ProviderInstance.noteManualInteraction */
2238
+ noteManualInteraction(now = Date.now()): void {
2239
+ this.manualAttendance.note(now);
2240
+ }
2241
+
2242
+ /**
2243
+ * Whether auto-approve should be treated as active *right now* for display
2244
+ * and firing decisions: the configured intent AND the user is not currently
2245
+ * attending this session by hand. When a human is attending, auto-approve is
2246
+ * held so the modal stays visible and they can drive it via the controlbar.
2247
+ * Provider-agnostic — the attendance signal is the command set, never any
2248
+ * CLI-specific modal text.
2249
+ */
2250
+ private autoApproveEffectivelyActive(status: string | undefined, now = Date.now()): boolean {
2251
+ return status === 'waiting_approval'
2252
+ && this.shouldAutoApprove()
2253
+ && !this.manualAttendance.isAttended(now);
2254
+ }
2255
+
1154
2256
  private recordAutoApproval(modalMessage?: string, buttonLabel?: string, now = Date.now()): void {
1155
2257
  this.appendRuntimeSystemMessage(
1156
2258
  formatAutoApprovalMessage(modalMessage, buttonLabel),
@@ -1238,7 +2340,7 @@ export class CliProviderInstance implements ProviderInstance {
1238
2340
  receivedAt: normalizedMessage.receivedAt || normalizedMessage.timestamp,
1239
2341
  historyDedupKey: dedupKey,
1240
2342
  }],
1241
- this.adapter.getScriptParsedStatus?.()?.title || this.workingDir.split('/').filter(Boolean).pop() || 'session',
2343
+ this.adapter.getScriptParsedStatus?.()?.title || workingDirBasename(this.workingDir),
1242
2344
  this.instanceId,
1243
2345
  this.providerSessionId,
1244
2346
  );
@@ -1258,12 +2360,28 @@ export class CliProviderInstance implements ProviderInstance {
1258
2360
  index,
1259
2361
  source: 'parsed',
1260
2362
  }));
2363
+ const getRole = (message: ChatMessage): string => typeof message.role === 'string'
2364
+ ? message.role.trim().toLowerCase()
2365
+ : '';
1261
2366
  const runtimeEntries: MergeEntry[] = this.runtimeMessages.map((entry, index) => ({
1262
2367
  message: entry.message,
1263
2368
  index: parsedMessages.length + index,
1264
- source: 'runtime',
2369
+ source: 'runtime' as const,
1265
2370
  runtimeKey: entry.key,
1266
- }));
2371
+ })).filter((entry) => {
2372
+ const meta = entry.message.meta && typeof entry.message.meta === 'object' && !Array.isArray(entry.message.meta)
2373
+ ? entry.message.meta as Record<string, unknown>
2374
+ : {};
2375
+ if (meta.runtimeInputAck !== true) return true;
2376
+ const runtimeText = flattenContent(entry.message.content).replace(/\s+/g, ' ').trim();
2377
+ if (!runtimeText) return false;
2378
+ return !parsedEntries.some((parsedEntry) => {
2379
+ const parsedRole = getRole(parsedEntry.message);
2380
+ if (parsedRole !== 'user' && parsedRole !== 'human') return false;
2381
+ const parsedText = flattenContent(parsedEntry.message.content).replace(/\s+/g, ' ').trim();
2382
+ return parsedText === runtimeText;
2383
+ });
2384
+ });
1267
2385
  const getTime = (message: ChatMessage): number => {
1268
2386
  const value = typeof message.receivedAt === 'number'
1269
2387
  ? message.receivedAt
@@ -1273,9 +2391,6 @@ export class CliProviderInstance implements ProviderInstance {
1273
2391
  return Number.isFinite(value) && value > 0 ? value : 0;
1274
2392
  };
1275
2393
 
1276
- const getRole = (message: ChatMessage): string => typeof message.role === 'string'
1277
- ? message.role.trim().toLowerCase()
1278
- : '';
1279
2394
  const isRuntimeOverlay = (entry: MergeEntry): boolean => {
1280
2395
  if (entry.source !== 'runtime') return false;
1281
2396
  const key = typeof entry.runtimeKey === 'string' ? entry.runtimeKey.trim().toLowerCase() : '';
@@ -1341,7 +2456,9 @@ export class CliProviderInstance implements ProviderInstance {
1341
2456
  this.providerSessionId = nextSessionId;
1342
2457
  this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
1343
2458
  this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
1344
- this.restorePersistedHistoryFromCurrentSession();
2459
+ if (this.shouldHydrateExistingProviderHistory()) {
2460
+ this.restorePersistedHistoryFromCurrentSession();
2461
+ }
1345
2462
  this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
1346
2463
  this.onProviderSessionResolved?.({
1347
2464
  instanceId: this.instanceId,
@@ -1354,13 +2471,39 @@ export class CliProviderInstance implements ProviderInstance {
1354
2471
  LOG.info('CLI', `[${this.type}] discovered provider session id: ${nextSessionId}`);
1355
2472
  }
1356
2473
 
1357
- private syncCanonicalSavedHistoryIfNeeded(): boolean {
2474
+ private shouldHydrateExistingProviderHistory(): boolean {
2475
+ return this.launchMode === 'resume' || this.launchMode === 'manual';
2476
+ }
2477
+
2478
+ private shouldSuppressFreshLaunchStartupReplay(parsedMessages: unknown[], parsedStatus: any, adapterStatus: any, parsedProviderSessionId = ''): boolean {
2479
+ if (this.launchMode !== 'new') return false;
2480
+ if (this.providerSessionId) return false;
2481
+ if (!Array.isArray(parsedMessages) || parsedMessages.length === 0) return false;
2482
+ if (!isIdleStatus(adapterStatus?.status) || !isIdleStatus(parsedStatus?.status)) return false;
2483
+ if (parsedProviderSessionId) return true;
2484
+
2485
+ const newestMessageAt = parsedMessages.reduce<number>((newest, message) => Math.max(newest, getMessageTime(message)), 0);
2486
+
2487
+ // Untimestamped idle parser output during a fresh launch is usually the
2488
+ // provider's last workspace transcript before a new turn exists.
2489
+ return newestMessageAt === 0;
2490
+ }
2491
+
2492
+ private syncCanonicalSavedHistoryIfNeeded(options: { full?: boolean } = {}): boolean {
1358
2493
  if (!this.providerSessionId) return false;
1359
- const canonicalHistory = this.provider.canonicalHistory;
2494
+ const canonicalHistory = this.provider.nativeHistory;
1360
2495
  if (!canonicalHistory) return false;
1361
2496
 
2497
+ // Per-status-report hydration reads only a bounded tail (snapshot needs at
2498
+ // most the newest 60). The once-per-resume restore path passes full:true
2499
+ // because seedSessionHistory needs the COMPLETE transcript to seed dedup
2500
+ // state. The read-cache key encodes the window so the bounded and full
2501
+ // reads don't share/clobber each other's 2s cache entry.
2502
+ const limit = options.full ? Number.MAX_SAFE_INTEGER : STATUS_HYDRATION_TAIL_LIMIT;
2503
+ const windowTag = options.full ? 'full' : `tail:${STATUS_HYDRATION_TAIL_LIMIT}`;
2504
+
1362
2505
  if (isNativeSourceCanonicalHistory(canonicalHistory)) {
1363
- const cacheKey = [this.type, this.providerSessionId, this.workingDir].join('\0');
2506
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, windowTag].join('\0');
1364
2507
  const now = Date.now();
1365
2508
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1366
2509
  return true;
@@ -1373,7 +2516,7 @@ export class CliProviderInstance implements ProviderInstance {
1373
2516
  historySessionId: this.providerSessionId,
1374
2517
  workspace: this.workingDir,
1375
2518
  offset: 0,
1376
- limit: Number.MAX_SAFE_INTEGER,
2519
+ limit,
1377
2520
  historyBehavior: this.provider.historyBehavior,
1378
2521
  scripts: this.provider.scripts as any,
1379
2522
  });
@@ -1390,7 +2533,7 @@ export class CliProviderInstance implements ProviderInstance {
1390
2533
  }
1391
2534
 
1392
2535
  try {
1393
- const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror'].join('\0');
2536
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror', windowTag].join('\0');
1394
2537
  const now = Date.now();
1395
2538
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1396
2539
  return true;
@@ -1401,7 +2544,14 @@ export class CliProviderInstance implements ProviderInstance {
1401
2544
  if (!materializeProviderNativeHistory(this.type, canonicalHistory, this.providerSessionId, this.workingDir, this.provider.scripts as any)) {
1402
2545
  return false;
1403
2546
  }
1404
- const restoredHistory = readChatHistory(this.type, 0, Number.MAX_SAFE_INTEGER, this.providerSessionId, 0, this.provider.historyBehavior);
2547
+ // Bounded by default: the per-status-report path only needs the newest
2548
+ // STATUS_HYDRATION_TAIL_LIMIT messages because the snapshot caps
2549
+ // activeChat.messages to the last 60 (status/normalize.ts) and loads
2550
+ // the rest lazily via read_chat on subscribe. The once-per-resume
2551
+ // restore path passes full:true so seedSessionHistory still sees the
2552
+ // COMPLETE transcript for prefix-dedup seeding. readChatHistory serves
2553
+ // a bounded limit as an O(tail) read.
2554
+ const restoredHistory = readChatHistory(this.type, 0, limit, this.providerSessionId, 0, this.provider.historyBehavior);
1405
2555
  this.lastPersistedHistoryMessages = restoredHistory.messages.map((message) => ({
1406
2556
  role: message.role,
1407
2557
  content: message.content,
@@ -1417,10 +2567,13 @@ export class CliProviderInstance implements ProviderInstance {
1417
2567
 
1418
2568
  private restorePersistedHistoryFromCurrentSession(): void {
1419
2569
  if (!this.providerSessionId) return;
1420
- this.syncCanonicalSavedHistoryIfNeeded();
1421
- const restoredHistory = isNativeSourceCanonicalHistory(this.provider.canonicalHistory)
2570
+ // Restore is the once-per-resume seeding path: it needs the COMPLETE
2571
+ // transcript so seedSessionHistory can prime dedup state. Pass full so the
2572
+ // hydration read is unbounded here (and only here).
2573
+ this.syncCanonicalSavedHistoryIfNeeded({ full: true });
2574
+ const restoredHistory = isNativeSourceCanonicalHistory(this.provider.nativeHistory)
1422
2575
  ? readProviderChatHistory(this.type, {
1423
- canonicalHistory: this.provider.canonicalHistory,
2576
+ canonicalHistory: this.provider.nativeHistory,
1424
2577
  historySessionId: this.providerSessionId,
1425
2578
  workspace: this.workingDir,
1426
2579
  offset: 0,