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

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 (335) 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 +15 -1
  20. package/dist/commands/handler.d.ts +125 -0
  21. package/dist/commands/low-family/index.d.ts +3 -0
  22. package/dist/commands/low-family/refine-config.d.ts +2 -0
  23. package/dist/commands/low-family/session-host.d.ts +2 -0
  24. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  25. package/dist/commands/low-family/types.d.ts +16 -0
  26. package/dist/commands/mesh-coordinator.d.ts +85 -1
  27. package/dist/commands/router.d.ts +336 -2
  28. package/dist/commands/upgrade-helper.d.ts +41 -1
  29. package/dist/config/chat-history.d.ts +9 -0
  30. package/dist/config/config.d.ts +5 -0
  31. package/dist/config/mesh-config.d.ts +77 -1
  32. package/dist/detection/ide-detector.d.ts +13 -0
  33. package/dist/detection/win32-ide-version.d.ts +37 -0
  34. package/dist/git/change-impact-config.d.ts +159 -0
  35. package/dist/git/git-commands.d.ts +11 -1
  36. package/dist/git/git-diff.d.ts +6 -0
  37. package/dist/git/git-executor.d.ts +11 -0
  38. package/dist/git/git-status.d.ts +23 -0
  39. package/dist/git/git-types.d.ts +2 -50
  40. package/dist/git/index.d.ts +2 -0
  41. package/dist/index.d.ts +54 -13
  42. package/dist/index.js +41337 -14723
  43. package/dist/index.js.map +1 -1
  44. package/dist/index.mjs +44100 -17614
  45. package/dist/index.mjs.map +1 -1
  46. package/dist/installer.d.ts +1 -4
  47. package/dist/ipc/local-ipc-server.d.ts +91 -0
  48. package/dist/launch.d.ts +1 -1
  49. package/dist/logging/async-batch-writer.d.ts +10 -0
  50. package/dist/logging/log-redactor.d.ts +24 -0
  51. package/dist/logging/log-tail-reader.d.ts +46 -0
  52. package/dist/logging/logger.d.ts +1 -1
  53. package/dist/mesh/contracts.d.ts +164 -0
  54. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  55. package/dist/mesh/coordinator-registry.d.ts +59 -0
  56. package/dist/mesh/mesh-active-work.d.ts +174 -0
  57. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  58. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  59. package/dist/mesh/mesh-events-coordinator.d.ts +170 -0
  60. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  61. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  62. package/dist/mesh/mesh-events-utils.d.ts +60 -0
  63. package/dist/mesh/mesh-events.d.ts +6 -49
  64. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  65. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  66. package/dist/mesh/mesh-init.d.ts +86 -0
  67. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  68. package/dist/mesh/mesh-ledger.d.ts +77 -1
  69. package/dist/mesh/mesh-missions.d.ts +164 -0
  70. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  71. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  72. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  73. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  74. package/dist/mesh/mesh-routing.d.ts +70 -0
  75. package/dist/mesh/mesh-runtime-store.d.ts +429 -0
  76. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  77. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  78. package/dist/mesh/mesh-work-queue.d.ts +246 -5
  79. package/dist/mesh/preview-freshness.d.ts +18 -0
  80. package/dist/mesh/refine-config.d.ts +216 -0
  81. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  82. package/dist/providers/acp-provider-instance.d.ts +5 -0
  83. package/dist/providers/approval-utils.d.ts +20 -0
  84. package/dist/providers/chat-message-normalization.d.ts +12 -0
  85. package/dist/providers/cli-provider-instance.d.ts +106 -3
  86. package/dist/providers/contracts.d.ts +139 -6
  87. package/dist/providers/external-sources.d.ts +71 -0
  88. package/dist/providers/manual-attendance.d.ts +63 -0
  89. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  90. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  91. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  92. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  93. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  94. package/dist/providers/native-history/index.d.ts +13 -0
  95. package/dist/providers/provider-instance-manager.d.ts +14 -0
  96. package/dist/providers/provider-instance.d.ts +23 -1
  97. package/dist/providers/provider-loader.d.ts +26 -4
  98. package/dist/providers/provider-trust.d.ts +31 -0
  99. package/dist/providers/read-chat-contract.d.ts +29 -0
  100. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  101. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  102. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  103. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  104. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  105. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  106. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  107. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  108. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  109. package/dist/providers/sdk/v1/index.d.ts +30 -0
  110. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  111. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  112. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  113. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  114. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  115. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  116. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  117. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  118. package/dist/providers/spec/adapter.d.ts +91 -0
  119. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  120. package/dist/providers/spec/evaluator.d.ts +45 -0
  121. package/dist/providers/spec/fsm-driver.d.ts +368 -0
  122. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  123. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  124. package/dist/providers/spec/fsm-types.d.ts +174 -0
  125. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  126. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  127. package/dist/providers/spec/route.d.ts +4 -0
  128. package/dist/providers/spec/types.d.ts +222 -0
  129. package/dist/providers/status-monitor.d.ts +7 -7
  130. package/dist/providers/transcript-v2.d.ts +176 -0
  131. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  132. package/dist/providers/working-dir.d.ts +17 -0
  133. package/dist/repo-mesh-types.d.ts +295 -13
  134. package/dist/sessions/registry.d.ts +6 -0
  135. package/dist/shared-types-extra.d.ts +2 -4
  136. package/dist/shared-types.d.ts +59 -2
  137. package/dist/status/normalize.d.ts +1 -1
  138. package/dist/status/normalize.js +1 -0
  139. package/dist/status/normalize.js.map +1 -1
  140. package/dist/status/normalize.mjs +1 -0
  141. package/dist/status/normalize.mjs.map +1 -1
  142. package/dist/status/reporter.d.ts +2 -0
  143. package/dist/status/snapshot.d.ts +26 -0
  144. package/dist/system/load-better-sqlite3.d.ts +21 -0
  145. package/dist/types.d.ts +5 -0
  146. package/package.json +7 -3
  147. package/src/agent-stream/poller.ts +2 -3
  148. package/src/agent-stream/provider-adapter.ts +1 -1
  149. package/src/boot/daemon-lifecycle.ts +55 -12
  150. package/src/boot/process-hardening.ts +89 -0
  151. package/src/build-info.ts +73 -0
  152. package/src/chat/source-machine.ts +534 -0
  153. package/src/chat/source-resolver.ts +0 -0
  154. package/src/chat/subscription-updates.ts +20 -1
  155. package/src/cli-adapter-types.d.ts +1 -0
  156. package/src/cli-adapter-types.ts +56 -2
  157. package/src/cli-adapters/cli-script-runner.ts +421 -0
  158. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  159. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  160. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  161. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  162. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  163. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  164. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  165. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  166. package/src/cli-adapters/pty-transport.ts +2 -1
  167. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  168. package/src/cli-adapters/resolve-executable.ts +90 -0
  169. package/src/cli-adapters/session-host-transport.ts +2 -1
  170. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  171. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  172. package/src/cli-adapters/terminal-screen.ts +16 -81
  173. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  174. package/src/commands/chat-commands.ts +1823 -62
  175. package/src/commands/cli-manager.ts +405 -23
  176. package/src/commands/handler.ts +841 -2
  177. package/src/commands/low-family/index.ts +23 -0
  178. package/src/commands/low-family/refine-config.ts +106 -0
  179. package/src/commands/low-family/session-host.ts +274 -0
  180. package/src/commands/low-family/spec-providerdev.ts +217 -0
  181. package/src/commands/low-family/types.ts +19 -0
  182. package/src/commands/mesh-coordinator.ts +332 -122
  183. package/src/commands/router.ts +7195 -1423
  184. package/src/commands/stream-commands.ts +8 -0
  185. package/src/commands/upgrade-helper.ts +310 -45
  186. package/src/config/chat-history.ts +483 -24
  187. package/src/config/config.ts +12 -0
  188. package/src/config/mesh-config.ts +388 -6
  189. package/src/config/recent-activity.ts +8 -2
  190. package/src/daemon/dev-auto-implement.ts +3 -2
  191. package/src/daemon/dev-cli-debug.ts +10 -1
  192. package/src/detection/cli-detector.ts +28 -9
  193. package/src/detection/ide-detector.ts +55 -16
  194. package/src/detection/win32-ide-version.ts +106 -0
  195. package/src/git/change-impact-config.ts +354 -0
  196. package/src/git/git-commands.ts +55 -14
  197. package/src/git/git-diff.ts +81 -11
  198. package/src/git/git-executor.ts +12 -0
  199. package/src/git/git-status.ts +574 -43
  200. package/src/git/git-types.ts +14 -62
  201. package/src/git/git-worktree.ts +8 -1
  202. package/src/git/index.ts +16 -0
  203. package/src/index.ts +156 -12
  204. package/src/installer.d.ts +1 -1
  205. package/src/installer.ts +8 -6
  206. package/src/ipc/local-ipc-server.ts +278 -0
  207. package/src/launch.d.ts +1 -1
  208. package/src/launch.ts +37 -28
  209. package/src/logging/async-batch-writer.ts +55 -0
  210. package/src/logging/command-log.ts +7 -5
  211. package/src/logging/log-redactor.ts +100 -0
  212. package/src/logging/log-tail-reader.ts +220 -0
  213. package/src/logging/logger.ts +14 -7
  214. package/src/mesh/contracts.ts +338 -0
  215. package/src/mesh/coordinator-prompt.ts +234 -31
  216. package/src/mesh/coordinator-registry.ts +121 -0
  217. package/src/mesh/mesh-active-work.ts +667 -0
  218. package/src/mesh/mesh-delivery-policy.ts +315 -0
  219. package/src/mesh/mesh-event-trace.ts +67 -0
  220. package/src/mesh/mesh-events-coordinator.ts +2572 -0
  221. package/src/mesh/mesh-events-pending.ts +599 -0
  222. package/src/mesh/mesh-events-stale.ts +309 -0
  223. package/src/mesh/mesh-events-utils.ts +361 -0
  224. package/src/mesh/mesh-events.ts +30 -1035
  225. package/src/mesh/mesh-fast-forward.ts +839 -0
  226. package/src/mesh/mesh-host-ownership.ts +73 -0
  227. package/src/mesh/mesh-init.ts +260 -0
  228. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  229. package/src/mesh/mesh-ledger.ts +591 -102
  230. package/src/mesh/mesh-missions.ts +322 -0
  231. package/src/mesh/mesh-reconcile-loop.ts +1096 -0
  232. package/src/mesh/mesh-refine-batch.ts +197 -0
  233. package/src/mesh/mesh-refine-status.ts +231 -0
  234. package/src/mesh/mesh-review-inbox.ts +307 -0
  235. package/src/mesh/mesh-routing.ts +291 -0
  236. package/src/mesh/mesh-runtime-store.ts +1697 -0
  237. package/src/mesh/mesh-task-stats.ts +161 -0
  238. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  239. package/src/mesh/mesh-work-queue.ts +997 -141
  240. package/src/mesh/preview-freshness.ts +118 -0
  241. package/src/mesh/refine-config.ts +423 -0
  242. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  243. package/src/providers/acp-provider-instance.ts +43 -10
  244. package/src/providers/approval-utils.d.ts +5 -0
  245. package/src/providers/approval-utils.ts +57 -5
  246. package/src/providers/chat-message-normalization.ts +45 -5
  247. package/src/providers/cli-provider-instance.ts +1267 -101
  248. package/src/providers/contracts.d.ts +55 -0
  249. package/src/providers/contracts.ts +150 -6
  250. package/src/providers/extension-provider-instance.ts +12 -7
  251. package/src/providers/external-sources.ts +218 -0
  252. package/src/providers/ide-provider-instance.ts +35 -12
  253. package/src/providers/manual-attendance.ts +85 -0
  254. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  255. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  256. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  257. package/src/providers/native-history/dispatcher.ts +340 -0
  258. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  259. package/src/providers/native-history/index.ts +30 -0
  260. package/src/providers/provider-instance-manager.ts +30 -0
  261. package/src/providers/provider-instance.ts +19 -1
  262. package/src/providers/provider-loader.ts +670 -50
  263. package/src/providers/provider-schema.ts +87 -14
  264. package/src/providers/provider-trust.ts +114 -0
  265. package/src/providers/read-chat-contract.ts +76 -16
  266. package/src/providers/sdk/README.md +49 -0
  267. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  268. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  269. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  270. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  271. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  272. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  273. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  274. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  275. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  276. package/src/providers/sdk/v1/index.ts +152 -0
  277. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  278. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  279. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  280. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  281. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  282. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  283. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  284. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  285. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  286. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  287. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  288. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  289. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  290. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  291. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  292. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  293. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  294. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  295. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  296. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  297. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  298. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  299. package/src/providers/sdk/v1/validators/index.ts +19 -0
  300. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  301. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  302. package/src/providers/spec/adapter.ts +235 -0
  303. package/src/providers/spec/cli-adapter.ts +1051 -0
  304. package/src/providers/spec/evaluator.ts +407 -0
  305. package/src/providers/spec/fsm-driver.ts +1251 -0
  306. package/src/providers/spec/fsm-evaluator.ts +272 -0
  307. package/src/providers/spec/fsm-loader.ts +120 -0
  308. package/src/providers/spec/fsm-types.ts +273 -0
  309. package/src/providers/spec/native-history-executor.ts +1136 -0
  310. package/src/providers/spec/pre-launch-trust.ts +104 -0
  311. package/src/providers/spec/route.ts +51 -0
  312. package/src/providers/spec/types.ts +262 -0
  313. package/src/providers/status-monitor.d.ts +7 -7
  314. package/src/providers/status-monitor.ts +37 -22
  315. package/src/providers/transcript-v2.ts +567 -0
  316. package/src/providers/types/interactive-prompt.ts +536 -0
  317. package/src/providers/version-archive.ts +64 -24
  318. package/src/providers/working-dir.ts +23 -0
  319. package/src/repo-mesh-types.ts +378 -14
  320. package/src/sessions/registry.ts +6 -0
  321. package/src/shared-types-extra.ts +2 -4
  322. package/src/shared-types.d.ts +8 -0
  323. package/src/shared-types.ts +64 -1
  324. package/src/status/builders.ts +26 -6
  325. package/src/status/normalize.ts +2 -0
  326. package/src/status/reporter.ts +19 -1
  327. package/src/status/snapshot.ts +95 -26
  328. package/src/system/host-memory.ts +29 -12
  329. package/src/system/load-better-sqlite3.ts +68 -0
  330. package/src/types.ts +5 -0
  331. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  332. package/dist/mesh/mesh-sync.d.ts +0 -53
  333. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  334. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  335. 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,165 @@ 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
