muonroi-cli 1.7.2 → 1.8.0

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 (322) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +122 -122
  3. package/dist/packages/agent-harness-core/src/event-filter.js +1 -0
  4. package/dist/packages/agent-harness-core/src/event-redact.js +8 -0
  5. package/dist/packages/agent-harness-core/src/mcp-server.d.ts +16 -0
  6. package/dist/packages/agent-harness-core/src/mcp-server.js +88 -10
  7. package/dist/packages/agent-harness-core/src/protocol.d.ts +15 -0
  8. package/dist/packages/agent-harness-core/src/selector.js +2 -2
  9. package/dist/packages/agent-harness-core/src/transports/sidechannel.js +1 -1
  10. package/dist/packages/agent-harness-opentui/src/agent-mode.js +1 -1
  11. package/dist/packages/agent-harness-opentui/src/install.js +1 -1
  12. package/dist/src/__test-stubs__/vitest-setup.js +4 -0
  13. package/dist/src/agent-harness/__tests__/mock-model.spec.js +54 -0
  14. package/dist/src/agent-harness/mock-model.d.ts +1 -1
  15. package/dist/src/agent-harness/mock-model.js +32 -3
  16. package/dist/src/agent-harness/test-spawn.js +3 -1
  17. package/dist/src/chat/chat-keychain.js +9 -1
  18. package/dist/src/cli/cost-forensics.js +12 -12
  19. package/dist/src/cli/keys.d.ts +2 -2
  20. package/dist/src/cli/keys.js +107 -28
  21. package/dist/src/cli/usage-report.js +2 -2
  22. package/dist/src/council/__tests__/abort-threading.test.d.ts +1 -0
  23. package/dist/src/council/__tests__/abort-threading.test.js +193 -0
  24. package/dist/src/council/__tests__/clarification-prompt.test.js +21 -1
  25. package/dist/src/council/__tests__/council-turn-length-emit.test.d.ts +1 -0
  26. package/dist/src/council/__tests__/council-turn-length-emit.test.js +130 -0
  27. package/dist/src/council/__tests__/debate-round-budget.test.d.ts +1 -0
  28. package/dist/src/council/__tests__/debate-round-budget.test.js +45 -0
  29. package/dist/src/council/__tests__/evaluator-metrics.test.js +3 -0
  30. package/dist/src/council/__tests__/post-debate-recommendation.test.d.ts +1 -0
  31. package/dist/src/council/__tests__/post-debate-recommendation.test.js +58 -0
  32. package/dist/src/council/__tests__/research-tools.test.js +4 -0
  33. package/dist/src/council/__tests__/round-tools.test.js +6 -0
  34. package/dist/src/council/clarifier-question-cap.test.d.ts +12 -0
  35. package/dist/src/council/clarifier-question-cap.test.js +73 -0
  36. package/dist/src/council/clarifier.d.ts +29 -1
  37. package/dist/src/council/clarifier.js +64 -1
  38. package/dist/src/council/debate-planner.d.ts +2 -1
  39. package/dist/src/council/debate-planner.js +5 -3
  40. package/dist/src/council/debate.d.ts +9 -0
  41. package/dist/src/council/debate.js +88 -8
  42. package/dist/src/council/index.d.ts +46 -1
  43. package/dist/src/council/index.js +125 -19
  44. package/dist/src/council/llm.js +41 -13
  45. package/dist/src/council/prompts.js +56 -21
  46. package/dist/src/council/types.d.ts +14 -1
  47. package/dist/src/ee/__tests__/export-transcripts.test.js +1 -1
  48. package/dist/src/ee/bridge.d.ts +3 -1
  49. package/dist/src/ee/bridge.js +9 -3
  50. package/dist/src/ee/bridge.test.js +1 -2
  51. package/dist/src/ee/client.js +15 -2
  52. package/dist/src/ee/recall-ledger.d.ts +20 -0
  53. package/dist/src/ee/recall-ledger.js +40 -1
  54. package/dist/src/ee/search.d.ts +25 -0
  55. package/dist/src/ee/search.js +73 -0
  56. package/dist/src/ee/types.d.ts +15 -1
  57. package/dist/src/ee/who-am-i.d.ts +41 -0
  58. package/dist/src/ee/who-am-i.js +143 -0
  59. package/dist/src/ee/who-am-i.test.d.ts +1 -0
  60. package/dist/src/ee/who-am-i.test.js +101 -0
  61. package/dist/src/generated/version.d.ts +1 -1
  62. package/dist/src/generated/version.js +1 -1
  63. package/dist/src/headless/council-answers.js +1 -0
  64. package/dist/src/headless/output.d.ts +30 -1
  65. package/dist/src/headless/output.js +180 -0
  66. package/dist/src/headless/output.test.js +61 -1
  67. package/dist/src/hooks/index.js +48 -2
  68. package/dist/src/index.d.ts +2 -0
  69. package/dist/src/index.js +55 -60
  70. package/dist/src/lsp/client-normalize.test.d.ts +12 -0
  71. package/dist/src/lsp/client-normalize.test.js +34 -0
  72. package/dist/src/lsp/client.d.ts +1 -0
  73. package/dist/src/lsp/client.js +10 -2
  74. package/dist/src/lsp/manager.d.ts +1 -1
  75. package/dist/src/lsp/manager.js +2 -2
  76. package/dist/src/lsp/manager.test.js +2 -2
  77. package/dist/src/lsp/runtime.d.ts +1 -1
  78. package/dist/src/lsp/runtime.js +2 -2
  79. package/dist/src/maintain/__tests__/gh-create-pr.test.js +7 -3
  80. package/dist/src/maintain/__tests__/pr-builder.test.js +7 -3
  81. package/dist/src/mcp/__tests__/client-pool.spec.js +3 -3
  82. package/dist/src/mcp/__tests__/ee-tools.test.js +42 -14
  83. package/dist/src/mcp/__tests__/forensics-tools.test.js +3 -3
  84. package/dist/src/mcp/__tests__/lsp-tools.test.js +4 -4
  85. package/dist/src/mcp/client-pool.d.ts +1 -1
  86. package/dist/src/mcp/client-pool.js +25 -9
  87. package/dist/src/mcp/ee-tools.d.ts +10 -0
  88. package/dist/src/mcp/ee-tools.js +34 -0
  89. package/dist/src/mcp/oauth-callback.js +2 -2
  90. package/dist/src/mcp/parse-headers.test.js +14 -14
  91. package/dist/src/mcp/self-verify-jobs.js +1 -3
  92. package/dist/src/mcp/setup-guide-text.js +74 -74
  93. package/dist/src/mcp/smoke.test.js +43 -43
  94. package/dist/src/models/catalog-gemini.test.js +12 -10
  95. package/dist/src/models/catalog.json +106 -38
  96. package/dist/src/ops/doctor.js +7 -7
  97. package/dist/src/orchestrator/__tests__/auto-commit.test.d.ts +1 -0
  98. package/dist/src/orchestrator/__tests__/auto-commit.test.js +142 -0
  99. package/dist/src/orchestrator/__tests__/batch-turn-runner.test.js +2 -0
  100. package/dist/src/orchestrator/__tests__/delegations.test.d.ts +1 -0
  101. package/dist/src/orchestrator/__tests__/delegations.test.js +96 -0
  102. package/dist/src/orchestrator/__tests__/message-processor.test.js +1 -0
  103. package/dist/src/orchestrator/__tests__/stream-runner.test.js +29 -0
  104. package/dist/src/orchestrator/agent.test.js +5 -2
  105. package/dist/src/orchestrator/auto-commit.d.ts +110 -0
  106. package/dist/src/orchestrator/auto-commit.js +364 -0
  107. package/dist/src/orchestrator/batch-turn-runner.d.ts +3 -2
  108. package/dist/src/orchestrator/batch-turn-runner.js +2 -1
  109. package/dist/src/orchestrator/compaction-proposer-prompt.d.ts +8 -0
  110. package/dist/src/orchestrator/compaction-proposer-prompt.js +43 -0
  111. package/dist/src/orchestrator/compaction.d.ts +22 -0
  112. package/dist/src/orchestrator/compaction.js +42 -0
  113. package/dist/src/orchestrator/delegations.d.ts +1 -0
  114. package/dist/src/orchestrator/delegations.js +41 -0
  115. package/dist/src/orchestrator/error-utils.js +27 -2
  116. package/dist/src/orchestrator/message-processor.d.ts +21 -5
  117. package/dist/src/orchestrator/message-processor.js +219 -2573
  118. package/dist/src/orchestrator/orchestrator.d.ts +8 -2
  119. package/dist/src/orchestrator/orchestrator.js +187 -34
  120. package/dist/src/orchestrator/preprocessor.d.ts +13 -0
  121. package/dist/src/orchestrator/preprocessor.js +145 -0
  122. package/dist/src/orchestrator/prompts.d.ts +8 -0
  123. package/dist/src/orchestrator/prompts.js +76 -60
  124. package/dist/src/orchestrator/safety-askcard.d.ts +66 -0
  125. package/dist/src/orchestrator/safety-askcard.js +74 -0
  126. package/dist/src/orchestrator/sandbox.test.js +8 -5
  127. package/dist/src/orchestrator/scope-ceiling.js +1 -1
  128. package/dist/src/orchestrator/stall-watchdog.d.ts +47 -0
  129. package/dist/src/orchestrator/stall-watchdog.js +23 -0
  130. package/dist/src/orchestrator/stall-watchdog.test.js +36 -1
  131. package/dist/src/orchestrator/stream-runner.js +52 -30
  132. package/dist/src/orchestrator/sub-agent-model-tier.js +1 -1
  133. package/dist/src/orchestrator/subagent-compactor.d.ts +14 -0
  134. package/dist/src/orchestrator/subagent-compactor.js +83 -10
  135. package/dist/src/orchestrator/subagent-compactor.spec.js +132 -0
  136. package/dist/src/orchestrator/text-tool-call-detector.d.ts +9 -5
  137. package/dist/src/orchestrator/text-tool-call-detector.js +16 -12
  138. package/dist/src/orchestrator/text-tool-call-detector.test.js +66 -8
  139. package/dist/src/orchestrator/tool-args-repair.js +1 -1
  140. package/dist/src/orchestrator/tool-engine.d.ts +151 -0
  141. package/dist/src/orchestrator/tool-engine.js +3079 -0
  142. package/dist/src/orchestrator/turn-runner-deps.d.ts +1 -0
  143. package/dist/src/pil/__tests__/discovery-types.test.js +15 -4
  144. package/dist/src/pil/__tests__/discovery.test.js +89 -145
  145. package/dist/src/pil/__tests__/dual-run.test.js +2 -0
  146. package/dist/src/pil/__tests__/layer1-intent-trace.test.js +3 -0
  147. package/dist/src/pil/__tests__/layer1-intent.test.js +3 -0
  148. package/dist/src/pil/__tests__/layer16-clarity.test.js +35 -32
  149. package/dist/src/pil/__tests__/layer18-acceptance.test.js +1 -78
  150. package/dist/src/pil/__tests__/layer2_5-ponytail.test.d.ts +1 -0
  151. package/dist/src/pil/__tests__/layer2_5-ponytail.test.js +53 -0
  152. package/dist/src/pil/__tests__/layer3-ee-injection.test.js +67 -4
  153. package/dist/src/pil/__tests__/layer3-injected-chunk.test.js +14 -2
  154. package/dist/src/pil/__tests__/layer4-gsd.test.js +30 -0
  155. package/dist/src/pil/__tests__/layer5-context.test.js +39 -1
  156. package/dist/src/pil/__tests__/layer6-output.test.js +30 -2
  157. package/dist/src/pil/__tests__/orchestrator-integration.test.js +3 -1
  158. package/dist/src/pil/__tests__/pipeline.test.js +11 -8
  159. package/dist/src/pil/__tests__/response-tools.test.js +52 -0
  160. package/dist/src/pil/agent-operating-contract.d.ts +1 -1
  161. package/dist/src/pil/agent-operating-contract.js +5 -3
  162. package/dist/src/pil/agent-operating-contract.test.js +2 -2
  163. package/dist/src/pil/cheap-model-playbook.d.ts +1 -1
  164. package/dist/src/pil/cheap-model-playbook.js +1 -1
  165. package/dist/src/pil/cheap-model-workbooks.d.ts +1 -1
  166. package/dist/src/pil/cheap-model-workbooks.js +1 -1
  167. package/dist/src/pil/config.d.ts +20 -0
  168. package/dist/src/pil/config.js +35 -0
  169. package/dist/src/pil/discovery-types.d.ts +32 -9
  170. package/dist/src/pil/discovery.d.ts +3 -3
  171. package/dist/src/pil/discovery.js +138 -244
  172. package/dist/src/pil/index.d.ts +1 -1
  173. package/dist/src/pil/index.js +1 -1
  174. package/dist/src/pil/layer1-intent.d.ts +9 -1
  175. package/dist/src/pil/layer1-intent.js +99 -44
  176. package/dist/src/pil/layer1-intent.test.js +112 -2
  177. package/dist/src/pil/layer15-context-scan.js +1 -1
  178. package/dist/src/pil/layer16-clarity.d.ts +21 -25
  179. package/dist/src/pil/layer16-clarity.js +52 -88
  180. package/dist/src/pil/layer18-acceptance.d.ts +13 -3
  181. package/dist/src/pil/layer18-acceptance.js +1 -75
  182. package/dist/src/pil/layer2-personality.js +7 -8
  183. package/dist/src/pil/layer2_5-ponytail.d.ts +2 -0
  184. package/dist/src/pil/layer2_5-ponytail.js +41 -0
  185. package/dist/src/pil/layer3-ee-injection.js +180 -14
  186. package/dist/src/pil/layer4-gsd.js +22 -8
  187. package/dist/src/pil/layer5-context.d.ts +1 -0
  188. package/dist/src/pil/layer5-context.js +26 -11
  189. package/dist/src/pil/layer6-output.js +23 -5
  190. package/dist/src/pil/llm-classify.js +3 -3
  191. package/dist/src/pil/native-capabilities-workbook.d.ts +1 -1
  192. package/dist/src/pil/native-capabilities-workbook.js +4 -3
  193. package/dist/src/pil/pipeline.js +15 -1
  194. package/dist/src/pil/response-tools.d.ts +16 -0
  195. package/dist/src/pil/response-tools.js +41 -0
  196. package/dist/src/pil/schema.d.ts +8 -0
  197. package/dist/src/pil/schema.js +24 -3
  198. package/dist/src/pil/task-tier-map.js +7 -7
  199. package/dist/src/pil/types.d.ts +9 -3
  200. package/dist/src/product-loop/__tests__/discovery-interview.test.js +103 -1
  201. package/dist/src/product-loop/__tests__/gather-selectable-alts.test.js +34 -0
  202. package/dist/src/product-loop/__tests__/sprint-self-verify.test.js +12 -12
  203. package/dist/src/product-loop/discovery-interview.d.ts +20 -0
  204. package/dist/src/product-loop/discovery-interview.js +121 -7
  205. package/dist/src/product-loop/done-gate.js +3 -3
  206. package/dist/src/product-loop/gather.js +19 -5
  207. package/dist/src/product-loop/loop-driver.js +20 -20
  208. package/dist/src/product-loop/progress-snapshot.js +4 -4
  209. package/dist/src/product-loop/sprint-self-verify.js +2 -2
  210. package/dist/src/providers/__tests__/reasoning-roundtrip.test.js +12 -0
  211. package/dist/src/providers/auth/__tests__/gemini-oauth.test.d.ts +1 -5
  212. package/dist/src/providers/auth/__tests__/gemini-oauth.test.js +1 -5
  213. package/dist/src/providers/auth/gcloud.d.ts +28 -0
  214. package/dist/src/providers/auth/gcloud.js +102 -0
  215. package/dist/src/providers/auth/gemini-oauth.d.ts +46 -19
  216. package/dist/src/providers/auth/gemini-oauth.js +292 -105
  217. package/dist/src/providers/auth/grok-oauth.d.ts +1 -1
  218. package/dist/src/providers/auth/grok-oauth.js +1 -1
  219. package/dist/src/providers/auth/registry.js +28 -6
  220. package/dist/src/providers/gemini.d.ts +1 -1
  221. package/dist/src/providers/gemini.js +10 -3
  222. package/dist/src/providers/keychain.d.ts +2 -2
  223. package/dist/src/providers/keychain.js +20 -2
  224. package/dist/src/providers/mcp-vision-bridge.js +48 -48
  225. package/dist/src/providers/openai.js +5 -1
  226. package/dist/src/providers/runtime.d.ts +1 -1
  227. package/dist/src/providers/runtime.js +11 -2
  228. package/dist/src/providers/siliconflow-sse-repair.js +1 -1
  229. package/dist/src/providers/strategies/google.strategy.d.ts +9 -2
  230. package/dist/src/providers/strategies/google.strategy.js +159 -9
  231. package/dist/src/providers/strategies/thinking-mode.js +19 -6
  232. package/dist/src/providers/types.d.ts +1 -1
  233. package/dist/src/reporter/index.js +1 -1
  234. package/dist/src/router/decide.test.js +40 -8
  235. package/dist/src/router/step-router.d.ts +20 -0
  236. package/dist/src/router/step-router.js +73 -0
  237. package/dist/src/scaffold/bb-ecosystem-apply.js +47 -47
  238. package/dist/src/scaffold/bb-quality-gate.js +5 -5
  239. package/dist/src/scaffold/continuation-prompt.js +60 -60
  240. package/dist/src/scaffold/init-new.js +453 -453
  241. package/dist/src/self-qa/__tests__/scenario-planner.test.js +3 -3
  242. package/dist/src/self-qa/agentic-loop.js +19 -19
  243. package/dist/src/self-qa/orchestrator.js +5 -5
  244. package/dist/src/self-qa/scenario-planner.js +1 -1
  245. package/dist/src/self-qa/spec-emitter.js +4 -4
  246. package/dist/src/storage/__tests__/migrations.test.js +2 -2
  247. package/dist/src/storage/index.d.ts +1 -1
  248. package/dist/src/storage/index.js +1 -1
  249. package/dist/src/storage/interaction-log.js +5 -5
  250. package/dist/src/storage/migrations.js +122 -122
  251. package/dist/src/storage/session-experience-store.js +4 -4
  252. package/dist/src/storage/sessions.js +43 -43
  253. package/dist/src/storage/transcript-view.js +7 -1
  254. package/dist/src/storage/transcript.d.ts +1 -0
  255. package/dist/src/storage/transcript.js +55 -0
  256. package/dist/src/storage/ui-interaction-log.d.ts +17 -0
  257. package/dist/src/storage/usage.js +14 -14
  258. package/dist/src/storage/workspaces.js +12 -12
  259. package/dist/src/tools/__tests__/native-tools.test.js +6 -0
  260. package/dist/src/tools/bash.d.ts +36 -23
  261. package/dist/src/tools/bash.js +59 -301
  262. package/dist/src/tools/bash.test.js +2 -257
  263. package/dist/src/tools/file-tracker.d.ts +5 -0
  264. package/dist/src/tools/file-tracker.js +14 -0
  265. package/dist/src/tools/file.js +2 -0
  266. package/dist/src/tools/git-safety.d.ts +38 -1
  267. package/dist/src/tools/git-safety.js +94 -4
  268. package/dist/src/tools/git-safety.test.js +45 -1
  269. package/dist/src/tools/native-tools.d.ts +1 -1
  270. package/dist/src/tools/native-tools.js +56 -0
  271. package/dist/src/tools/registry-bash-empty-command.test.js +4 -3
  272. package/dist/src/tools/registry-git-safety.test.js +17 -6
  273. package/dist/src/tools/registry.d.ts +5 -0
  274. package/dist/src/tools/registry.js +185 -11
  275. package/dist/src/types/index.d.ts +7 -1
  276. package/dist/src/ui/app.d.ts +1 -0
  277. package/dist/src/ui/app.js +0 -0
  278. package/dist/src/ui/components/council-question-card.js +1 -0
  279. package/dist/src/ui/components/message-view.js +37 -3
  280. package/dist/src/ui/components/structured-response-view.js +7 -0
  281. package/dist/src/ui/components/task-list-panel.js +3 -12
  282. package/dist/src/ui/containers/chat-feed.d.ts +40 -0
  283. package/dist/src/ui/containers/chat-feed.js +66 -0
  284. package/dist/src/ui/containers/modals-layer.d.ts +87 -0
  285. package/dist/src/ui/containers/modals-layer.js +18 -0
  286. package/dist/src/ui/slash/__tests__/menu-parity.test.d.ts +1 -0
  287. package/dist/src/ui/slash/__tests__/menu-parity.test.js +1 -0
  288. package/dist/src/ui/slash/__tests__/ponytail.test.d.ts +1 -0
  289. package/dist/src/ui/slash/__tests__/ponytail.test.js +37 -0
  290. package/dist/src/ui/slash/council-inspect.js +4 -4
  291. package/dist/src/ui/slash/export.js +16 -1
  292. package/dist/src/ui/slash/menu-items.js +1 -0
  293. package/dist/src/ui/slash/ponytail.d.ts +2 -0
  294. package/dist/src/ui/slash/ponytail.js +19 -0
  295. package/dist/src/ui/status-bar/store.js +0 -1
  296. package/dist/src/ui/status-bar/store.test.js +2 -2
  297. package/dist/src/ui/use-app-logic.d.ts +26 -0
  298. package/dist/src/ui/use-app-logic.js +0 -0
  299. package/dist/src/ui/utils/relaunch.js +1 -1
  300. package/dist/src/ui/utils/text.d.ts +11 -0
  301. package/dist/src/ui/utils/text.js +21 -1
  302. package/dist/src/ui/utils/text.test.js +25 -1
  303. package/dist/src/ui/utils/tools.js +3 -1
  304. package/dist/src/usage/cost-log.js +2 -2
  305. package/dist/src/usage/estimator.d.ts +14 -0
  306. package/dist/src/usage/estimator.js +22 -0
  307. package/dist/src/utils/__tests__/compaction-caps.test.d.ts +21 -0
  308. package/dist/src/utils/__tests__/compaction-caps.test.js +187 -0
  309. package/dist/src/utils/__tests__/llm-deadline-abort.test.d.ts +1 -0
  310. package/dist/src/utils/__tests__/llm-deadline-abort.test.js +33 -0
  311. package/dist/src/utils/clipboard-image.js +23 -23
  312. package/dist/src/utils/llm-deadline.d.ts +9 -1
  313. package/dist/src/utils/llm-deadline.js +31 -2
  314. package/dist/src/utils/permission-mode.d.ts +33 -0
  315. package/dist/src/utils/permission-mode.js +164 -3
  316. package/dist/src/utils/permission-mode.test.js +92 -1
  317. package/dist/src/utils/settings.d.ts +27 -31
  318. package/dist/src/utils/settings.js +100 -109
  319. package/dist/src/utils/side-question.js +2 -2
  320. package/dist/src/utils/skills.js +3 -3
  321. package/dist/src/verify/__tests__/coverage-parsers.test.js +30 -30
  322. package/package.json +1 -1