+ // WTCLAIM (A): track the bound node id under BOTH the active marker
914
+ // (meshNodeId, cleared on detach) and a sticky marker (meshLastNodeId,
915
+ // preserved across detach). The sticky marker lets a detached but still
916
+ // coordinator-owned session be re-picked ONLY for the SAME node it served
917
+ // — never auto-adopted for a sibling node (e.g. a cloned worktree) that
918
+ // shares this daemon. See isMeshOwnedDelegateSession's post-detach gate.
919
+ ...(assignment.nodeId ? { meshNodeId: assignment.nodeId, meshLastNodeId: assignment.nodeId } : {}),
920
+ ...(assignment.taskId ? { meshActiveTaskId: assignment.taskId } : {}),
921
+ ...(assignment.coordinatorDaemonId ? { meshCoordinatorDaemonId: assignment.coordinatorDaemonId } : {}),
922
+ // Session-level routing anchor: the originating coordinator session, so this
923
+ // worker's completion events route back to the exact session that dispatched it.
924
+ ...(assignment.coordinatorSessionId ? { meshCoordinatorSessionId: assignment.coordinatorSessionId } : {}),
925
+ };
926
+ this.adapter.updateRuntimeSettings?.(this.settings);
927
+ }
928
+
929
+ /**
930
+ * Clear a previously-attached mesh assignment after the task reaches a
931
+ * terminal state. Leaving meshNodeFor pinned would route this session's
932
+ * subsequent unrelated turns (e.g. ad-hoc dashboard chats) to the
933
+ * coordinator as if they were task completions.
934
+ */
935
+ detachMeshAssignment(): void {
936
+ if (!this.settings.meshNodeFor && !this.settings.meshActiveTaskId && !this.settings.meshNodeId) return;
937
+ const { meshNodeFor, meshNodeId, meshActiveTaskId, ...rest } = this.settings;
938
+ void meshNodeFor; void meshActiveTaskId;
939
+ // WTCLAIM (A): clear the active binding but PRESERVE the last bound node id
940
+ // (meshLastNodeId) so a later sessionless dispatch can re-adopt this idle
941
+ // session ONLY for the node it last served. Carry the id being cleared, or
942
+ // keep an already-present sticky marker if meshNodeId was absent.
943
+ const lastNodeId = (typeof meshNodeId === 'string' && meshNodeId.trim())
944
+ ? meshNodeId.trim()
945
+ : (typeof rest.meshLastNodeId === 'string' && rest.meshLastNodeId.trim() ? rest.meshLastNodeId.trim() : undefined);
946
+ this.settings = lastNodeId ? { ...rest, meshLastNodeId: lastNodeId } : rest;
947
+ this.adapter.updateRuntimeSettings?.(this.settings);
948
+ }
949
+
950
+ /**
951
+ * The resolved modal-park status of this session, or null when it is not
952
+ * parked on a modal awaiting a human answer. Mirrors the overlay logic in
953
+ * getState(): an active AskUserQuestion interactive prompt resolves to
954
+ * waiting_choice; otherwise the adapter's waiting_approval (tool consent)
955
+ * counts — UNLESS auto-approve will dismiss it, in which case the session is
956
+ * effectively generating and is NOT modal-parked. This is the single signal
957
+ * the mesh force-inject guard consults, and the same status string the
958
+ * reconcile loop reads off get_status_metadata. Lowercase literals only —
959
+ * the SessionStatus enum is forked across modules and waiting_choice is
960
+ * absent from some of them.
961
+ */
962
+ resolveModalParkStatus(): 'waiting_choice' | 'waiting_approval' | null {
963
+ if (this.activeInteractivePrompt) return 'waiting_choice';
964
+ let adapterStatus: { status?: string };
965
+ try {
966
+ adapterStatus = this.adapter.getStatus({ allowParse: false });
967
+ } catch {
968
+ return null;
969
+ }
970
+ // A session whose auto-approve is held by manual attendance IS parked on a
971
+ // modal awaiting the human — autoApproveEffectivelyActive folds that in, so
972
+ // the mesh force-inject guard correctly treats it as modal-parked.
973
+ if (adapterStatus.status === 'waiting_approval' && !this.autoApproveEffectivelyActive(adapterStatus.status)) {
974
+ return 'waiting_approval';
975
+ }
976
+ return null;
977
+ }
978
+
979
+ /** True when this session is parked on a modal awaiting a human answer. */
980
+ isModalParked(): boolean {
981
+ return this.resolveModalParkStatus() !== null;
982
+ }
983
+
677
984
  onEvent(event: string, data?: any): void {
678
985
  if (event === 'send_message') {
679
986
  const input = normalizeInputEnvelope(data);
680
987
  assertProviderSupportsDeclaredInput(this.provider, input);
681
988
  const promptText = buildCliStructuredInputPrompt(input);
682
989
  if (promptText) {
683
- void this.adapter.sendMessage(promptText).catch((e: any) => {
990
+ // force:true bypasses the busy/generating send guard so terminal mesh
991
+ // events (completion/failure/bootstrap) land in a coordinator session that
992
+ // is itself parked in `generating` while awaiting that very event.
993
+ // Without it the message is queued and only flushed on the coordinator's
994
+ // own idle transition — which never happens until it receives the message.
995
+ const force = data?.force === true;
996
+ // Modal guard: a force-inject still writes raw keystrokes into the PTY,
997
+ // bypassing the busy send-guard. If the coordinator is parked on a
998
+ // harness modal (claude-cli AskUserQuestion → waiting_choice, or a
999
+ // tool-consent waiting_approval), those keystrokes are consumed by the
1000
+ // modal's key handler and silently select a choice the user never made
1001
+ // (data corruption). Hold the force-inject in that narrow window —
1002
+ // the event stays queued and the reconcile loop redelivers it on the
1003
+ // next tick once the modal is resolved. We ONLY hold for the two modal
1004
+ // states; generating is still force-injected (that is the deadlock the
1005
+ // force path exists to break — see mesh-events-coordinator).
1006
+ if (force && this.isModalParked()) {
1007
+ LOG.info('CLI', `[${this.type}] force send_message held — coordinator parked on modal (${this.resolveModalParkStatus()})`);
1008
+ return;
1009
+ }
1010
+ void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e: any) => {
684
1011
  LOG.warn('CLI', `[${this.type}] send_message failed: ${e?.message || e}`);
685
1012
  });
686
1013
  }
@@ -690,14 +1017,73 @@ export class CliProviderInstance implements ProviderInstance {
690
1017
  void this.adapter.resolveAction(data).catch((e: any) => {
691
1018
  LOG.warn('CLI', `[${this.type}] resolve_action failed: ${e?.message || e}`);
692
1019
  });
1020
+ } else if (event === 'interactive_prompt' && data) {
1021
+ const prompt = normalizeInteractivePrompt(data);
1022
+ if (prompt) {
1023
+ this.activeInteractivePrompt = prompt;
1024
+ this.events.push({
1025
+ event: 'interactive_prompt',
1026
+ timestamp: Date.now(),
1027
+ promptId: prompt.promptId,
1028
+ });
1029
+ }
1030
+ } else if (event === 'interactive_prompt_response' && data) {
1031
+ try {
1032
+ const response = normalizeInteractivePromptResponse(data);
1033
+ if (this.activeInteractivePrompt?.promptId === response.promptId) {
1034
+ this.activeInteractivePrompt = null;
1035
+ }
1036
+ if (typeof this.adapter.setInteractivePromptResponse !== 'function') {
1037
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response ignored: adapter does not support interactive prompts`);
1038
+ return;
1039
+ }
1040
+ void this.adapter.setInteractivePromptResponse(response).catch((e: any) => {
1041
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response failed: ${e?.message || e}`);
1042
+ });
1043
+ } catch (e: any) {
1044
+ LOG.warn('CLI', `[${this.type}] invalid interactive_prompt_response: ${e?.message || e}`);
1045
+ }
693
1046
  } else if (event === 'provider_state_patch' && data && typeof data === 'object') {
694
1047
  this.applyProviderResponse(data, { phase: 'immediate' });
695
1048
  }
696
1049
  }
697
1050
 
1051
+ recordAcknowledgedUserInput(input: InputEnvelope | string): void {
1052
+ const content = typeof input === 'string'
1053
+ ? input.trim()
1054
+ : buildCliStructuredInputPrompt(input).trim();
1055
+ if (!content) return;
1056
+
1057
+ const receivedAt = Date.now();
1058
+ this.lastAcknowledgedUserInputAt = receivedAt;
1059
+ const dedupKey = `user_input_ack:${crypto
1060
+ .createHash('sha256')
1061
+ .update(`${this.instanceId}:${content}:${receivedAt}`)
1062
+ .digest('hex')
1063
+ .slice(0, 24)}`;
1064
+ this.appendRuntimeMessage(buildChatMessage({
1065
+ role: 'user',
1066
+ senderName: 'User',
1067
+ kind: 'standard',
1068
+ content,
1069
+ receivedAt,
1070
+ timestamp: receivedAt,
1071
+ source: 'runtime_input_ack',
1072
+ meta: {
1073
+ runtimeInputAck: true,
1074
+ provider: this.type,
1075
+ workspace: this.workingDir,
1076
+ },
1077
+ } as ChatMessage), dedupKey);
1078
+ }
1079
+
698
1080
  dispose(): void {
699
1081
  this.adapter.shutdown();
700
1082
  this.monitor.reset();
1083
+ // Cancel any armed auto-approve timers so a pending settle re-check
1084
+ // can't fire resolveModal/detectStatusTransition against a dead adapter.
1085
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1086
+ if (this.autoApproveBusyTimer) { clearTimeout(this.autoApproveBusyTimer); this.autoApproveBusyTimer = null; }
701
1087
  this.appliedEffectKeys.clear();
702
1088
  try { this.cachedSqliteDb?.close(); } catch { /* noop */ }
703
1089
  this.cachedSqliteDb = null;
@@ -706,6 +1092,7 @@ export class CliProviderInstance implements ProviderInstance {
706
1092
 
707
1093
  private completedDebounceTimer: NodeJS.Timeout | null = null;
708
1094
  private completedDebouncePending: CompletedDebouncePending | null = null;
1095
+ private lastExternalCompletionProbe: ExternalTranscriptProbe | null = null;
709
1096
 
710
1097
  private async enforceFreshSessionLaunchIfNeeded(): Promise<void> {
711
1098
  const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
@@ -740,7 +1127,180 @@ export class CliProviderInstance implements ProviderInstance {
740
1127
  const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
741
1128
  const role = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : '';
742
1129
  const content = lastVisible ? flattenContent(lastVisible.content).trim() : '';
743
- return role === 'assistant' && !!content;
1130
+ if (role !== 'assistant' || !content) return false;
1131
+ // Guard: if the last assistant message looks like an active approval/input prompt,
1132
+ // it is not a real completion — the session is still awaiting user input.
1133
+ if (looksLikeActiveApprovalPromptText(content)) return false;
1134
+ return true;
1135
+ }
1136
+
1137
+ private buildExternalTranscriptProbe(messages: unknown[], sourcePath?: string, sourceMtimeMs?: number): ExternalTranscriptProbe {
1138
+ const visibleMessages = messages.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1139
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1140
+ const readAt = Date.now();
1141
+ const mtimeMs = Number(sourceMtimeMs) || 0;
1142
+ return {
1143
+ readAt,
1144
+ msgCount: messages.length,
1145
+ lastRole: typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null,
1146
+ lastKind: typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null,
1147
+ contentLen: lastVisible ? flattenContent(lastVisible.content).trim().length : 0,
1148
+ sourcePath: typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
1149
+ sourceMtimeMs: mtimeMs || null,
1150
+ mtimeAgeMs: mtimeMs ? Math.max(0, readAt - mtimeMs) : null,
1151
+ };
1152
+ }
1153
+
1154
+ private recordPendingTranscriptProbe(pending: CompletedDebouncePending): ExternalTranscriptProbe | null {
1155
+ const probe = this.lastExternalCompletionProbe;
1156
+ if (!probe) return null;
1157
+ const history = pending.transcriptProbeHistory || [];
1158
+ const last = history[history.length - 1];
1159
+ if (!last || last.readAt !== probe.readAt || last.msgCount !== probe.msgCount || last.lastRole !== probe.lastRole || last.contentLen !== probe.contentLen) {
1160
+ history.push(probe);
1161
+ pending.transcriptProbeHistory = history.slice(-5);
1162
+ }
1163
+ return probe;
1164
+ }
1165
+
1166
+ private readExternalCompletionMessages(): unknown[] | null {
1167
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1168
+ if (!adapterOwnsMessagesElsewhere) return null;
1169
+ if (!this.providerSessionId) return null;
1170
+ if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
1171
+
1172
+ if (this.lastExternalCompletionProbe?.sourcePath) {
1173
+ try { fs.statSync(this.lastExternalCompletionProbe.sourcePath); } catch { /* best-effort metadata refresh */ }
1174
+ }
1175
+ const restoredHistory = readProviderChatHistory(this.type, {
1176
+ canonicalHistory: this.provider.nativeHistory,
1177
+ historySessionId: this.providerSessionId,
1178
+ workspace: this.workingDir,
1179
+ offset: 0,
1180
+ limit: Number.MAX_SAFE_INTEGER,
1181
+ historyBehavior: this.provider.historyBehavior,
1182
+ scripts: this.provider.scripts as any,
1183
+ sessionStartedAtMs: this.startedAt,
1184
+ forceRefresh: true,
1185
+ });
1186
+ if (restoredHistory.source !== 'provider-native') {
1187
+ this.lastExternalCompletionProbe = null;
1188
+ return null;
1189
+ }
1190
+ this.lastExternalCompletionProbe = this.buildExternalTranscriptProbe(
1191
+ restoredHistory.messages,
1192
+ restoredHistory.sourcePath,
1193
+ restoredHistory.sourceMtimeMs,
1194
+ );
1195
+ return restoredHistory.messages;
1196
+ }
1197
+
1198
+ private completionFinalAssistantEvidence(parsedMessages: unknown): CompletionFinalAssistantEvidence {
1199
+ if (this.completionHasFinalAssistantMessage(parsedMessages)) {
1200
+ return {
1201
+ present: true,
1202
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1203
+ source: 'parsed',
1204
+ };
1205
+ }
1206
+
1207
+ const externalMessages = this.readExternalCompletionMessages();
1208
+ if (externalMessages) {
1209
+ return {
1210
+ present: this.completionHasFinalAssistantMessage(externalMessages),
1211
+ messages: externalMessages,
1212
+ source: 'external-native',
1213
+ };
1214
+ }
1215
+
1216
+ return {
1217
+ present: false,
1218
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1219
+ source: 'unavailable',
1220
+ };
1221
+ }
1222
+
1223
+ private completionFinalSummary(parsedMessages: unknown): string | undefined {
1224
+ // For native-source providers (claude-cli: chatMessagesOwnedExternally), the PTY
1225
+ // screen parse is NOT the source of truth for the final summary — the terminal
1226
+ // wraps/scrolls/clips text, so a screen-parsed assistant message is often a partial
1227
+ // prefix (e.g. 76 chars of a 112-char turn). The append-only native transcript holds
1228
+ // the complete turn. Prefer it whenever it yields a longer/complete summary; fall back
1229
+ // to the parsed screen only when the transcript is unavailable. This is the real cause
1230
+ // of the truncated finalSummary — independent of cloud vs standalone (it surfaces on
1231
+ // any short, fast-completing task where screen parse wins the race).
1232
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1233
+ const parsedSummary = extractFinalSummaryFromMessages(
1234
+ (this.completionHasFinalAssistantMessage(parsedMessages)
1235
+ ? (Array.isArray(parsedMessages) ? parsedMessages : [])
1236
+ : []) as any,
1237
+ );
1238
+ if (adapterOwnsMessagesElsewhere) {
1239
+ const externalMessages = this.readExternalCompletionMessages();
1240
+ const externalSummary = externalMessages
1241
+ ? extractFinalSummaryFromMessages(externalMessages as any)
1242
+ : '';
1243
+ // The transcript is authoritative for native-source providers. Use it unless it is
1244
+ // empty (not yet written) — only then fall back to whatever the screen parsed.
1245
+ if (externalSummary) return externalSummary;
1246
+ return parsedSummary || undefined;
1247
+ }
1248
+ return parsedSummary || undefined;
1249
+ }
1250
+
1251
+ private buildCompletedFinalizationDiagnostic(args: {
1252
+ blockReason: string;
1253
+ latestStatus?: any;
1254
+ latestVisibleStatus: string;
1255
+ waitedMs: number;
1256
+ pending: CompletedDebouncePending;
1257
+ emittedAfterFinalizationTimeout: boolean;
1258
+ }): Record<string, unknown> {
1259
+ let parsed: any = null;
1260
+ let parseError: string | undefined;
1261
+ try {
1262
+ parsed = this.adapter.getScriptParsedStatus();
1263
+ } catch (error: any) {
1264
+ parseError = error?.message || String(error);
1265
+ }
1266
+
1267
+ const evidence = this.completionFinalAssistantEvidence(parsed?.messages);
1268
+ if (evidence.source === 'external-native') {
1269
+ this.recordPendingTranscriptProbe(args.pending);
1270
+ }
1271
+ const visibleMessages = (Array.isArray(evidence.messages) ? evidence.messages : [])
1272
+ .filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1273
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1274
+ const lastVisibleRole = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null;
1275
+ const lastVisibleKind = typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null;
1276
+ const lastVisibleContentLength = lastVisible ? flattenContent(lastVisible.content).trim().length : 0;
1277
+
1278
+ return {
1279
+ providerType: this.type,
1280
+ sessionId: this.instanceId,
1281
+ providerSessionId: this.providerSessionId || null,
1282
+ workspace: this.workingDir,
1283
+ blockReason: args.blockReason,
1284
+ emittedAfterFinalizationTimeout: args.emittedAfterFinalizationTimeout,
1285
+ waitedMs: args.waitedMs,
1286
+ maxWaitMs: COMPLETED_FINALIZATION_MAX_WAIT_MS,
1287
+ adapterStatus: typeof args.latestStatus?.status === 'string' ? args.latestStatus.status : null,
1288
+ latestVisibleStatus: args.latestVisibleStatus,
1289
+ parsedStatus: typeof parsed?.status === 'string' ? parsed.status : (parseError ? 'parse_error' : 'unknown'),
1290
+ parseError: parseError || undefined,
1291
+ finalAssistantPresent: evidence.present,
1292
+ finalAssistantEvidenceSource: evidence.source,
1293
+ visibleMessageCount: visibleMessages.length,
1294
+ lastVisibleRole,
1295
+ lastVisibleKind,
1296
+ lastVisibleContentLength,
1297
+ pendingStartedAt: this.generatingStartedAt || null,
1298
+ pendingFirstObservedAt: args.pending.firstObservedAt,
1299
+ pendingTimestamp: args.pending.timestamp,
1300
+ pendingDurationSec: args.pending.duration,
1301
+ previousBlockReason: args.pending.loggedBlockReason || null,
1302
+ transcriptProbeHistory: args.pending.transcriptProbeHistory || [],
1303
+ };
744
1304
  }
745
1305
 
746
1306
  private hasAdapterPendingResponse(): boolean {
@@ -765,32 +1325,97 @@ export class CliProviderInstance implements ProviderInstance {
765
1325
  if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
766
1326
  if (adapterRawStatus !== 'idle') return false;
767
1327
  if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
768
- return !this.hasAdapterPendingResponse();
1328
+ if (this.hasAdapterPendingResponse()) return false;
1329
+ // Do not suppress when the adapter's raw response buffer is still non-empty.
1330
+ // This catches the case where isWaitingForResponse has already flipped to false
1331
+ // (so getPartialResponse() returns '') but the provider's native parser still
1332
+ // reports generating because it's parsing buffered content. Suppressing the
1333
+ // finalization block here would emit a false completion event while the provider
1334
+ // session is still actively processing its response stream.
1335
+ const adapterAny = this.adapter as any;
1336
+ if (typeof adapterAny?.responseBuffer === 'string' && adapterAny.responseBuffer.trim()) return false;
1337
+ return true;
769
1338
  }
770
1339
 
771
- private getCompletedFinalizationBlockReason(latestVisibleStatus: string): string | null {
772
- if (latestVisibleStatus !== 'idle') return `status:${latestVisibleStatus}`;
1340
+ private getCompletedFinalizationBlock(latestVisibleStatus: string, pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1341
+ if (latestVisibleStatus !== 'idle') return { reason: `status:${latestVisibleStatus}`, terminal: true };
773
1342
 
774
1343
  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';
1344
+ const approvalResolvedIdle = pending.previousStatus === 'waiting_approval';
1345
+ if (!approvalResolvedIdle) {
1346
+ if (adapterAny?.isWaitingForResponse === true) return { reason: 'adapter_waiting_for_response', terminal: true };
1347
+ if (adapterAny?.currentTurnScope) return { reason: 'adapter_turn_scope_active', terminal: true };
1348
+ if (this.hasAdapterPendingResponse()) return { reason: 'adapter_pending_response', terminal: true };
1349
+ }
777
1350
 
778
1351
  const partial = typeof this.adapter.getPartialResponse === 'function'
779
1352
  ? this.adapter.getPartialResponse()
780
1353
  : '';
781
- if (typeof partial === 'string' && partial.trim()) return 'partial_response_pending';
1354
+ if (typeof partial === 'string' && partial.trim()) return { reason: 'partial_response_pending', terminal: true };
782
1355
 
783
1356
  let parsed: any;
784
1357
  try {
785
1358
  parsed = this.adapter.getScriptParsedStatus();
786
1359
  } catch (error: any) {
787
- return `parse_error:${error?.message || String(error)}`;
1360
+ return { reason: `parse_error:${error?.message || String(error)}` };
788
1361
  }
789
1362
 
790
1363
  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';
1364
+ if (parsedStatus !== 'idle') {
1365
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1366
+ if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
1367
+ return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
1368
+ }
1369
+ if (parsed?.activeModal || parsed?.modal) return { reason: 'parsed_modal_active', terminal: true };
1370
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1371
+ const finalAssistantEvidence = this.completionFinalAssistantEvidence(parsed?.messages);
1372
+ const allowMissingAssistantTimeout = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1373
+ LOG.debug('CLI', `[${this.type}] finalAssistantEvidence: present=${finalAssistantEvidence.present} source=${finalAssistantEvidence.source} adapterOwnsMessagesElsewhere=${adapterOwnsMessagesElsewhere} parsedStatus=${parsedStatus}`);
1374
+ if (!finalAssistantEvidence.present) {
1375
+ if (adapterOwnsMessagesElsewhere) {
1376
+ if (finalAssistantEvidence.source === 'external-native') {
1377
+ const probe = this.recordPendingTranscriptProbe(pending);
1378
+ if (probe && !pending.loggedTranscriptProbe) {
1379
+ 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`);
1380
+ pending.loggedTranscriptProbe = true;
1381
+ }
1382
+ LOG.debug('CLI', `[${this.type}] external-native probe result: lastRole=${probe?.lastRole} contentLen=${probe?.contentLen}`);
1383
+ if (probe?.lastRole === 'assistant' && (probe.contentLen ?? 0) > 0) {
1384
+ return null;
1385
+ }
1386
+ if (this.type === 'antigravity-cli') {
1387
+ return null;
1388
+ }
1389
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1390
+ }
1391
+ if ((this.provider as any).requiresFinalAssistantBeforeIdle === true) {
1392
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1393
+ }
1394
+ } else {
1395
+ LOG.debug('CLI', `[${this.type}] missing_final_assistant (not ownsExternal) requiresFinalAssistant=${!!(this.provider as any).requiresFinalAssistantBeforeIdle}`);
1396
+ return {
1397
+ reason: 'missing_final_assistant',
1398
+ terminal: (this.provider as any).requiresFinalAssistantBeforeIdle === true,
1399
+ allowTimeout: allowMissingAssistantTimeout,
1400
+ };
1401
+ }
1402
+ }
1403
+
1404
+ // Guard: if the screen still shows an approval/choice prompt as the last visible text,
1405
+ // the turn is not complete even if the parsed status says idle and there is an assistant
1406
+ // message. This catches the case where waiting_approval→idle transitions occur before
1407
+ // the modal has been resolved (e.g. the PTY rendered the prompt but no button press fired).
1408
+ try {
1409
+ const screenText = typeof (this.adapter as any).getScreenText === 'function'
1410
+ ? String((this.adapter as any).getScreenText() || '')
1411
+ : '';
1412
+ if (screenText) {
1413
+ const tailLines = screenText.split(/\r?\n/).slice(-16).join('\n');
1414
+ if (looksLikeActiveApprovalPromptText(tailLines)) {
1415
+ return { reason: 'screen_shows_approval_prompt', terminal: approvalResolvedIdle };
1416
+ }
1417
+ }
1418
+ } catch { /* defensive: screen text read is best-effort */ }
794
1419
 
795
1420
  return null;
796
1421
  }
@@ -800,6 +1425,26 @@ export class CliProviderInstance implements ProviderInstance {
800
1425
  this.completedDebounceTimer = setTimeout(() => this.flushCompletedDebounceIfFinalized(), delayMs);
801
1426
  }
802
1427
 
1428
+ // EVTTRACE (observation-only): is this a mesh worker session whose completion
1429
+ // events must route to a coordinator? Used purely to gate trace logging so a
1430
+ // non-mesh CLI session's completions don't add EvtTrace noise. No decision logic.
1431
+ private isMeshWorkerSession(): boolean {
1432
+ return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId
1433
+ || this.settings.meshNodeId || this.settings.launchedByCoordinator);
1434
+ }
1435
+
1436
+ // EVTTRACE correlation context for this session's completion lifecycle. taskId is
1437
+ // the primary grep anchor; instanceId is the session fallback.
1438
+ private meshTraceCtx(event = 'agent:generating_completed'): Record<string, unknown> {
1439
+ return {
1440
+ taskId: this.settings.meshActiveTaskId,
1441
+ sessionId: this.instanceId,
1442
+ nodeId: this.settings.meshNodeId,
1443
+ meshId: this.settings.meshNodeFor,
1444
+ event,
1445
+ };
1446
+ }
1447
+
803
1448
  private flushCompletedDebounceIfFinalized(): void {
804
1449
  const pending = this.completedDebouncePending;
805
1450
  if (!pending) {
@@ -809,7 +1454,8 @@ export class CliProviderInstance implements ProviderInstance {
809
1454
 
810
1455
  const latestStatus = this.adapter.getStatus({ allowParse: false });
811
1456
  const latestAutoApproveActive = latestStatus.status === 'waiting_approval' && this.shouldAutoApprove();
812
- const latestVisibleStatus = latestAutoApproveActive ? 'generating' : latestStatus.status;
1457
+ const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? 'generating' : latestStatus.status;
1458
+ 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
1459
  if (latestVisibleStatus !== 'idle') {
814
1460
  LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
815
1461
  this.completedDebouncePending = null;
@@ -817,84 +1463,350 @@ export class CliProviderInstance implements ProviderInstance {
817
1463
  return;
818
1464
  }
819
1465
 
820
- const blockReason = this.getCompletedFinalizationBlockReason(latestVisibleStatus);
821
- if (blockReason) {
1466
+ const block = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
1467
+ if (block) {
1468
+ const blockReason = block.reason;
822
1469
  const waitedMs = Date.now() - pending.firstObservedAt;
823
- if (waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
1470
+ // CANON-C (completion-gate decouple): a block carrying `allowTimeout` is the
1471
+ // transcript-evidence gate — the worker FSM has ALREADY reached idle and the only
1472
+ // thing missing is the append-only transcript's final assistant turn (a native-source
1473
+ // race: claude-cli owns its history externally and the file write trails the idle
1474
+ // transition). `allowTimeout` is set ONLY on the missing_final_assistant block, and
1475
+ // ONLY for mesh worker sessions (meshNodeFor / meshActiveTaskId / launchedByCoordinator).
1476
+ // The coordinator's sole path to learn this session is idle is agent:generating_completed,
1477
+ // so holding it up to COMPLETED_FINALIZATION_MAX_WAIT_MS (30s) leaves the coordinator
1478
+ // false-generating while the worker is done. Decouple the idle NOTIFICATION from the
1479
+ // transcript evidence: emit the completion immediately, marked weak
1480
+ // (completionDiagnostic.blockReason=missing_final_assistant, finalAssistantPresent=false).
1481
+ // The finalSummary is enriched on a SEPARATE path — the mesh reconcile loop reads the
1482
+ // transcript once written and re-emits a GENUINE completion (CANON-B weak→genuine
1483
+ // upgrade; buildPendingEventFingerprint keeps weak and genuine distinct so the enriched
1484
+ // one still surfaces, and isFalseIdleCompletion keeps the direct dispatch active until
1485
+ // then). All OTHER blocks (genuinely-busy adapter/partial/parsed states, transient
1486
+ // parse_error) keep the existing terminal-hold / 30s-retry behavior unchanged.
1487
+ const isTranscriptEvidenceGate = block.allowTimeout === true;
1488
+ LOG.debug('CLI', `[${this.type}] finalization block: reason=${blockReason} terminal=${block.terminal} allowTimeout=${isTranscriptEvidenceGate} waitedMs=${waitedMs} maxWait=${COMPLETED_FINALIZATION_MAX_WAIT_MS}`);
1489
+ if (!isTranscriptEvidenceGate && (block.terminal || waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS)) {
824
1490
  if (pending.loggedBlockReason !== blockReason) {
825
1491
  LOG.info('CLI', `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
1492
+ // EVTTRACE: completion held by the finalization gate (CANON-C). Observation
1493
+ // only — does not change the hold decision above.
1494
+ if (this.isMeshWorkerSession()) {
1495
+ traceMeshEventDrop('completion_gate_hold', this.meshTraceCtx(), `${blockReason} waited=${waitedMs}ms`);
1496
+ }
826
1497
  pending.loggedBlockReason = blockReason;
827
1498
  }
828
1499
  this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
829
1500
  return;
830
1501
  }
831
- LOG.warn('CLI', `[${this.type}] suppressed completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
1502
+ const emittedAfterFinalizationTimeout = waitedMs >= COMPLETED_FINALIZATION_MAX_WAIT_MS;
1503
+ const completionDiagnostic = this.buildCompletedFinalizationDiagnostic({
1504
+ blockReason,
1505
+ latestStatus,
1506
+ latestVisibleStatus,
1507
+ waitedMs,
1508
+ pending,
1509
+ emittedAfterFinalizationTimeout,
1510
+ });
1511
+ // Surface the CANON-C immediate-emit path distinctly so a delegated worker's idle
1512
+ // notification (transcript still pending) is not mistaken for a 30s-timeout fallback.
1513
+ (completionDiagnostic as Record<string, unknown>).decoupledImmediateEmit = isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout;
1514
+ LOG.warn('CLI', `[${this.type}] emitting completed event (${isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout ? 'CANON-C decoupled-immediate, transcript pending' : `after ${waitedMs}ms`}) without finalized assistant turn (${blockReason})`);
1515
+ // EVTTRACE: completion fired (forced past the finalization timeout / CANON-C decoupled-immediate).
1516
+ if (this.isMeshWorkerSession()) {
1517
+ traceMeshEventStage('fired', this.meshTraceCtx(), `forced after ${waitedMs}ms (${blockReason})`);
1518
+ }
1519
+ this.pushEvent({
1520
+ event: 'agent:generating_completed',
1521
+ chatTitle: pending.chatTitle,
1522
+ duration: pending.duration,
1523
+ timestamp: pending.timestamp,
1524
+ // When finalization is forced past the timeout on a `parsed_status:` block
1525
+ // (the parser never confirmed a final assistant turn) we previously rode an
1526
+ // empty `finalSummary` unconditionally. That empty value propagates to the
1527
+ // mesh coordinator's mirror preview (meshSessionLastMessagePreview), leaving a
1528
+ // delegated session's inbox preview blank — or, for a LOCAL worktree session,
1529
+ // stuck on the dispatched user task. If the parser DID surface assistant text,
1530
+ // prefer it; only fall back to '' when no assistant summary can be derived.
1531
+ finalSummary: blockReason.startsWith('parsed_status:')
1532
+ ? (this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages) ?? '')
1533
+ : this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
1534
+ completionDiagnostic,
1535
+ });
832
1536
  this.completedDebouncePending = null;
833
1537
  this.completedDebounceTimer = null;
834
1538
  this.generatingStartedAt = 0;
1539
+ this.lastApprovalEventFingerprint = '';
835
1540
  return;
836
1541
  }
837
1542
 
838
1543
  LOG.info('CLI', `[${this.type}] completed in ${pending.duration}s`);
1544
+ // EVTTRACE: completion fired (transcript finalized cleanly).
1545
+ if (this.isMeshWorkerSession()) {
1546
+ traceMeshEventStage('fired', this.meshTraceCtx(), `duration=${pending.duration}s`);
1547
+ }
839
1548
  this.pushEvent({
840
1549
  event: 'agent:generating_completed',
841
1550
  chatTitle: pending.chatTitle,
842
1551
  duration: pending.duration,
843
1552
  timestamp: pending.timestamp,
844
- finalSummary: extractFinalSummaryFromMessages(this.adapter?.getScriptParsedStatus()?.messages),
1553
+ finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
845
1554
  });
846
1555
  this.completedDebouncePending = null;
847
1556
  this.completedDebounceTimer = null;
848
1557
  this.generatingStartedAt = 0;
1558
+ this.lastApprovalEventFingerprint = '';
849
1559
  }
850
1560
 
851
1561
  private maybeAutoApproveStatus(adapterStatus: any, now = Date.now()): boolean {
1562
+ // Manual-attendance suppression (provider-common): when a human is
1563
+ // actively driving this session from the dashboard, hold auto-approve so
1564
+ // the modal stays visible and they can pick a button / use the controlbar
1565
+ // themselves. Return false (NOT auto-approving) so getState keeps the
1566
+ // modal surfaced. Clear any in-progress settle gate — a genuine fire
1567
+ // after the window lapses must re-settle from scratch — and arm a
1568
+ // re-check for the lapse moment, because the PTY may have gone silent and
1569
+ // would otherwise never re-drive this decision. Background mesh workers
1570
+ // are never attended, so their delegated auto-approve is untouched.
1571
+ if (adapterStatus?.status === 'waiting_approval'
1572
+ && this.shouldAutoApprove()
1573
+ && this.manualAttendance.isAttended(now)) {
1574
+ this.lastAutoApprovalSignature = '';
1575
+ this.pendingAutoApprovalSignature = '';
1576
+ this.pendingAutoApprovalSince = 0;
1577
+ this.autoApproveInactiveSince = 0;
1578
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1579
+ this.autoApproveSettleTimer = setTimeout(() => {
1580
+ this.autoApproveSettleTimer = null;
1581
+ this.recheckAutoApproveSettled();
1582
+ }, this.manualAttendance.remainingMs(now) + 20);
1583
+ return false;
1584
+ }
852
1585
  const autoApproveActive = adapterStatus?.status === 'waiting_approval' && this.shouldAutoApprove();
853
1586
  // Guard re-entry: onStatusChange/getState can observe the same modal multiple
854
1587
  // times while the PTY absorbs the approval key. Without this flag, repeated
855
1588
  // 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);
1589
+ // However, Claude Code can present a second approval immediately after the
1590
+ // first. Resolve a changed modal signature even while the previous write is
1591
+ // still inside the short busy window.
1592
+ if (!autoApproveActive) {
1593
+ this.lastAutoApprovalSignature = '';
1594
+ // Hysteresis: if a settle gate is mid-progress, a momentary
1595
+ // status!=waiting_approval blip (a generating flip while the same
1596
+ // modal's button block is still on screen) must NOT wipe the settle
1597
+ // clock otherwise the modal→generating→modal flap restarts the
1598
+ // 600ms window every time and auto-approve never fires. Keep the
1599
+ // gate warm for AUTO_APPROVE_GATE_HYSTERESIS_MS; re-arm a timer so
1600
+ // that if the modal does NOT come back the gate is cleared on the
1601
+ // re-check (a genuine resolution → idle frees the gate normally).
1602
+ if (this.pendingAutoApprovalSince) {
1603
+ if (!this.autoApproveInactiveSince) this.autoApproveInactiveSince = now;
1604
+ const goneForMs = now - this.autoApproveInactiveSince;
1605
+ if (goneForMs < CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS) {
1606
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1607
+ this.autoApproveSettleTimer = setTimeout(() => {
1608
+ this.autoApproveSettleTimer = null;
1609
+ this.recheckAutoApproveSettled();
1610
+ }, CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS - goneForMs + 20);
1611
+ return autoApproveActive;
1612
+ }
1613
+ }
1614
+ // Clear the settle gate so the next approval starts its own quiet
1615
+ // window from scratch (a stale timestamp would let it fire instantly).
1616
+ this.pendingAutoApprovalSignature = '';
1617
+ this.pendingAutoApprovalSince = 0;
1618
+ this.autoApproveInactiveSince = 0;
1619
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1620
+ return autoApproveActive;
1621
+ }
1622
+ // Active approval observed — reset the inactivity tracker so a later
1623
+ // blip starts its hysteresis window fresh.
1624
+ this.autoApproveInactiveSince = 0;
1625
+ const modal = adapterStatus.activeModal;
1626
+ // (fix) Do not auto-approve when no concrete modal/buttons are present.
1627
+ // Claude TUI flaps between paints; without this guard adapterStatus
1628
+ // could report status=waiting_approval with activeModal=null (or with
1629
+ // an empty buttons array briefly) and we'd still call
1630
+ // resolveModal(-1) — which used to type "1" into the prompt
1631
+ // repeatedly. Skip until a real modal is captured.
1632
+ const buttons = Array.isArray(modal?.buttons)
1633
+ ? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
1634
+ : [];
1635
+ if (!modal || buttons.length === 0) {
1636
+ return autoApproveActive;
1637
+ }
1638
+ // Picker/confirm exclusion (provider-common). A /model or /mode picker is
1639
+ // surfaced with status=waiting_approval so the dashboard shows it, but it
1640
+ // has no "correct" answer to auto-pick — blindly selecting the first
1641
+ // option silently switches the model (the "always Opus, before I even
1642
+ // choose" bug). Two independent gates, BOTH must pass to fire:
1643
+ //
1644
+ // (1) modal_kind — the spec/FSM tells us this is an 'approval' modal,
1645
+ // not a 'picker'/'confirm'. A modal whose kind is unknown (legacy
1646
+ // adapter, or a spec that predates modal_kind) reads as 'approval'
1647
+ // so genuine approvals keep auto-approving; only an explicit
1648
+ // 'picker'/'confirm' is excluded here.
1649
+ // (2) structural anchor — a real approval offers an affirmative AND a
1650
+ // decline option (pickApprovalButton finds a positive that isn't a
1651
+ // decline, and hasNegativeApprovalOption confirms a No/Cancel/Deny
1652
+ // is present). A model picker ("1. Default 2. Opus 3. Sonnet")
1653
+ // has no decline, so even an un-migrated picker is caught here.
1654
+ //
1655
+ // Mirrors the SDK v1 detect-status approval heuristic (detect-status.ts).
1656
+ const modalKind = typeof modal?.kind === 'string' ? modal.kind : 'approval';
1657
+ if (modalKind !== 'approval') {
1658
+ // Picker/confirm — leave it for the user; keep the modal surfaced.
1659
+ return autoApproveActive;
869
1660
  }
1661
+ const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(buttons, this.provider);
1662
+ if (buttonIndex < 0 || !hasNegativeApprovalOption(buttons)) {
1663
+ // No affirmative matched, or no decline option present (→ not a real
1664
+ // consent prompt, e.g. a picker that slipped past the kind gate).
1665
+ // Surface the modal so the user decides; never pick blindly.
1666
+ return autoApproveActive;
1667
+ }
1668
+ // Modal *identity* signature — the question/button set only, NO volatile
1669
+ // counters. This is what the settle gate tracks: the FSM bumps
1670
+ // approvalEntrySeq on every fresh waiting_approval entry, and a
1671
+ // modal→generating→modal flap (the question line scrolled out of the
1672
+ // captured frame while the button block stays) re-enters and bumps it
1673
+ // again. Folding that seq into the settle signature made the 600ms
1674
+ // settle clock restart on every flap, so the modal never stayed stable
1675
+ // long enough to fire — the gate was never satisfied. Identity excludes
1676
+ // the seq so button/seq flap of the SAME modal keeps one settle clock.
1677
+ const modalSignature = [
1678
+ typeof modal?.message === 'string' ? modal.message.trim() : '',
1679
+ buttons.join('|'),
1680
+ buttonIndex,
1681
+ ].join('::');
1682
+ // Busy-window re-entry guard still needs the seq: two DISTINCT
1683
+ // back-to-back approvals can carry identical message/buttons (common
1684
+ // with claude-cli). Without the seq their busy signatures collide and
1685
+ // the 5s busy-window guard below would swallow the second auto-approve,
1686
+ // leaving it stuck. The seq is bumped by the FSM on every fresh
1687
+ // waiting_approval entry, so a new approval always yields a new busy
1688
+ // signature and fires through.
1689
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
1690
+ ? adapterStatus.approvalEntrySeq
1691
+ : 0;
1692
+ const busySignature = `${approvalEntrySeq}::${modalSignature}`;
1693
+ // Already fired for this exact modal entry and still inside the busy
1694
+ // window — nothing to do (re-entry guard for repeated snapshots of one
1695
+ // modal).
1696
+ if (this.autoApproveBusy && busySignature === this.lastAutoApprovalSignature) {
1697
+ return autoApproveActive;
1698
+ }
1699
+
1700
+ // Settle gate: only fire once this modal identity has been stable for
1701
+ // AUTO_APPROVE_SETTLE_MS. A still-streaming prompt mutates its
1702
+ // message/buttons each frame → new identity → clock restarts, so we
1703
+ // never approve a half-rendered prompt (the "resolves too fast" bug).
1704
+ if (modalSignature !== this.pendingAutoApprovalSignature) {
1705
+ this.pendingAutoApprovalSignature = modalSignature;
1706
+ this.pendingAutoApprovalSince = now;
1707
+ }
1708
+ const settledForMs = now - this.pendingAutoApprovalSince;
1709
+ if (settledForMs < CliProviderInstance.AUTO_APPROVE_SETTLE_MS) {
1710
+ // Not yet settled. Arm a timer to re-check after the remaining quiet
1711
+ // window — the PTY may go silent once the prompt finishes painting,
1712
+ // so there is no guaranteed status-change frame to re-drive us.
1713
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1714
+ this.autoApproveSettleTimer = setTimeout(() => {
1715
+ this.autoApproveSettleTimer = null;
1716
+ this.recheckAutoApproveSettled();
1717
+ }, CliProviderInstance.AUTO_APPROVE_SETTLE_MS - settledForMs + 20);
1718
+ return autoApproveActive;
1719
+ }
1720
+
1721
+ // Settled — fire the approve key.
1722
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1723
+ this.autoApproveBusy = true;
1724
+ this.lastAutoApprovalSignature = busySignature;
1725
+ this.pendingAutoApprovalSignature = '';
1726
+ this.pendingAutoApprovalSince = 0;
1727
+ this.autoApproveInactiveSince = 0;
1728
+ if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
1729
+ this.autoApproveBusyTimer = setTimeout(() => {
1730
+ this.autoApproveBusy = false;
1731
+ this.autoApproveBusyTimer = null;
1732
+ this.lastAutoApprovalSignature = '';
1733
+ }, 5000);
1734
+ this.recordAutoApproval(modal?.message, buttonLabel, now);
1735
+ setTimeout(() => {
1736
+ this.adapter.resolveModal(buttonIndex);
1737
+ }, 0);
870
1738
  return autoApproveActive;
871
1739
  }
872
1740
 
1741
+ /**
1742
+ * Re-drive the auto-approve check after the settle quiet window elapses.
1743
+ * The PTY may have gone silent once the approval prompt finished painting,
1744
+ * so no status-change frame is guaranteed to re-enter maybeAutoApproveStatus
1745
+ * — this timer-driven re-check picks up the now-settled modal and fires.
1746
+ * Deliberately lighter than detectStatusTransition(): it only re-evaluates
1747
+ * the approval decision; the next real PTY frame refreshes visible status.
1748
+ */
1749
+ private recheckAutoApproveSettled(): void {
1750
+ try {
1751
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1752
+ this.maybeAutoApproveStatus(adapterStatus, Date.now());
1753
+ } catch { /* adapter gone / transient — next frame retries */ }
1754
+ }
1755
+
873
1756
  private detectStatusTransition(): void {
874
1757
  const now = Date.now();
875
1758
  // Status-change handling is a hot path: PTY output can fire it many times
876
1759
  // during long-running CLI sessions. Keep this path on adapter-owned light
877
1760
  // state only; rich provider parsing is reserved for getState/read_chat.
878
1761
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
1762
+ const adapterProviderSessionId = normalizeProviderSessionId(
1763
+ this.provider,
1764
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
1765
+ );
1766
+ if (adapterProviderSessionId) {
1767
+ this.promoteProviderSessionId(adapterProviderSessionId);
1768
+ }
879
1769
  const parsedStatus = null;
880
1770
  const rawStatus = adapterStatus.status;
881
1771
  const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
882
- const newStatus = autoApproveActive ? 'generating' : rawStatus;
883
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
1772
+ // During the autoApproveBusy window (2s after firing approval key), the PTY
1773
+ // can briefly report 'idle' before the next generating phase starts. Treat that
1774
+ // transient idle as 'generating' to suppress a spurious agent:generating_completed
1775
+ // push notification. The adapter's status is otherwise authoritative — native
1776
+ // transcript shape does NOT override the FSM's busy/idle decision.
1777
+ const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === 'idle';
1778
+ const newStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : rawStatus;
1779
+ const dirName = workingDirBasename(this.workingDir);
884
1780
  const chatTitle = `${this.provider.name} · ${dirName}`;
885
1781
  const partial = this.adapter.getPartialResponse();
1782
+ // Liveness fingerprint for the no-progress watchdog. The parsed
1783
+ // assistant buffer (`partial`) alone goes static while a tool/build runs
1784
+ // — the assistant emits no tokens even though the PTY is actively
1785
+ // printing tool output — which made the watchdog false-fire a "stuck"
1786
+ // alert mid-turn. Fold in the adapter's raw-activity timestamps so any
1787
+ // visible terminal progress (lastScreenChangeAt) or raw PTY byte
1788
+ // (lastOutputAt) keeps the fingerprint moving. The watchdog then only
1789
+ // survives a genuine stall where nothing at all is happening.
886
1790
  const progressFingerprint = newStatus === 'generating'
887
- ? `${partial || ''}`.slice(-2000)
1791
+ ? `${`${partial || ''}`.slice(-2000)}::scr=${adapterStatus.lastScreenChangeAt ?? 0}::out=${adapterStatus.lastOutputAt ?? 0}`
888
1792
  : undefined;
889
1793
 
890
1794
  const previousStatus = this.lastStatus;
891
1795
  if (newStatus !== this.lastStatus) {
892
1796
  LOG.info('CLI', `[${this.type}] status: ${this.lastStatus} → ${newStatus}`);
893
1797
  if (this.lastStatus === 'idle' && newStatus === 'generating') {
1798
+ // If a completion event is already pending and the turn has ended
1799
+ // (generatingStartedAt===0), the PTY is painting its prompt area
1800
+ // after completing. Ignore this blip — do not cancel the pending
1801
+ // completion and do not advance lastStatus to generating.
1802
+ if (this.completedDebouncePending && this.generatingStartedAt === 0) {
1803
+ LOG.debug('CLI', `[${this.type}] ignoring post-completion PTY generating blip (generatingStartedAt=0)`);
1804
+ return;
1805
+ }
894
1806
  this.suppressIdleHistoryReplay = false;
895
1807
  // Cancel any pending completed event (multi-step: idle→generating resume)
896
1808
  if (this.completedDebouncePending) {
897
- LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating)`);
1809
+ LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating) generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse}`);
898
1810
  if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
899
1811
  this.completedDebouncePending = null;
900
1812
  }
@@ -926,10 +1838,29 @@ export class CliProviderInstance implements ProviderInstance {
926
1838
  if (!this.generatingStartedAt) this.generatingStartedAt = now;
927
1839
  const modal = adapterStatus.activeModal;
928
1840
  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;
1841
+ // Include the FSM's approval entry seq, mirroring the auto-approve
1842
+ // path (maybeAutoApproveStatus) and resolveModal's sameEntryReResolve
1843
+ // guard. Two distinct back-to-back approvals can carry identical
1844
+ // message/buttons (very common with claude-cli's "Allow Bash
1845
+ // command?"). Without the seq their fingerprints collide and the dedup
1846
+ // below silently drops the second waiting_approval event — it is never
1847
+ // emitted, so it cannot even land in the pending inbox for a later
1848
+ // read_chat reconcile to recover. The seq is bumped by the FSM on every
1849
+ // fresh waiting_approval entry, so a new approval always yields a new
1850
+ // fingerprint and emits.
1851
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
1852
+ ? adapterStatus.approvalEntrySeq
1853
+ : 0;
1854
+ const approvalFingerprint = JSON.stringify({
1855
+ message: typeof modal?.message === 'string' ? modal.message.trim() : '',
1856
+ buttons: Array.isArray(modal?.buttons) ? modal.buttons.map((button: unknown) => String(button).trim()) : [],
1857
+ seq: approvalEntrySeq,
1858
+ });
1859
+ // PTY redraws repeat the same modal content; fingerprint dedup prevents duplicate events.
1860
+ // Do NOT also gate on lastStatus: consecutive approvals can arrive waiting_approval→waiting_approval
1861
+ // (e.g. antigravity-cli resolves one prompt and immediately shows the next) and would be silently dropped.
1862
+ if (approvalFingerprint !== this.lastApprovalEventFingerprint) {
1863
+ this.lastApprovalEventFingerprint = approvalFingerprint;
933
1864
  this.appendRuntimeSystemMessage(
934
1865
  this.formatApprovalRequestMessage(modal?.message, modal?.buttons),
935
1866
  `approval_request:${now}`,
@@ -941,22 +1872,118 @@ export class CliProviderInstance implements ProviderInstance {
941
1872
  modalButtons: modal?.buttons,
942
1873
  });
943
1874
  }
1875
+ } else if (newStatus === 'generating' && this.lastStatus === 'waiting_approval') {
1876
+ // Approval resolved and the agent resumed work. Defense-in-depth:
1877
+ // clear the approval emit fingerprint here too (not only on
1878
+ // completion at scheduleCompletedDebounceFlush). A subsequent
1879
+ // waiting_approval with the same modal content as the one just
1880
+ // resolved would otherwise collide with the stale fingerprint and be
1881
+ // dropped. The seq in the fingerprint already separates entries; this
1882
+ // reset is a belt-and-suspenders guard for the re-entry case.
1883
+ this.lastApprovalEventFingerprint = '';
944
1884
  } else if (newStatus === 'idle' && (this.lastStatus === 'generating' || this.lastStatus === 'waiting_approval')) {
945
1885
  const duration = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : 0;
946
- // If debounce still pending (generating lasted < 1s), cancel both events
1886
+ // Guard: if generatingStartedAt===0 and no debounce pending, the generating phase
1887
+ // was entered from 'starting' state (startup PTY noise), not from a real idle→generating
1888
+ // task dispatch. The idle→generating handler is the only code path that sets
1889
+ // generatingStartedAt and generatingDebouncePending, so both being absent means no
1890
+ // task was ever dispatched. Suppress the spurious completion event and fall through
1891
+ // to a simple lastStatus update.
1892
+ if (!this.generatingStartedAt && !this.generatingDebouncePending) {
1893
+ LOG.debug('CLI', `[${this.type}] suppressed startup-phase generating→idle blip (generatingStartedAt=0, no debounce pending)`);
1894
+ } else
1895
+ // If debounce still pending (generating lasted < 1s), cancel both UI events.
1896
+ // Still emit agent:generating_completed so mesh orchestration can record
1897
+ // task_completed for direct dispatches that complete faster than the debounce.
947
1898
  if (this.generatingDebouncePending) {
948
- LOG.info('CLI', `[${this.type}] suppressed short generating (${now - this.generatingStartedAt}ms)`);
1899
+ const shortDurationMs = this.generatingStartedAt ? now - this.generatingStartedAt : 0;
1900
+ LOG.info('CLI', `[${this.type}] suppressed short generating (${shortDurationMs}ms)`);
949
1901
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
1902
+ // Emit completion for mesh task association even though the UI generating
1903
+ // started/completed pair is suppressed (too short for visible UI update).
1904
+ let shortFinalSummary: string | undefined;
1905
+ let shortEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
1906
+ try {
1907
+ const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
1908
+ const evidence = this.completionFinalAssistantEvidence(parsedMessages);
1909
+ shortEvidenceSource = evidence.source;
1910
+ shortFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
1911
+ } catch { /* best-effort */ }
1912
+ // If a real response is confirmed, retroactively emit started so the chat
1913
+ // bubble appears even though the debounce suppressed the original event.
1914
+ if (shortFinalSummary) {
1915
+ this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now - shortDurationMs });
1916
+ }
950
1917
  this.generatingDebouncePending = null;
951
1918
  this.generatingStartedAt = 0;
1919
+ const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === 'external-native') && !shortFinalSummary;
1920
+ if (missingEvidence) {
1921
+ LOG.warn('CLI', `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
1922
+ }
1923
+ // When evidence is missing and there is no active mesh task context, suppress
1924
+ // the completion event. Providers with requiresFinalAssistantBeforeIdle or
1925
+ // external-native history must confirm a final assistant message before the
1926
+ // coordinator records task_completed. Only emit here if a mesh task is active
1927
+ // so the coordinator can apply its own timeout/retry logic.
1928
+ const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1929
+ if (missingEvidence && !hasMeshContext) {
1930
+ LOG.info('CLI', `[${this.type}] short completion suppressed: missing final assistant evidence, no mesh context (source=${shortEvidenceSource})`);
1931
+ // completedDebouncePending intentionally left null — the session is now idle
1932
+ // with no confirmed turn, matching the startup-blip suppression semantics.
1933
+ // (No EvtTrace: not a mesh session, so nothing routes to a coordinator.)
1934
+ } else {
1935
+ // EVTTRACE: completion fired (short-generating idle path).
1936
+ if (this.isMeshWorkerSession()) {
1937
+ traceMeshEventStage('fired', this.meshTraceCtx(), `short-generating idle (source=${shortEvidenceSource})`);
1938
+ }
1939
+ this.pushEvent({
1940
+ event: 'agent:generating_completed',
1941
+ chatTitle,
1942
+ duration: 0,
1943
+ timestamp: now,
1944
+ finalSummary: shortFinalSummary,
1945
+ completionDiagnostic: {
1946
+ reason: 'short_generating_suppressed',
1947
+ shortDurationMs,
1948
+ finalAssistantEvidenceSource: shortEvidenceSource,
1949
+ ...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
1950
+ },
1951
+ });
1952
+ }
952
1953
  } else {
953
1954
  // Debounce completed, then require the rich transcript path that read_chat
954
1955
  // 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);
1956
+ this.completedDebouncePending = {
1957
+ chatTitle,
1958
+ duration,
1959
+ timestamp: now,
1960
+ firstObservedAt: now,
1961
+ previousStatus: this.lastStatus,
1962
+ };
1963
+ const ownsExternalHistory = !!(this.adapter as any)?.chatMessagesOwnedExternally;
1964
+ const flushDelay = ownsExternalHistory ? 0 : 3000;
1965
+ LOG.debug('CLI', `[${this.type}] set completedDebouncePending duration=${duration}s ownsExternalHistory=${ownsExternalHistory} flushDelay=${flushDelay}ms generatingStartedAt=${this.generatingStartedAt}`);
1966
+ this.scheduleCompletedDebounceFlush(flushDelay);
957
1967
  }
958
1968
  } else if (newStatus === 'idle' && this.lastStatus === 'starting') {
959
1969
  this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
1970
+ } else if (newStatus === 'error') {
1971
+ if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
1972
+ this.generatingDebouncePending = null;
1973
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
1974
+ this.completedDebouncePending = null;
1975
+ this.errorMessage = adapterStatus.errorMessage || this.errorMessage;
1976
+ this.errorReason = (adapterStatus.errorReason as ProviderErrorReason) || this.errorReason;
1977
+ this.pushEvent({
1978
+ event: 'agent:stopped',
1979
+ chatTitle,
1980
+ timestamp: now,
1981
+ finalSummary: adapterStatus.errorMessage || adapterStatus.errorReason || 'Provider reported an error',
1982
+ completionDiagnostic: {
1983
+ reason: adapterStatus.errorReason || 'provider_error',
1984
+ errorMessage: adapterStatus.errorMessage || undefined,
1985
+ },
1986
+ });
960
1987
  } else if (newStatus === 'stopped') {
961
1988
  // Cancel any pending debounce
962
1989
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
@@ -976,8 +2003,43 @@ export class CliProviderInstance implements ProviderInstance {
976
2003
 
977
2004
  // Monitor check (cooldown based notification, IDE/CLI common)
978
2005
  const agentKey = `${this.type}:cli`;
979
- const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint);
2006
+ // Approval pending is detected from the raw adapter status, not `newStatus`:
2007
+ // auto-approve synthesizes `waiting_approval` → 'generating', which would
2008
+ // otherwise let the no-progress watchdog accumulate the approval wait.
2009
+ const approvalPending = rawStatus === 'waiting_approval';
2010
+ const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint, approvalPending);
2011
+ const monitorParsedStatus: any = parsedStatus;
980
2012
  for (const me of monitorEvents) {
2013
+ if (
2014
+ me.type === 'monitor:no_progress'
2015
+ && this.completionHasFinalAssistantMessage(monitorParsedStatus?.messages)
2016
+ && !this.hasAdapterPendingResponse()
2017
+ && !hasNonEmptyCliModalButtons(monitorParsedStatus?.activeModal ?? monitorParsedStatus?.modal)
2018
+ ) {
2019
+ // EVTTRACE: completion fired (no-progress monitor reconciled to completion).
2020
+ if (this.isMeshWorkerSession()) {
2021
+ traceMeshEventStage('fired', this.meshTraceCtx(), 'no_progress_monitor_final_summary');
2022
+ }
2023
+ this.pushEvent({
2024
+ event: 'agent:generating_completed',
2025
+ chatTitle,
2026
+ duration: this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : undefined,
2027
+ timestamp: me.timestamp,
2028
+ finalSummary: extractFinalSummaryFromMessages(monitorParsedStatus?.messages),
2029
+ completionDiagnostic: {
2030
+ providerType: this.type,
2031
+ sessionId: this.instanceId,
2032
+ providerSessionId: this.providerSessionId || null,
2033
+ reconciliationReason: 'no_progress_monitor_final_summary',
2034
+ finalAssistantPresent: true,
2035
+ },
2036
+ });
2037
+ this.generatingStartedAt = 0;
2038
+ // Cancel any pending debounce flush — monitor already fired completion.
2039
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
2040
+ this.completedDebouncePending = null;
2041
+ continue;
2042
+ }
981
2043
  this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
982
2044
  }
983
2045
  }
@@ -997,15 +2059,49 @@ export class CliProviderInstance implements ProviderInstance {
997
2059
  workspaceName: typeof event.workspaceName === 'string' && event.workspaceName.trim()
998
2060
  ? event.workspaceName
999
2061
  : this.workingDir,
2062
+ // Carry the workspace under BOTH `workspace` and `workspaceName` so the
2063
+ // downstream mesh forward/merge path — which reads `workspace` — can
2064
+ // propagate it to the coordinator snapshot. Without `workspace` the live
2065
+ // event path delivers an empty workspace and the dashboard falls back to
2066
+ // the generic "Terminal (Mesh Node)" title.
2067
+ workspace: typeof event.workspace === 'string' && event.workspace.trim()
2068
+ ? event.workspace
2069
+ : this.workingDir,
1000
2070
  providerSessionId: typeof event.providerSessionId === 'string' && event.providerSessionId.trim()
1001
2071
  ? event.providerSessionId
1002
2072
  : this.providerSessionId,
1003
2073
  };
2074
+ // TASKIDLESS: stamp the mesh task primary key on lifecycle events emitted by
2075
+ // a mesh worker session. The consumer (updateDirectDispatchStatus) was switched
2076
+ // to key on task_id (CANON-B), but the producer never carried it — so every
2077
+ // forwarded metadataEvent.taskId arrived undefined and the coordinator fell back
2078
+ // to a session_id match, which can flip a sibling dispatch row. The session
2079
+ // already knows its own taskId via attachMeshAssignment (settings.meshActiveTaskId);
2080
+ // surface it here so updateDirectDispatchStatus hits the exact PK row and the
2081
+ // session_id fallback is never exercised. Non-mesh sessions get no taskId
2082
+ // (regression guard) — isMeshWorkerSession() gates the injection.
2083
+ if (this.isMeshWorkerSession() && this.settings.meshActiveTaskId) {
2084
+ const existingTaskId = typeof enrichedEvent.taskId === 'string' && enrichedEvent.taskId.trim()
2085
+ ? enrichedEvent.taskId
2086
+ : undefined;
2087
+ if (!existingTaskId) {
2088
+ enrichedEvent.taskId = this.settings.meshActiveTaskId;
2089
+ }
2090
+ }
1004
2091
  if (this.context?.emitProviderEvent) {
1005
2092
  this.context.emitProviderEvent(enrichedEvent);
1006
- return;
2093
+ } else {
2094
+ this.events.push(enrichedEvent);
2095
+ }
2096
+ // Auto-detach a direct-dispatch mesh assignment once the dispatched
2097
+ // task reaches a terminal state. Leaving meshNodeFor pinned would
2098
+ // route this session's next unrelated turn (a dashboard chat) into
2099
+ // the coordinator as if it were the completion of another task.
2100
+ // We schedule after the emit so the originating coordinator still
2101
+ // observes the completion event with its routing marker intact.
2102
+ if (TERMINAL_MESH_EVENTS.has(event.event) && this.settings.meshActiveTaskId) {
2103
+ try { this.detachMeshAssignment(); } catch { /* best-effort */ }
1007
2104
  }
1008
- this.events.push(enrichedEvent);
1009
2105
  }
1010
2106
 
1011
2107
  private flushEvents(): ProviderEvent[] {
@@ -1151,6 +2247,25 @@ export class CliProviderInstance implements ProviderInstance {
1151
2247
  return false;
1152
2248
  }
1153
2249
 
2250
+ /** @see ProviderInstance.noteManualInteraction */
2251
+ noteManualInteraction(now = Date.now()): void {
2252
+ this.manualAttendance.note(now);
2253
+ }
2254
+
2255
+ /**
2256
+ * Whether auto-approve should be treated as active *right now* for display
2257
+ * and firing decisions: the configured intent AND the user is not currently
2258
+ * attending this session by hand. When a human is attending, auto-approve is
2259
+ * held so the modal stays visible and they can drive it via the controlbar.
2260
+ * Provider-agnostic — the attendance signal is the command set, never any
2261
+ * CLI-specific modal text.
2262
+ */
2263
+ private autoApproveEffectivelyActive(status: string | undefined, now = Date.now()): boolean {
2264
+ return status === 'waiting_approval'
2265
+ && this.shouldAutoApprove()
2266
+ && !this.manualAttendance.isAttended(now);
2267
+ }
2268
+
1154
2269
  private recordAutoApproval(modalMessage?: string, buttonLabel?: string, now = Date.now()): void {
1155
2270
  this.appendRuntimeSystemMessage(
1156
2271
  formatAutoApprovalMessage(modalMessage, buttonLabel),
@@ -1238,7 +2353,7 @@ export class CliProviderInstance implements ProviderInstance {
1238
2353
  receivedAt: normalizedMessage.receivedAt || normalizedMessage.timestamp,
1239
2354
  historyDedupKey: dedupKey,
1240
2355
  }],
1241
- this.adapter.getScriptParsedStatus?.()?.title || this.workingDir.split('/').filter(Boolean).pop() || 'session',
2356
+ this.adapter.getScriptParsedStatus?.()?.title || workingDirBasename(this.workingDir),
1242
2357
  this.instanceId,
1243
2358
  this.providerSessionId,
1244
2359
  );
@@ -1258,12 +2373,28 @@ export class CliProviderInstance implements ProviderInstance {
1258
2373
  index,
1259
2374
  source: 'parsed',
1260
2375
  }));