@@ -0,0 +1,3079 @@
1
+ // MessageProcessor — extracted from orchestrator.ts as part of Phase 12.4.
2
+ //
3
+ // Owns the main streaming turn loop that lives in `Agent.processMessage`:
4
+ // - Abort wiring (external AbortContext + per-turn AbortController)
5
+ // - Trajectory + phase tracker observations on user_turn / abort
6
+ // - PIL enrichment pipeline (layers 1/3/6 — fail-open with logging)
7
+ // - ROUTE-11 per-turn model routing (decide + fallback to non-disabled
8
+ // provider via CouncilManager)
9
+ // - Vision proxy (history + current turn)
10
+ // - Auto-council gate (PIL taskType + heavy tier + role count) — routes
11
+ // into runCouncilV2 and re-enters processMessage with synthesis
12
+ // - System prompt assembly (chitchat / playwright gating + PIL suffix +
13
+ // model constraints)
14
+ // - SAMR step-aware routing (phase1 reasoning → phase2 execution)
15
+ // - Tool roundtrip loop:
16
+ // - Compaction (relax on overflow recovery, B4 top-level prepareStep)
17
+ // - Tool set assembly: builtin + MCP (smart filter for chitchat /
18
+ // browser-vocab) + PIL response tools, all wrapped with top-level
19
+ // cumulative cap (F1), cross-turn dedup (C3), read-path budget
20
+ // - ProviderOptions composition (buildTurnProviderOptions +
21
+ // taskTypeToReasoningEffort budget + thinkingType adaptive override
22
+ // + O1 shape capture)
23
+ // - streamText({...}) with prepareStep (top-level compactor +
24
+ // capability sanitizeHistory), onStepStart/Finish, onFinish
25
+ // (correlation cleanup)
26
+ // - fullStream consumer (text-delta / reasoning-delta / tool-call
27
+ // with EE PreToolUse intercept / tool-result with EE PostToolUse
28
+ // and vision-bridge / tool-error / tool-approval-request /
29
+ // error / abort)
30
+ // - Write-ahead persistence (Phase A4 tool_calls, A5 message_seq)
31
+ // - Context-overflow recovery + transient retry with exponential backoff
32
+ // - Post-turn compact + Stop / StopFailure hooks
33
+ // - Debug pipeline trace
34
+ //
35
+ // Zero behavioral changes — every method body mirrors the original
36
+ // `processMessage` (see commit history). The DI surface (`MessageProcessorDeps`)
37
+ // is the minimum proxy onto Agent state needed to reach back into Agent
38
+ // without holding a circular reference. Public `Agent.processMessage`
39
+ // signature is unchanged and continues to be the entrypoint; internally it
40
+ // constructs a `MessageProcessor` per call.
41
+ //
42
+ // Cost-leak code paths preserved here:
43
+ // - F1 (top-level cumulative cap) — wrapToolSetWithCap (top-level)
44
+ // - F1 (openai.promptCacheKey) — buildTurnProviderOptions
45
+ // - G1 (OAuth `maxOutputTokens` drop) — shouldDropParam(runtime, ...)
46
+ // - B4 (top-level prepareStep compaction) — compactSubAgentMessages
47
+ // - C3 (cross-turn dedup wrap) — wrapToolSetWithDedup
48
+ // - A4 (tool_call write-ahead) — persistToolCallWriteAhead
49
+ // - A5 (message_seq write-ahead) — persistMessageWriteAhead
50
+ // - O1 (providerOptions shape forensics) — extractProviderOptionsShape
51
+ // - siliconflow reasoning-strip — turnCaps.sanitizeHistory
52
+ import { generateText, stepCountIs, streamText } from "ai";
53
+ import { recordArtifact } from "../ee/artifact-cache.js";
54
+ import { routeFeedback } from "../ee/bridge.js";
55
+ import { getDefaultEEClient } from "../ee/intercept.js";
56
+ import { acquireMcpTools } from "../mcp/client-pool.js";
57
+ import { dropRedundantFsMcpTools, filterMcpServersByMessage } from "../mcp/smart-filter.js";
58
+ import { getModelInfo } from "../models/registry.js";
59
+ import { cheapModelShellLine, injectCheapModelPlaybook, injectCheapModelShellDirective, shouldInjectCheapModelPlaybook, } from "../pil/cheap-model-playbook.js";
60
+ import { injectCheapModelWorkbook, shouldInjectCheapModelWorkbook } from "../pil/cheap-model-workbooks.js";
61
+ import { getResponseTaskType, isResponseTool, normalizeStructuredResponseTaskType, shouldHaltOnResponseTool, } from "../pil/index.js";
62
+ import { isMetaAnalysisPrompt } from "../pil/layer6-output.js";
63
+ import { taskTypeToMaxTokens, taskTypeToReasoningEffort, taskTypeToTier } from "../pil/task-tier-map.js";
64
+ import { mentionsEcosystemScope } from "../playbook/directives.js";
65
+ import { getProviderCapabilities } from "../providers/capabilities.js";
66
+ import { bridgeMcpToolResult, listCachedImages, scrubImagePayloadsInMessages, } from "../providers/mcp-vision-bridge.js";
67
+ import { captureToolSchemas } from "../providers/patch-zod-schema.js";
68
+ import { buildTurnProviderOptions, requireRuntimeProvider, shouldDropParam, } from "../providers/runtime.js";
69
+ import { wireDebug } from "../providers/wire-debug.js";
70
+ import { reportRouteOutcome } from "../router/decide.js";
71
+ import { getNextMessageSequence, logInteraction, markMessageErrored, markToolCallErrored, persistToolCallWriteAhead, } from "../storage/index.js";
72
+ import { persistSessionExperience } from "../storage/session-experience-store.js";
73
+ import { createBuiltinTools } from "../tools/registry.js";
74
+ import { snapshotFromTodoWriteArgs } from "../tools/todo-write-snapshot.js";
75
+ import { visionToolsNeeded } from "../tools/vision-gate.js";
76
+ import { recordTurnTrace } from "../ui/slash/debug.js";
77
+ import { statusBarStore } from "../ui/status-bar/store.js";
78
+ import { appendDecisionLog } from "../usage/decision-log.js";
79
+ import { openUrl } from "../utils/open-url.js";
80
+ import { appendAudit, toolNeedsApproval } from "../utils/permission-mode.js";
81
+ import { getAutoCouncilConfidence, getAutoCouncilMinRoles, getProviderStallRetries, getProviderStallTimeoutMs, getRoleModels, getSteerInjectionEnabled, getTopLevelCompactKeepLast, getTopLevelCompactThresholdChars, getTopLevelToolBudgetChars, isAutoCouncilEnabled, loadMcpServers, } from "../utils/settings.js";
82
+ import { resolveShell } from "../utils/shell.js";
83
+ import { relaxCompactionSettings } from "./compaction.js";
84
+ import { wrapToolSetWithDedup } from "./cross-turn-dedup.js";
85
+ import { humanizeApiError, isAuthenticationError, isContextLimitError, summarizeApiErrorForLog } from "./error-utils.js";
86
+ import { buildGroundingFootnote, findUnverifiedClaims } from "./grounding-check.js";
87
+ import { buildInterruptedTurnNote } from "./interrupted-turn.js";
88
+ import { stableCallId } from "./pending-calls.js";
89
+ import { buildMcpCapabilityBlock } from "./prompts.js";
90
+ import { extractProviderOptionsShape } from "./provider-options-shape.js";
91
+ import { wrapToolSetWithReadBudget } from "./read-path-budget.js";
92
+ import { containsEncryptedReasoning, sanitizeModelMessages } from "./reasoning.js";
93
+ import { repairToolCallHook } from "./repair-tool-call.js";
94
+ import { buildRepetitionReminder, recordAssistantBurst, shouldInjectRepetitionReminder, } from "./repetition-detector.js";
95
+ import { classifyStreamError } from "./retry-classifier.js";
96
+ import { forcedFinalize, incSessionStep, } from "./scope-ceiling.js";
97
+ import { attachReminderToMessages, buildCheckpointReminder, buildScopeReminder, cadenceForSize, shouldInjectCeilingCrossing, shouldInjectReminder, shouldInjectSoftWarn, shouldPreWarnCompaction, } from "./scope-reminder.js";
98
+ import { formatElisionManifest, getSessionExperienceCounts, recordCompaction, recordElision, } from "./session-experience.js";
99
+ import { attemptStallRescue, pushStallToolResult } from "./stall-rescue.js";
100
+ import { createStallWatchdog, STALL_ERROR_MESSAGE, shouldContinueAfterMidLoopStall, shouldRepromptStall, stallRepromptBackoffMs, } from "./stall-watchdog.js";
101
+ import { planSteerInjection } from "./steer-inbox.js";
102
+ import { wrapToolSetWithCap } from "./sub-agent-cap.js";
103
+ import { applyAnthropicPromptCaching, compactSubAgentMessages, cumulativeMessageChars } from "./subagent-compactor.js";
104
+ import { detectTextEmittedToolCall, parseDsmlToolCalls } from "./text-tool-call-detector.js";
105
+ import { createToolLoopCapPredicate } from "./tool-loop-cap.js";
106
+ import { buildToolRepetitionAbortMessage, recordToolError as recordToolRepetitionError, recordToolSuccess as recordToolRepetitionSuccess, } from "./tool-repetition-detector.js";
107
+ /**
108
+ * F2 — approximate the char cost of the FIXED prompt envelope (system +
109
+ * tools JSON-Schema) that streamText re-sends on every step. Used to feed
110
+ * the compactor a realistic total-prompt size so it fires when billed input
111
+ * is actually large, not when only `messages[]` is.
112
+ */
113
+ function computeEnvelopeChars(system, tools) {
114
+ let n = 0;
115
+ if (typeof system === "string")
116
+ n += system.length;
117
+ else if (system && typeof system === "object") {
118
+ try {
119
+ n += JSON.stringify(system).length;
120
+ }
121
+ catch {
122
+ /* ignore — best-effort estimate */
123
+ }
124
+ }
125
+ if (tools && typeof tools === "object") {
126
+ try {
127
+ n += JSON.stringify(tools).length;
128
+ }
129
+ catch {
130
+ /* ignore */
131
+ }
132
+ }
133
+ return n;
134
+ }
135
+ import { combineAbortSignals, getFinishReason, getStepNumber, getUsage, notifyObserver, toToolCall, toToolResult, } from "./tool-utils.js";
136
+ /**
137
+ * Session-scoped cache for [EE Session Guidance] dedup. Maps sessionId to the
138
+ * sha256 prefix of the last-injected guidance content. Prevents the same block
139
+ * from being re-injected on every turn — once the model has seen a set of
140
+ * guidance entries it stays informed until new entries arrive.
141
+ */
142
+ const _injectedGuidanceSha = new Map();
143
+ /**
144
+ * MessageProcessor — extracted streaming turn loop.
145
+ *
146
+ * Lifecycle:
147
+ * const processor = new MessageProcessor(deps);
148
+ * yield* processor.run(userMessage, observer, images);
149
+ *
150
+ * Constructed per call (heap allocation is negligible against the streamText
151
+ * cost), matching the StreamRunner / CouncilManager pattern.
152
+ */
153
+ /**
154
+ * Max response-tool (`respond_*`) calls tolerated within a single turn before
155
+ * the orchestrator finalizes early with the best answer buffered so far. A
156
+ * well-behaved turn emits the response tool ONCE; a hedge-then-answer emits 2.
157
+ * Beyond that is degenerate spam (session 8d8f498268ed: 80× identical
158
+ * respond_general in one generation). Set to 3 so the legitimate ≤2 patterns
159
+ * are never cut short.
160
+ */
161
+ const RESPONSE_TOOL_SPAM_CAP = 3;
162
+ /**
163
+ * Rewrites tool-result parts in the AI SDK's final response history if the
164
+ * user manually approved a safety-blocked command. This ensures the model sees
165
+ * its own retry context accurately (as a success) rather than a repeated block
166
+ * message, avoiding infinite retry loops or hallucinated failures.
167
+ */
168
+ export function rewriteSafetyApprovedToolResults(messages) {
169
+ const _globalSafety = globalThis;
170
+ const approvedMap = _globalSafety.__muonroiSafetyApproved;
171
+ if (!approvedMap || approvedMap.size === 0) {
172
+ return messages;
173
+ }
174
+ return messages.map((m) => {
175
+ if (m.role !== "tool" || !Array.isArray(m.content))
176
+ return m;
177
+ let changed = false;
178
+ const newContent = m.content.map((part) => {
179
+ if (part.type === "tool-result" && typeof part.toolCallId === "string") {
180
+ const approved = approvedMap.get(part.toolCallId);
181
+ if (approved) {
182
+ changed = true;
183
+ return {
184
+ ...part,
185
+ isError: false,
186
+ result: `Approved (${approved.kind}): blocked command was allowed by user`,
187
+ };
188
+ }
189
+ }
190
+ return part;
191
+ });
192
+ return changed ? { ...m, content: newContent } : m;
193
+ });
194
+ }
195
+ import { stripDsmlMarkup } from "./message-processor.js";
196
+ export async function* executeToolEngine(args) {
197
+ let { deps, stepRouterPhase, phase2Runtime, runtime, modelInfo, _debugSteps, _ceilingHit, userMessage, pilCtx, turnModelId, turnProvider, _stepCeiling, userModelMessage, userEnrichedMessage, signal, observer, taskHash, provider, system, routerStore, attemptedOverflowRecovery, patternLoopForceHalt, userWriteAheadSeq, streamRetryCount, MAX_STREAM_RETRIES, subagents, systemParts, playwrightGuidance, _hasResponseTools, _pilResponseTools, patternLoopInjectCount, agentLoopDecisionCount, MAX_AGENT_LOOP_DECISIONS, _naturalCeiling, _ceilingTaskType, _ceilingSize, textToolReSteerCount, MAX_TEXT_TOOL_RESTEER, turnStartMs, _debugOn, _debugTurnId, _pilEnrichmentDeltaSnapshot, isChitchat, } = args;
198
+ // Put all extracted code here:
199
+ let stallTriggered = false;
200
+ // Time-to-first-byte stall RE-PROMPT: some providers (observed:
201
+ // xai/grok-build-0.1) accept the request then never send the first byte —
202
+ // a single wedged socket, not a down backend, so a fresh request usually
203
+ // goes through. When the watchdog fires with ZERO chunks received this
204
+ // attempt, we re-issue the SAME request up to `maxStallRetries` times
205
+ // (loop-persistent counter). Gated on zero-chunks so it can NEVER restart a
206
+ // turn that already ran tools or emitted text — those go to the partial-
207
+ // answer rescue path instead. maxStallRetries = 0 restores legacy behaviour.
208
+ let stallRetryCount = 0;
209
+ const maxStallRetries = getProviderStallRetries();
210
+ // Mid-loop dead-socket CONTINUATION counter (loop-persistent). Distinct from
211
+ // the TTFB re-prompt above: when the watchdog fires AFTER earlier tool steps
212
+ // ran (chunksThisAttempt > 0) but the in-flight step produced zero bytes
213
+ // (chunksThisStep === 0 — observed live: xai/grok-build-0.1 wedges the socket
214
+ // on an inter-step request mid-investigation, session 247a0cea2eac), we
215
+ // append the completed steps' messages to history and re-issue streamText to
216
+ // RESUME from the stalled step. Because completed tool-calls + tool-results
217
+ // are in history, no tool is re-run and no text is duplicated — safe even
218
+ // for write tools (the TTFB re-prompt is NOT, hence its zero-chunks gate).
219
+ // Bounded by the same maxStallRetries cap so a persistently-dead provider
220
+ // still falls through to the partial-answer rescue.
221
+ let midLoopStallRetryCount = 0;
222
+ // Live-queue steering: messages the user typed mid-turn are drained at a
223
+ // prepareStep boundary and accumulated here, then re-appended (deduped) to
224
+ // the messages returned for each subsequent step. Loop-persistent so they
225
+ // survive a stall-reprompt restart of streamText. NOT pushed into
226
+ // deps.messages in v1 — model-context only; the assistant response captures
227
+ // the steering effect and is persisted via appendCompletedTurn.
228
+ const pendingSteers = [];
229
+ const steerEnabled = getSteerInjectionEnabled();
230
+ // Auto-council: route to multi-model debate when EITHER
231
+ // (a) PIL classified taskType=plan|analyze with high confidence AND the
232
+ // prompt is complex enough to justify the debate cost, OR
233
+ // (b) GSD-native tier === "heavy" (wholesale / multi-step / cross-repo work).
234
+ // After the debate finishes, runCouncilV2 records synthesis on
235
+ // councilManager.lastSynthesis; we then re-enter processMessage with the synthesis
236
+ // as the next user turn so the main loop continues with full debate context.
237
+ // Skip if this is already a council continuation turn (prevent infinite recursion).
238
+ //
239
+ // Phase 5 BUG-I (session f1a2a2a547db) — the gate previously fired on
240
+ // taskType=analyze + conf≥0.85 alone, with no complexity check. Result:
241
+ // "improve test coverage cho src/X.ts" (single-file, scoreComplexity=low,
242
+ // score=2) sank 13 minutes into council debate, then halted on pattern-loop
243
+ // after sprint 1 read 6 files. The complexity gate below bypasses council
244
+ // for low-complexity analyze prompts — they get the hot-path direct exec
245
+ // and stay productive. `plan` keeps the old behaviour (architectural
246
+ // decisions deserve debate regardless of length).
247
+ const autoCouncilTypes = new Set(["plan", "analyze"]);
248
+ const councilRoles = getRoleModels();
249
+ const configuredRoleCount = Object.values(councilRoles).filter(Boolean).length;
250
+ const heavyTier = pilCtx.complexityTier === "heavy";
251
+ const autoCouncilConfidence = getAutoCouncilConfidence();
252
+ const autoCouncilMinRoles = getAutoCouncilMinRoles();
253
+ const _complexityFromTrace = pilCtx._intentTrace
254
+ ?.complexity;
255
+ const _complexityGatePassed = pilCtx.taskType === "plan" || _complexityFromTrace === undefined || _complexityFromTrace !== "low";
256
+ const taskTypeMatch = pilCtx.taskType &&
257
+ autoCouncilTypes.has(pilCtx.taskType) &&
258
+ pilCtx.confidence >= autoCouncilConfidence &&
259
+ _complexityGatePassed;
260
+ const shouldAutoCouncil = !deps.councilManager.isContinuation &&
261
+ isAutoCouncilEnabled() &&
262
+ configuredRoleCount >= autoCouncilMinRoles &&
263
+ (taskTypeMatch || heavyTier);
264
+ // Always log the auto-council decision (taken or skipped) with the gate
265
+ // values that decided it. Lets reports answer "why did this turn cost
266
+ // $0.30?" and "is the confidence floor tuned wrong for my prompts?".
267
+ const autoCouncilSkipReason = (() => {
268
+ if (deps.councilManager.isContinuation)
269
+ return "continuation-turn";
270
+ if (!isAutoCouncilEnabled())
271
+ return "feature-disabled";
272
+ if (configuredRoleCount < autoCouncilMinRoles)
273
+ return `role-count<${autoCouncilMinRoles} (have ${configuredRoleCount})`;
274
+ if (!taskTypeMatch && !heavyTier) {
275
+ if (!pilCtx.taskType || !autoCouncilTypes.has(pilCtx.taskType))
276
+ return `taskType=${pilCtx.taskType ?? "null"} not in plan|analyze`;
277
+ if (pilCtx.confidence < autoCouncilConfidence)
278
+ return `confidence<${autoCouncilConfidence} (got ${pilCtx.confidence.toFixed(2)})`;
279
+ if (!_complexityGatePassed)
280
+ return `complexity=low + taskType=${pilCtx.taskType} (analyze needs medium+; plan bypasses gate)`;
281
+ return "no-trigger";
282
+ }
283
+ return "taken";
284
+ })();
285
+ appendDecisionLog({
286
+ ts: Date.now(),
287
+ sessionId: deps.session?.id ?? null,
288
+ kind: "auto-council",
289
+ taken: shouldAutoCouncil,
290
+ reason: autoCouncilSkipReason,
291
+ meta: {
292
+ taskType: pilCtx.taskType ?? null,
293
+ confidence: pilCtx.confidence,
294
+ complexityTier: pilCtx.complexityTier ?? null,
295
+ complexityScore: _complexityFromTrace ?? null,
296
+ complexityGatePassed: _complexityGatePassed,
297
+ configuredRoleCount,
298
+ autoCouncilConfidence,
299
+ autoCouncilMinRoles,
300
+ heavyTier,
301
+ isContinuation: deps.councilManager.isContinuation,
302
+ },
303
+ }).catch(() => undefined);
304
+ if (shouldAutoCouncil) {
305
+ const reason = heavyTier
306
+ ? `complexity=heavy${pilCtx.taskType ? ` task=${pilCtx.taskType}` : ""}`
307
+ : `${pilCtx.taskType} task detected with ${(pilCtx.confidence * 100).toFixed(0)}% confidence`;
308
+ yield { type: "content", content: `\n[Auto-council triggered: ${reason}]\n` };
309
+ yield* deps.runCouncilV2(userMessage, { skipClarification: true, observer, userModelMessage });
310
+ const synthesis = deps.councilManager.lastSynthesis;
311
+ deps.councilManager.setLastSynthesis(null);
312
+ if (synthesis) {
313
+ yield { type: "content", content: "\n[Auto-continuing with council recommendations...]\n" };
314
+ deps.councilManager.setContinuation(true);
315
+ try {
316
+ yield* deps.processMessage(`Council debate completed. Synthesis:\n\n${synthesis}\n\nProceed with the recommended action items.`, observer);
317
+ }
318
+ finally {
319
+ deps.councilManager.setContinuation(false);
320
+ }
321
+ }
322
+ return;
323
+ }
324
+ if (deps.batchApi) {
325
+ try {
326
+ yield* deps.processMessageBatchTurn({
327
+ userModelMessage,
328
+ userEnrichedMessage,
329
+ observer,
330
+ provider,
331
+ subagents,
332
+ system,
333
+ runtime,
334
+ modelInfo,
335
+ signal,
336
+ });
337
+ }
338
+ finally {
339
+ if (deps.getAbortController()?.signal === signal) {
340
+ deps.setAbortController(null);
341
+ }
342
+ }
343
+ return;
344
+ }
345
+ try {
346
+ streamAttempt: while (true) {
347
+ // SAMR Phase 2: switch to fast model for tool-execution steps
348
+ if (stepRouterPhase === "phase2" && phase2Runtime) {
349
+ runtime = phase2Runtime;
350
+ modelInfo = runtime.modelInfo;
351
+ }
352
+ deps.setCompactedThisTurn(false);
353
+ let assistantText = "";
354
+ // Count of stream parts received in THIS attempt. Stays 0 only when the
355
+ // provider never sent a first byte → the safe-to-re-prompt stall case.
356
+ let chunksThisAttempt = 0;
357
+ // Count of stream parts received since the last step boundary (reset in
358
+ // prepareStep). Distinguishes a mid-loop dead socket (a single step's
359
+ // request got zero bytes while every prior step completed) from a stall
360
+ // that interrupted text mid-generation. See shouldContinueAfterMidLoopStall.
361
+ let chunksThisStep = 0;
362
+ // Decide whether a fired stall watchdog should re-prompt (re-issue the
363
+ // same request) instead of falling through to rescue/error. Returns the
364
+ // backoff ms to wait before re-issuing, or null to NOT re-prompt. Reads
365
+ // the live per-attempt locals; safe to call only when stallTriggered.
366
+ const planStallReprompt = () => {
367
+ if (!shouldRepromptStall({
368
+ stallTriggered,
369
+ stallRetryCount,
370
+ maxStallRetries,
371
+ chunksThisAttempt,
372
+ assistantTextEmpty: assistantText.trim() === "",
373
+ aborted: signal.aborted,
374
+ })) {
375
+ return null;
376
+ }
377
+ stallRetryCount++;
378
+ const backoffMs = stallRepromptBackoffMs(stallRetryCount);
379
+ try {
380
+ const _ar = globalThis.__muonroiAgentRuntime;
381
+ _ar?.emitEvent({
382
+ t: "event",
383
+ kind: "stream-retry",
384
+ attempt: stallRetryCount,
385
+ maxAttempts: maxStallRetries + 1,
386
+ errorName: "TimeoutError",
387
+ errorMessage: "provider-stall (no first byte) — re-prompting",
388
+ nextDelayMs: backoffMs,
389
+ });
390
+ _ar?.emitEvent({
391
+ t: "event",
392
+ kind: "toast",
393
+ level: "warning",
394
+ text: `Model stalled — re-prompting (attempt ${stallRetryCount}/${maxStallRetries})…`,
395
+ });
396
+ }
397
+ catch (emitErr) {
398
+ console.error(`[message-processor] stall-reprompt telemetry failed: ${emitErr?.message}`);
399
+ }
400
+ try {
401
+ if (deps.session) {
402
+ logInteraction(deps.session.id, "stream_retry", {
403
+ data: {
404
+ attempt: stallRetryCount,
405
+ maxAttempts: maxStallRetries + 1,
406
+ errorName: "provider-stall",
407
+ errorMessage: "no first byte within stall timeout — re-prompted",
408
+ nextDelayMs: backoffMs,
409
+ },
410
+ });
411
+ }
412
+ }
413
+ catch (logErr) {
414
+ console.error(`[message-processor] stall-reprompt log failed: ${logErr?.message}`);
415
+ }
416
+ return backoffMs;
417
+ };
418
+ // Tracks where `assistantText` was at the previous step boundary so
419
+ // `onStepFinish` can compute the text emitted within the just-finished
420
+ // step (input to the self-repetition detector).
421
+ let _assistantTextAtLastStep = 0;
422
+ let reasoningPreview = "";
423
+ let encryptedReasoningHidden = false;
424
+ let streamOk = false;
425
+ let closeMcp;
426
+ let stepNumber = -1;
427
+ const activeToolCalls = [];
428
+ // Capped digest of tool outputs gathered this attempt — fuels the
429
+ // best-effort answer rescue if the stream stalls mid-turn (see
430
+ // stall-rescue.ts). Reset per attempt; only the most recent results win.
431
+ const turnToolResults = [];
432
+ // SAMR: track whether Phase 1 produced tool calls
433
+ let phase1HadToolCalls = false;
434
+ let _pendingStructuredResponse = null;
435
+ let _pendingStructuredResponseLen = -1;
436
+ try {
437
+ const settings = attemptedOverflowRecovery
438
+ ? relaxCompactionSettings(deps.getCompactionSettings(modelInfo?.contextWindow))
439
+ : deps.getCompactionSettings(modelInfo?.contextWindow);
440
+ if (modelInfo?.contextWindow) {
441
+ await deps.compactForContext(provider, system, modelInfo.contextWindow, signal, settings, attemptedOverflowRecovery);
442
+ }
443
+ // Vision-tool gate: for vision-proxy (text-only) models the registry
444
+ // adds 3 image tools (~500-700 tok) on every turn. Drop them when the
445
+ // turn has no plausible image involvement. Bias is KEEP — retained on
446
+ // any image signal, attachment, cached image, or prior-tool turn.
447
+ const includeVisionTools = visionToolsNeeded({
448
+ userMessage,
449
+ messages: deps.messages,
450
+ cachedImageCount: listCachedImages().length,
451
+ priorTurnHadTools: deps.messages.some((m) => m?.role === "tool"),
452
+ });
453
+ const baseToolsRaw = createBuiltinTools(deps.bash, deps.mode, {
454
+ runTask: (request, abortSignal) => deps.runTask(request, combineAbortSignals(signal, abortSignal)),
455
+ runDelegation: (request, abortSignal) => deps.runDelegation(request, combineAbortSignals(signal, abortSignal)),
456
+ readDelegation: (id) => deps.readDelegation(id),
457
+ listDelegations: () => deps.listDelegations(),
458
+ modelId: turnModelId,
459
+ includeVisionTools,
460
+ });
461
+ // Top-level cumulative cap state. We accumulate the raw tool set
462
+ // (base + MCP + PIL response tools) across the assembly below,
463
+ // then apply the cap once. Tier ratios are looser than the
464
+ // sub-agent cap (50%/80%) so casual single-tool turns are not
465
+ // trimmed. See sub-agent-cap.ts.
466
+ // Chitchat: drop builtin tools too (not just MCP). A 1-word greeting
467
+ // never needs bash/read_file/edit_file/grep — those schemas alone
468
+ // cost ~1.5K input tokens on this CLI. Falls back to baseTools for
469
+ // every non-chitchat turn (PIL gates conservatively).
470
+ //
471
+ // BUG-A guard — when prior turns already issued tool_calls (their
472
+ // results still live in the messages history), DROPPING tools on a
473
+ // continuation chitchat ("tiếp tục" / "continue") causes two
474
+ // failures: (1) DeepSeek goes into native DSML markup fallback
475
+ // because it sees tool-call history but no schema (visible in
476
+ // sessions 002df4014cb4 + fc19b4daee20); (2) the agent has no way
477
+ // to actually CONTINUE the prior task — the user's clear intent.
478
+ // Detect prior-tool-context and keep the base tool set in that
479
+ // case. The 1.5K token saving for true greetings (no prior tool
480
+ // history) is preserved.
481
+ const turnCaps = getProviderCapabilities(requireRuntimeProvider(runtime));
482
+ const _priorTurnHadTools = deps.messages.some((m) => m?.role === "tool");
483
+ let rawToolSet = !turnCaps.supportsClientTools(runtime.modelInfo)
484
+ ? {}
485
+ : isChitchat && !_priorTurnHadTools
486
+ ? {}
487
+ : baseToolsRaw;
488
+ // MCP skip: chitchat / greeting inputs don't need 7 MCP servers'
489
+ // worth of tool schemas (~20K input tokens). PIL Layer 1 already
490
+ // gates this conservatively (≤10 chars + ≤2 words OR brain "none").
491
+ if (deps.mode === "agent" &&
492
+ (!isChitchat || _priorTurnHadTools) &&
493
+ turnCaps.supportsClientTools(runtime.modelInfo)) {
494
+ // Smart MCP filter: drop OPTIONAL MCP servers whose category the
495
+ // current message gives no signal for. Browser/vision servers
496
+ // (Playwright/Chrome/Figma/Canva) skip unless the message touches a
497
+ // page; docs/web servers (context7/fetch) skip unless the message
498
+ // looks like an external lookup. Each MCP contributes 8-15 tools at
499
+ // ~150 tok each, so local code work — the majority of turns — saves
500
+ // ~13K input tokens it would otherwise pay every turn. Domain
501
+ // servers (filesystem/tools/harness) always pass through. Logic is
502
+ // a pure helper (src/mcp/smart-filter.ts) so it is unit-tested.
503
+ // Override with MUONROI_DISABLE_SMART_MCP=1.
504
+ const filteredServers = filterMcpServersByMessage(loadMcpServers(), userMessage, {
505
+ disabled: process.env.MUONROI_DISABLE_SMART_MCP === "1",
506
+ });
507
+ // Ecosystem question → muonroi-docs is the authoritative source the
508
+ // agent is nudged to consult FIRST. Wait for it specifically beyond the
509
+ // normal deadline so a cold first-connect lands THIS turn instead of
510
+ // "ready next turn" (session 584ba476c07a: first ecosystem question
511
+ // missed docs while warming → agent guessed from local files).
512
+ const criticalServerIds = mentionsEcosystemScope(userMessage)
513
+ ? filteredServers.filter((s) => /(^|[-_])docs([-_]|$)/.test(s.id) && /muonroi/i.test(s.id)).map((s) => s.id)
514
+ : undefined;
515
+ // MCP non-blocking: acquireMcpTools self-bounds — it connects servers
516
+ // in parallel and returns PARTIAL results at its internal deadline
517
+ // (fast/cached servers included; slow first-connects reported in
518
+ // .errors and available next turn). Clients are POOLED across turns
519
+ // (client-pool.ts), so a server cold-spawns at most once per session
520
+ // instead of every turn. No outer race: the old race discarded the
521
+ // WHOLE bundle on timeout (Phase 1c — session f6f7881a5fae).
522
+ let mcpBundle = null;
523
+ try {
524
+ mcpBundle = await acquireMcpTools(filteredServers, {
525
+ onOAuthRequired: (_serverId, url) => {
526
+ // Server-supplied URL is untrusted — openUrl validates the
527
+ // scheme and spawns via execFile (no shell), closing the
528
+ // command-injection vector the old exec() opener had.
529
+ openUrl(url);
530
+ },
531
+ ...(criticalServerIds && criticalServerIds.length > 0 ? { criticalServerIds } : {}),
532
+ });
533
+ }
534
+ catch (err) {
535
+ console.error("[MCP] buildMcpToolSet failed, proceeding with builtins only", err);
536
+ }
537
+ if (mcpBundle) {
538
+ closeMcp = mcpBundle.close;
539
+ // Drop filesystem-MCP read/write/edit tools that duplicate the
540
+ // first-class builtin file tools. Without this, models re-read the
541
+ // SAME file via both `read_file` and `mcp_filesystem__read_text_file`
542
+ // (live grok session f5dfab0ce0ca: a 772-line file read 6×), wasting
543
+ // ~150 tok/schema PLUS re-injecting whole files into context. The
544
+ // builtins are strictly better (read-before-write, LSP, CRLF match,
545
+ // dedup/read-budget wrappers). Non-duplicate fs tools are untouched.
546
+ const _builtinToolNames = new Set(Object.keys(rawToolSet));
547
+ const { tools: _dedupedMcpTools, dropped: _droppedFsMcp } = dropRedundantFsMcpTools(mcpBundle.tools, _builtinToolNames);
548
+ rawToolSet = { ...rawToolSet, ..._dedupedMcpTools };
549
+ // muonroi-tools is THIS CLI: every tool it exposes (ee_query,
550
+ // ee_feedback, ee_health, usage_forensics, lsp_query, setup_guide,
551
+ // selfverify_*) is now a NATIVE in-process builtin (src/tools/
552
+ // native-tools.ts) — strictly better (no subprocess, no cold-start).
553
+ // If an external/legacy config still self-spawns muonroi-tools, drop
554
+ // any MCP twin whose native equivalent is present so the model never
555
+ // sees two interchangeable copies. (The CLI no longer self-spawns it
556
+ // by default — see auto-setup.ts.)
557
+ for (const key of Object.keys(rawToolSet)) {
558
+ const twin = key.match(/^mcp_muonroi-tools__(.+)$/);
559
+ if (twin && rawToolSet[twin[1]])
560
+ delete rawToolSet[key];
561
+ }
562
+ if (_droppedFsMcp.length > 0 && deps.session) {
563
+ try {
564
+ logInteraction(deps.session.id, "routing", {
565
+ model: turnModelId,
566
+ data: { droppedRedundantFsMcp: _droppedFsMcp },
567
+ });
568
+ }
569
+ catch {
570
+ /* telemetry best-effort */
571
+ }
572
+ }
573
+ if (mcpBundle.errors.length > 0) {
574
+ // A pooled server that is still cold-starting is NOT "unavailable"
575
+ // — it's warming up and will be ready next turn. Only surface
576
+ // GENUINE failures as "unavailable"; show warming servers as a
577
+ // soft, non-alarming note (and only the first time, since the
578
+ // pool connects them in the background).
579
+ const warming = mcpBundle.errors.filter((e) => /still connecting/.test(e));
580
+ const failed = mcpBundle.errors.filter((e) => !/still connecting/.test(e));
581
+ if (failed.length > 0) {
582
+ yield { type: "content", content: `MCP unavailable: ${failed.join(" | ")}\n\n` };
583
+ }
584
+ if (warming.length > 0) {
585
+ const names = warming.map((e) => e.split(":")[0]).join(", ");
586
+ yield { type: "content", content: `MCP warming up (${names}) — ready from the next turn.\n\n` };
587
+ }
588
+ }
589
+ }
590
+ }
591
+ // PIL response tools: inject structured output tool when taskType detected
592
+ if (_hasResponseTools && turnCaps.supportsClientTools(runtime.modelInfo)) {
593
+ rawToolSet = { ...rawToolSet, ..._pilResponseTools };
594
+ captureToolSchemas(_pilResponseTools);
595
+ }
596
+ // Apply the top-level cumulative cap once over the fully-assembled
597
+ // raw tool set. State is per-turn; each turn gets a fresh budget.
598
+ const topLevelCap = wrapToolSetWithCap(rawToolSet, {
599
+ maxCumulativeChars: getTopLevelToolBudgetChars(),
600
+ midTierRatio: 0.5,
601
+ highTierRatio: 0.8,
602
+ label: "top-level",
603
+ });
604
+ // Phase C3: layer cross-turn dedup on top of the top-level cap.
605
+ const tools = wrapToolSetWithReadBudget(wrapToolSetWithDedup(topLevelCap.tools, deps.crossTurnDedup), deps.readBudget);
606
+ captureToolSchemas(tools);
607
+ let responseToolCalled = false;
608
+ // A turn must surface exactly ONE final structured answer. Cheap
609
+ // models sometimes emit the response tool MORE THAN ONCE in a single
610
+ // step (session 9b1b39bf4dc6: grok emitted respond_general twice —
611
+ // a 278-char "I must read the code" hedge, then the 3782-char real
612
+ // answer — both in one step). Yielding each inline appends two
613
+ // stacked structured_response blocks and shows the hedge first.
614
+ // Instead we BUFFER the response-tool payloads and yield only the
615
+ // most complete one (longest serialized data) after the stream
616
+ // drains — robust to either ordering (hedge-then-answer or
617
+ // answer-then-summary).
618
+ _pendingStructuredResponse = null;
619
+ _pendingStructuredResponseLen = -1;
620
+ let _responseToolEmitCount = 0;
621
+ // G3: providerOptions assembly is owned by the capability layer
622
+ // (src/providers/capabilities.ts). buildTurnProviderOptions feeds
623
+ // sessionId in so openai.promptCacheKey is derived per turn.
624
+ // The task-type-driven anthropic.thinking budget override stays
625
+ // here because it depends on PIL task context, not provider quirks.
626
+ // biome-ignore lint/suspicious/noExplicitAny: matches RuntimeResult.providerOptions shape (any) used downstream
627
+ const baseProviderOpts = buildTurnProviderOptions(runtime, { sessionId: deps.session?.id }) ?? {};
628
+ const providerOpts = runtime.modelInfo?.reasoning && runtime.modelInfo?.provider === "anthropic"
629
+ ? {
630
+ ...baseProviderOpts,
631
+ anthropic: {
632
+ ...(baseProviderOpts.anthropic ?? {}),
633
+ thinking: {
634
+ type: "enabled",
635
+ budgetTokens: taskTypeToReasoningEffort(pilCtx.taskType) === "high"
636
+ ? 32_768
637
+ : taskTypeToReasoningEffort(pilCtx.taskType) === "medium"
638
+ ? 8_192
639
+ : 2_048,
640
+ },
641
+ },
642
+ }
643
+ : baseProviderOpts;
644
+ // Use catalog's thinkingType field instead of regex matching.
645
+ // providerOpts is loosely typed (Record<string, unknown>) after the
646
+ // g1 capability refactor — narrow with a local typed view.
647
+ const thinkingModelInfo = getModelInfo(runtime.modelId);
648
+ const providerOptsAnyView = providerOpts;
649
+ if (providerOptsAnyView.anthropic?.thinking?.type === "enabled" &&
650
+ thinkingModelInfo?.thinkingType === "adaptive") {
651
+ providerOptsAnyView.anthropic.thinking = { type: "adaptive" };
652
+ }
653
+ // OpenAI api-key path: `store: true` is seeded by OpenAIStrategy
654
+ // via factory.defaultProviderOptions (Phase 12.2-G4 migration).
655
+ // OAuth backend (ChatGPT Codex) overrides with `store: false` via
656
+ // the auth registry. Both flow through resolveModelRuntime →
657
+ // runtime.providerOptions → buildTurnProviderOptions and arrive
658
+ // here merged into providerOpts.openai.
659
+ // Top-level dropParam — shared with sub-agent path via shouldDropParam.
660
+ // See src/providers/runtime.ts for the central rule.
661
+ const dropParam = (p) => shouldDropParam(runtime, p);
662
+ // Tier-aware behavioural suffix. Cheap models (DeepSeek V4 Flash etc.)
663
+ // ignore well-worded tool descriptions but DO adopt instructions when
664
+ // surfaced in the system prompt. Smart models don't need this — gated
665
+ // by `modelInfo.tier === "fast"`. See cheap-model-playbook.ts for
666
+ // motivation + escape hatch (MUONROI_DISABLE_CHEAP_MODEL_PLAYBOOK=1).
667
+ // Fast-tier steering, front-loaded for primacy: task convergence
668
+ // workbook (anti-ramble — cuts tool-call count, the dominant
669
+ // cheap-model cost) layered UNDER the tool-use playbook so the
670
+ // CRITICAL tool rules stay at the very front. Both fixed per turn, so
671
+ // they stay inside the cached prefix.
672
+ const systemWithWorkbook = shouldInjectCheapModelWorkbook(runtime.modelInfo)
673
+ ? injectCheapModelWorkbook(system, pilCtx.taskType)
674
+ : system;
675
+ const systemWithPlaybook = shouldInjectCheapModelPlaybook(runtime.modelInfo)
676
+ ? injectCheapModelPlaybook(systemWithWorkbook)
677
+ : systemWithWorkbook;
678
+ // A2: front-load a one-line shell/env directive for fast-tier models.
679
+ // The authoritative ENVIRONMENT block already states OS/shell/cwd in
680
+ // the prompt body, but budget models underweight non-front-loaded
681
+ // rules — so echo the correct-syntax line at the very front. Derived
682
+ // from resolveShell({}) (same source as buildEnvironmentBlock) so it
683
+ // is always accurate to the actual shell the bash tool will spawn.
684
+ // Gated to fast tier, so the claude branch below still sees `system`.
685
+ const systemWithShell = shouldInjectCheapModelPlaybook(runtime.modelInfo)
686
+ ? injectCheapModelShellDirective(systemWithPlaybook, cheapModelShellLine(resolveShell({}).kind, process.platform))
687
+ : systemWithPlaybook;
688
+ // Append the LIVE MCP tool roster so the agent calls connected MCP
689
+ // tools by their exact mcp_<server>__<tool> name instead of shelling
690
+ // out (session f6f7881a5fae). Built from the FINAL toolset for this
691
+ // iteration (post smart-filter + fs-dedup), so it never names a tool
692
+ // the model can't actually call. Dynamic per turn → must live OUTSIDE
693
+ // the cached staticPrefix; for claude it lands in the second
694
+ // (non-cached) system message via the slice below.
695
+ const mcpCapabilityBlock = buildMcpCapabilityBlock(Object.keys(tools));
696
+ const systemWithCaps = mcpCapabilityBlock ? `${systemWithShell}${mcpCapabilityBlock}` : systemWithShell;
697
+ const systemForModel = runtime.modelId.startsWith("claude")
698
+ ? [
699
+ {
700
+ role: "system",
701
+ content: systemParts.staticPrefix,
702
+ providerOptions: { anthropic: { cacheControl: { type: "ephemeral" } } },
703
+ },
704
+ {
705
+ role: "system",
706
+ content: systemWithCaps.slice(systemParts.staticPrefix.length),
707
+ },
708
+ ]
709
+ : systemWithCaps;
710
+ // Capture prompt-size breakdown so recordUsage can attach it to the
711
+ // cost-log entry. Without this, "system prompt is huge" is unfalsifiable.
712
+ // chars/4 ≈ tokens for English; reported as chars to keep math obvious.
713
+ const messagesChars = deps.messages.reduce((s, m) => {
714
+ const c = m.content;
715
+ if (typeof c === "string")
716
+ return s + c.length;
717
+ if (Array.isArray(c)) {
718
+ for (const part of c) {
719
+ if (typeof part.text === "string") {
720
+ s += part.text.length;
721
+ }
722
+ }
723
+ }
724
+ return s;
725
+ }, 0);
726
+ let toolsChars = 0;
727
+ let toolsCount = 0;
728
+ for (const [name, t] of Object.entries(tools)) {
729
+ toolsCount += 1;
730
+ toolsChars += name.length;
731
+ const desc = t.description;
732
+ if (typeof desc === "string")
733
+ toolsChars += desc.length;
734
+ try {
735
+ // Schemas often dominate tool size on non-Anthropic providers
736
+ // (Zod-derived JSON schemas can be 2-5K chars per tool).
737
+ const params = t.parameters ??
738
+ t.inputSchema;
739
+ if (params)
740
+ toolsChars += JSON.stringify(params).length;
741
+ }
742
+ catch {
743
+ /* best-effort */
744
+ }
745
+ }
746
+ deps.setLastPromptBreakdown({
747
+ systemChars: system.length,
748
+ staticPrefixChars: systemParts.staticPrefix.length,
749
+ dynamicSuffixChars: systemParts.dynamicSuffix.length,
750
+ playwrightGuidanceChars: playwrightGuidance.length,
751
+ messagesChars,
752
+ messagesCount: deps.messages.length,
753
+ toolsChars,
754
+ toolsCount,
755
+ });
756
+ // Task 2.6a — assign a fresh correlation ID for this top-level streamText call.
757
+ const _topCallId = crypto.randomUUID();
758
+ deps.setCurrentCallId(_topCallId);
759
+ // Capture finishReason so we can surface "round cap hit" as a visible
760
+ // toast — without this, the agent silently stops mid-flight when
761
+ // stepCountIs(maxToolRounds) fires and the user sees the TUI freeze
762
+ // (session 7dcf8fd7d6a4 hit exactly 100 rounds → looked like a crash).
763
+ let _lastFinishReason = null;
764
+ // Phase B4: compact older tool_result parts before each top-level
765
+ // step once cumulative message chars exceed the configured threshold.
766
+ // The compactor preserves system + first user verbatim and keeps the
767
+ // last N tool turns intact; older results are rewritten into short
768
+ // stubs. Symmetric to the B3 sub-agent path; reuses the same module
769
+ // with `label: "top-level"` so the stub text reflects which loop
770
+ // elided the content.
771
+ const topLevelCompactThreshold = getTopLevelCompactThresholdChars();
772
+ const topLevelCompactKeepLast = getTopLevelCompactKeepLast();
773
+ // Phase O1 — capture providerOptions SHAPE (types only) for forensics.
774
+ deps.setLastProviderOptionsShape(Object.keys(providerOpts).length > 0 ? extractProviderOptionsShape(providerOpts) : null);
775
+ // Substitute the enriched user message for the current turn so the LLM sees PIL additions,
776
+ // while leaving the DB-persisted `deps.messages` clean for future turns.
777
+ const _messagesForCall = deps.messages.map((m) => m === userModelMessage ? userEnrichedMessage : m);
778
+ if (wireDebug.enabled) {
779
+ wireDebug.logRequest({
780
+ providerId: runtime.modelInfo?.provider ?? "unknown",
781
+ modelId: runtime.modelId,
782
+ messages: _messagesForCall,
783
+ systemChars: systemForModel?.length ?? 0,
784
+ toolNames: tools ? Object.keys(tools) : undefined,
785
+ providerOptions: providerOpts,
786
+ });
787
+ }
788
+ // sanitizeHistory is identity for every provider (kept as a hook
789
+ // for future provider-specific quirks). Reasoning round-trips
790
+ // natively via @ai-sdk/openai-compatible — see
791
+ // src/providers/__tests__/reasoning-roundtrip.test.ts.
792
+ const _topMessagesForCall = applyAnthropicPromptCaching(turnCaps.sanitizeHistory(_messagesForCall), runtime.modelId);
793
+ // Closure-mutable cap for the tool-loop askcard rescue.
794
+ // Phase 1 (SAMR) skips the dynamic cap (it's a single-step path).
795
+ // Algorithm extracted to ./tool-loop-cap.ts so it can be unit-tested.
796
+ const _baseDynamicStopWhen = createToolLoopCapPredicate({
797
+ initialCap: deps.maxToolRounds,
798
+ ask: async (info) => {
799
+ if (info.kind === "pattern") {
800
+ if (patternLoopInjectCount < 1) {
801
+ patternLoopInjectCount++;
802
+ patternLoopForceHalt = true;
803
+ deps.messages.push({
804
+ role: "user",
805
+ content: `[System Warning: You have called tool '${info.toolName}' ${info.count} times with similar arguments in this turn. If you are stuck in a loop, please re-evaluate your plan, change your approach, or explain the blocker. Do not repeat the same unsuccessful tool call.]`,
806
+ });
807
+ return "stop";
808
+ }
809
+ }
810
+ // Query the agent itself to make the decision instead of showing a raw user askcard
811
+ // Active only in headless (batchApi) mode — TUI users expect the CLI to stop and wait.
812
+ if (deps.batchApi && agentLoopDecisionCount < MAX_AGENT_LOOP_DECISIONS) {
813
+ try {
814
+ const _ar = globalThis.__muonroiAgentRuntime;
815
+ _ar?.emitEvent({
816
+ t: "event",
817
+ kind: "toast",
818
+ level: "info",
819
+ text: info.kind === "pattern"
820
+ ? `phát hiện lặp tool liên tục — đang hỏi ý kiến agent có muốn tiếp tục không...`
821
+ : `đạt giới hạn số bước (${info.stepNumber} bước) — đang hỏi ý kiến agent có muốn tiếp tục không...`,
822
+ });
823
+ const loopContext = info.kind === "pattern"
824
+ ? `You have called the tool '${info.toolName}' repeatedly ${info.count} times in a row with similar inputs. This indicates you might be stuck in a tool loop.`
825
+ : `You have reached the tool execution limit of ${info.stepNumber} steps (cap: ${info.cap}).`;
826
+ const systemPrompt = `You are an AI loop-guard assistant. Your task is to evaluate the agent's progress and decide whether they should keep trying to run tools (continue) or stop and present their best answer now (stop).\n` +
827
+ `Choose 'stop' if the agent is stuck in an unproductive loop (e.g. repeated unsuccessful commands, permission errors, file reading loops without making progress), or if they already have enough information to write a final response.\n` +
828
+ `Choose 'continue' only if they are making active progress, are close to a breakthrough, or genuinely need a few more steps to verify their changes.\n\n` +
829
+ `Format your decision EXACTLY as:\n` +
830
+ `<decision>continue</decision> or <decision>stop</decision>\n` +
831
+ `followed by a brief 1-sentence explanation of your decision (in English).`;
832
+ const recentMessages = deps.messages.slice(-10);
833
+ const modelMessages = [
834
+ ...recentMessages,
835
+ {
836
+ role: "user",
837
+ content: `[System Loop Guard Context: ${loopContext}\nBased on the conversation history and recent tool executions, do you need to continue executing tools or should you stop and summarize now?]`,
838
+ },
839
+ ];
840
+ const { text: decisionText } = await generateText({
841
+ model: runtime.model,
842
+ system: systemPrompt,
843
+ messages: modelMessages,
844
+ abortSignal: signal,
845
+ });
846
+ const cleanText = decisionText.trim();
847
+ const match = cleanText.match(/<decision>(continue|stop)<\/decision>/i);
848
+ const decision = match ? match[1].toLowerCase() : "stop";
849
+ let reason = cleanText.replace(/<decision>.*?<\/decision>/gs, "").trim();
850
+ // Strip DeepSeek's raw DSML or other XML tool leaks from the toast reason
851
+ reason = reason.replace(/<[^>]+>/g, "").trim();
852
+ _ar?.emitEvent({
853
+ t: "event",
854
+ kind: "toast",
855
+ level: "info",
856
+ text: `Agent quyết định: ${decision === "continue" ? "TIẾP TỤC" : "DỪNG LẠI"} (${reason || "không có lý do"})`,
857
+ });
858
+ agentLoopDecisionCount++;
859
+ if (decision === "continue") {
860
+ return "continue";
861
+ }
862
+ else {
863
+ return "stop";
864
+ }
865
+ }
866
+ catch (err) {
867
+ console.error(`[Agent] loop auto-decision failed: ${err?.message ?? err}`);
868
+ }
869
+ }
870
+ return deps.askToolLoopContinue ? await deps.askToolLoopContinue(info) : "stop";
871
+ },
872
+ // Phase 5 BUG-H — thread the resolved natural ceiling down so the
873
+ // pattern askcard can pick a context-aware default action (continue
874
+ // early in the run, stop once we're past 50% of the natural budget).
875
+ naturalCeiling: _naturalCeiling,
876
+ });
877
+ // Phase 4 Plan 04 (4B) — compose per-session ceiling alongside the
878
+ // existing cap + pattern guard. Logical OR: any condition true → halt.
879
+ // Counter is per-SESSION and increments once per stopWhen invocation
880
+ // (i.e. once per finished tool step), persisting across user turns
881
+ // so a wandering 3-turn burst still trips at the matrix limit.
882
+ const _ceilingSessionId = deps.session?.id ?? "no-session";
883
+ // Phase 5 Fix 3 — capture the actual step number when the ceiling
884
+ // trips so the halt toast can report the real value, not the
885
+ // ceiling/ceiling literal that always showed e.g. "5/5" regardless
886
+ // of how many steps the turn actually ran.
887
+ const _ceilingHitAtStep = 0;
888
+ // Phase 5 Fix 5 — matrix ceiling is now a SOFT BOUNDARY, never a
889
+ // hard halt. Phase 4's hard halt was a blunt anti-wandering
890
+ // measure that also blocked legitimate multi-step work: every
891
+ // long task (improve coverage, optimize startup, refactor) ran
892
+ // out of budget mid-flight and required the user to manually
893
+ // type "tiếp tục". Wrong philosophy — "done" must be the agent's
894
+ // call, not the counter's.
895
+ //
896
+ // What replaced the hard halt:
897
+ // - Scope-reminders (4A path, prepareStep above) inject
898
+ // "[approaching ceiling]" reminder at floor(ceiling*0.7) and
899
+ // repeat at K cadence. Past the ceiling, every step gets a
900
+ // re-anchor so the model is repeatedly nudged toward closure.
901
+ // - The dynamicStopWhen no longer checks the matrix ceiling at
902
+ // all. The only halt source is `_baseDynamicStopWhen` which
903
+ // enforces `deps.maxToolRounds` as the ULTIMATE runaway safety
904
+ // net (default raised; see CLI default).
905
+ // - 4R bash repeat detector still catches the dominant wandering
906
+ // pattern (identical command twice in a row).
907
+ // - F6 synthesis still ensures any natural stream-end without
908
+ // text gets a final summary.
909
+ //
910
+ // _ceilingHit and _ceilingHitAtStep are kept for telemetry: a
911
+ // crossing event is logged for forensics, but no action is taken.
912
+ const dynamicStopWhen = (async (state) => {
913
+ // Terminal response tool: a `respond_*` call IS the model's final
914
+ // structured answer (its `execute` is identity — the payload lives
915
+ // in the tool-call args). `shouldHaltOnResponseTool` decides if the
916
+ // emission is terminal vs a premature "blind" announce:
917
+ // - response tool AFTER real tool work (read/grep/bash) → terminal,
918
+ // halt now (kills d95113d3be09 seq=27: 7 reads → 87× respond loop
919
+ // at call #1, no extra round-trip for the common case).
920
+ // - a single blind response (no prior investigation) → do NOT halt;
921
+ // give the model the step it announced it would use to read code
922
+ // (session e4a9d97a90: lone blind respond_general was force-stopped
923
+ // by the old halt-on-first rule and the agent never investigated).
924
+ // - a 2nd blind response with still no real work → narration loop,
925
+ // halt. In-step spam (80× in one generation) is bounded separately
926
+ // by RESPONSE_TOOL_SPAM_CAP — stopWhen only runs BETWEEN steps.
927
+ // Read from `state.steps` (the SDK's own per-step record) rather than
928
+ // the for-await consumer's `responseToolCalled` flag — stopWhen runs
929
+ // between steps and may evaluate before our consumer processed the
930
+ // tool-result part, so the flag would race.
931
+ const _steps = state.steps;
932
+ if (shouldHaltOnResponseTool(_steps))
933
+ return true;
934
+ const base = await _baseDynamicStopWhen(state);
935
+ if (base)
936
+ return true;
937
+ const next = incSessionStep(_ceilingSessionId);
938
+ // Telemetry-only: record the first time the counter crosses
939
+ // the matrix ceiling, so post-hoc queries can correlate the
940
+ // ceiling crossing with task completion outcomes. No halt.
941
+ if (next === _stepCeiling) {
942
+ try {
943
+ if (deps.session?.id) {
944
+ logInteraction(deps.session.id, "f6_synthesis", {
945
+ data: {
946
+ outcome: "ceiling_crossed_softly",
947
+ stepAtCrossing: next,
948
+ naturalCeiling: _naturalCeiling,
949
+ taskType: _ceilingTaskType,
950
+ size: _ceilingSize,
951
+ hardCapMaxToolRounds: deps.maxToolRounds,
952
+ },
953
+ });
954
+ }
955
+ }
956
+ catch {
957
+ /* telemetry only */
958
+ }
959
+ }
960
+ return false;
961
+ });
962
+ // BUG-A fix — when this turn carries an empty tool set (the
963
+ // chitchat optimization at line ~1107 drops all schemas), AI SDK
964
+ // sends `tools:[], tool_choice:undefined` to the provider. DeepSeek
965
+ // V4 Flash sees prior `tool_call`/`tool_result` parts still in the
966
+ // messages history (the previous turn used 20 tools) and the
967
+ // model stays in agent-mode — but with no schema to call, it
968
+ // falls back to its NATIVE DSML markup syntax and emits that as
969
+ // plain text. AI SDK does not parse the native format, so the
970
+ // markup leaks straight to the TUI as garbage and the turn
971
+ // produces no useful output. Setting `toolChoice:"none"` is the
972
+ // canonical way to tell the model "you cannot call tools this
973
+ // turn" so it emits text-only. Verified by stream_start telemetry
974
+ // on sessions 002df4014cb4 (leak) + fc19b4daee20 (leak): both had
975
+ // toolCount=0 + toolChoice=undefined on chitchat continuation.
976
+ const _toolsAreEmpty = Object.keys(tools).length === 0;
977
+ const _finalToolChoice = _toolsAreEmpty
978
+ ? "none"
979
+ : _hasResponseTools && turnCaps.supportsClientTools(runtime.modelInfo)
980
+ ? "auto"
981
+ : undefined;
982
+ // BUG-C telemetry — record tool availability + toolChoice at the
983
+ // call site so future regressions show up in telemetry not in TUI.
984
+ try {
985
+ const _toolNamesAtCall = Object.keys(tools);
986
+ logInteraction(deps.session?.id ?? "no-session", "stream_start", {
987
+ model: turnModelId,
988
+ data: {
989
+ toolCount: _toolNamesAtCall.length,
990
+ hasBash: _toolNamesAtCall.includes("bash"),
991
+ toolNames: _toolNamesAtCall.slice(0, 25),
992
+ toolChoice: _finalToolChoice ?? "undefined",
993
+ hasResponseTools: _hasResponseTools,
994
+ supportsClientTools: turnCaps.supportsClientTools(runtime.modelInfo),
995
+ priorTurnHadTools: _topMessagesForCall.some((m) => m?.role === "tool"),
996
+ },
997
+ });
998
+ }
999
+ catch {
1000
+ /* telemetry only */
1001
+ }
1002
+ // Silent-hang guard: abort the stream (and surface a toast in the
1003
+ // catch below) if the provider sends no chunk for too long. Re-armed
1004
+ // on every chunk via stall.pet(), so it never kills an actively
1005
+ // streaming call. Disposed when the stream ends or errors.
1006
+ stallTriggered = false;
1007
+ const stall = createStallWatchdog(getProviderStallTimeoutMs(), () => {
1008
+ stallTriggered = true;
1009
+ });
1010
+ const result = streamText({
1011
+ model: runtime.model,
1012
+ system: systemForModel,
1013
+ messages: _topMessagesForCall,
1014
+ tools,
1015
+ toolChoice: _finalToolChoice,
1016
+ stopWhen: stepRouterPhase === "phase1" ? stepCountIs(1) : dynamicStopWhen,
1017
+ maxRetries: 0,
1018
+ abortSignal: combineAbortSignals(signal, stall.signal),
1019
+ // Repair malformed tool-call JSON args before they bubble up as
1020
+ // InvalidToolInputError → tool-error → repetition-detector abort.
1021
+ // Conservative: only fixes the two observed Qwen-style defects.
1022
+ // See src/orchestrator/tool-args-repair.ts for the transforms.
1023
+ experimental_repairToolCall: repairToolCallHook,
1024
+ prepareStep: ({ stepNumber: sn, messages: stepMessages }) => {
1025
+ // A new step's provider request is about to go out — reset the
1026
+ // per-step chunk counter. Fires after the previous step's chunks
1027
+ // were counted (prepareStep runs post tool-execution), so if THIS
1028
+ // step's request wedges before any byte, chunksThisStep stays 0 and
1029
+ // the mid-loop dead-socket continuation can safely resume from here.
1030
+ chunksThisStep = 0;
1031
+ // --- Live-queue steering injection ---------------------------
1032
+ // Drain the UI steer queue ONCE per prepareStep call (sn >= 1),
1033
+ // accumulate into pendingSteers, and graft pendingSteers onto the
1034
+ // messages this step returns. Dedup-by-content makes re-appending
1035
+ // idempotent even if a stall-reprompt restart re-reads history.
1036
+ const withSteers = (r) => {
1037
+ // Guard the drain on !signal.aborted too: planSteerInjection
1038
+ // already refuses to inject on abort, but draining still CLEARS
1039
+ // the UI queue — so on a (programmatic) abort we must not drain,
1040
+ // or a queued-but-uninjected message is lost (spec §143).
1041
+ const _drained = sn >= 1 && steerEnabled && !signal.aborted ? (deps.drainSteerMessages?.() ?? []) : [];
1042
+ const _newSteers = planSteerInjection({
1043
+ drained: _drained,
1044
+ aborted: signal.aborted,
1045
+ enabled: steerEnabled,
1046
+ });
1047
+ if (_newSteers.length > 0) {
1048
+ pendingSteers.push(..._newSteers);
1049
+ deps.appendMidTurnMessages?.(_newSteers);
1050
+ try {
1051
+ const _ar = globalThis.__muonroiAgentRuntime;
1052
+ _ar?.emitEvent({
1053
+ t: "event",
1054
+ kind: "steer-inject",
1055
+ count: _newSteers.length,
1056
+ atStep: sn,
1057
+ runId: deps.getActiveRunId() ?? "",
1058
+ });
1059
+ }
1060
+ catch (emitErr) {
1061
+ console.error(`[message-processor] steer-inject telemetry failed: ${emitErr?.message}`);
1062
+ }
1063
+ }
1064
+ const baseRes = (() => {
1065
+ if (pendingSteers.length === 0)
1066
+ return r;
1067
+ const _base = r.messages ?? stepMessages;
1068
+ const _existingContents = new Set(_base
1069
+ .filter((m) => m.role === "user")
1070
+ .map((m) => (typeof m.content === "string" ? m.content : JSON.stringify(m.content))));
1071
+ const steersToAdd = pendingSteers.filter((s) => {
1072
+ const sContent = typeof s.content === "string" ? s.content : JSON.stringify(s.content);
1073
+ return !_existingContents.has(sContent);
1074
+ });
1075
+ if (steersToAdd.length === 0)
1076
+ return r;
1077
+ const insertIdx = _base.length;
1078
+ return {
1079
+ ...r,
1080
+ messages: [
1081
+ ..._base.slice(0, insertIdx),
1082
+ ...steersToAdd,
1083
+ ..._base.slice(insertIdx),
1084
+ ],
1085
+ };
1086
+ })();
1087
+ if (baseRes.messages) {
1088
+ baseRes.messages = applyAnthropicPromptCaching(baseRes.messages, runtime.modelId);
1089
+ }
1090
+ return baseRes;
1091
+ };
1092
+ const stripped = turnCaps.sanitizeHistory(stepMessages);
1093
+ // Agent-controlled veto (PRESERVE) or lighter selective keep (KEEP_TOOL_IDS) for this turn's B4 compaction.
1094
+ // PRESERVE_FULL_CONTEXT skips the compactor entirely (full history).
1095
+ // KEEP_TOOL_IDS: id1,id2 (from prior stub " (id=...) ") protects only those specific tool results
1096
+ // without the cost of a full veto. Parsed from reasoning or assistant note.
1097
+ let keepToolIds = [];
1098
+ const hasPreserve = stripped.some((m) => {
1099
+ const c = m?.content;
1100
+ const texts = [];
1101
+ if (typeof c === "string")
1102
+ texts.push(c);
1103
+ if (Array.isArray(c)) {
1104
+ for (const p of c)
1105
+ if (typeof p?.text === "string")
1106
+ texts.push(p.text);
1107
+ }
1108
+ const joined = texts.join(" ");
1109
+ if (joined.includes("PRESERVE_FULL_CONTEXT"))
1110
+ return true;
1111
+ // Idea 3: parse lighter token
1112
+ const mKeep = joined.match(/KEEP_TOOL_IDS\s*[:=]\s*([a-z0-9_, -]+)/i);
1113
+ if (mKeep) {
1114
+ keepToolIds = mKeep[1]
1115
+ .split(/[,\s]+/)
1116
+ .map((s) => s.trim())
1117
+ .filter(Boolean);
1118
+ }
1119
+ return false;
1120
+ });
1121
+ if (hasPreserve) {
1122
+ return withSteers({ messages: stripped });
1123
+ }
1124
+ // F2 — envelope = system prompt + JSON-Schema of every tool
1125
+ // re-sent on every step. Without this the threshold check
1126
+ // ignored 20-50K of fixed prompt overhead and the compactor
1127
+ // sat dormant just below its limit while billed input climbed.
1128
+ const envelopeChars = computeEnvelopeChars(systemForModel, tools);
1129
+ // G1 + G2 — feed the model's context window so the compactor
1130
+ // can pick a token-aware threshold and shrink keepLastTurns
1131
+ // when the window is approaching its ceiling.
1132
+ const contextWindowTokens = runtime.modelInfo?.contextWindow ?? 0;
1133
+ // Idea 4: fire-and-forget persist of elided tool outputs to EE (source=tool-artifact)
1134
+ // so later layer3/ee.query "tool-artifact id=xxx" or "full tool result id=..." can re-hydrate.
1135
+ // Use process-level fallbacks (prepareStep closure does not directly expose outer cwd/session in this scope).
1136
+ const _cwd = process.cwd();
1137
+ const _sess = undefined; // best-effort; EE artifact still indexable by content + meta.toolCallId
1138
+ const persistArtifact = (toolCallId, toolName, fullContent, reason) => {
1139
+ // Local-first: record the FULL output in-process so ee_query can
1140
+ // rehydrate it even if EE is down (the EE extract below caps at 8k
1141
+ // and needs the network; the cache keeps up to 200k, no network).
1142
+ recordArtifact(toolCallId, toolName, fullContent);
1143
+ // Lived-experience telemetry: count this elision so a later
1144
+ // "cảm nhận trong CLI" question answers from data, and so the
1145
+ // post-compaction note can list what it just stubbed.
1146
+ recordElision(toolCallId, toolName, fullContent.length, sn);
1147
+ try {
1148
+ getDefaultEEClient()
1149
+ .extract({
1150
+ transcript: fullContent.slice(0, 8000),
1151
+ projectPath: _cwd,
1152
+ meta: {
1153
+ source: "tool-artifact",
1154
+ toolCallId,
1155
+ toolName,
1156
+ reason,
1157
+ sessionId: _sess,
1158
+ elidedAtStep: sn,
1159
+ },
1160
+ }, AbortSignal.timeout(700))
1161
+ .catch(() => { });
1162
+ }
1163
+ catch {
1164
+ /* fail-open, no silent swallow of the decision */
1165
+ }
1166
+ };
1167
+ // T1.1 + T1.2 — reasoning models (DeepSeek V4 Flash, R1) emit 2K-5K
1168
+ // CoT tokens per turn that accumulate across the multi-step loop.
1169
+ // Strip old reasoning and compact earlier (ratio 0.3 vs 0.5) to
1170
+ // cut ~40-60% of cumulative input tokens.
1171
+ const isReasoningModel = runtime.modelInfo?.reasoning === true;
1172
+ const compacted = compactSubAgentMessages(stripped, {
1173
+ thresholdChars: topLevelCompactThreshold,
1174
+ // Rec #1 (cheap part): on meta/self-eval turns keep a couple more
1175
+ // trailing tool turns verbatim — those carry the reasoning the
1176
+ // agent is being asked to reflect on, and over-eliding them is
1177
+ // exactly what starves a self-evaluation. One boolean, no new
1178
+ // detection logic (isMetaAnalysisPrompt already gates layer3/5).
1179
+ keepLastTurns: topLevelCompactKeepLast + (isMetaAnalysisPrompt(userMessage) ? 2 : 0),
1180
+ label: "top-level",
1181
+ envelopeChars,
1182
+ contextWindowTokens,
1183
+ contextFillRatio: isReasoningModel ? 0.3 : undefined,
1184
+ keepToolIds: keepToolIds.length ? keepToolIds : undefined,
1185
+ persistArtifact,
1186
+ stripOldReasoning: isReasoningModel,
1187
+ });
1188
+ if (compacted !== stripped)
1189
+ recordCompaction(sn);
1190
+ // Pre-compaction visibility: give the agent one step of notice
1191
+ // before B4 actually rewrites history into stubs. This is the
1192
+ // advance warning that was missing — agent can now decide to
1193
+ // summarize, finish, or request preservation. Fires when we did
1194
+ // NOT compact this step (compacted === stripped, restored by the
1195
+ // compactSubAgentMessages no-op ref contract) AND the prompt is
1196
+ // approaching the threshold. Must compare CHARS (messages +
1197
+ // envelope), not stripped.length (a message count that never
1198
+ // exceeds a char-scaled threshold) — session 2b7a10219499.
1199
+ const _preWarnChars = cumulativeMessageChars(stripped) + envelopeChars;
1200
+ if (compacted === stripped && shouldPreWarnCompaction(_preWarnChars, topLevelCompactThreshold)) {
1201
+ const _cp = buildCheckpointReminder(sn, true);
1202
+ const _pre = `[pre-compaction warning at step ${sn} — next step(s) will likely rewrite older tool results to stubs (threshold ${topLevelCompactThreshold}, keepLast=${topLevelCompactKeepLast}). ${_cp} Summarize or finish if possible, or warn the user they can run the "/compact" command if they want a clean compressed history.]`;
1203
+ return withSteers({ messages: attachReminderToMessages(stripped, _pre) });
1204
+ }
1205
+ // Phase 4A — scope reminder injection (REQ-005).
1206
+ // Cadence K = 3/5/8 for small/medium/large. Soft-warn fires
1207
+ // ONCE per session at floor(ceiling*0.7). Reminder lives in
1208
+ // the tool_result/system channel so B3/B4 compaction cannot
1209
+ // strip it (system-prompt path is unsafe at high step counts).
1210
+ // Ceiling reuses the 4B (task_type × size) matrix result
1211
+ // resolved above (`_stepCeiling`, `_ceilingTaskType`,
1212
+ // `_ceilingSize`, `_ceilingSessionId`) so the reminder and the
1213
+ // halt boundary agree on the same number.
1214
+ const _scopeSize = _ceilingSize;
1215
+ const _scopeK = cadenceForSize(_scopeSize);
1216
+ const _scopeCeiling = Math.max(1, _stepCeiling ?? deps.maxToolRounds ?? 30);
1217
+ const _scopeStep = sn;
1218
+ const _shouldRemind = shouldInjectReminder(_scopeStep, _scopeK);
1219
+ const _shouldWarn = shouldInjectSoftWarn(_scopeStep, _scopeCeiling, _ceilingSessionId);
1220
+ // Phase 5 Fix 5 (revised) — past the natural matrix ceiling the
1221
+ // orchestrator emits a STRONG re-anchor reminder, but only when
1222
+ // (a) crossing the ceiling for the first time (one-shot), OR
1223
+ // (b) hitting a normal cadence step (multiple of K).
1224
+ // Original Phase 5 Fix 5 fired on EVERY step past ceiling, which
1225
+ // on long-running sessions (e.g. step 77 / ceiling 6 in session
1226
+ // 1f29e238a816) produced 70+ redundant reminders that bloated
1227
+ // the tool_result channel and forced the model into a "YES still
1228
+ // on scope" loop on every tool call.
1229
+ const _pastNaturalCeiling = _scopeStep > _naturalCeiling;
1230
+ const _justCrossedCeiling = shouldInjectCeilingCrossing(_scopeStep, _naturalCeiling, _ceilingSessionId);
1231
+ const _pastCeilingAtCadence = _pastNaturalCeiling && _shouldRemind;
1232
+ // Fix #8 — self-repetition one-shot. Fires when the assistant
1233
+ // has opened the last 3 streamText steps with the same 4-word
1234
+ // phrase (e.g. "YES still on scope" — session 1f29e238a816
1235
+ // emitted 15 such bursts past ceiling). Reminder is attached
1236
+ // alongside (and before) any scope reminder so the model sees
1237
+ // the behavioural correction first.
1238
+ const _shouldRepeatReminder = shouldInjectRepetitionReminder(_ceilingSessionId);
1239
+ if (_shouldRemind || _shouldWarn || _justCrossedCeiling || _shouldRepeatReminder) {
1240
+ const _baseReminder = buildScopeReminder({
1241
+ step: _scopeStep,
1242
+ ceiling: _scopeCeiling,
1243
+ taskType: _ceilingTaskType,
1244
+ size: _scopeSize,
1245
+ originalPrompt: userMessage,
1246
+ });
1247
+ // Strong "past natural budget" prefix only applies when we
1248
+ // ACTUALLY want the model to consider wrapping up — i.e. on
1249
+ // the crossing event or at a cadence step past ceiling, not
1250
+ // on every silent step in between.
1251
+ const _useStrong = _justCrossedCeiling || _pastCeilingAtCadence;
1252
+ const _scopePart = _shouldRemind || _shouldWarn || _justCrossedCeiling
1253
+ ? _useStrong
1254
+ ? `[past natural budget — step ${_scopeStep}/${_naturalCeiling}] If task is COMPLETE, emit final answer NOW. If you need to keep working in this long session, suggest that the user run the "/compact" slash command to compress the conversation history before continuing. Otherwise, simplify the next step. ${_baseReminder}`
1255
+ : _shouldWarn
1256
+ ? `[approaching ceiling] ${_baseReminder}`
1257
+ : _baseReminder
1258
+ : null;
1259
+ const _reminder = _shouldRepeatReminder
1260
+ ? _scopePart
1261
+ ? `${buildRepetitionReminder(_ceilingSessionId)}\n${_scopePart}`
1262
+ : buildRepetitionReminder(_ceilingSessionId)
1263
+ : _scopePart;
1264
+ const withReminder = attachReminderToMessages(compacted, _reminder);
1265
+ return withSteers({ messages: withReminder });
1266
+ }
1267
+ if (compacted === stripped && stripped === stepMessages)
1268
+ return withSteers({});
1269
+ // Self-awareness note: tell the model compaction happened so it
1270
+ // knows earlier context was elided and can adjust its behavior.
1271
+ // Enhanced per EE anti-mù plan (docs/ee-anti-mu-compaction-plan.md Phase 2): include proactive
1272
+ // "task finished?", "compacted yet?", "EE checkpoint" so agent can self-assess and avoid mù
1273
+ // even when the top-level summary is not in its immediate focus (sub-agents, long loops).
1274
+ const _compactNote = compacted !== stripped
1275
+ ? (() => {
1276
+ // Rec #2: turn the generic "high-value elided? use ee_query"
1277
+ // prose into a concrete, actionable manifest of what was just
1278
+ // stubbed (id/tool/size) — sourced from the elisions recorded
1279
+ // by persistArtifact above — so the rehydrate round-trip is
1280
+ // informed, not blind.
1281
+ const _m = formatElisionManifest();
1282
+ return `[context compacted at step ${sn} — older or low-value tool results rewritten to stubs to fit budget. High-value evidence (file reads, bash, your previous responses) is kept verbatim. ${buildCheckpointReminder(sn, true)}${_m ? ` ${_m}` : ""}]`;
1283
+ })()
1284
+ : null;
1285
+ if (_compactNote) {
1286
+ return withSteers({ messages: attachReminderToMessages(compacted, _compactNote) });
1287
+ }
1288
+ return withSteers({ messages: compacted });
1289
+ },
1290
+ ...(dropParam("temperature") ? {} : { temperature: 0.7 }),
1291
+ ...(dropParam("maxOutputTokens") ? {} : { maxOutputTokens: taskTypeToMaxTokens(pilCtx.taskType) }),
1292
+ ...(Object.keys(providerOpts).length > 0 ? { providerOptions: providerOpts } : {}),
1293
+ experimental_onStepStart: (event) => {
1294
+ stepNumber = getStepNumber(event, stepNumber + 1);
1295
+ notifyObserver(observer?.onStepStart, {
1296
+ stepNumber,
1297
+ timestamp: Date.now(),
1298
+ });
1299
+ },
1300
+ onStepFinish: (event) => {
1301
+ const currentStep = getStepNumber(event, Math.max(stepNumber, 0));
1302
+ stepNumber = Math.max(stepNumber, currentStep);
1303
+ const stepUsage = getUsage(event);
1304
+ notifyObserver(observer?.onStepFinish, {
1305
+ stepNumber: currentStep,
1306
+ timestamp: Date.now(),
1307
+ finishReason: getFinishReason(event),
1308
+ usage: stepUsage,
1309
+ });
1310
+ // Realtime status bar update per step
1311
+ if (stepUsage.inputTokens || stepUsage.outputTokens) {
1312
+ // O1 — thread THIS turn's providerOptions shape per step so every
1313
+ // step event records it (not just step 1) and an interleaved task
1314
+ // can't overwrite it. Mirrors the gate used for the call itself.
1315
+ deps.recordUsage(stepUsage, "message", runtime.modelId, Object.keys(providerOpts).length > 0 ? extractProviderOptionsShape(providerOpts) : null);
1316
+ }
1317
+ // Fix #8 — feed the assistant text emitted in this step into
1318
+ // the self-repetition detector. The slice covers everything
1319
+ // appended to `assistantText` since the previous step boundary;
1320
+ // a step with no text (pure tool call) records as empty, which
1321
+ // recordAssistantBurst treats as a no-op so the current run is
1322
+ // preserved across tool interludes.
1323
+ const _stepText = assistantText.slice(_assistantTextAtLastStep);
1324
+ _assistantTextAtLastStep = assistantText.length;
1325
+ recordAssistantBurst(_ceilingSessionId, _stepText);
1326
+ },
1327
+ onFinish: ({ finishReason }) => {
1328
+ _lastFinishReason = finishReason ?? null;
1329
+ // Task 2.6b — emit llm-done (agent-mode only).
1330
+ try {
1331
+ const _ar = globalThis.__muonroiAgentRuntime;
1332
+ _ar?.emitEvent({
1333
+ t: "event",
1334
+ kind: "llm-done",
1335
+ correlationId: _topCallId,
1336
+ totalChars: assistantText.length,
1337
+ finishReason: finishReason ?? "stop",
1338
+ });
1339
+ }
1340
+ catch (err) {
1341
+ console.error("[Agent:onFinish] failed to emit llm-done", err);
1342
+ }
1343
+ deps.setCurrentCallId("");
1344
+ // Rec #1 persisted forensics: onFinish fires once per top-level turn,
1345
+ // so flush this session's cumulative experience counts here. Readers
1346
+ // take the latest row per session, so the last turn's row is the
1347
+ // session total. No-ops on missing id / all-zero. Fail-open.
1348
+ try {
1349
+ persistSessionExperience(deps.session?.id ?? null, getSessionExperienceCounts());
1350
+ }
1351
+ catch (err) {
1352
+ console.error("[Agent:onFinish] persistSessionExperience failed", err);
1353
+ }
1354
+ },
1355
+ });
1356
+ let _topTokenIndex = 0;
1357
+ const _wireProviderIdTop = runtime.modelInfo?.provider ?? "unknown";
1358
+ for await (const part of result.fullStream) {
1359
+ stall.pet(); // chunk arrived — reset the stall watchdog
1360
+ // Count only real content parts. The watchdog abort itself surfaces
1361
+ // as an "abort" part — counting it would defeat the TTFB-stall gate
1362
+ // (a frozen-before-first-byte stall yields ONLY the abort part).
1363
+ if (part.type !== "abort") {
1364
+ chunksThisAttempt++;
1365
+ chunksThisStep++;
1366
+ }
1367
+ if (signal.aborted) {
1368
+ yield { type: "content", content: "\n\n[Cancelled]" };
1369
+ break;
1370
+ }
1371
+ if (wireDebug.enabled) {
1372
+ wireDebug.logChunk(_wireProviderIdTop, String(part.type ?? "unknown"), {
1373
+ hasText: typeof part.text === "string"
1374
+ ? part.text.length
1375
+ : undefined,
1376
+ hasReasoning: typeof part.reasoning === "string"
1377
+ ? part.reasoning.length
1378
+ : undefined,
1379
+ });
1380
+ if (part.type === "error") {
1381
+ wireDebug.logError(_wireProviderIdTop, part.error);
1382
+ }
1383
+ }
1384
+ switch (part.type) {
1385
+ case "text-delta":
1386
+ assistantText += part.text;
1387
+ // Task 2.6b — emit llm-token (agent-mode only; high-volume, default-off per Phase 4).
1388
+ try {
1389
+ const _ar = globalThis.__muonroiAgentRuntime;
1390
+ _ar?.emitEvent({
1391
+ t: "event",
1392
+ kind: "llm-token",
1393
+ correlationId: _topCallId,
1394
+ delta: part.text,
1395
+ tokenIndex: _topTokenIndex++,
1396
+ });
1397
+ }
1398
+ catch {
1399
+ /* best-effort */
1400
+ }
1401
+ yield { type: "content", content: part.text };
1402
+ break;
1403
+ case "reasoning-delta":
1404
+ reasoningPreview = `${reasoningPreview}${part.text}`.slice(-256);
1405
+ if (containsEncryptedReasoning(reasoningPreview)) {
1406
+ if (!encryptedReasoningHidden) {
1407
+ encryptedReasoningHidden = true;
1408
+ yield { type: "reasoning", content: "[Encrypted reasoning hidden]" };
1409
+ }
1410
+ break;
1411
+ }
1412
+ // P0 native observation: accumulate reasoning for intent context.
1413
+ deps.appendTurnAssistantReasoning(part.text);
1414
+ yield { type: "reasoning", content: part.text };
1415
+ break;
1416
+ case "tool-call": {
1417
+ const tc = toToolCall(part);
1418
+ activeToolCalls.push(tc);
1419
+ // SAMR: track that Phase 1 produced tool calls → transition to Phase 2
1420
+ if (stepRouterPhase === "phase1")
1421
+ phase1HadToolCalls = true;
1422
+ // Response tool = the terminal final answer (identity execute;
1423
+ // the payload lives in the call args). Buffer it (longest-wins)
1424
+ // straight from the args and gate UI/DB/exec spam: cheap models
1425
+ // sometimes emit the response tool MANY times in ONE generation
1426
+ // (session 8d8f498268ed: 80× identical respond_general hedge in
1427
+ // one step). stopWhen only halts BETWEEN steps, so it can't stop
1428
+ // an in-step spam — this does. Surface only the first indicator;
1429
+ // if the model spams past the cap, finalize NOW with the
1430
+ // buffered answer instead of streaming out the degenerate step.
1431
+ if (isResponseTool(tc.function.name)) {
1432
+ _responseToolEmitCount += 1;
1433
+ try {
1434
+ const _payload = JSON.parse(tc.function.arguments || "{}");
1435
+ const _len = JSON.stringify(_payload).length;
1436
+ if (_len > _pendingStructuredResponseLen) {
1437
+ _pendingStructuredResponseLen = _len;
1438
+ _pendingStructuredResponse = {
1439
+ taskType: getResponseTaskType(tc.function.name) ?? tc.function.name,
1440
+ data: _payload,
1441
+ };
1442
+ }
1443
+ }
1444
+ catch {
1445
+ /* keep the prior buffered payload */
1446
+ }
1447
+ responseToolCalled = true;
1448
+ // Only the first response-tool call gets a UI indicator.
1449
+ if (_responseToolEmitCount === 1) {
1450
+ yield { type: "tool_calls", toolCalls: [tc] };
1451
+ }
1452
+ if (_responseToolEmitCount >= RESPONSE_TOOL_SPAM_CAP && _pendingStructuredResponse) {
1453
+ if (deps.session) {
1454
+ try {
1455
+ logInteraction(deps.session.id, "f6_synthesis", {
1456
+ eventSubtype: "response_tool_spam_abort",
1457
+ data: { emitted: _responseToolEmitCount, keptChars: _pendingStructuredResponseLen },
1458
+ });
1459
+ }
1460
+ catch {
1461
+ /* telemetry best-effort */
1462
+ }
1463
+ }
1464
+ // Persist a clean turn (user + the single buffered answer)
1465
+ // so history stays usable; the spam is dropped. Mirrors the
1466
+ // tool-repetition abort: yield + done + return (do NOT await
1467
+ // result.response — the stream is still spewing calls).
1468
+ const _data = _pendingStructuredResponse.data;
1469
+ const _answerText = typeof _data.response === "string"
1470
+ ? _data.response
1471
+ : JSON.stringify(_pendingStructuredResponse.data);
1472
+ try {
1473
+ deps.appendCompletedTurn(userModelMessage, [
1474
+ { role: "assistant", content: _answerText },
1475
+ ]);
1476
+ }
1477
+ catch (persistErr) {
1478
+ console.error(`[message-processor] response-tool-spam persist failed: ${persistErr?.message}`);
1479
+ }
1480
+ yield {
1481
+ type: "structured_response",
1482
+ structuredResponse: _pendingStructuredResponse,
1483
+ };
1484
+ yield { type: "done" };
1485
+ return;
1486
+ }
1487
+ break; // response tools skip write-ahead/hooks/normal tool_calls yield
1488
+ }
1489
+ // EE PreToolUse hook: fire intercept before tool execution.
1490
+ {
1491
+ const turnAssistantReasoning = deps.getTurnAssistantReasoning();
1492
+ const intentContext = {
1493
+ ...(turnAssistantReasoning ? { assistantReasoningExcerpt: turnAssistantReasoning.slice(-200) } : {}),
1494
+ ...(deps.priorWarningIdsInSession?.size > 0
1495
+ ? {
1496
+ priorWarningIdsInSession: Array.from(deps.priorWarningIdsInSession).slice(-20),
1497
+ }
1498
+ : {}),
1499
+ ...(pilCtx.gsdPhase ? { gsdPhase: pilCtx.gsdPhase } : {}),
1500
+ ...(userMessage.slice(0, 200) ? { userGoalExcerpt: userMessage.slice(0, 200) } : {}),
1501
+ };
1502
+ const preInput = {
1503
+ hook_event_name: "PreToolUse",
1504
+ tool_name: tc.function.name,
1505
+ tool_input: JSON.parse(tc.function.arguments || "{}"),
1506
+ session_id: deps.session?.id,
1507
+ cwd: deps.bash.getCwd(),
1508
+ ...(Object.keys(intentContext).length > 0 ? { intent_context: intentContext } : {}),
1509
+ };
1510
+ const preResult = await deps.fireHook(preInput, signal).catch(() => ({
1511
+ blocked: false,
1512
+ blockingErrors: [],
1513
+ preventContinuation: false,
1514
+ additionalContexts: [],
1515
+ results: [],
1516
+ eeMatches: [],
1517
+ }));
1518
+ for (const ctx of preResult.additionalContexts ?? []) {
1519
+ yield { type: "content", content: `${ctx}\n` };
1520
+ }
1521
+ // Store structured EE matches for session guidance injection on next turn.
1522
+ for (const m of preResult.eeMatches ?? []) {
1523
+ deps.sessionEEGuidance.set(m.id, {
1524
+ toolName: m.toolName,
1525
+ message: m.message,
1526
+ why: m.why,
1527
+ confidence: m.confidence,
1528
+ });
1529
+ // Cap at 30 entries — oldest first, trim when exceeded.
1530
+ if (deps.sessionEEGuidance.size > 30) {
1531
+ const firstKey = deps.sessionEEGuidance.keys().next().value;
1532
+ if (firstKey !== undefined)
1533
+ deps.sessionEEGuidance.delete(firstKey);
1534
+ }
1535
+ }
1536
+ // P0 native observation: track which principle IDs surfaced
1537
+ // this turn so the next intercept can dedup server-side.
1538
+ try {
1539
+ const { getLastSurfacedState } = await import("../ee/intercept.js");
1540
+ const { surfacedIds } = getLastSurfacedState();
1541
+ for (const id of surfacedIds)
1542
+ deps.priorWarningIdsInSession.add(id);
1543
+ // Cap memory: keep only most-recent 100 IDs.
1544
+ if (deps.priorWarningIdsInSession.size > 100) {
1545
+ const arr = Array.from(deps.priorWarningIdsInSession);
1546
+ deps.setPriorWarningIdsInSession(new Set(arr.slice(-100)));
1547
+ }
1548
+ }
1549
+ catch {
1550
+ /* fail-open */
1551
+ }
1552
+ }
1553
+ // Pitfall 9: log the pending call so reconcile() can recover any
1554
+ // staged .tmp files if the process is killed before tool-result.
1555
+ if (deps.pendingCalls) {
1556
+ const turnId = deps.session?.id ?? "anon";
1557
+ const callId = stableCallId(turnId, tc.function.name, tc.function.arguments);
1558
+ // Phase 0: predictStagedPaths = [] for all tools (refined in Phase 1).
1559
+ void deps.pendingCalls.begin({ call_id: callId, tool_name: tc.function.name }).catch(() => { });
1560
+ // Attach callId to the ToolCall so tool-result can end it.
1561
+ tc._pendingCallId = callId;
1562
+ }
1563
+ // Phase A4: write-ahead persistence — insert a pending row into
1564
+ // tool_calls BEFORE executing the tool. If the stream throws
1565
+ // mid-call (e.g. provider 5xx, abort, network drop), this row
1566
+ // remains as `pending` so `usage forensics` can show the args
1567
+ // the model passed. The post-stream appendMessages() path
1568
+ // (INSERT OR IGNORE + UPDATE) will finalize this row to
1569
+ // `completed` once the turn settles normally.
1570
+ if (deps.sessionStore && deps.session) {
1571
+ // Predicted assistant seq: user message + assistant message
1572
+ // are appended atomically by appendCompletedTurn().
1573
+ // getNextMessageSequence() returns the seq the user message
1574
+ // will get; the assistant message is the next one after.
1575
+ let predictedSeq = -1;
1576
+ try {
1577
+ predictedSeq = getNextMessageSequence(deps.session.id) + 1;
1578
+ }
1579
+ catch {
1580
+ /* fail-open — leave predictedSeq=-1; post-stream UPDATE corrects it */
1581
+ }
1582
+ persistToolCallWriteAhead(deps.session.id, predictedSeq, tc.id, tc.function.name, tc.function.arguments || "{}");
1583
+ }
1584
+ notifyObserver(observer?.onToolStart, {
1585
+ toolCall: tc,
1586
+ timestamp: Date.now(),
1587
+ });
1588
+ // Interaction log: tool call start
1589
+ try {
1590
+ if (deps.session) {
1591
+ logInteraction(deps.session.id, "tool_call", {
1592
+ eventSubtype: tc.function.name,
1593
+ data: {
1594
+ toolCallId: tc.id,
1595
+ argsPreview: tc.function.arguments.slice(0, 200),
1596
+ },
1597
+ });
1598
+ }
1599
+ }
1600
+ catch {
1601
+ /* fail-open */
1602
+ }
1603
+ yield { type: "tool_calls", toolCalls: [tc] };
1604
+ break;
1605
+ }
1606
+ case "tool-result": {
1607
+ const tc = {
1608
+ id: part.toolCallId,
1609
+ type: "function",
1610
+ function: { name: part.toolName, arguments: JSON.stringify(part.input ?? {}) },
1611
+ };
1612
+ let tr = toToolResult(part.output);
1613
+ // Vision Bridge: proxy image-bearing tool results for text-only models (any tool, not just MCP)
1614
+ try {
1615
+ const bridgeResult = await bridgeMcpToolResult(part.toolName, tr.output, turnModelId, signal, part.toolCallId);
1616
+ if (bridgeResult.proxied) {
1617
+ tr = {
1618
+ ...tr,
1619
+ output: typeof bridgeResult.output === "string"
1620
+ ? bridgeResult.output
1621
+ : JSON.stringify(bridgeResult.output),
1622
+ };
1623
+ yield { type: "content", content: `[Vision Bridge: image → text for ${turnModelId}]\n` };
1624
+ }
1625
+ }
1626
+ catch (err) {
1627
+ console.error("[Agent:visionBridge] failed to process image for tool result", err);
1628
+ }
1629
+ // Safety-block intercept: when bash.execute returns a
1630
+ // "BLOCKED (...):" error, surface an askcard to the user via
1631
+ // deps.askSafetyOverride. If allowed, rewrite the output as a
1632
+ // success so the model knows the command was approved (it may
1633
+ // retry on the next turn). The approved command is stored in
1634
+ // the global __muonroiSafetyApproved map so registry.ts's
1635
+ // bash.execute bypasses the block on the retry.
1636
+ const _outputText = [tr.output, tr.error].filter((x) => typeof x === "string").join("\n");
1637
+ const _blockMatch = _outputText.match(/^BLOCKED \(([^)]+)\):\s*(.*)/);
1638
+ if (_blockMatch && part.toolName === "bash") {
1639
+ const _blockKind = _blockMatch[1];
1640
+ const _blockReason = _blockMatch[2];
1641
+ const _command = typeof part.input === "object" && part.input != null
1642
+ ? String(part.input.command ?? "")
1643
+ : "";
1644
+ // empty-bash: auto-block without askcard.
1645
+ // The BLOCKED error from registry.ts already steers the agent
1646
+ // to self-correct. Showing an askcard adds user friction for
1647
+ // no benefit (empty bash calls are never intentional) and
1648
+ // wastes a turn of user interaction per strike.
1649
+ if (_blockKind === "empty-bash") {
1650
+ tr = { ...tr, success: false, error: _outputText, output: _outputText };
1651
+ }
1652
+ else {
1653
+ const _verdict = deps.askSafetyOverride
1654
+ ? await deps.askSafetyOverride({
1655
+ kind: _blockKind,
1656
+ toolName: part.toolName,
1657
+ blockedItem: _command,
1658
+ reason: _blockReason,
1659
+ source: "bash.execute",
1660
+ })
1661
+ : { action: "block" };
1662
+ if (_verdict.action === "allow-once" || _verdict.action === "allow-session") {
1663
+ // Store approval so registry.ts can bypass the block on retry.
1664
+ const _globalSafety = globalThis;
1665
+ if (!_globalSafety.__muonroiSafetyApproved) {
1666
+ _globalSafety.__muonroiSafetyApproved = new Map();
1667
+ }
1668
+ _globalSafety.__muonroiSafetyApproved.set(part.toolCallId, {
1669
+ kind: _verdict.action === "allow-session" ? "session" : "once",
1670
+ command: _command,
1671
+ });
1672
+ // Rewrite tool result as success so the stream continues
1673
+ // without an error. The model will see "Approved: ..." and
1674
+ // may retry the tool call on the next turn, at which point
1675
+ // registry.ts will see the approval and actually run it.
1676
+ tr = { ...tr, success: true, output: `Approved (${_verdict.action}): ${_blockReason}` };
1677
+ yield {
1678
+ type: "content",
1679
+ content: `[User approved blocked command: ${_blockKind} — ${_verdict.action}]\n`,
1680
+ };
1681
+ }
1682
+ if (_verdict.action === "block") {
1683
+ tr = { ...tr, success: false, error: _outputText, output: _outputText };
1684
+ }
1685
+ }
1686
+ }
1687
+ // Capture into the stall-rescue digest before any further
1688
+ // processing — if the stream stalls after this, these outputs
1689
+ // are all we have to synthesize a final answer from.
1690
+ pushStallToolResult(turnToolResults, part.toolName, typeof tr.output === "string" ? tr.output : JSON.stringify(tr.output));
1691
+ // Pitfall 9: settle the pending call log entry.
1692
+ if (deps.pendingCalls) {
1693
+ const pending = activeToolCalls.find((t) => t.id === part.toolCallId);
1694
+ const callId = pending?._pendingCallId;
1695
+ if (callId) {
1696
+ const endStatus = signal.aborted ? "aborted" : "settled";
1697
+ void deps.pendingCalls.end(callId, endStatus).catch(() => { });
1698
+ }
1699
+ }
1700
+ // EE PostToolUse hook: fire-and-forget after tool execution.
1701
+ {
1702
+ const postInput = {
1703
+ hook_event_name: "PostToolUse",
1704
+ tool_name: part.toolName,
1705
+ tool_input: part.input ?? {},
1706
+ tool_output: typeof tr.output === "string"
1707
+ ? { text: tr.output }
1708
+ : (tr.output ?? {}),
1709
+ session_id: deps.session?.id,
1710
+ cwd: deps.bash.getCwd(),
1711
+ };
1712
+ await deps.fireHook(postInput, signal).catch((err) => {
1713
+ console.error("[Agent:PostToolUse hook] failed", err);
1714
+ });
1715
+ }
1716
+ // Response tool: yield as structured_response instead of tool_result.
1717
+ // AI SDK v5 wraps tool outputs as `{type:"json", value:{...}}`; unwrap
1718
+ // to expose the schema-shaped payload to the UI renderer.
1719
+ if (isResponseTool(part.toolName)) {
1720
+ responseToolCalled = true;
1721
+ // Payload was already buffered (longest-wins) from the
1722
+ // tool-CALL args above; re-buffer from the executed result as
1723
+ // a fallback (unwraps the AI-SDK `{type:"json",value}` shape).
1724
+ // Counting + the spam cap live in the tool-call branch.
1725
+ const taskType = getResponseTaskType(part.toolName);
1726
+ const rawOutput = part.output;
1727
+ const unwrapped = rawOutput && typeof rawOutput === "object" && rawOutput.type === "json"
1728
+ ? (rawOutput.value ?? {})
1729
+ : (rawOutput ?? {});
1730
+ const _len = JSON.stringify(unwrapped ?? {}).length;
1731
+ if (_len > _pendingStructuredResponseLen) {
1732
+ _pendingStructuredResponseLen = _len;
1733
+ _pendingStructuredResponse = {
1734
+ taskType: taskType ?? part.toolName,
1735
+ data: unwrapped,
1736
+ };
1737
+ }
1738
+ notifyObserver(observer?.onToolFinish, { toolCall: tc, toolResult: tr, timestamp: Date.now() });
1739
+ break;
1740
+ }
1741
+ notifyObserver(observer?.onToolFinish, {
1742
+ toolCall: tc,
1743
+ toolResult: tr,
1744
+ timestamp: Date.now(),
1745
+ });
1746
+ // Interaction log: tool result.
1747
+ // Phase 5 BUG-J — for edit/write/update tools, persist the
1748
+ // structured diff (file_path, +N/-M counts, isNew flag, and
1749
+ // a bounded patch preview) so forensics queries can audit
1750
+ // what actually changed in each turn without re-reading
1751
+ // git history. Earlier the log only had the summary string
1752
+ // ("Edited X (+1 -1)") — the patch text was lost.
1753
+ try {
1754
+ if (deps.session) {
1755
+ const outputPreview = typeof tr.output === "string" ? tr.output.slice(0, 200) : JSON.stringify(tr.output).slice(0, 200);
1756
+ const _trWithDiff = tr;
1757
+ const diffMeta = _trWithDiff.diff &&
1758
+ (tc.function.name === "edit_file" ||
1759
+ tc.function.name === "write_file" ||
1760
+ tc.function.name === "update_file")
1761
+ ? {
1762
+ filePath: _trWithDiff.diff.filePath,
1763
+ additions: _trWithDiff.diff.additions,
1764
+ removals: _trWithDiff.diff.removals,
1765
+ isNew: _trWithDiff.diff.isNew,
1766
+ // Cap at 4000 chars — enough to inspect small/medium
1767
+ // edits without ballooning the SQLite row. Large
1768
+ // refactors get truncated with a tail marker so
1769
+ // readers know the patch is partial.
1770
+ patchPreview: _trWithDiff.diff.patch.length > 4000
1771
+ ? `${_trWithDiff.diff.patch.slice(0, 4000)}\n…[truncated]`
1772
+ : _trWithDiff.diff.patch,
1773
+ }
1774
+ : undefined;
1775
+ logInteraction(deps.session.id, "tool_result", {
1776
+ eventSubtype: tc.function.name,
1777
+ data: { success: tr.success, outputPreview, ...(diffMeta ? { diff: diffMeta } : {}) },
1778
+ });
1779
+ }
1780
+ }
1781
+ catch {
1782
+ /* fail-open */
1783
+ }
1784
+ yield { type: "tool_result", toolCall: tc, toolResult: tr };
1785
+ // Reset tool-repetition counter on any non-error result. A
1786
+ // successful call between two failures of the same shape is
1787
+ // progress and should not accumulate toward the abort gate.
1788
+ if (tr.success) {
1789
+ recordToolRepetitionSuccess(deps.session?.id ?? null);
1790
+ }
1791
+ // todo_write side-effect: surface the task list to the UI via a
1792
+ // dedicated chunk so the sticky checklist panel can re-render
1793
+ // without parsing tool args itself. Skipped when the snapshot
1794
+ // doesn't parse (malformed args) so the UI is never poisoned.
1795
+ if (tc.function.name === "todo_write" && tr.success) {
1796
+ const snap = snapshotFromTodoWriteArgs(tc.function.arguments);
1797
+ if (snap)
1798
+ yield { type: "task_list_update", taskListSnapshot: snap };
1799
+ }
1800
+ break;
1801
+ }
1802
+ case "tool-error": {
1803
+ // AI SDK emits this when tool execution throws/aborts before
1804
+ // producing a tool-result. Without this branch, the tool_call
1805
+ // log row has no matching tool_result and the EE judge never
1806
+ // sees the failure → silent ~1.6% pairing leak in prod DB.
1807
+ const errPart = part;
1808
+ const tc = {
1809
+ id: errPart.toolCallId,
1810
+ type: "function",
1811
+ function: { name: errPart.toolName, arguments: JSON.stringify(errPart.input ?? {}) },
1812
+ };
1813
+ const errMsg = errPart.error instanceof Error
1814
+ ? errPart.error.message
1815
+ : typeof errPart.error === "string"
1816
+ ? errPart.error
1817
+ : JSON.stringify(errPart.error);
1818
+ const tr = { success: false, output: `[tool-error] ${errMsg}` };
1819
+ // A respond_* (response) tool that ERRORED still carries the
1820
+ // model's terminal answer in its call args — for response tools
1821
+ // execution is identity, so an execution failure is usually a
1822
+ // post-processing issue and the payload is intact. Recover it so
1823
+ // the turn is not left empty (textLength:0) and the answer is not
1824
+ // swallowed on turn-finalize. Mirrors the tool-call / tool-result
1825
+ // buffering above.
1826
+ if (isResponseTool(errPart.toolName)) {
1827
+ if (!_pendingStructuredResponse && errPart.input && typeof errPart.input === "object") {
1828
+ const data = errPart.input;
1829
+ const _len = JSON.stringify(data).length;
1830
+ if (_len > _pendingStructuredResponseLen) {
1831
+ _pendingStructuredResponseLen = _len;
1832
+ _pendingStructuredResponse = {
1833
+ taskType: getResponseTaskType(errPart.toolName) ?? errPart.toolName,
1834
+ data,
1835
+ };
1836
+ }
1837
+ }
1838
+ if (!_pendingStructuredResponse) {
1839
+ // Nothing recoverable (args never parsed). Do NOT suppress F6
1840
+ // synthesis — let it produce a visible prose answer instead
1841
+ // of an empty turn.
1842
+ responseToolCalled = false;
1843
+ }
1844
+ }
1845
+ // Settle pending-call ledger so we don't leak stale .tmp files.
1846
+ if (deps.pendingCalls) {
1847
+ const pending = activeToolCalls.find((t) => t.id === errPart.toolCallId);
1848
+ const callId = pending?._pendingCallId;
1849
+ if (callId)
1850
+ void deps.pendingCalls.end(callId, "settled").catch(() => { });
1851
+ }
1852
+ // Phase A4: mark the write-ahead tool_calls row as `errored`.
1853
+ // The post-stream appendMessages() path does NOT see tool-error
1854
+ // parts in the assistant message content (the SDK doesn't emit
1855
+ // them there), so without this explicit update the row would
1856
+ // remain `pending` after a clean tool failure.
1857
+ if (deps.session) {
1858
+ markToolCallErrored(deps.session.id, errPart.toolCallId, errMsg);
1859
+ }
1860
+ // Fire PostToolUseFailure so EE judge can record IGNORED outcome.
1861
+ {
1862
+ const failInput = {
1863
+ hook_event_name: "PostToolUseFailure",
1864
+ tool_name: errPart.toolName,
1865
+ tool_input: errPart.input ?? {},
1866
+ error: errMsg,
1867
+ session_id: deps.session?.id,
1868
+ cwd: deps.bash.getCwd(),
1869
+ };
1870
+ await deps.fireHook(failInput, signal).catch(() => { });
1871
+ }
1872
+ try {
1873
+ if (deps.session) {
1874
+ logInteraction(deps.session.id, "tool_result", {
1875
+ eventSubtype: errPart.toolName,
1876
+ data: { success: false, error: errMsg.slice(0, 500), reason: "tool-error" },
1877
+ });
1878
+ }
1879
+ }
1880
+ catch (logErr) {
1881
+ console.error(`[message-processor] interaction-log tool_result failed: ${logErr?.message}`);
1882
+ }
1883
+ notifyObserver(observer?.onToolFinish, { toolCall: tc, toolResult: tr, timestamp: Date.now() });
1884
+ yield { type: "tool_result", toolCall: tc, toolResult: tr };
1885
+ // Tool-call perseveration guard. After N consecutive identical
1886
+ // (toolName, args, error) triples, abort the streaming loop
1887
+ // before TPM rate limits do (session 080fe2fcbf24).
1888
+ const repetition = recordToolRepetitionError(deps.session?.id ?? null, errPart.toolName, errPart.input, errMsg);
1889
+ if (repetition.shouldAbort) {
1890
+ const abortMsg = buildToolRepetitionAbortMessage(errPart.toolName, repetition.runLength, errMsg);
1891
+ try {
1892
+ if (deps.session) {
1893
+ logInteraction(deps.session.id, "error", {
1894
+ eventSubtype: "tool_repetition_abort",
1895
+ data: {
1896
+ toolName: errPart.toolName,
1897
+ runLength: repetition.runLength,
1898
+ errorPreview: errMsg.slice(0, 200),
1899
+ },
1900
+ });
1901
+ }
1902
+ }
1903
+ catch (logErr) {
1904
+ console.error(`[message-processor] interaction-log tool_repetition_abort failed: ${logErr?.message}`);
1905
+ }
1906
+ notifyObserver(observer?.onError, { message: abortMsg, timestamp: Date.now() });
1907
+ yield { type: "error", content: abortMsg, isAuthError: false };
1908
+ yield { type: "done" };
1909
+ return;
1910
+ }
1911
+ break;
1912
+ }
1913
+ case "tool-approval-request": {
1914
+ const approvalPart = part;
1915
+ const toolCallId = approvalPart.toolCall?.toolCallId ?? "";
1916
+ const pendingTc = activeToolCalls.find((tc) => tc.id === toolCallId);
1917
+ const tcForChunk = pendingTc ?? {
1918
+ id: toolCallId,
1919
+ type: "function",
1920
+ function: {
1921
+ name: approvalPart.toolCall?.toolName ?? "paid_request",
1922
+ arguments: JSON.stringify(approvalPart.toolCall?.input ?? {}),
1923
+ },
1924
+ };
1925
+ // Payment pre-check disabled — Stripe billing pending.
1926
+ const paymentPrecheck = undefined;
1927
+ // Plan 03-01: check permission mode before yielding approval request to UI.
1928
+ // auto-edit auto-approves file ops; yolo auto-approves everything.
1929
+ const toolName = approvalPart.toolCall?.toolName ?? "";
1930
+ const input = approvalPart.toolCall?.input ?? {};
1931
+ const context = toolName === "bash"
1932
+ ? { command: String(input.command ?? "") }
1933
+ : toolName === "write_file" ||
1934
+ toolName === "edit_file" ||
1935
+ toolName === "read_file" ||
1936
+ toolName === "grep"
1937
+ ? { path: String(input.path ?? input.file_path ?? "") }
1938
+ : undefined;
1939
+ if (!toolNeedsApproval(toolName, deps.permissionMode, context)) {
1940
+ // Auto-approve: respond directly without surfacing to UI.
1941
+ deps.respondToToolApproval(approvalPart.approvalId, true);
1942
+ appendAudit({
1943
+ kind: deps.permissionMode === "yolo" ? "yolo-override" : "permission-override",
1944
+ tool: toolName,
1945
+ mode: deps.permissionMode,
1946
+ context,
1947
+ ts: Date.now(),
1948
+ });
1949
+ break;
1950
+ }
1951
+ yield {
1952
+ type: "tool_approval_request",
1953
+ approvalId: approvalPart.approvalId,
1954
+ toolCall: tcForChunk,
1955
+ paymentPrecheck,
1956
+ };
1957
+ break;
1958
+ }
1959
+ case "error": {
1960
+ // F6b: a TRANSIENT error delivered as a stream PART (e.g. a provider
1961
+ // 5xx / dropped socket surfaced mid-loop after a tool step) otherwise
1962
+ // BYPASSES the thrown-error transient-retry path below — the turn would
1963
+ // surface the error and stop instead of retrying a flaky transient
1964
+ // (observed live: SiliconFlow 500 error-part ended a multi-step turn).
1965
+ // Route it through the SAME bounded budget (shared streamRetryCount /
1966
+ // MAX_STREAM_RETRIES) and the same no-content guard, so an error-part
1967
+ // and a thrown error behave identically. (A 2026-06-20 council debate
1968
+ // independently endorsed bounded auto-retry for exactly this case.)
1969
+ {
1970
+ const { transient: _partTransient } = classifyStreamError(part.error);
1971
+ if (_partTransient &&
1972
+ !assistantText.trim() &&
1973
+ streamRetryCount < MAX_STREAM_RETRIES &&
1974
+ !signal.aborted &&
1975
+ !stallTriggered) {
1976
+ streamRetryCount++;
1977
+ // Exponential backoff: 500 → 8000 ms with ±25% jitter (mirrors the
1978
+ // thrown-error path).
1979
+ const baseMs = 500;
1980
+ const expMs = Math.min(baseMs * 4 ** (streamRetryCount - 1), 8_000);
1981
+ const spread = expMs * 0.25;
1982
+ const nextDelayMs = Math.round(expMs + (Math.random() * 2 - 1) * spread);
1983
+ const errName = part.error instanceof Error ? part.error.name : "Error";
1984
+ const errMsg = part.error instanceof Error ? part.error.message : String(part.error);
1985
+ try {
1986
+ const _ar = globalThis.__muonroiAgentRuntime;
1987
+ _ar?.emitEvent({
1988
+ t: "event",
1989
+ kind: "stream-retry",
1990
+ attempt: streamRetryCount,
1991
+ maxAttempts: MAX_STREAM_RETRIES + 1,
1992
+ errorName: errName,
1993
+ errorMessage: errMsg,
1994
+ nextDelayMs,
1995
+ });
1996
+ }
1997
+ catch {
1998
+ /* best-effort telemetry */
1999
+ }
2000
+ try {
2001
+ if (deps.session) {
2002
+ logInteraction(deps.session.id, "stream_retry", {
2003
+ data: {
2004
+ attempt: streamRetryCount,
2005
+ maxAttempts: MAX_STREAM_RETRIES + 1,
2006
+ errorName: errName,
2007
+ errorMessage: errMsg.slice(0, 200),
2008
+ nextDelayMs,
2009
+ source: "error-part",
2010
+ },
2011
+ });
2012
+ }
2013
+ }
2014
+ catch (logErr) {
2015
+ console.error(`[message-processor] error-part retry log failed: ${logErr?.message}`);
2016
+ }
2017
+ await new Promise((resolve) => setTimeout(resolve, nextDelayMs));
2018
+ if (!signal.aborted) {
2019
+ continue streamAttempt;
2020
+ }
2021
+ }
2022
+ }
2023
+ // F6b-2: a TRANSIENT error-part that arrives AFTER content/tool steps
2024
+ // (F6b's no-content guard above skipped it — assistantText/tools already
2025
+ // flowed). Try to graft the COMPLETED steps onto history and re-issue, so
2026
+ // a flaky 5xx after a tool step RESUMES instead of ending the turn (the
2027
+ // observed Cycle-1 "fail liên tục" case: read big file → finish-step → 500).
2028
+ // SAFE by construction: if result.response can't yield the completed steps
2029
+ // (it rejects on a hard stream error), _appended stays 0 and we fall through
2030
+ // to surface the error — identical to prior behavior. No tool re-run: the
2031
+ // completed steps are grafted onto history, not replayed. Shares the
2032
+ // mid-loop recovery budget (midLoopStallRetryCount / maxStallRetries).
2033
+ {
2034
+ const { transient: _contTransient } = classifyStreamError(part.error);
2035
+ if (_contTransient && midLoopStallRetryCount < maxStallRetries && !signal.aborted && !stallTriggered) {
2036
+ let _appended = 0;
2037
+ try {
2038
+ const _resp = (await Promise.race([
2039
+ result.response,
2040
+ new Promise((_r, rej) => setTimeout(() => rej(new Error("response-timeout")), 3_000)),
2041
+ ]));
2042
+ const _gen = sanitizeModelMessages(scrubImagePayloadsInMessages(_resp.messages));
2043
+ for (const _m of _gen) {
2044
+ deps.messages.push(_m);
2045
+ _appended++;
2046
+ }
2047
+ }
2048
+ catch (respErr) {
2049
+ console.error(`[message-processor] error-part continuation: completed steps unavailable: ${respErr?.message}`);
2050
+ }
2051
+ if (_appended > 0) {
2052
+ midLoopStallRetryCount++;
2053
+ const _contBackoff = stallRepromptBackoffMs(midLoopStallRetryCount);
2054
+ const _errName = part.error instanceof Error ? part.error.name : "Error";
2055
+ const _errMsg = part.error instanceof Error ? part.error.message : String(part.error);
2056
+ try {
2057
+ const _ar = globalThis.__muonroiAgentRuntime;
2058
+ _ar?.emitEvent({
2059
+ t: "event",
2060
+ kind: "stream-retry",
2061
+ attempt: midLoopStallRetryCount,
2062
+ maxAttempts: maxStallRetries + 1,
2063
+ errorName: _errName,
2064
+ errorMessage: "transient error-part after tool step — resuming from completed steps",
2065
+ nextDelayMs: _contBackoff,
2066
+ });
2067
+ _ar?.emitEvent({
2068
+ t: "event",
2069
+ kind: "toast",
2070
+ level: "warning",
2071
+ text: `Transient error mid-task — resuming (attempt ${midLoopStallRetryCount}/${maxStallRetries})…`,
2072
+ });
2073
+ }
2074
+ catch {
2075
+ /* best-effort telemetry */
2076
+ }
2077
+ try {
2078
+ if (deps.session) {
2079
+ logInteraction(deps.session.id, "stream_retry", {
2080
+ data: {
2081
+ attempt: midLoopStallRetryCount,
2082
+ maxAttempts: maxStallRetries + 1,
2083
+ errorName: _errName,
2084
+ errorMessage: `${_errMsg.slice(0, 160)} — resumed from completed steps`,
2085
+ appendedMessages: _appended,
2086
+ nextDelayMs: _contBackoff,
2087
+ source: "error-part-continuation",
2088
+ },
2089
+ });
2090
+ }
2091
+ }
2092
+ catch (logErr) {
2093
+ console.error(`[message-processor] error-part continuation log failed: ${logErr?.message}`);
2094
+ }
2095
+ await new Promise((resolve) => setTimeout(resolve, _contBackoff));
2096
+ if (!signal.aborted) {
2097
+ continue streamAttempt;
2098
+ }
2099
+ }
2100
+ }
2101
+ }
2102
+ const authError = isAuthenticationError(part.error);
2103
+ const friendly = humanizeApiError(part.error, {
2104
+ modelId: runtime.modelId,
2105
+ providerId: runtime.modelInfo?.provider,
2106
+ });
2107
+ const forensics = summarizeApiErrorForLog(part.error);
2108
+ notifyObserver(observer?.onError, {
2109
+ message: friendly,
2110
+ timestamp: Date.now(),
2111
+ });
2112
+ // Interaction log: error + forensics envelope so opaque
2113
+ // provider 4xx ("parameter is invalid" / unknown 400s) leave
2114
+ // an actionable wire-level trace without needing a repro.
2115
+ try {
2116
+ if (deps.session) {
2117
+ logInteraction(deps.session.id, "error", {
2118
+ eventSubtype: authError ? "auth" : "api",
2119
+ data: {
2120
+ message: friendly.slice(0, 200),
2121
+ ...(forensics ? { forensics } : {}),
2122
+ },
2123
+ });
2124
+ }
2125
+ }
2126
+ catch (logErr) {
2127
+ console.error(`[message-processor] interaction-log error failed: ${logErr?.message}`);
2128
+ }
2129
+ yield {
2130
+ type: "error",
2131
+ content: friendly,
2132
+ isAuthError: authError,
2133
+ };
2134
+ break;
2135
+ }
2136
+ case "abort":
2137
+ // A stall-watchdog abort arrives here as an "abort" stream part
2138
+ // (the SDK surfaces it as a part, not a throw). Distinguish it
2139
+ // from a genuine user cancel — which is caught at the top of the
2140
+ // loop via `signal.aborted` — and surface it as a visible error
2141
+ // instead of a benign "[Cancelled]" so a hung provider no longer
2142
+ // looks like a silent freeze.
2143
+ if (stallTriggered) {
2144
+ // Time-to-first-byte stall (no real chunk this attempt): the
2145
+ // socket wedged before any output — re-issue the SAME request
2146
+ // rather than giving up. Bounded by maxStallRetries; never
2147
+ // fires once tools ran or text flowed (planStallReprompt gate).
2148
+ const _stallBackoff = planStallReprompt();
2149
+ if (_stallBackoff != null) {
2150
+ stall.dispose();
2151
+ await new Promise((r) => setTimeout(r, _stallBackoff));
2152
+ if (!signal.aborted) {
2153
+ stallTriggered = false;
2154
+ continue streamAttempt;
2155
+ }
2156
+ }
2157
+ // Mid-loop dead-socket CONTINUATION (distinct from the TTFB
2158
+ // re-prompt above): the watchdog fired AFTER earlier steps ran
2159
+ // (chunksThisAttempt > 0) but the in-flight step produced zero
2160
+ // bytes (chunksThisStep === 0) — a single wedged inter-step
2161
+ // socket (xai/grok-build-0.1 mid-investigation, session
2162
+ // 247a0cea2eac), not a down backend. The TTFB re-prompt can't
2163
+ // recover this (its zero-chunks gate refuses, since restarting
2164
+ // the whole request would re-run the tools that already ran).
2165
+ // Instead, append the COMPLETED steps' generated messages
2166
+ // (assistant tool-calls + their tool-results) to history and
2167
+ // re-issue streamText: with the results already in context, no
2168
+ // tool re-runs and no text duplicates, so this is safe even for
2169
+ // write/commit tools. Falls through to the rescue path if the
2170
+ // completed steps can't be recovered.
2171
+ if (shouldContinueAfterMidLoopStall({
2172
+ stallTriggered,
2173
+ chunksThisAttempt,
2174
+ chunksThisStep,
2175
+ retryCount: midLoopStallRetryCount,
2176
+ maxRetries: maxStallRetries,
2177
+ aborted: signal.aborted,
2178
+ })) {
2179
+ let _appended = 0;
2180
+ try {
2181
+ // result.response settles fast here (the stream was already
2182
+ // aborted via stall.signal). Race a short timeout so a
2183
+ // doubly-wedged provider can't re-hang the recovery itself.
2184
+ const _resp = (await Promise.race([
2185
+ result.response,
2186
+ new Promise((_r, rej) => setTimeout(() => rej(new Error("response-timeout")), 3_000)),
2187
+ ]));
2188
+ const _gen = sanitizeModelMessages(scrubImagePayloadsInMessages(_resp.messages));
2189
+ for (const _m of _gen) {
2190
+ deps.messages.push(_m);
2191
+ _appended++;
2192
+ }
2193
+ }
2194
+ catch (respErr) {
2195
+ console.error(`[message-processor] mid-loop stall continuation: completed steps unavailable: ${respErr?.message}`);
2196
+ }
2197
+ // A re-issue with zero preserved steps would restart from the
2198
+ // original prompt and re-run every tool — only continue when
2199
+ // the completed steps were actually grafted onto history.
2200
+ if (_appended > 0) {
2201
+ midLoopStallRetryCount++;
2202
+ const _midBackoff = stallRepromptBackoffMs(midLoopStallRetryCount);
2203
+ try {
2204
+ const _ar = globalThis.__muonroiAgentRuntime;
2205
+ _ar?.emitEvent({
2206
+ t: "event",
2207
+ kind: "stream-retry",
2208
+ attempt: midLoopStallRetryCount,
2209
+ maxAttempts: maxStallRetries + 1,
2210
+ errorName: "TimeoutError",
2211
+ errorMessage: "provider-stall (mid-loop) — resuming from completed steps",
2212
+ nextDelayMs: _midBackoff,
2213
+ });
2214
+ _ar?.emitEvent({
2215
+ t: "event",
2216
+ kind: "toast",
2217
+ level: "warning",
2218
+ text: `Model stalled mid-task — resuming (attempt ${midLoopStallRetryCount}/${maxStallRetries})…`,
2219
+ });
2220
+ }
2221
+ catch (emitErr) {
2222
+ console.error(`[message-processor] mid-loop continuation telemetry failed: ${emitErr?.message}`);
2223
+ }
2224
+ try {
2225
+ if (deps.session) {
2226
+ logInteraction(deps.session.id, "stream_retry", {
2227
+ data: {
2228
+ attempt: midLoopStallRetryCount,
2229
+ maxAttempts: maxStallRetries + 1,
2230
+ errorName: "provider-stall-midloop",
2231
+ errorMessage: "no byte on inter-step request — resumed from completed steps",
2232
+ appendedMessages: _appended,
2233
+ nextDelayMs: _midBackoff,
2234
+ },
2235
+ });
2236
+ }
2237
+ }
2238
+ catch (logErr) {
2239
+ console.error(`[message-processor] mid-loop continuation log failed: ${logErr?.message}`);
2240
+ }
2241
+ stall.dispose();
2242
+ await new Promise((r) => setTimeout(r, _midBackoff));
2243
+ if (!signal.aborted) {
2244
+ stallTriggered = false;
2245
+ continue streamAttempt;
2246
+ }
2247
+ }
2248
+ }
2249
+ stall.dispose();
2250
+ // A response tool already produced the terminal structured
2251
+ // answer (buffered from its call args) before the provider
2252
+ // stalled on a LATER step. Surface it and finish cleanly —
2253
+ // never bury the model's actual answer behind a "not
2254
+ // responding" error. Root cause of the "respond_* indicator
2255
+ // shows but no answer block renders" report: this stall-abort
2256
+ // path returned before the post-loop structured_response yield,
2257
+ // dropping the captured answer. A response tool is terminal,
2258
+ // so there is nothing to rescue — just emit what we have.
2259
+ if (_pendingStructuredResponse) {
2260
+ if (!streamOk) {
2261
+ try {
2262
+ const _d = _pendingStructuredResponse.data;
2263
+ const _ans = typeof _d.response === "string" ? _d.response : JSON.stringify(_pendingStructuredResponse.data);
2264
+ deps.appendCompletedTurn(userModelMessage, [
2265
+ { role: "assistant", content: _ans },
2266
+ ]);
2267
+ streamOk = true;
2268
+ }
2269
+ catch (persistErr) {
2270
+ console.error(`[message-processor] stall+response-tool persist failed: ${persistErr?.message}`);
2271
+ }
2272
+ }
2273
+ yield {
2274
+ type: "structured_response",
2275
+ structuredResponse: _pendingStructuredResponse,
2276
+ };
2277
+ yield { type: "done" };
2278
+ return;
2279
+ }
2280
+ // Best-effort answer rescue: a turn that already ran tools but
2281
+ // stalled before the final synthesis would otherwise return
2282
+ // ONLY "Model not responding", discarding all that work (live
2283
+ // obs 2026-06-04, deepseek session 734e65cffdf6: 67 tool calls
2284
+ // → user got nothing). Make ONE guarded forced-finalize call
2285
+ // over the gathered tool outputs. forcedFinalize has its own
2286
+ // stall timeout, so a still-dead provider just falls through.
2287
+ let _rescued = null;
2288
+ if (turnToolResults.length > 0) {
2289
+ try {
2290
+ const _userText = typeof userModelMessage?.content === "string"
2291
+ ? userModelMessage.content
2292
+ : JSON.stringify(userModelMessage?.content ?? "");
2293
+ _rescued = await attemptStallRescue({
2294
+ baseMessages: _topMessagesForCall,
2295
+ userText: _userText.slice(0, 4000),
2296
+ toolResults: turnToolResults,
2297
+ system: typeof systemForModel === "string" ? systemForModel : undefined,
2298
+ finalize: (a) => forcedFinalize({ model: runtime.model, messages: a.messages, system: a.system }),
2299
+ });
2300
+ }
2301
+ catch {
2302
+ _rescued = null;
2303
+ }
2304
+ try {
2305
+ if (deps.session) {
2306
+ logInteraction(deps.session.id, "stall_rescue", {
2307
+ data: {
2308
+ outcome: _rescued ? "rescued" : "no_text",
2309
+ toolResultCount: turnToolResults.length,
2310
+ chars: _rescued?.length ?? 0,
2311
+ },
2312
+ });
2313
+ }
2314
+ }
2315
+ catch {
2316
+ /* telemetry is best-effort */
2317
+ }
2318
+ }
2319
+ if (_rescued) {
2320
+ assistantText += (assistantText ? "\n\n" : "") + _rescued;
2321
+ yield { type: "content", content: _rescued };
2322
+ }
2323
+ // Persist a record of the interrupted turn BEFORE returning so
2324
+ // the next turn is not amnesiac. Previously this returned with
2325
+ // nothing persisted → the next turn saw "no previous turn" and
2326
+ // redid the work, orphaning any edits the stalled turn applied
2327
+ // (live obs 2026-06-04, deepseek-v4-flash). When rescued, the
2328
+ // note now carries the synthesized answer too (assistantText).
2329
+ // Best-effort: never let persistence failure block surfacing.
2330
+ if (!streamOk) {
2331
+ try {
2332
+ const _stallNote = buildInterruptedTurnNote(assistantText, activeToolCalls.map((c) => c.function.name));
2333
+ deps.appendCompletedTurn(userModelMessage, [
2334
+ { role: "assistant", content: _stallNote },
2335
+ ]);
2336
+ streamOk = true;
2337
+ }
2338
+ catch {
2339
+ /* best-effort — surface the stall regardless */
2340
+ }
2341
+ }
2342
+ if (_rescued) {
2343
+ // Recovered a best-effort answer from partial data — surface
2344
+ // a soft notice instead of the scary "not responding" error.
2345
+ yield {
2346
+ type: "content",
2347
+ content: "\n\n[Note: the model connection stalled; the answer above is a best-effort synthesis " +
2348
+ "from the tool results gathered before the stall and may be incomplete.]",
2349
+ };
2350
+ yield { type: "done" };
2351
+ return;
2352
+ }
2353
+ notifyObserver(observer?.onError, { message: STALL_ERROR_MESSAGE, timestamp: Date.now() });
2354
+ yield { type: "error", content: STALL_ERROR_MESSAGE, isAuthError: false };
2355
+ yield { type: "done" };
2356
+ return;
2357
+ }
2358
+ yield { type: "content", content: "\n\n[Cancelled]" };
2359
+ break;
2360
+ }
2361
+ }
2362
+ stall.dispose(); // stream drained normally — stop the stall watchdog
2363
+ // ─── SAMR Phase 1 → Phase 2 transition ─────────────────────────
2364
+ // Phase 1 (premium model) produced tool calls but the SDK stopped
2365
+ // before executing them (stopWhen: stepCountIs(1)). Append the
2366
+ // assistant message to deps.messages and restart the loop with
2367
+ // the fast execution model. Phase 2's streamText call will see
2368
+ // the pending tool calls and execute them automatically.
2369
+ //
2370
+ // EXCEPT when Phase 1 emitted a response tool: a `respond_*` call IS
2371
+ // the terminal structured answer (identity execute), not work to hand
2372
+ // to Phase 2. Transitioning here would (a) skip the structured_response
2373
+ // yield below — the answer never reaches the TUI — and (b) append a
2374
+ // dangling assistant tool-call WITHOUT its tool-result (only assistant
2375
+ // msgs are pushed), corrupting Phase 2's history. Fall through instead
2376
+ // so the buffered answer is yielded + persisted on this turn.
2377
+ if (stepRouterPhase === "phase1" && phase1HadToolCalls && !responseToolCalled) {
2378
+ try {
2379
+ const phase1Response = await result.response;
2380
+ // Append only new messages (assistant message with tool calls)
2381
+ const newMsgs = phase1Response.messages.slice(deps.messages.length);
2382
+ for (const msg of newMsgs) {
2383
+ if (msg.role === "assistant") {
2384
+ deps.messages.push(msg);
2385
+ }
2386
+ }
2387
+ }
2388
+ catch {
2389
+ // If response extraction fails, fall through to normal completion
2390
+ }
2391
+ stepRouterPhase = "phase2";
2392
+ continue; // Re-enter while loop with Phase 2 (fast) model
2393
+ }
2394
+ // Surface the single most-complete response-tool answer buffered
2395
+ // during the stream (see _pendingStructuredResponse). Yielding here —
2396
+ // once, after the stream drained and after the Phase 1 transition —
2397
+ // collapses any duplicate response-tool emissions in the turn into a
2398
+ // single structured_response block for the UI.
2399
+ if (_pendingStructuredResponse) {
2400
+ // Schema-mismatch normalization: when the model calls a typed
2401
+ // respond_<task> (e.g. respond_analyze) but sends a payload shaped
2402
+ // like respond_general ({ response: "..." } without schema-specific
2403
+ // fields like `findings`), the TUI typed renderer renders an empty
2404
+ // box. Normalize taskType to 'general' so the plain-markdown
2405
+ // renderer is used. See normalizeStructuredResponseTaskType() docs.
2406
+ // Session 48d22fe436f6: respond_analyze({ response: "..." }) →
2407
+ // analyze renderer showed empty findings list → answer swallowed.
2408
+ const _normalizedType = normalizeStructuredResponseTaskType(_pendingStructuredResponse.taskType, _pendingStructuredResponse.data);
2409
+ if (_normalizedType !== _pendingStructuredResponse.taskType) {
2410
+ _pendingStructuredResponse = { taskType: _normalizedType, data: _pendingStructuredResponse.data };
2411
+ }
2412
+ yield {
2413
+ type: "structured_response",
2414
+ structuredResponse: _pendingStructuredResponse,
2415
+ };
2416
+ // Ensure DB has the answer as assistant row even if later _finalMessages
2417
+ // or buildChatEntries path drops the tool-call-only assistant (sanitize,
2418
+ // response-tool terminal, vision bridge, sub-delegate). Prevents TUI
2419
+ // "flashed then vanished" on finalizeActiveTurn + getChatEntries().
2420
+ if (deps.session) {
2421
+ try {
2422
+ const _d = _pendingStructuredResponse.data;
2423
+ const _ans = typeof _d.response === "string" ? _d.response : JSON.stringify(_pendingStructuredResponse.data);
2424
+ deps.appendCompletedTurn(userModelMessage, [{ role: "assistant", content: _ans }]);
2425
+ }
2426
+ catch { }
2427
+ }
2428
+ if (_responseToolEmitCount > 1 && deps.session) {
2429
+ try {
2430
+ logInteraction(deps.session.id, "f6_synthesis", {
2431
+ eventSubtype: "response_tool_deduped",
2432
+ data: { emitted: _responseToolEmitCount, keptChars: _pendingStructuredResponseLen },
2433
+ });
2434
+ }
2435
+ catch {
2436
+ /* telemetry best-effort */
2437
+ }
2438
+ }
2439
+ }
2440
+ if (signal.aborted) {
2441
+ if (_pendingStructuredResponse) {
2442
+ try {
2443
+ const _d = _pendingStructuredResponse.data;
2444
+ const _ans = typeof _d.response === "string" ? _d.response : JSON.stringify(_pendingStructuredResponse.data);
2445
+ deps.appendCompletedTurn(userModelMessage, [{ role: "assistant", content: _ans }]);
2446
+ }
2447
+ catch { }
2448
+ }
2449
+ deps.discardAbortedTurn(userModelMessage);
2450
+ yield { type: "done" };
2451
+ return;
2452
+ }
2453
+ try {
2454
+ const response = await result.response;
2455
+ if (!signal.aborted) {
2456
+ // Scrub oversized base64 image payloads from tool-result parts
2457
+ // BEFORE persisting. The vision bridge above only modified the
2458
+ // transient `tr` shown to the user — `response.messages` from
2459
+ // the AI SDK still carries the full base64 (e.g. Playwright
2460
+ // screenshot, ~1.5MB). Persisting that lets it accumulate and
2461
+ // overflow the model's context on subsequent turns.
2462
+ const scrubbed = rewriteSafetyApprovedToolResults(scrubImagePayloadsInMessages(response.messages));
2463
+ // Phase 5 F6 — synthesis step when stream ended without a final
2464
+ // text response. Cheap models (DeepSeek V4 Flash) frequently
2465
+ // emit only tool-calls in their last step and stop, leaving the
2466
+ // user staring at "Here's the summary:..." truncation that
2467
+ // required a manual "tiếp tục" turn-2 to coax out. Detect that
2468
+ // shape and inject ONE forcedFinalize call (same path as 4B
2469
+ // ceiling-hit) so the answer arrives on turn 1.
2470
+ //
2471
+ // Skip when 4B ceiling already triggered its own forcedFinalize
2472
+ // below — running both would double-bill and duplicate text.
2473
+ let _f6SynthesisText = null;
2474
+ const _f6LastMsg = scrubbed[scrubbed.length - 1];
2475
+ const _f6LastRole = _f6LastMsg?.role ?? "none";
2476
+ let _f6Outcome = "skip_ceiling";
2477
+ let _f6Elapsed = 0;
2478
+ let _f6ChunkChars = 0;
2479
+ let _f6Error = null;
2480
+ // A response tool already produced the final structured answer —
2481
+ // F6 synthesis would duplicate it as prose. Skip entirely. With
2482
+ // the stopWhen terminal-halt above, the turn now ends right after
2483
+ // the response tool (last scrubbed message is the response
2484
+ // tool-result, role "tool"), which would otherwise trip the
2485
+ // _needsSynthesis "ended on a tool" branch and double-respond.
2486
+ if (responseToolCalled) {
2487
+ _f6Outcome = "skip_response_tool";
2488
+ }
2489
+ else if (!_ceilingHit) {
2490
+ const _needsSynthesis = (() => {
2491
+ if (!_f6LastMsg)
2492
+ return false;
2493
+ if (_f6LastMsg.role === "tool")
2494
+ return true;
2495
+ if (_f6LastMsg.role !== "assistant")
2496
+ return false;
2497
+ const _c = _f6LastMsg.content;
2498
+ if (typeof _c === "string")
2499
+ return !_c.trim();
2500
+ if (!Array.isArray(_c))
2501
+ return false;
2502
+ return !_c.some((p) => p && p.type === "text" && typeof p.text === "string" && p.text.trim().length > 0);
2503
+ })();
2504
+ if (!_needsSynthesis) {
2505
+ _f6Outcome = "skip_has_text";
2506
+ }
2507
+ else {
2508
+ const _f6Start = Date.now();
2509
+ try {
2510
+ const _ff = await forcedFinalize({
2511
+ model: runtime.model,
2512
+ messages: _topMessagesForCall,
2513
+ system: typeof systemForModel === "string" ? systemForModel : undefined,
2514
+ });
2515
+ _f6Elapsed = Date.now() - _f6Start;
2516
+ _f6ChunkChars = (_ff.text ?? "").length;
2517
+ if (_ff.text.trim()) {
2518
+ _f6SynthesisText = _ff.text;
2519
+ assistantText += _ff.text;
2520
+ yield { type: "content", content: _ff.text };
2521
+ _f6Outcome = "fired_text";
2522
+ }
2523
+ else {
2524
+ _f6Outcome = "fired_empty";
2525
+ }
2526
+ }
2527
+ catch (_err) {
2528
+ _f6Elapsed = Date.now() - _f6Start;
2529
+ _f6Outcome = "error";
2530
+ _f6Error = _err?.message?.slice(0, 200) ?? String(_err).slice(0, 200);
2531
+ }
2532
+ }
2533
+ }
2534
+ try {
2535
+ if (deps.session) {
2536
+ logInteraction(deps.session.id, "f6_synthesis", {
2537
+ data: {
2538
+ outcome: _f6Outcome,
2539
+ lastMsgRole: _f6LastRole,
2540
+ elapsedMs: _f6Elapsed,
2541
+ chars: _f6ChunkChars,
2542
+ error: _f6Error,
2543
+ ceilingHit: _ceilingHit,
2544
+ scrubbedLen: scrubbed.length,
2545
+ },
2546
+ });
2547
+ }
2548
+ }
2549
+ catch {
2550
+ /* telemetry is best-effort */
2551
+ }
2552
+ // Summary-phase grounding check (Agent Operating Contract, runtime
2553
+ // half). Soft-flag counts / file:line refs in the final synthesis
2554
+ // that don't appear in this turn's tool outputs — possible
2555
+ // hallucination. Never blocks: emits a grounding-flag event + a
2556
+ // warn toast + an inline advisory footnote. Only runs when the
2557
+ // turn actually produced tool output (a corpus to ground against)
2558
+ // and is not chitchat. See grounding-check.ts.
2559
+ if (process.env.MUONROI_DISABLE_GROUNDING_CHECK !== "1" && !isChitchat && assistantText.trim().length > 0) {
2560
+ try {
2561
+ const _gParts = [];
2562
+ let _gHadTool = false;
2563
+ for (const _gm of scrubbed) {
2564
+ if (!_gm || _gm.role === "assistant")
2565
+ continue;
2566
+ if (_gm.role === "tool")
2567
+ _gHadTool = true;
2568
+ const _gc = _gm.content;
2569
+ _gParts.push(typeof _gc === "string" ? _gc : JSON.stringify(_gc));
2570
+ }
2571
+ if (_gHadTool) {
2572
+ const _claims = findUnverifiedClaims(assistantText, _gParts.join("\n"));
2573
+ if (_claims.length > 0) {
2574
+ const _footnote = buildGroundingFootnote(_claims);
2575
+ assistantText += _footnote;
2576
+ yield { type: "content", content: _footnote };
2577
+ const _gar = globalThis.__muonroiAgentRuntime;
2578
+ const _claimTexts = _claims.map((c) => c.text);
2579
+ _gar?.emitEvent({
2580
+ t: "event",
2581
+ kind: "grounding-flag",
2582
+ claims: _claimTexts,
2583
+ count: _claims.length,
2584
+ ts: Date.now(),
2585
+ });
2586
+ _gar?.emitEvent({
2587
+ t: "event",
2588
+ kind: "toast",
2589
+ level: "warn",
2590
+ text: `grounding: ${_claims.length} unverified claim(s) — ${_claimTexts.join(", ")}`,
2591
+ });
2592
+ if (deps.session) {
2593
+ try {
2594
+ logInteraction(deps.session.id, "grounding_flag", {
2595
+ data: { claims: _claimTexts, count: _claims.length },
2596
+ });
2597
+ }
2598
+ catch {
2599
+ /* telemetry is best-effort */
2600
+ }
2601
+ }
2602
+ }
2603
+ }
2604
+ }
2605
+ catch {
2606
+ /* grounding check is best-effort — never break finalize */
2607
+ }
2608
+ }
2609
+ const _finalMessages = sanitizeModelMessages(scrubbed);
2610
+ if (_f6SynthesisText !== null) {
2611
+ _finalMessages.push({
2612
+ role: "assistant",
2613
+ content: _f6SynthesisText,
2614
+ });
2615
+ }
2616
+ deps.appendCompletedTurn(userModelMessage, _finalMessages);
2617
+ streamOk = true;
2618
+ }
2619
+ }
2620
+ catch (responseError) {
2621
+ if (!attemptedOverflowRecovery && !assistantText.trim() && modelInfo && isContextLimitError(responseError)) {
2622
+ attemptedOverflowRecovery = true;
2623
+ continue;
2624
+ }
2625
+ }
2626
+ if (signal.aborted) {
2627
+ deps.discardAbortedTurn(userModelMessage);
2628
+ yield { type: "done" };
2629
+ return;
2630
+ }
2631
+ if (patternLoopForceHalt) {
2632
+ patternLoopForceHalt = false;
2633
+ try {
2634
+ const _ar = globalThis.__muonroiAgentRuntime;
2635
+ _ar?.emitEvent({
2636
+ t: "event",
2637
+ kind: "toast",
2638
+ level: "info",
2639
+ text: "vòng lặp tool được phát hiện — đang tự động tiêm prompt nhắc nhở để agent tự sửa đổi",
2640
+ });
2641
+ }
2642
+ catch {
2643
+ /* best-effort */
2644
+ }
2645
+ stall.dispose();
2646
+ await closeMcp?.().catch(() => { });
2647
+ continue;
2648
+ }
2649
+ // Phase 5 Fix 5 — the Phase 4 4B forced-finalize-on-ceiling-hit
2650
+ // block lived here. With the matrix ceiling no longer halting the
2651
+ // stream (it's pure telemetry now), _ceilingHit can never be true
2652
+ // and this branch is dead. F6 synthesis above already covers the
2653
+ // "stream ended with no final text" case for both natural model
2654
+ // termination AND maxToolRounds halt. Keeping the comment as a
2655
+ // breadcrumb for future archaeology.
2656
+ if (!streamOk && assistantText.trim()) {
2657
+ deps.appendCompletedTurn(userModelMessage, [{ role: "assistant", content: stripDsmlMarkup(assistantText) }]);
2658
+ }
2659
+ // Fallback: model responded in text despite tool_choice=required
2660
+ // Attempt JSON extraction from assistant text → yield as structured_response
2661
+ if (_hasResponseTools && !responseToolCalled && pilCtx.taskType && assistantText.trim()) {
2662
+ try {
2663
+ const jsonMatch = assistantText.match(/\{[\s\S]*\}/);
2664
+ if (jsonMatch) {
2665
+ const parsed = JSON.parse(jsonMatch[0]);
2666
+ if (Object.keys(parsed).length > 0) {
2667
+ responseToolCalled = true;
2668
+ yield {
2669
+ type: "structured_response",
2670
+ structuredResponse: {
2671
+ taskType: pilCtx.taskType,
2672
+ data: parsed,
2673
+ },
2674
+ };
2675
+ }
2676
+ }
2677
+ }
2678
+ catch {
2679
+ // JSON parse failed — leave as text-fallback
2680
+ }
2681
+ }
2682
+ // Track PIL output mode for /optimize metrics
2683
+ {
2684
+ const { setLastOutputMode } = await import("../pil/store.js");
2685
+ if (!_hasResponseTools)
2686
+ setLastOutputMode("conversational");
2687
+ else if (responseToolCalled)
2688
+ setLastOutputMode("structured");
2689
+ else
2690
+ setLastOutputMode("text-fallback");
2691
+ }
2692
+ // ROUTE-11: Fire routeFeedback after turn completes (success path).
2693
+ // Must come AFTER posttool calls (posttool fires during tool-result processing above).
2694
+ // Fire-and-forget — no await. Skipped when taskHash is null (bridge absent).
2695
+ {
2696
+ const turnDuration = Date.now() - turnStartMs;
2697
+ if (taskHash) {
2698
+ const tier = taskTypeToTier(pilCtx.taskType);
2699
+ void routeFeedback(taskHash, tier, runtime.modelId, "success", // Phase 6: all normal completions = 'success'
2700
+ 0, // retryCount: 0 for first attempt
2701
+ turnDuration);
2702
+ }
2703
+ // HTTP path: also report via router store taskHash (covers warm/cold EE routes)
2704
+ const storeHash = routerStore.getState().taskHash;
2705
+ if (storeHash) {
2706
+ reportRouteOutcome(storeHash, "success", turnDuration);
2707
+ }
2708
+ }
2709
+ // Detect a tool call emitted as plain TEXT (wrong dialect) in the final
2710
+ // assistant answer — the action never ran, so the turn would otherwise
2711
+ // end silently with broken/half-done work (live: deepseek session
2712
+ // 905d564dbde4 emitted `<read_file>` as text after a destructive edit).
2713
+ // Detect regardless of how many real tool calls already succeeded: the
2714
+ // common failure is the model doing a few real tools, then emitting the
2715
+ // NEXT call as text and stopping (live deepseek-native, full-fix CLI: 2
2716
+ // real read_file calls, then `<read_file><path>` as text → silent stop).
2717
+ // An earlier `activeToolCalls.length === 0` guard suppressed exactly
2718
+ // that case. Detector precision (structural invocation shape, not a bare
2719
+ // mention) guards against false-firing on a normal final answer.
2720
+ const _textToolCall = detectTextEmittedToolCall(assistantText);
2721
+ // Interaction log: agent response complete
2722
+ try {
2723
+ if (deps.session) {
2724
+ const sb = statusBarStore.getState();
2725
+ const turnDurationMs = Date.now() - turnStartMs;
2726
+ // BUG-A telemetry — detect raw DeepSeek native tool-call markup
2727
+ // leaking into assistant text. Signature is `<||DSML||` (the
2728
+ // fullwidth vertical bars are NOT pipes, they're U+FF5C).
2729
+ const _dsmlSig = "||DSML||";
2730
+ const _dsmlMatches = assistantText.includes(_dsmlSig);
2731
+ const _codeBlockBash = /```\s*bash\b/i.test(assistantText);
2732
+ logInteraction(deps.session.id, "agent_response", {
2733
+ model: turnModelId,
2734
+ inputTokens: sb.in_tokens,
2735
+ outputTokens: sb.out_tokens,
2736
+ durationMs: turnDurationMs,
2737
+ data: {
2738
+ textLength: assistantText.length,
2739
+ toolCallCount: activeToolCalls.length,
2740
+ compacted: deps.getCompactedThisTurn(),
2741
+ dsmlLeak: _dsmlMatches,
2742
+ bashCodeBlock: _codeBlockBash,
2743
+ textToolXmlLeak: _textToolCall.detected,
2744
+ textToolXmlTool: _textToolCall.tool,
2745
+ },
2746
+ });
2747
+ }
2748
+ }
2749
+ catch {
2750
+ /* fail-open */
2751
+ }
2752
+ // Surface the round-cap stop so the user knows why the agent halted
2753
+ // (session 7dcf8fd7d6a4 hit stepCountIs(100) silently, looked like a
2754
+ // crash). AI SDK reports finishReason='tool-calls' when the step cap
2755
+ // fires with tool calls still pending — distinct from 'stop' (model
2756
+ // chose to end). We only warn when stepNumber ≥ cap so a model that
2757
+ // legitimately terminates mid-tool-call (rare) doesn't get a false
2758
+ // warning.
2759
+ if (_lastFinishReason === "tool-calls" && stepNumber >= deps.maxToolRounds - 1) {
2760
+ yield {
2761
+ type: "content",
2762
+ content: `\n\n[Stopped: Agent paused execution to prevent runaway loops (hit step cap of ${deps.maxToolRounds}). ` +
2763
+ `If you want to continue the current task, simply reply with "continue" or "tiếp tục". ` +
2764
+ `For long tasks, we strongly recommend running the \`/compact\` command first to free up context memory before continuing.]\n`,
2765
+ };
2766
+ }
2767
+ // Tool-call-as-text leak: the model wrote a tool invocation as plain
2768
+ // text (wrong dialect) and made NO real tool call, so the action never
2769
+ // ran. Auto-recover ONCE: append a corrective message and re-run the
2770
+ // turn so the model can invoke the tool properly. The just-finished
2771
+ // (text-only) turn is already persisted above — the model sees its own
2772
+ // mistake plus the correction. Mirrors the proven phase-switch re-entry
2773
+ // (it also pushes to deps.messages then `continue`s); bounded by
2774
+ // MAX_TEXT_TOOL_RESTEER so a persistently-degrading model can't loop.
2775
+ if (_textToolCall.detected && streamOk && textToolReSteerCount < MAX_TEXT_TOOL_RESTEER) {
2776
+ textToolReSteerCount++;
2777
+ // Recover the model's INTENT from the leaked markup (DeepSeek-native
2778
+ // DSML carries the tool + args) so the corrective restates the exact
2779
+ // call — far more effective than a generic "use the tool" nudge.
2780
+ const _parsedCalls = parseDsmlToolCalls(assistantText);
2781
+ const _intent = _parsedCalls.length > 0
2782
+ ? ` You appear to have intended: ${_parsedCalls
2783
+ .map((c) => `${c.name}(${Object.entries(c.args)
2784
+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
2785
+ .join(", ")})`)
2786
+ .join("; ")}. Make those exact call(s) via the tool interface now.`
2787
+ : "";
2788
+ deps.messages.push({
2789
+ role: "user",
2790
+ content: `Your previous reply wrote a \`${_textToolCall.tool}\` tool call as XML/text. That is NOT how tools are invoked here — ` +
2791
+ "writing tool calls as text does nothing, so the action did not run. " +
2792
+ "Use the actual tool-calling interface (function/tool calls) to perform the action now. " +
2793
+ "Do NOT output XML tags like <read_file>, <write_to_file>, <execute_command>, or <tool_call> (or DSML markup) as text." +
2794
+ _intent,
2795
+ });
2796
+ if (deps.session) {
2797
+ try {
2798
+ logInteraction(deps.session.id, "text_tool_resteer", {
2799
+ model: turnModelId,
2800
+ data: { tool: _textToolCall.tool, attempt: textToolReSteerCount },
2801
+ });
2802
+ }
2803
+ catch {
2804
+ /* telemetry best-effort */
2805
+ }
2806
+ }
2807
+ {
2808
+ const _gar = globalThis.__muonroiAgentRuntime;
2809
+ _gar?.emitEvent({
2810
+ t: "event",
2811
+ kind: "toast",
2812
+ level: "info",
2813
+ text: `model wrote a ${_textToolCall.tool} tool call as text — re-steering to use the tool interface`,
2814
+ });
2815
+ }
2816
+ await closeMcp?.().catch(() => { });
2817
+ continue;
2818
+ }
2819
+ // Re-steer exhausted: inject DSML intent as a user message so the
2820
+ // model re-issues the same calls via the real tool interface.
2821
+ if (_textToolCall.detected) {
2822
+ const _parsedDsml = assistantText ? parseDsmlToolCalls(assistantText) : [];
2823
+ if (_parsedDsml.length > 0 && textToolReSteerCount < MAX_TEXT_TOOL_RESTEER) {
2824
+ textToolReSteerCount++;
2825
+ const _intentStr = _parsedDsml
2826
+ .map((c) => `${c.name}(${Object.entries(c.args)
2827
+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
2828
+ .join(", ")})`)
2829
+ .join("; ");
2830
+ deps.messages.push({
2831
+ role: "user",
2832
+ content: `[DSML intent: ${_intentStr} — re-issue via the tool interface now.]`,
2833
+ });
2834
+ await closeMcp?.().catch(() => { });
2835
+ continue;
2836
+ }
2837
+ // No parseable DSML — surface the dead-end warning.
2838
+ yield {
2839
+ type: "content",
2840
+ content: `\n\n[⚠ The model wrote a \`${_textToolCall.tool}\` tool call as TEXT instead of invoking the tool, ` +
2841
+ "so that action did NOT run and this turn made no real progress. " +
2842
+ "Re-run the request (optionally with a more capable model) — the tool interface was not used.]\n",
2843
+ };
2844
+ const _gar2 = globalThis.__muonroiAgentRuntime;
2845
+ _gar2?.emitEvent({
2846
+ t: "event",
2847
+ kind: "toast",
2848
+ level: "warn",
2849
+ text: `model emitted a ${_textToolCall.tool} tool call as text — action not executed`,
2850
+ });
2851
+ }
2852
+ const stopInput = {
2853
+ hook_event_name: "Stop",
2854
+ session_id: deps.session?.id,
2855
+ cwd: deps.bash.getCwd(),
2856
+ };
2857
+ await deps.fireHook(stopInput, signal).catch(() => { });
2858
+ // Debug trace: emit pipeline summary
2859
+ if (_debugOn) {
2860
+ const sb = statusBarStore.getState();
2861
+ const defaultInfo = getModelInfo(deps.modelId);
2862
+ const usedInfo = getModelInfo(turnModelId);
2863
+ const routerSaved = defaultInfo && usedInfo && defaultInfo.outputPrice > usedInfo.outputPrice
2864
+ ? (sb.out_tokens * (defaultInfo.outputPrice - usedInfo.outputPrice)) / 1_000_000
2865
+ : 0;
2866
+ const cacheSaved = sb.cache_read_tokens > 0 && defaultInfo
2867
+ ? (sb.cache_read_tokens *
2868
+ (defaultInfo.inputPrice - (defaultInfo.cachedInputPrice ?? defaultInfo.inputPrice * 0.1))) /
2869
+ 1_000_000
2870
+ : 0;
2871
+ const trace = {
2872
+ turn_id: _debugTurnId,
2873
+ timestamp: turnStartMs,
2874
+ raw_prompt: userMessage,
2875
+ steps: _debugSteps,
2876
+ model_requested: deps.modelId,
2877
+ model_used: turnModelId,
2878
+ routed: turnModelId !== deps.modelId,
2879
+ input_tokens: sb.in_tokens,
2880
+ output_tokens: sb.out_tokens,
2881
+ cache_read_tokens: sb.cache_read_tokens,
2882
+ cost_usd: sb.session_usd,
2883
+ estimated_savings: {
2884
+ pil_tokens_saved: _pilEnrichmentDeltaSnapshot > 0 ? _pilEnrichmentDeltaSnapshot : 0,
2885
+ cache_tokens_saved: sb.cache_read_tokens,
2886
+ router_cost_saved_usd: routerSaved,
2887
+ total_tokens_saved: (_pilEnrichmentDeltaSnapshot > 0 ? _pilEnrichmentDeltaSnapshot : 0) + sb.cache_read_tokens,
2888
+ total_cost_saved_usd: routerSaved + cacheSaved,
2889
+ },
2890
+ };
2891
+ recordTurnTrace(trace);
2892
+ const traceLines = [];
2893
+ traceLines.push("\n┌─ Pipeline Trace ─────────────────────────");
2894
+ for (const step of _debugSteps) {
2895
+ const dur = step.duration_ms < 1 ? "<1ms" : `${step.duration_ms}ms`;
2896
+ const saved = step.tokens_saved ? ` (saved ~${step.tokens_saved} tok)` : "";
2897
+ traceLines.push(`│ ▸ ${step.name} [${dur}]${saved}`);
2898
+ traceLines.push(`│ ${step.output_summary}`);
2899
+ }
2900
+ const routeLabel = trace.routed ? `${trace.model_requested}→${trace.model_used}` : trace.model_used;
2901
+ traceLines.push(`│ Model: ${routeLabel} | ↑${sb.in_tokens} ↓${sb.out_tokens} | $${sb.session_usd.toFixed(4)}`);
2902
+ if (trace.estimated_savings.total_cost_saved_usd > 0) {
2903
+ traceLines.push(`│ Savings: ~${trace.estimated_savings.total_tokens_saved} tok, ~$${trace.estimated_savings.total_cost_saved_usd.toFixed(4)}`);
2904
+ }
2905
+ traceLines.push("└──────────────────────────────────────────\n");
2906
+ yield { type: "content", content: traceLines.join("\n") };
2907
+ }
2908
+ // Yield done FIRST so the UI releases isProcessing immediately.
2909
+ // postTurnCompact is a background optimization that must not block
2910
+ // the composer — without this, DeepSeek's 5-30s compaction call
2911
+ // keeps the input in loading state and queued messages hang.
2912
+ //
2913
+ // CRITICAL: postTurnCompact MUST be fire-and-forget (void, NOT await).
2914
+ // Even though yield-done happens first, the for-await loop in
2915
+ // use-app-logic.tsx does NOT exit until the generator returns.
2916
+ // An awaited postTurnCompact blocks the generator's return, which
2917
+ // blocks the for-await loop, which blocks finalizeActiveTurn.
2918
+ if (modelInfo?.contextWindow) {
2919
+ void deps.postTurnCompact(provider, system, modelInfo.contextWindow, signal).catch(() => { });
2920
+ }
2921
+ yield { type: "done" };
2922
+ return;
2923
+ }
2924
+ catch (err) {
2925
+ if (signal.aborted) {
2926
+ deps.discardAbortedTurn(userModelMessage);
2927
+ // ROUTE-11: Fire routeFeedback for cancelled turns (abort path).
2928
+ // Fire-and-forget — no await. Skipped when taskHash is null.
2929
+ {
2930
+ const turnDuration = Date.now() - turnStartMs;
2931
+ if (taskHash) {
2932
+ const tier = taskTypeToTier(pilCtx.taskType);
2933
+ void routeFeedback(taskHash, tier, runtime.modelId, "cancelled", 0, turnDuration);
2934
+ }
2935
+ const storeHash = routerStore.getState().taskHash;
2936
+ if (storeHash) {
2937
+ reportRouteOutcome(storeHash, "cancelled", turnDuration);
2938
+ }
2939
+ }
2940
+ yield { type: "content", content: "\n\n[Cancelled]" };
2941
+ yield { type: "done" };
2942
+ return;
2943
+ }
2944
+ if (!attemptedOverflowRecovery && !assistantText.trim() && modelInfo && isContextLimitError(err)) {
2945
+ attemptedOverflowRecovery = true;
2946
+ continue;
2947
+ }
2948
+ // Stall surfaced as a throw (rather than an "abort" stream part):
2949
+ // apply the SAME time-to-first-byte re-prompt as the abort-part path.
2950
+ // The watchdog already fired (stallTriggered) so its timer is spent —
2951
+ // no dispose needed; the next attempt arms a fresh watchdog.
2952
+ if (stallTriggered) {
2953
+ const _stallBackoff = planStallReprompt();
2954
+ if (_stallBackoff != null) {
2955
+ await new Promise((r) => setTimeout(r, _stallBackoff));
2956
+ if (!signal.aborted) {
2957
+ stallTriggered = false;
2958
+ continue;
2959
+ }
2960
+ }
2961
+ }
2962
+ // Transient network/server error retry — up to MAX_STREAM_RETRIES extra attempts.
2963
+ // Only retry when no content has flowed yet (assistantText empty) to avoid
2964
+ // partial-output corruption. Honour the abort signal between retries.
2965
+ // Skip retry on a stall abort: the provider is unresponsive, so a retry
2966
+ // just burns another full stall timeout of silence — surface it instead.
2967
+ if (!assistantText.trim() && streamRetryCount < MAX_STREAM_RETRIES && !signal.aborted && !stallTriggered) {
2968
+ const { transient } = classifyStreamError(err);
2969
+ if (transient) {
2970
+ streamRetryCount++;
2971
+ // Exponential backoff: 500 → 2000 ms with ±25% jitter
2972
+ const baseMs = 500;
2973
+ const expMs = Math.min(baseMs * 4 ** (streamRetryCount - 1), 8_000);
2974
+ const spread = expMs * 0.25;
2975
+ const nextDelayMs = Math.round(expMs + (Math.random() * 2 - 1) * spread);
2976
+ const errorName = err instanceof Error ? err.name : "Error";
2977
+ const errorMessage = err instanceof Error ? err.message : String(err);
2978
+ // Emit harness telemetry event
2979
+ try {
2980
+ const _ar = globalThis.__muonroiAgentRuntime;
2981
+ _ar?.emitEvent({
2982
+ t: "event",
2983
+ kind: "stream-retry",
2984
+ attempt: streamRetryCount,
2985
+ maxAttempts: MAX_STREAM_RETRIES + 1,
2986
+ errorName,
2987
+ errorMessage,
2988
+ nextDelayMs,
2989
+ });
2990
+ }
2991
+ catch {
2992
+ /* best-effort */
2993
+ }
2994
+ try {
2995
+ if (deps.session) {
2996
+ logInteraction(deps.session.id, "stream_retry", {
2997
+ data: {
2998
+ attempt: streamRetryCount,
2999
+ maxAttempts: MAX_STREAM_RETRIES + 1,
3000
+ errorName,
3001
+ errorMessage: errorMessage.slice(0, 200),
3002
+ nextDelayMs,
3003
+ },
3004
+ });
3005
+ }
3006
+ }
3007
+ catch {
3008
+ /* fail-open */
3009
+ }
3010
+ await new Promise((resolve) => setTimeout(resolve, nextDelayMs));
3011
+ if (!signal.aborted) {
3012
+ continue;
3013
+ }
3014
+ }
3015
+ }
3016
+ const authError = isAuthenticationError(err);
3017
+ // Stall aborts carry an opaque DOMException; show the clear stall
3018
+ // message instead of the raw abort reason.
3019
+ const friendly = stallTriggered
3020
+ ? STALL_ERROR_MESSAGE
3021
+ : humanizeApiError(err, { modelId: runtime.modelId, providerId: runtime.modelInfo?.provider });
3022
+ notifyObserver(observer?.onError, {
3023
+ message: friendly,
3024
+ timestamp: Date.now(),
3025
+ });
3026
+ yield {
3027
+ type: "error",
3028
+ content: friendly,
3029
+ isAuthError: authError,
3030
+ };
3031
+ if (_pendingStructuredResponse) {
3032
+ const _d = _pendingStructuredResponse.data;
3033
+ const _ans = typeof _d.response === "string" ? _d.response : JSON.stringify(_pendingStructuredResponse.data);
3034
+ deps.appendCompletedTurn(userModelMessage, [{ role: "assistant", content: _ans }]);
3035
+ }
3036
+ else if (assistantText.trim()) {
3037
+ deps.appendCompletedTurn(userModelMessage, [{ role: "assistant", content: stripDsmlMarkup(assistantText) }]);
3038
+ }
3039
+ else if (deps.session && userWriteAheadSeq != null) {
3040
+ markMessageErrored(deps.session.id, userWriteAheadSeq);
3041
+ }
3042
+ // ROUTE-11: Fire routeFeedback for failed turns (error path).
3043
+ // Must come AFTER posttool calls. Fire-and-forget — no await.
3044
+ {
3045
+ const turnDuration = Date.now() - turnStartMs;
3046
+ if (taskHash) {
3047
+ const tier = taskTypeToTier(pilCtx.taskType);
3048
+ void routeFeedback(taskHash, tier, runtime.modelId, "fail", 0, turnDuration);
3049
+ }
3050
+ const storeHash = routerStore.getState().taskHash;
3051
+ if (storeHash) {
3052
+ reportRouteOutcome(storeHash, "fail", turnDuration);
3053
+ }
3054
+ }
3055
+ const stopFailureInput = {
3056
+ hook_event_name: "StopFailure",
3057
+ error: friendly,
3058
+ session_id: deps.session?.id,
3059
+ cwd: deps.bash.getCwd(),
3060
+ };
3061
+ await deps.fireHook(stopFailureInput, signal).catch(() => { });
3062
+ // Yield done FIRST — same rationale as the success path above.
3063
+ // postTurnCompact fire-and-forget so generator returns immediately.
3064
+ if (modelInfo?.contextWindow) {
3065
+ void deps.postTurnCompact(provider, system, modelInfo.contextWindow, signal).catch(() => { });
3066
+ }
3067
+ yield { type: "done" };
3068
+ return;
3069
+ }
3070
+ finally {
3071
+ await closeMcp?.().catch(() => { });
3072
+ }
3073
+ }
3074
+ }
3075
+ catch (err) {
3076
+ throw err;
3077
+ }
3078
+ }
3079
+ //# sourceMappingURL=tool-engine.js.map