2376
+ const getRole = (message: ChatMessage): string => typeof message.role === 'string'
2377
+ ? message.role.trim().toLowerCase()
2378
+ : '';
1261
2379
  const runtimeEntries: MergeEntry[] = this.runtimeMessages.map((entry, index) => ({
1262
2380
  message: entry.message,
1263
2381
  index: parsedMessages.length + index,
1264
- source: 'runtime',
2382
+ source: 'runtime' as const,
1265
2383
  runtimeKey: entry.key,
1266
- }));
2384
+ })).filter((entry) => {
2385
+ const meta = entry.message.meta && typeof entry.message.meta === 'object' && !Array.isArray(entry.message.meta)
2386
+ ? entry.message.meta as Record<string, unknown>
2387
+ : {};
2388
+ if (meta.runtimeInputAck !== true) return true;
2389
+ const runtimeText = flattenContent(entry.message.content).replace(/\s+/g, ' ').trim();
2390
+ if (!runtimeText) return false;
2391
+ return !parsedEntries.some((parsedEntry) => {
2392
+ const parsedRole = getRole(parsedEntry.message);
2393
+ if (parsedRole !== 'user' && parsedRole !== 'human') return false;
2394
+ const parsedText = flattenContent(parsedEntry.message.content).replace(/\s+/g, ' ').trim();
2395
+ return parsedText === runtimeText;
2396
+ });
2397
+ });
1267
2398
  const getTime = (message: ChatMessage): number => {
1268
2399
  const value = typeof message.receivedAt === 'number'
1269
2400
  ? message.receivedAt
@@ -1273,9 +2404,6 @@ export class CliProviderInstance implements ProviderInstance {
1273
2404
  return Number.isFinite(value) && value > 0 ? value : 0;
1274
2405
  };
1275
2406
 
1276
- const getRole = (message: ChatMessage): string => typeof message.role === 'string'
1277
- ? message.role.trim().toLowerCase()
1278
- : '';
1279
2407
  const isRuntimeOverlay = (entry: MergeEntry): boolean => {
1280
2408
  if (entry.source !== 'runtime') return false;
1281
2409
  const key = typeof entry.runtimeKey === 'string' ? entry.runtimeKey.trim().toLowerCase() : '';
@@ -1341,7 +2469,9 @@ export class CliProviderInstance implements ProviderInstance {
1341
2469
  this.providerSessionId = nextSessionId;
1342
2470
  this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
1343
2471
  this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
1344
- this.restorePersistedHistoryFromCurrentSession();
2472
+ if (this.shouldHydrateExistingProviderHistory()) {
2473
+ this.restorePersistedHistoryFromCurrentSession();
2474
+ }
1345
2475
  this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
1346
2476
  this.onProviderSessionResolved?.({
1347
2477
  instanceId: this.instanceId,
@@ -1354,13 +2484,39 @@ export class CliProviderInstance implements ProviderInstance {
1354
2484
  LOG.info('CLI', `[${this.type}] discovered provider session id: ${nextSessionId}`);
1355
2485
  }
1356
2486
 
1357
- private syncCanonicalSavedHistoryIfNeeded(): boolean {
2487
+ private shouldHydrateExistingProviderHistory(): boolean {
2488
+ return this.launchMode === 'resume' || this.launchMode === 'manual';
2489
+ }
2490
+
2491
+ private shouldSuppressFreshLaunchStartupReplay(parsedMessages: unknown[], parsedStatus: any, adapterStatus: any, parsedProviderSessionId = ''): boolean {
2492
+ if (this.launchMode !== 'new') return false;
2493
+ if (this.providerSessionId) return false;
2494
+ if (!Array.isArray(parsedMessages) || parsedMessages.length === 0) return false;
2495
+ if (!isIdleStatus(adapterStatus?.status) || !isIdleStatus(parsedStatus?.status)) return false;
2496
+ if (parsedProviderSessionId) return true;
2497
+
2498
+ const newestMessageAt = parsedMessages.reduce<number>((newest, message) => Math.max(newest, getMessageTime(message)), 0);
2499
+
2500
+ // Untimestamped idle parser output during a fresh launch is usually the
2501
+ // provider's last workspace transcript before a new turn exists.
2502
+ return newestMessageAt === 0;
2503
+ }
2504
+
2505
+ private syncCanonicalSavedHistoryIfNeeded(options: { full?: boolean } = {}): boolean {
1358
2506
  if (!this.providerSessionId) return false;
1359
- const canonicalHistory = this.provider.canonicalHistory;
2507
+ const canonicalHistory = this.provider.nativeHistory;
1360
2508
  if (!canonicalHistory) return false;
1361
2509
 
2510
+ // Per-status-report hydration reads only a bounded tail (snapshot needs at
2511
+ // most the newest 60). The once-per-resume restore path passes full:true
2512
+ // because seedSessionHistory needs the COMPLETE transcript to seed dedup
2513
+ // state. The read-cache key encodes the window so the bounded and full
2514
+ // reads don't share/clobber each other's 2s cache entry.
2515
+ const limit = options.full ? Number.MAX_SAFE_INTEGER : STATUS_HYDRATION_TAIL_LIMIT;
2516
+ const windowTag = options.full ? 'full' : `tail:${STATUS_HYDRATION_TAIL_LIMIT}`;
2517
+
1362
2518
  if (isNativeSourceCanonicalHistory(canonicalHistory)) {
1363
- const cacheKey = [this.type, this.providerSessionId, this.workingDir].join('\0');
2519
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, windowTag].join('\0');
1364
2520
  const now = Date.now();
1365
2521
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1366
2522
  return true;
@@ -1373,7 +2529,7 @@ export class CliProviderInstance implements ProviderInstance {
1373
2529
  historySessionId: this.providerSessionId,
1374
2530
  workspace: this.workingDir,
1375
2531
  offset: 0,
1376
- limit: Number.MAX_SAFE_INTEGER,
2532
+ limit,
1377
2533
  historyBehavior: this.provider.historyBehavior,
1378
2534
  scripts: this.provider.scripts as any,
1379
2535
  });
@@ -1390,7 +2546,7 @@ export class CliProviderInstance implements ProviderInstance {
1390
2546
  }
1391
2547
 
1392
2548
  try {
1393
- const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror'].join('\0');
2549
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror', windowTag].join('\0');
1394
2550
  const now = Date.now();
1395
2551
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1396
2552
  return true;
@@ -1401,7 +2557,14 @@ export class CliProviderInstance implements ProviderInstance {
1401
2557
  if (!materializeProviderNativeHistory(this.type, canonicalHistory, this.providerSessionId, this.workingDir, this.provider.scripts as any)) {
1402
2558
  return false;
1403
2559
  }
1404
- const restoredHistory = readChatHistory(this.type, 0, Number.MAX_SAFE_INTEGER, this.providerSessionId, 0, this.provider.historyBehavior);
2560
+ // Bounded by default: the per-status-report path only needs the newest
2561
+ // STATUS_HYDRATION_TAIL_LIMIT messages because the snapshot caps
2562
+ // activeChat.messages to the last 60 (status/normalize.ts) and loads
2563
+ // the rest lazily via read_chat on subscribe. The once-per-resume
2564
+ // restore path passes full:true so seedSessionHistory still sees the
2565
+ // COMPLETE transcript for prefix-dedup seeding. readChatHistory serves
2566
+ // a bounded limit as an O(tail) read.
2567
+ const restoredHistory = readChatHistory(this.type, 0, limit, this.providerSessionId, 0, this.provider.historyBehavior);
1405
2568
  this.lastPersistedHistoryMessages = restoredHistory.messages.map((message) => ({
1406
2569
  role: message.role,
1407
2570
  content: message.content,
@@ -1417,10 +2580,13 @@ export class CliProviderInstance implements ProviderInstance {
1417
2580
 
1418
2581
  private restorePersistedHistoryFromCurrentSession(): void {
1419
2582
  if (!this.providerSessionId) return;
1420
- this.syncCanonicalSavedHistoryIfNeeded();
1421
- const restoredHistory = isNativeSourceCanonicalHistory(this.provider.canonicalHistory)
2583
+ // Restore is the once-per-resume seeding path: it needs the COMPLETE
2584
+ // transcript so seedSessionHistory can prime dedup state. Pass full so the
2585
+ // hydration read is unbounded here (and only here).
2586
+ this.syncCanonicalSavedHistoryIfNeeded({ full: true });
2587
+ const restoredHistory = isNativeSourceCanonicalHistory(this.provider.nativeHistory)
1422
2588
  ? readProviderChatHistory(this.type, {
1423
- canonicalHistory: this.provider.canonicalHistory,
2589
+ canonicalHistory: this.provider.nativeHistory,
1424
2590
  historySessionId: this.providerSessionId,
1425
2591
  workspace: this.workingDir,
1426
2592
  offset: 0,