somora 2026.930.1

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 (404) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +364 -0
  3. package/bin/node-version.d.mts +3 -0
  4. package/bin/node-version.mjs +45 -0
  5. package/bin/somora.mjs +77 -0
  6. package/config.example.yaml +896 -0
  7. package/docs/agents.md +677 -0
  8. package/docs/api.md +3194 -0
  9. package/docs/browser.md +317 -0
  10. package/docs/builder.md +331 -0
  11. package/docs/cache-strategy.md +373 -0
  12. package/docs/compaction.md +253 -0
  13. package/docs/display.md +154 -0
  14. package/docs/dream-phases.md +891 -0
  15. package/docs/files.md +387 -0
  16. package/docs/imagegen.md +366 -0
  17. package/docs/images/somora-hero.png +0 -0
  18. package/docs/images/somora-mobile-2026-05-23.png +0 -0
  19. package/docs/images/somora-tui-2026-05-23.png +0 -0
  20. package/docs/images/somora-web-2026-05-23.png +0 -0
  21. package/docs/index.md +178 -0
  22. package/docs/lsp.md +93 -0
  23. package/docs/mcp.md +332 -0
  24. package/docs/memory.md +407 -0
  25. package/docs/mobile.md +310 -0
  26. package/docs/models.md +379 -0
  27. package/docs/projects.md +425 -0
  28. package/docs/realtime-voice.md +293 -0
  29. package/docs/resources.md +230 -0
  30. package/docs/sampling.md +128 -0
  31. package/docs/security.md +189 -0
  32. package/docs/sentinel.md +295 -0
  33. package/docs/setup.md +1217 -0
  34. package/docs/skills.md +501 -0
  35. package/docs/team.md +189 -0
  36. package/docs/thinking.md +463 -0
  37. package/docs/tmux.md +399 -0
  38. package/docs/tools.md +117 -0
  39. package/docs/videogen.md +191 -0
  40. package/docs/voice.md +288 -0
  41. package/docs/web.md +893 -0
  42. package/docs/wiki.md +583 -0
  43. package/npm-shrinkwrap.json +5670 -0
  44. package/package.json +116 -0
  45. package/src/attachments/store.ts +196 -0
  46. package/src/browser/change-stream.ts +31 -0
  47. package/src/browser/display.ts +108 -0
  48. package/src/browser/policy.ts +121 -0
  49. package/src/browser/screencast.ts +374 -0
  50. package/src/browser/service.ts +1337 -0
  51. package/src/browser/session.ts +15 -0
  52. package/src/browser/snapshot.ts +40 -0
  53. package/src/cli/auth.ts +117 -0
  54. package/src/cli/codex.ts +41 -0
  55. package/src/cli/lsp.ts +71 -0
  56. package/src/cli/resolvers/clawhub.ts +400 -0
  57. package/src/cli/setup.ts +835 -0
  58. package/src/cli/skill.ts +619 -0
  59. package/src/cli/somora.ts +548 -0
  60. package/src/cli/systemd-unit.ts +72 -0
  61. package/src/cli/team.ts +148 -0
  62. package/src/cli/tui/activity-stream.ts +121 -0
  63. package/src/cli/tui/api.ts +479 -0
  64. package/src/cli/tui/app.tsx +1169 -0
  65. package/src/cli/tui/autocomplete.tsx +55 -0
  66. package/src/cli/tui/commands.ts +913 -0
  67. package/src/cli/tui/dream-glyphs.ts +22 -0
  68. package/src/cli/tui/footer.tsx +15 -0
  69. package/src/cli/tui/format.ts +28 -0
  70. package/src/cli/tui/header.tsx +279 -0
  71. package/src/cli/tui/index.tsx +120 -0
  72. package/src/cli/tui/markdown.tsx +63 -0
  73. package/src/cli/tui/sampling.ts +162 -0
  74. package/src/cli/tui/separator.tsx +13 -0
  75. package/src/cli/tui/state.ts +42 -0
  76. package/src/cli/tui/stream.ts +330 -0
  77. package/src/cli/tui/thinking-text.ts +54 -0
  78. package/src/cli/tui/turn-views.tsx +499 -0
  79. package/src/cli/tui/types.ts +410 -0
  80. package/src/cli/tui/work-queue.ts +161 -0
  81. package/src/cli/update-args.ts +55 -0
  82. package/src/cli/wiki.ts +406 -0
  83. package/src/compaction/index.ts +28 -0
  84. package/src/compaction/midturn.ts +210 -0
  85. package/src/compaction/policy.ts +154 -0
  86. package/src/compaction/summarize.ts +691 -0
  87. package/src/compaction/template.ts +90 -0
  88. package/src/compaction/types.ts +148 -0
  89. package/src/config/loader.ts +276 -0
  90. package/src/config/reload.ts +43 -0
  91. package/src/config/types.ts +2292 -0
  92. package/src/dream/deep-actions.ts +324 -0
  93. package/src/dream/deep-dispatcher.ts +237 -0
  94. package/src/dream/deep-llm.ts +388 -0
  95. package/src/dream/deep-prompts.ts +106 -0
  96. package/src/dream/deep-runner.ts +757 -0
  97. package/src/dream/deep-skip-cache.ts +199 -0
  98. package/src/dream/deep-worker.ts +229 -0
  99. package/src/dream/json-salvage.ts +34 -0
  100. package/src/dream/judge.ts +188 -0
  101. package/src/dream/loop-state.ts +286 -0
  102. package/src/dream/lucid-actions.ts +303 -0
  103. package/src/dream/lucid-batches.ts +94 -0
  104. package/src/dream/lucid-prompt.ts +82 -0
  105. package/src/dream/lucid-runner.ts +744 -0
  106. package/src/dream/lucid-storage.ts +277 -0
  107. package/src/dream/lucid-structure.ts +102 -0
  108. package/src/dream/lucid-types.ts +137 -0
  109. package/src/dream/lucid-worker.ts +224 -0
  110. package/src/dream/rem-dedup.ts +502 -0
  111. package/src/dream/rem-extract.ts +782 -0
  112. package/src/dream/rem-reset-run.ts +67 -0
  113. package/src/dream/rem-runner.ts +696 -0
  114. package/src/dream/rem-worker.ts +527 -0
  115. package/src/dream/review-window.ts +71 -0
  116. package/src/dream/scheduler-state.ts +129 -0
  117. package/src/dream/storage.ts +497 -0
  118. package/src/dream/types.ts +133 -0
  119. package/src/dream/wiki-context.ts +133 -0
  120. package/src/engine/a2a.ts +33 -0
  121. package/src/engine/availability.ts +63 -0
  122. package/src/engine/claude-cli.ts +969 -0
  123. package/src/engine/codex-app-server-client.ts +294 -0
  124. package/src/engine/codex-bin.ts +49 -0
  125. package/src/engine/codex-cli.ts +1014 -0
  126. package/src/engine/codex-dynamic-tools.ts +239 -0
  127. package/src/engine/codex-home.ts +63 -0
  128. package/src/engine/codex-thread-config.ts +74 -0
  129. package/src/engine/context-budget.ts +257 -0
  130. package/src/engine/engine-meta-labels.ts +211 -0
  131. package/src/engine/grok-cli.ts +941 -0
  132. package/src/engine/inline-think.ts +59 -0
  133. package/src/engine/model-availability.ts +105 -0
  134. package/src/engine/openai-compatible.ts +2464 -0
  135. package/src/engine/reasoning-retry.ts +83 -0
  136. package/src/engine/registry.ts +13 -0
  137. package/src/engine/replay.ts +195 -0
  138. package/src/engine/sampling.ts +90 -0
  139. package/src/engine/thinking-params.ts +264 -0
  140. package/src/engine/types.ts +269 -0
  141. package/src/engine/user-tag.ts +24 -0
  142. package/src/imagegen/aspect.ts +128 -0
  143. package/src/imagegen/generate.ts +642 -0
  144. package/src/imagegen/references.ts +75 -0
  145. package/src/imagegen/types.ts +154 -0
  146. package/src/lsp/client.ts +183 -0
  147. package/src/lsp/fake-server.helper.mjs +42 -0
  148. package/src/lsp/format.ts +29 -0
  149. package/src/lsp/index.ts +21 -0
  150. package/src/lsp/manager.ts +238 -0
  151. package/src/lsp/registry.ts +151 -0
  152. package/src/mcp/config.ts +117 -0
  153. package/src/mcp/hub/audit.ts +55 -0
  154. package/src/mcp/hub/bridge.ts +115 -0
  155. package/src/mcp/hub/catalog.ts +69 -0
  156. package/src/mcp/hub/credentials.ts +406 -0
  157. package/src/mcp/hub/env-expand.ts +14 -0
  158. package/src/mcp/hub/manager.ts +770 -0
  159. package/src/mcp/hub/normalize.ts +213 -0
  160. package/src/mcp/server.ts +368 -0
  161. package/src/mcp/tool-schema.ts +20 -0
  162. package/src/media/capabilities.ts +392 -0
  163. package/src/media/records.ts +175 -0
  164. package/src/media/store.ts +217 -0
  165. package/src/media/types.ts +69 -0
  166. package/src/memory/chunking.ts +168 -0
  167. package/src/memory/embeddings.ts +262 -0
  168. package/src/memory/index.ts +15 -0
  169. package/src/memory/inject.ts +197 -0
  170. package/src/memory/manager.ts +996 -0
  171. package/src/memory/registry.ts +176 -0
  172. package/src/memory/rescan.ts +101 -0
  173. package/src/memory/retrieval.ts +586 -0
  174. package/src/memory/shared-index.ts +372 -0
  175. package/src/memory/slug.ts +39 -0
  176. package/src/memory/storage.ts +385 -0
  177. package/src/memory/watcher.ts +134 -0
  178. package/src/multimodal/blocks.ts +101 -0
  179. package/src/multimodal/dimensions.ts +214 -0
  180. package/src/multimodal/load.ts +86 -0
  181. package/src/multimodal/mime.ts +135 -0
  182. package/src/multimodal/pdf-render.ts +80 -0
  183. package/src/multimodal/user-content.ts +266 -0
  184. package/src/persona/files.ts +144 -0
  185. package/src/persona/loader.ts +598 -0
  186. package/src/persona/skill-gating-store.ts +59 -0
  187. package/src/persona/tool-gating-store.ts +113 -0
  188. package/src/projects/focus.ts +186 -0
  189. package/src/projects/prompt-block.ts +106 -0
  190. package/src/projects/scheme.ts +107 -0
  191. package/src/projects/store.ts +144 -0
  192. package/src/projects/types.ts +73 -0
  193. package/src/sentinel/dispatcher.ts +97 -0
  194. package/src/sentinel/schedule.ts +271 -0
  195. package/src/sentinel/scheduler.ts +840 -0
  196. package/src/sentinel/store.ts +259 -0
  197. package/src/sentinel/types.ts +221 -0
  198. package/src/server/activity-stream.ts +160 -0
  199. package/src/server/ask-calls.ts +137 -0
  200. package/src/server/ask-wait-graph.ts +171 -0
  201. package/src/server/async-tasks.ts +199 -0
  202. package/src/server/builder-busy.ts +86 -0
  203. package/src/server/builder-prompt.ts +204 -0
  204. package/src/server/builder-questions.ts +117 -0
  205. package/src/server/builder-session.ts +249 -0
  206. package/src/server/chat-aborts.ts +83 -0
  207. package/src/server/claude-config-dir.ts +71 -0
  208. package/src/server/claude-credential-sync.ts +454 -0
  209. package/src/server/env-file.ts +100 -0
  210. package/src/server/env.ts +115 -0
  211. package/src/server/heal-session.ts +151 -0
  212. package/src/server/history-page.ts +46 -0
  213. package/src/server/index.ts +7244 -0
  214. package/src/server/lockfile.ts +89 -0
  215. package/src/server/logger.ts +67 -0
  216. package/src/server/logs.ts +187 -0
  217. package/src/server/loopback-fetch.ts +130 -0
  218. package/src/server/openai-client.ts +89 -0
  219. package/src/server/prompt-assembly.ts +334 -0
  220. package/src/server/restart-reconcile.ts +139 -0
  221. package/src/server/run-turn-fallback.ts +275 -0
  222. package/src/server/run-turn-types.ts +91 -0
  223. package/src/server/run-turn.ts +1474 -0
  224. package/src/server/sanitize-assistant-text.ts +112 -0
  225. package/src/server/session-export.ts +220 -0
  226. package/src/server/session-queue.ts +376 -0
  227. package/src/server/session-workdir.ts +49 -0
  228. package/src/server/sse-h2-safe.ts +61 -0
  229. package/src/server/sse-liveness.ts +162 -0
  230. package/src/server/sse-serializer.ts +161 -0
  231. package/src/server/start-turn.ts +249 -0
  232. package/src/server/steer-inbox.ts +107 -0
  233. package/src/server/tls-keeper.ts +153 -0
  234. package/src/server/tool-format.ts +167 -0
  235. package/src/server/turn-framing.ts +52 -0
  236. package/src/server/turn-origin-kind.ts +74 -0
  237. package/src/server/turn-origin.ts +40 -0
  238. package/src/server/work-ledger.ts +975 -0
  239. package/src/server/workspace.ts +114 -0
  240. package/src/setup/config-edit.ts +201 -0
  241. package/src/setup/presets.ts +71 -0
  242. package/src/setup/prompt.ts +163 -0
  243. package/src/setup/tailscale.ts +44 -0
  244. package/src/skills/bin-checks.ts +227 -0
  245. package/src/skills/bootstrap.ts +347 -0
  246. package/src/skills/env-scope.ts +175 -0
  247. package/src/skills/gating.ts +71 -0
  248. package/src/skills/lint.ts +202 -0
  249. package/src/skills/load.ts +368 -0
  250. package/src/skills/path-helpers.ts +102 -0
  251. package/src/skills/registry.ts +178 -0
  252. package/src/ssh/exec.ts +142 -0
  253. package/src/ssh/index.ts +12 -0
  254. package/src/ssh/known-hosts.ts +109 -0
  255. package/src/ssh/pool.ts +307 -0
  256. package/src/storage/sessions.ts +602 -0
  257. package/src/team/render.ts +149 -0
  258. package/src/team/resolve.ts +122 -0
  259. package/src/team/store.ts +124 -0
  260. package/src/team/types.ts +111 -0
  261. package/src/team/write.ts +95 -0
  262. package/src/testing/isolated-home.mts +46 -0
  263. package/src/tmux/attention-watcher.ts +272 -0
  264. package/src/tmux/attention.ts +336 -0
  265. package/src/tmux/list.ts +91 -0
  266. package/src/tmux/origin-store.ts +102 -0
  267. package/src/tmux/tui-markers.ts +267 -0
  268. package/src/tools/agents/ask-cancel.ts +94 -0
  269. package/src/tools/agents/ask-result.ts +235 -0
  270. package/src/tools/agents/ask.ts +704 -0
  271. package/src/tools/agents/builder-dispatch.ts +217 -0
  272. package/src/tools/agents/images.ts +104 -0
  273. package/src/tools/agents/index.ts +42 -0
  274. package/src/tools/agents/long-task-timeouts.ts +39 -0
  275. package/src/tools/agents/session-list.ts +136 -0
  276. package/src/tools/agents/session-model.ts +106 -0
  277. package/src/tools/agents/spawn.ts +845 -0
  278. package/src/tools/agents/status.ts +589 -0
  279. package/src/tools/browser/index.ts +6 -0
  280. package/src/tools/browser/ops.ts +145 -0
  281. package/src/tools/browser/tools.ts +184 -0
  282. package/src/tools/builder/short-descriptions.ts +80 -0
  283. package/src/tools/builder/tools.ts +222 -0
  284. package/src/tools/docs/index.ts +1 -0
  285. package/src/tools/docs/tools.ts +228 -0
  286. package/src/tools/dream/index.ts +11 -0
  287. package/src/tools/dream/tools.ts +1002 -0
  288. package/src/tools/exec/allowlist.ts +233 -0
  289. package/src/tools/exec/background-detach.helper.mts +27 -0
  290. package/src/tools/exec/blacklist.ts +336 -0
  291. package/src/tools/exec/concurrency.ts +150 -0
  292. package/src/tools/exec/fit-output.ts +82 -0
  293. package/src/tools/exec/index.ts +7 -0
  294. package/src/tools/exec/internal-env.ts +89 -0
  295. package/src/tools/exec/job-store.ts +403 -0
  296. package/src/tools/exec/local.ts +649 -0
  297. package/src/tools/exec/remote.ts +399 -0
  298. package/src/tools/exec/tools.ts +934 -0
  299. package/src/tools/file/analyze.ts +378 -0
  300. package/src/tools/file/index.ts +2 -0
  301. package/src/tools/file/local.ts +707 -0
  302. package/src/tools/file/lsp-hook.ts +72 -0
  303. package/src/tools/file/persona-guard.ts +61 -0
  304. package/src/tools/file/policy.ts +292 -0
  305. package/src/tools/file/read-format.ts +129 -0
  306. package/src/tools/file/remote.ts +680 -0
  307. package/src/tools/file/replace.ts +507 -0
  308. package/src/tools/file/search-window.ts +224 -0
  309. package/src/tools/file/tools.ts +658 -0
  310. package/src/tools/file/write-scope.ts +182 -0
  311. package/src/tools/gating.ts +106 -0
  312. package/src/tools/image/budget.ts +82 -0
  313. package/src/tools/image/index.ts +7 -0
  314. package/src/tools/image/tools.ts +601 -0
  315. package/src/tools/index.ts +99 -0
  316. package/src/tools/memory/index.ts +12 -0
  317. package/src/tools/memory/tools.ts +399 -0
  318. package/src/tools/projects/index.ts +1 -0
  319. package/src/tools/projects/tools.ts +643 -0
  320. package/src/tools/registry.ts +427 -0
  321. package/src/tools/resources/index.ts +8 -0
  322. package/src/tools/resources/tools.ts +176 -0
  323. package/src/tools/resources/visibility.ts +60 -0
  324. package/src/tools/sentinel/index.ts +1 -0
  325. package/src/tools/sentinel/tools.ts +592 -0
  326. package/src/tools/skill/index.ts +4 -0
  327. package/src/tools/skill/tools.ts +285 -0
  328. package/src/tools/time/index.ts +5 -0
  329. package/src/tools/time/tools.ts +123 -0
  330. package/src/tools/tmux/index.ts +1 -0
  331. package/src/tools/tmux/local.ts +277 -0
  332. package/src/tools/tmux/remote.ts +168 -0
  333. package/src/tools/tmux/tools.ts +1064 -0
  334. package/src/tools/tool-output.ts +97 -0
  335. package/src/tools/types.ts +227 -0
  336. package/src/tools/video/index.ts +1 -0
  337. package/src/tools/video/tools.ts +425 -0
  338. package/src/tools/web/fetch.ts +337 -0
  339. package/src/tools/web/index.ts +4 -0
  340. package/src/tools/web/tools.ts +186 -0
  341. package/src/tools/wiki/index.ts +1 -0
  342. package/src/tools/wiki/tools.ts +445 -0
  343. package/src/tts/cache-gc.ts +128 -0
  344. package/src/tts/prepare-for-tts.ts +114 -0
  345. package/src/tts/service.ts +332 -0
  346. package/src/types/events.ts +695 -0
  347. package/src/types/turn-origin.ts +53 -0
  348. package/src/version.ts +21 -0
  349. package/src/videogen/dialects.ts +222 -0
  350. package/src/videogen/generate.ts +484 -0
  351. package/src/videogen/jobs.ts +178 -0
  352. package/src/videogen/runner.ts +125 -0
  353. package/src/videogen/wake.ts +119 -0
  354. package/src/voice/realtime/call.ts +948 -0
  355. package/src/voice/realtime/consult.ts +293 -0
  356. package/src/voice/realtime/fake-provider.ts +134 -0
  357. package/src/voice/realtime/manager.ts +384 -0
  358. package/src/voice/realtime/openai-provider.ts +471 -0
  359. package/src/voice/realtime/persona.ts +227 -0
  360. package/src/voice/realtime/session-match.ts +116 -0
  361. package/src/voice/realtime/types.ts +182 -0
  362. package/src/wiki/conflict.ts +113 -0
  363. package/src/wiki/explorer.ts +578 -0
  364. package/src/wiki/index-builder.ts +172 -0
  365. package/src/wiki/language.ts +134 -0
  366. package/src/wiki/log-builder.ts +150 -0
  367. package/src/wiki/map.ts +258 -0
  368. package/src/wiki/migration/analyze.ts +304 -0
  369. package/src/wiki/migration/execute.ts +689 -0
  370. package/src/wiki/migration/refine.ts +402 -0
  371. package/src/wiki/migration/store.ts +100 -0
  372. package/src/wiki/move-page.ts +57 -0
  373. package/src/wiki/structure-file.ts +192 -0
  374. package/src/wiki/taxonomy.ts +140 -0
  375. package/src/wiki/templates.ts +163 -0
  376. package/src/wiki/types.ts +133 -0
  377. package/templates/skills/README.md +24 -0
  378. package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
  379. package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
  380. package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
  381. package/templates/skills/_templates/default/SKILL.md +25 -0
  382. package/templates/skills/builder-handover/SKILL.md +96 -0
  383. package/templates/skills/builder-handover/assets/ORDER.md +12 -0
  384. package/templates/skills/skill-author/SKILL.md +110 -0
  385. package/tsconfig.json +22 -0
  386. package/web/dist/assets/index-BaVv6pB2.js +631 -0
  387. package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
  388. package/web/dist/assets/index-V3FV3Z25.css +32 -0
  389. package/web/dist/favicon.svg +8 -0
  390. package/web/dist/index.html +20 -0
  391. package/web/package.json +36 -0
  392. package/web/tsconfig.json +25 -0
  393. package/web-mobile/dist/apple-touch-icon.png +0 -0
  394. package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
  395. package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
  396. package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
  397. package/web-mobile/dist/favicon.svg +8 -0
  398. package/web-mobile/dist/icon-192.png +0 -0
  399. package/web-mobile/dist/icon-512.png +0 -0
  400. package/web-mobile/dist/index.html +27 -0
  401. package/web-mobile/dist/manifest.webmanifest +32 -0
  402. package/web-mobile/dist/service-worker.js +90 -0
  403. package/web-mobile/package.json +28 -0
  404. package/web-mobile/tsconfig.json +25 -0
@@ -0,0 +1,1474 @@
1
+ // runChatTurn — single chokepoint for "run one chat turn through the
2
+ // somora pipeline". Used by the live chat/send HTTP handler (which
3
+ // publishes events to SSE subscribers as they happen) and by
4
+ // spawn_subagent (which omits SSE since sub-flows are silent and
5
+ // just collects the final result).
6
+ //
7
+ // Pipeline stages:
8
+ // 1. resolve persona, session, model
9
+ // 2. append user_message to JSONL (with optional from_agent)
10
+ // 3. cancel any in-flight auto-dream + reset idle timer
11
+ // 4. compute self-pointer + system prompt
12
+ // 5. memory auto-inject (best-effort)
13
+ // 6. build tool-invoker bound to the per-turn ToolContext
14
+ // 7. run engine via runTurnWithFallback
15
+ // 8. for each event: persist (skip assistant_delta), invoke
16
+ // optional publishSse callback, accumulate final text + usage
17
+ // 9. return the collected result
18
+ //
19
+ // publishSse is optional. When omitted, the turn runs silently; the
20
+ // agent's auto-dream worker still resets, JSONL still grows, memory
21
+ // inject still happens. This is the hot path for spawn_subagent.
22
+
23
+ import { randomUUID } from 'node:crypto';
24
+ import type {
25
+ ChatTurnMedia,
26
+ ChatTurnOutcome,
27
+ ChatTurnResolveDeps,
28
+ ChatTurnResult,
29
+ } from './run-turn-types.ts';
30
+ import { appendEvent, getHistory } from '../storage/sessions.ts';
31
+ import { healOrphanToolCalls } from './heal-session.ts';
32
+ import { resolveCompactionConfig } from '../compaction/index.ts';
33
+ import {
34
+ type Config,
35
+ describeModelRefs,
36
+ listAllModels,
37
+ resolveAnyRef,
38
+ workerChain,
39
+ type ThinkingLevel,
40
+ type SamplingConfig,
41
+ } from '../config/types.ts';
42
+ import { describeMedia } from '../tools/file/analyze.ts';
43
+ import { loadAttachment } from '../multimodal/load.ts';
44
+ import { engineRegistry } from '../engine/registry.ts';
45
+ import { runTurnWithFallback } from './run-turn-fallback.ts';
46
+ import { clearTurnOrigin, setTurnOrigin } from './turn-origin.ts';
47
+ import { drainSteer, frameSteerMessage, markSteerable, requeueSteer, unmarkSteerable } from './steer-inbox.ts';
48
+ import { BUILDER_LOOP_DEFAULTS } from './builder-prompt.ts';
49
+ import { builderSessionAllows, ensureBuilderState, type BuilderSessionState } from './builder-session.ts';
50
+ import { builderToolDescription } from '../tools/builder/short-descriptions.ts';
51
+ import { workdirFromMeta } from './session-workdir.ts';
52
+ import { claimWorkdir, describeClaim, noteToolCall, workdirClaimedBy } from './builder-busy.ts';
53
+ import { originKind, type TurnOrigin } from './turn-origin-kind.ts';
54
+ import { assembleSystemPrompt } from './prompt-assembly.ts';
55
+ import type { ResolvedAttachment } from '../engine/types.ts';
56
+ import { resolveAttachmentByHash } from '../attachments/store.ts';
57
+ import { listRecords as listMediaRecords, readRecord as readMediaRecord } from '../media/records.ts';
58
+ import {
59
+ buildReviewLoopBlock,
60
+ refreshLoopActivity,
61
+ resetWikiCallCounter,
62
+ } from '../dream/loop-state.ts';
63
+ import { injectMemoryContext } from '../memory/inject.ts';
64
+ import { getMemoryManager } from '../memory/registry.ts';
65
+ import { logger } from './logger.ts';
66
+ import { loadPersona, type Persona } from '../persona/loader.ts';
67
+ import { isToolAllowed } from '../tools/gating.ts';
68
+ import { createTurnSerializer } from './sse-serializer.ts';
69
+ import { sanitizeAssistantText } from './sanitize-assistant-text.ts';
70
+ import { synthesize } from '../tts/service.ts';
71
+ import { prepareForTts } from '../tts/prepare-for-tts.ts';
72
+ import type { ToolRegistry } from '../tools/index.ts';
73
+ import type { NormalizedEvent, SseEvent } from '../types/events.ts';
74
+ import { resolveOpenAiReasoning } from '../engine/thinking-params.ts';
75
+ import { mergeSampling } from '../engine/sampling.ts';
76
+ import { SOMORA_HOME_DIR } from './logger.ts';
77
+
78
+ const VALID_THINKING_LEVELS = new Set<ThinkingLevel>(['off', 'low', 'medium', 'high']);
79
+
80
+ // Injected into the system prompt when the agent has tools and
81
+ // `agentLoop.toolUsageReminder` is on. Kept short and constant — it has
82
+ // to earn its place in every single prompt.
83
+ // Exported so prompt-effect probes can assemble the same system prompt
84
+ // the runtime sends. Measuring a variant that omits it measures a prompt
85
+ // nobody ever sees.
86
+ export { TOOL_USAGE_REMINDER } from './prompt-assembly.ts';
87
+
88
+ function resolveEffectiveModel(
89
+ config: Config,
90
+ persona: Persona,
91
+ sessionMeta: Record<string, unknown>,
92
+ ) {
93
+ const override = sessionMeta.modelOverride;
94
+ const ref = typeof override === 'string' && override.length > 0 ? override : persona.model;
95
+ if (!ref) return null;
96
+ return resolveAnyRef(config, ref);
97
+ }
98
+
99
+ // Resolve the idle-event watchdog timeout per engine. Defaults live in
100
+ // EngineWatchdogConfigSchema; this just bridges engine-name → field.
101
+ function pickIdleTimeoutForEngine(
102
+ cfg: import('../config/types.ts').EngineWatchdogConfig,
103
+ engine: import('../config/types.ts').EngineName,
104
+ ): number {
105
+ switch (engine) {
106
+ case 'claude-cli':
107
+ return cfg.claudeCliIdleMs;
108
+ case 'codex-cli':
109
+ return cfg.codexCliIdleMs;
110
+ case 'grok-cli':
111
+ return cfg.grokCliIdleMs;
112
+ case 'openai-compatible':
113
+ return cfg.openaiCompatibleIdleMs;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Relaxed idle threshold to use while a tool call is outstanding on a CLI
119
+ * engine — the MCP tool timeout, so a legit long tool isn't cut off by
120
+ * the much shorter normal idle watchdog (Juni-Audit 2026-06). Returns
121
+ * undefined for openai-compatible (it disarms the watchdog during its own
122
+ * in-process tool loop instead).
123
+ */
124
+ function pickToolIdleTimeoutForEngine(
125
+ config: import('../config/types.ts').Config,
126
+ engine: import('../config/types.ts').EngineName,
127
+ ): number | undefined {
128
+ switch (engine) {
129
+ case 'claude-cli':
130
+ return config.claudeCli.mcpToolTimeoutMs;
131
+ case 'codex-cli':
132
+ return config.codexCli.toolTimeoutSec * 1000;
133
+ case 'grok-cli':
134
+ // No grok-specific knob (the MCP-side timeout is grok's own); the
135
+ // question here is only "how long may a tool run before the
136
+ // engine counts as wedged", so borrow the larger sibling budget.
137
+ return Math.max(config.claudeCli.mcpToolTimeoutMs, config.codexCli.toolTimeoutSec * 1000);
138
+ case 'openai-compatible':
139
+ return undefined;
140
+ }
141
+ }
142
+
143
+ function resolveEffectiveThinking(
144
+ persona: Persona,
145
+ sessionMeta: Record<string, unknown>,
146
+ ): ThinkingLevel | undefined {
147
+ const override = sessionMeta.thinkingOverride;
148
+ if (typeof override === 'string' && VALID_THINKING_LEVELS.has(override as ThinkingLevel)) {
149
+ return override as ThinkingLevel;
150
+ }
151
+ return persona.thinking;
152
+ }
153
+
154
+ /** Sampling: model default < agent.yaml < session override, per key. */
155
+ export function resolveEffectiveSampling(
156
+ model: { sampling?: SamplingConfig },
157
+ persona: Persona,
158
+ sessionMeta: Record<string, unknown>,
159
+ ): SamplingConfig | undefined {
160
+ const override = sessionMeta.samplingOverride;
161
+ return mergeSampling(
162
+ model.sampling,
163
+ persona.sampling,
164
+ override && typeof override === 'object' ? (override as Record<string, unknown>) : undefined,
165
+ );
166
+ }
167
+
168
+ export interface RunChatTurnArgs {
169
+ agent: string;
170
+ session: string;
171
+ /** The new user-message text (the model's input for this turn). */
172
+ text: string;
173
+ /** Stable id used to correlate all log lines produced for this turn —
174
+ * from /chat/send acceptance through engine init, first event, and
175
+ * completion. Auto-generated when omitted; callers (HTTP handlers)
176
+ * pass one if they logged it earlier so the trace stays connected. */
177
+ turnId?: string;
178
+ /** A2A: when set, this turn was authored by another agent, not by the
179
+ * human user. Persists in user_message.from_agent. */
180
+ fromAgent?: string;
181
+ /** A2A: session the asking agent wrote from (id or 'main'). Persists
182
+ * in user_message.from_session and registers the turn's origin for
183
+ * agent_ask's reply-back default (src/server/turn-origin.ts). */
184
+ fromSession?: string;
185
+ /** Synthesized inbound marker: when set, this turn's text was
186
+ * produced by an internal subsystem — a sentinel fire, a tmux or
187
+ * browser wake, a voice consult, or a wake-up about a finished
188
+ * agent_ask / sub-agent / video job. Persists in
189
+ * user_message.from_system and on the SSE event, so clients render
190
+ * the message as a centered system divider rather than a normal
191
+ * user-bubble. Mutually exclusive with fromAgent. Derived from
192
+ * `origin` when a caller goes through startTurn. */
193
+ fromSystem?: 'sentinel' | 'tmux' | 'subagent' | 'job' | 'browser' | 'voice' | 'a2a';
194
+ /** Where this turn came from, as one value (src/types/turn-origin.ts).
195
+ * Persisted additively on user_message and the SSE event; the
196
+ * legacy fields above stay what old sessions, clients and engines
197
+ * read. Set by startTurn for every caller that goes through it. */
198
+ origin?: TurnOrigin;
199
+ /**
200
+ * Scaffolding for THIS turn that the model sees and the record does
201
+ * not: why the turn looks the way it does, what was said around it.
202
+ *
203
+ * It joins the memory block in `ephemeral`, which every engine puts in
204
+ * front of the user message and which replays byte-identically, so
205
+ * nothing about caching changes. `text` stays what the human asked —
206
+ * and `text` is what the dream phase learns from, what the recall
207
+ * search is built from, and what a reader sees. Introduced for voice
208
+ * calls, whose framing was half of every stored turn (2026-09-12).
209
+ */
210
+ turnPrefix?: string;
211
+ /** Media made before this turn that nevertheless belongs to it —
212
+ * a finished video announced by a wake-up. See publishTurnMedia. */
213
+ attachMediaIds?: string[];
214
+ /** A2A correlation UUID. Persisted on user_message.agent_ask_call_id;
215
+ * surfaced in the SSE user_message event so a human watching the
216
+ * session sees the inbound message appear in real time. */
217
+ agentAskCallId?: string;
218
+ /** Sub-agent nesting depth (0 = top-level user turn). */
219
+ subagentDepth?: number;
220
+ /** Optional override of the per-session model — caller passes the alias
221
+ * or "provider/id". Bypasses persona/session-meta resolution. */
222
+ modelOverride?: string;
223
+ /** Optional per-call override of the agent-loop tunables. Used by
224
+ * spawn_subagent to give orchestrator subs a higher maxRounds budget
225
+ * than the global default. Falls back to deps.config.agentLoop. */
226
+ agentLoopOverride?: {
227
+ maxRounds?: number;
228
+ toolCallTimeoutMs?: number;
229
+ };
230
+ /** Optional SSE publisher. When provided, the turn streams agent-start,
231
+ * memory, tool, chat-delta/final, and agent-end events as they happen
232
+ * (live chat/send case). When omitted, no events are published — the
233
+ * spawn_subagent / silent-runner case. */
234
+ publishSse?: (event: SseEvent) => Promise<void>;
235
+ /** Optional abort signal. POST /chat/abort (Stop button, TUI ESC,
236
+ * subagent_cancel) triggers it; the engine adapter (claude-cli/
237
+ * codex-cli/openai-compatible) honors it and cuts the in-flight LLM
238
+ * call cleanly. startTurn registers one for every turn. */
239
+ signal?: AbortSignal;
240
+ /** User-attached files for this turn (Phase Y.B). Refs persisted on
241
+ * the user_message event in JSONL; resolved to absolute paths +
242
+ * metadata before the engine runs. */
243
+ attachments?: Array<{ hash: string; name: string; mime: string; size: number }>;
244
+ /** Voice: how the user produced this turn. `voice` ⇒ STT-transcribed
245
+ * on web/mobile or via /voice/turn. `text` (or undefined) ⇒ typed.
246
+ * Persists on user_message.input.modality and gates auto-TTS. */
247
+ inputModality?: 'text' | 'voice';
248
+ /** Voice: free-form tag for the STT path used (provider name). */
249
+ sttProvider?: string;
250
+ /** Voice: did the client request a spoken reply for this turn? The
251
+ * auto-TTS hook fires only when (inputModality==='voice' AND
252
+ * autoPlayRequested===true). Default-off keeps text-only sessions
253
+ * silent. */
254
+ autoPlayRequested?: boolean;
255
+ /** Wiring deps. Server boot constructs these once and reuses. */
256
+ deps: ChatTurnResolveDeps;
257
+ }
258
+
259
+ /**
260
+ * Auto-TTS background task. Called fire-and-forget after a turn
261
+ * completes whose user_message arrived via voice + autoPlayRequested.
262
+ * Sanitizes the assistant text for speech, synthesizes audio (or
263
+ * grabs from cache), appends an `assistant_audio` event to JSONL, and
264
+ * broadcasts via SSE so live clients can render a Play-button and
265
+ * auto-play if their toggle is on.
266
+ */
267
+ async function generateAutoTts(args: {
268
+ agent: string;
269
+ session: string;
270
+ turnId: string;
271
+ text: string;
272
+ engine: string;
273
+ config: Config;
274
+ publishSse?: (event: SseEvent) => Promise<void>;
275
+ parentTurnId: string;
276
+ }): Promise<void> {
277
+ const { agent, session, turnId, text, engine, config, publishSse, parentTurnId } = args;
278
+ const ttsCfg = config.tts;
279
+ if (!ttsCfg?.enabled) return;
280
+
281
+ const prepared = prepareForTts(text);
282
+ if (prepared.skipped) {
283
+ logger.info({
284
+ msg: 'turn.auto_tts_skipped',
285
+ turnId: parentTurnId,
286
+ agent,
287
+ session,
288
+ reason: prepared.reason,
289
+ });
290
+ return;
291
+ }
292
+
293
+ const start = Date.now();
294
+ // Auto-TTS always serves opus when reencode is on — smallest
295
+ // payload for mobile auto-play. Falls back to wav otherwise.
296
+ const fmt: 'wav' | 'opus' = ttsCfg.reencode.enabled ? 'opus' : 'wav';
297
+ const synth = await synthesize(
298
+ {
299
+ text: prepared.text,
300
+ ...(ttsCfg.voice ? { voice: ttsCfg.voice } : {}),
301
+ ...(ttsCfg.language ? { language: ttsCfg.language } : {}),
302
+ format: fmt,
303
+ agent,
304
+ },
305
+ config,
306
+ );
307
+ const url = `/tts/cache/${synth.cacheKey}.${synth.ext}`;
308
+ logger.info({
309
+ msg: 'turn.auto_tts_ready',
310
+ turnId: parentTurnId,
311
+ agent,
312
+ session,
313
+ cacheHit: synth.cacheHit,
314
+ cacheKey: synth.cacheKey,
315
+ bytes: synth.bytes.length,
316
+ durationMs: synth.durationMs ?? null,
317
+ ms: Date.now() - start,
318
+ });
319
+
320
+ const evt = {
321
+ kind: 'assistant_audio' as const,
322
+ ts: Date.now(),
323
+ engine,
324
+ turnId,
325
+ audio: {
326
+ url,
327
+ mime: synth.mime,
328
+ ...(synth.durationMs !== undefined ? { durationMs: synth.durationMs } : {}),
329
+ cacheKey: synth.cacheKey,
330
+ },
331
+ };
332
+ await appendEvent(agent, session, evt);
333
+ if (publishSse) {
334
+ await publishSse({
335
+ event: 'assistant_audio',
336
+ data: {
337
+ turnId,
338
+ url,
339
+ mime: synth.mime,
340
+ ...(synth.durationMs !== undefined ? { durationMs: synth.durationMs } : {}),
341
+ cacheKey: synth.cacheKey,
342
+ },
343
+ });
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Publish the images generated during a turn so they show up in the
349
+ * user's chat.
350
+ *
351
+ * Found by querying the image records for this agent+session created
352
+ * since the turn started, rather than by watching tool results go by.
353
+ * That's deliberate: with claude-cli / codex-cli the tool runs inside
354
+ * an MCP CHILD PROCESS, so an in-memory hook here would see nothing and
355
+ * images would appear in chat for some engines but not others. The
356
+ * records are on disk and the same for every engine.
357
+ *
358
+ * The window is [turnStartedAt, now]. A concurrent turn in the same
359
+ * session could in principle overlap, but turns in a session are
360
+ * serialized by the turn lock, so the only overlap available is a
361
+ * subagent — which carries its own session.
362
+ */
363
+ async function publishTurnMedia(args: {
364
+ agent: string;
365
+ session: string;
366
+ turnId: string;
367
+ engine: string;
368
+ startedAt: number;
369
+ /**
370
+ * Media that belongs to this turn but was NOT made during it. A video
371
+ * render finishes minutes after the turn that ordered it, and the
372
+ * turn that reports it is a wake-up started afterwards — so the file
373
+ * predates its own announcement and the time window below would miss
374
+ * it. Naming it explicitly is the honest fix; widening the window
375
+ * would sweep in whatever else happened to be lying around.
376
+ */
377
+ attachMediaIds?: string[];
378
+ publishSse?: (event: SseEvent) => Promise<void>;
379
+ }): Promise<ChatTurnMedia[]> {
380
+ const { agent, session, turnId, engine, startedAt, publishSse } = args;
381
+ const { items } = await listMediaRecords({
382
+ agent,
383
+ session,
384
+ since: new Date(startedAt).toISOString(),
385
+ limit: 50,
386
+ });
387
+ const seen = new Set(items.map((i) => i.id));
388
+ for (const id of args.attachMediaIds ?? []) {
389
+ if (seen.has(id)) continue;
390
+ const extra = await readMediaRecord(id);
391
+ if (extra) {
392
+ items.push(extra);
393
+ seen.add(id);
394
+ }
395
+ }
396
+ if (items.length === 0) return [];
397
+
398
+ // listRecords returns newest first; chat should read in the order
399
+ // they were made.
400
+ const ordered = [...items].reverse();
401
+ const evt = {
402
+ kind: 'assistant_media' as const,
403
+ ts: Date.now(),
404
+ engine,
405
+ turnId,
406
+ media: ordered.map((m) => ({
407
+ type: (m.kind ?? 'image') as 'image' | 'video',
408
+ id: m.id,
409
+ prompt: m.prompt,
410
+ mime: m.mime,
411
+ filename: m.filename,
412
+ url: `/media/${m.id}/file`,
413
+ ...(m.thumbPath ? { thumbUrl: `/media/${m.id}/thumb` } : {}),
414
+ ...(m.durationSec !== undefined ? { durationSec: m.durationSec } : {}),
415
+ })),
416
+ };
417
+ await appendEvent(agent, session, evt);
418
+ if (publishSse) {
419
+ await publishSse({ event: 'assistant_media', data: { turnId, media: evt.media } });
420
+ }
421
+ logger.info({ msg: 'turn.media_published', turnId, agent, session, count: evt.media.length });
422
+ return ordered.map((m) => ({
423
+ type: (m.kind ?? 'image') as 'image' | 'video',
424
+ id: m.id,
425
+ path: m.path,
426
+ filename: m.filename,
427
+ mime: m.mime,
428
+ prompt: m.prompt,
429
+ url: `/media/${m.id}/file`,
430
+ }));
431
+ }
432
+
433
+ export async function runChatTurn(args: RunChatTurnArgs): Promise<ChatTurnResult> {
434
+ const start = Date.now();
435
+ const {
436
+ agent,
437
+ session,
438
+ text,
439
+ fromAgent,
440
+ fromSession,
441
+ fromSystem,
442
+ origin,
443
+ turnPrefix,
444
+ attachMediaIds,
445
+ agentAskCallId,
446
+ subagentDepth = 0,
447
+ modelOverride,
448
+ agentLoopOverride,
449
+ publishSse,
450
+ signal,
451
+ attachments,
452
+ inputModality,
453
+ sttProvider,
454
+ autoPlayRequested,
455
+ deps,
456
+ } = args;
457
+ // Turn-lifecycle id — stable across every log line this turn produces,
458
+ // so an overnight forensics pass can trace a hung turn from /chat/send
459
+ // through memory inject + engine init + first event + completion.
460
+ // Caller may pre-generate one (HTTP /chat/send does, so the trace
461
+ // begins at request acceptance) — otherwise we mint here.
462
+ const turnId = args.turnId ?? randomUUID();
463
+ // Lower bound for the generated-images lookup at the end of the
464
+ // turn. Taken before any engine work so an image produced by the
465
+ // very first tool call is inside the window.
466
+ const turnStartedAt = Date.now();
467
+ /** Set when run-turn-fallback re-ran this turn on the fallback model —
468
+ * the phase:'end' payload and the result report the ACTUAL model. */
469
+ let turnFallback: ChatTurnResult['fallback'];
470
+ logger.info({
471
+ msg: 'turn.started',
472
+ turnId,
473
+ agent,
474
+ session,
475
+ subagentDepth,
476
+ fromAgent: fromAgent ?? null,
477
+ fromSession: fromSession ?? null,
478
+ fromSystem: fromSystem ?? null,
479
+ origin: origin ? originKind(origin) : null,
480
+ textLen: text.length,
481
+ attachmentCount: attachments?.length ?? 0,
482
+ });
483
+
484
+ const persona = await loadPersona(agent);
485
+ if (!persona) {
486
+ throw new Error(`agent '${agent}' not found`);
487
+ }
488
+
489
+ let sessionMeta = await deps.sessionMetaStore.get(agent, session);
490
+ const effectiveMetaForResolve = modelOverride
491
+ ? { ...sessionMeta, modelOverride }
492
+ : sessionMeta;
493
+ const resolvedModel = resolveEffectiveModel(deps.config, persona, effectiveMetaForResolve);
494
+ if (!resolvedModel) {
495
+ const ref = effectiveMetaForResolve.modelOverride ?? persona.model ?? '(none)';
496
+ throw new Error(
497
+ `model '${String(ref)}' for agent '${agent}' cannot be resolved from config.yaml — ` +
498
+ `use an alias or provider/modelId exactly as configured. Available: ${describeModelRefs(deps.config)}`,
499
+ );
500
+ }
501
+ const engine = engineRegistry[resolvedModel.provider.engine];
502
+ if (!engine) {
503
+ throw new Error(`no engine '${resolvedModel.provider.engine}' registered`);
504
+ }
505
+
506
+ // Compute the per-turn memory recall block FIRST so we can persist
507
+ // it on the user_message event. Storing the recall block alongside
508
+ // the user-typed text is what lets stateless openai-compatible
509
+ // backends benefit from prefix-cache: history reconstruction at
510
+ // turn N+1 produces the SAME byte sequence we sent at turn N (incl.
511
+ // memory block), so the cache match holds across the entire prior
512
+ // conversation. Without persistence, every turn would reconstruct
513
+ // past user_messages without their memory blocks → byte-mismatch
514
+ // → cache invalidates at the latest user-message position every
515
+ // turn. Engines with stateful resumed sessions (claude-cli,
516
+ // codex-cli) ignore this field — they inline the block once into
517
+ // the outgoing message and the provider remembers everything.
518
+ const historyBeforeTurn = await getHistory(agent, session);
519
+
520
+ // Self-heal: if the previous turn died mid-flight (engine subprocess
521
+ // crash after tool_use but before tool_result), the JSONL tail will
522
+ // have an orphan tool_call. Inject synthetic tool_result + turn_end
523
+ // and clear the SDK session-id BEFORE we append the new user_message
524
+ // so the engine sees a consistent history when it starts. The user
525
+ // gets self-recovery just by sending another message; no /reset
526
+ // needed. Reference: jarvis 2026-05-13 silent claude-cli crash.
527
+ try {
528
+ await healOrphanToolCalls({
529
+ agent,
530
+ session,
531
+ history: historyBeforeTurn,
532
+ metaStore: deps.sessionMetaStore,
533
+ fallbackEngine: engine.name,
534
+ });
535
+ } catch (err) {
536
+ logger.warn({
537
+ msg: 'session.heal_failed',
538
+ agent,
539
+ session,
540
+ err: (err as Error).message,
541
+ });
542
+ }
543
+
544
+ let ephemeralContext: string | undefined;
545
+ let memoryHits: Array<{ source: string; slug: string; score: number }> = [];
546
+ let memoryInjectedCount = 0;
547
+ // A builder gets no recall block: its context is the repository, and
548
+ // the block competes with code for the window (and, measured, with
549
+ // tool calls — feedback 2026-08). It still has memory_search as a tool.
550
+ if (persona.kind === 'builder') {
551
+ logger.debug({ msg: 'memory.inject_skipped_builder', turnId, agent });
552
+ } else
553
+ try {
554
+ const mgr = await getMemoryManager(agent, {
555
+ config: deps.config.memory,
556
+ wiki: deps.config.wiki,
557
+ obsidian: deps.config.obsidian,
558
+ });
559
+ const inject = await injectMemoryContext({
560
+ mgr,
561
+ history: historyBeforeTurn,
562
+ userMessage: text,
563
+ cfg: deps.config.memory.autoInject,
564
+ });
565
+ ephemeralContext = inject.ephemeralContext;
566
+ memoryInjectedCount = inject.injectedCount;
567
+ memoryHits = inject.hits;
568
+ if (inject.injectedCount > 0) {
569
+ logger.info({
570
+ msg: 'memory.injected',
571
+ turnId,
572
+ agent,
573
+ session,
574
+ count: inject.injectedCount,
575
+ slugs: inject.hits.map((h) => `${h.source}/${h.slug}`),
576
+ topScore: inject.hits[0]?.score,
577
+ });
578
+ }
579
+ } catch (err) {
580
+ logger.warn({ msg: 'memory.inject_failed', turnId, agent, err: (err as Error).message });
581
+ }
582
+
583
+ // Turn scaffolding goes in front of everything injected for this
584
+ // turn — it explains the shape of the turn, so it is read first.
585
+ if (turnPrefix && turnPrefix.trim().length > 0) {
586
+ ephemeralContext = ephemeralContext ? `${turnPrefix}\n\n${ephemeralContext}` : turnPrefix;
587
+ }
588
+
589
+ // Loop-holder gets the active Lucid review block prepended to the
590
+ // ephemeral context. Refreshed on every turn so the user can see
591
+ // that the agent stays on topic until dream_review({action:'end'}).
592
+ // Each new user turn also resets the per-turn wiki_* call counter
593
+ // so the cap (MAX_WIKI_CALLS_PER_TURN) applies to *this* turn only.
594
+ try {
595
+ const reviewBlock = await buildReviewLoopBlock(agent);
596
+ if (reviewBlock) {
597
+ ephemeralContext = ephemeralContext
598
+ ? `${reviewBlock}\n\n${ephemeralContext}`
599
+ : reviewBlock;
600
+ refreshLoopActivity(agent);
601
+ resetWikiCallCounter();
602
+ logger.debug({ msg: 'dream.loop.injected', agent, session });
603
+ }
604
+ } catch (err) {
605
+ logger.warn({ msg: 'dream.loop.inject_failed', agent, err: (err as Error).message });
606
+ }
607
+
608
+ // Resolve attachment refs to absolute paths + metadata BEFORE the
609
+ // user_message is persisted. If a hash isn't on disk we fail the
610
+ // whole turn early (clean error to client) rather than persisting
611
+ // a ref that points at nothing. Per-turn count + per-file caps
612
+ // were enforced at upload time; here we just do a sanity stat.
613
+ const resolvedAttachments: ResolvedAttachment[] = [];
614
+ /** Worker descriptions of files the model cannot see, appended to the
615
+ * message the engine gets. The persisted user_message keeps the
616
+ * original attachment refs, so the clients still show the picture. */
617
+ const describedAttachments: string[] = [];
618
+ if (attachments && attachments.length > 0) {
619
+ if (attachments.length > deps.config.attachments.maxPerTurn) {
620
+ throw new Error(
621
+ `${attachments.length} attachments exceed the per-turn cap of ${deps.config.attachments.maxPerTurn} (config.attachments.maxPerTurn)`,
622
+ );
623
+ }
624
+ for (const a of attachments) {
625
+ const r = await resolveAttachmentByHash({ hash: a.hash, expectedMime: a.mime });
626
+ resolvedAttachments.push({
627
+ hash: a.hash,
628
+ path: r.path,
629
+ name: a.name,
630
+ mime: r.mime,
631
+ size: r.size,
632
+ });
633
+ }
634
+ // Capability gate. A model that cannot see the attached kind used to
635
+ // end the turn with "switch models". That is exactly the situation
636
+ // the vision worker exists for (Rene 2026-09-10), so the worker
637
+ // describes the file and its text rides along with the message. The
638
+ // refusal stays for the case where no worker is configured.
639
+ //
640
+ // PDFs ride either as native document blocks (cap=pdf) or as
641
+ // rasterised PNGs (cap=image), so either capability is enough.
642
+ const caps = resolvedModel.model.capabilities;
643
+ const unseeable = resolvedAttachments.filter(
644
+ (r) =>
645
+ (r.mime.kind === 'image' && !caps.includes('image')) ||
646
+ (r.mime.kind === 'pdf' && !caps.includes('pdf') && !caps.includes('image')),
647
+ );
648
+ if (unseeable.length > 0) {
649
+ const modelLabel = `${resolvedModel.providerName}/${resolvedModel.modelId}`;
650
+ const kinds = [...new Set(unseeable.map((r) => r.mime.kind))].join('/');
651
+ if (workerChain(deps.config.vision.worker).length === 0) {
652
+ throw new Error(
653
+ `model '${modelLabel}' does not support ${kinds} inputs — switch to a capable model (try /model), ` +
654
+ `or configure config.vision.worker so somora can have a vision worker describe attachments for it`,
655
+ );
656
+ }
657
+ for (const r of unseeable) {
658
+ let described;
659
+ try {
660
+ const att = await loadAttachment(r.path, {
661
+ maxImageBytes: deps.config.attachments.maxImageBytes,
662
+ maxPdfBytes: deps.config.attachments.maxPdfBytes,
663
+ maxTextBytes: deps.config.attachments.maxTextBytes,
664
+ });
665
+ described = await describeMedia({
666
+ att,
667
+ config: deps.config,
668
+ agent,
669
+ session,
670
+ caller: 'chat_attachment',
671
+ });
672
+ } catch (err) {
673
+ throw new Error(
674
+ `model '${modelLabel}' cannot see '${r.name}', and the vision worker could not describe it either: ` +
675
+ `${(err as Error).message}`,
676
+ );
677
+ }
678
+ // Second-hand sight, and the model is told so. A described
679
+ // picture that pretends to be the picture is how an agent ends
680
+ // up asserting detail nobody ever saw.
681
+ describedAttachments.push(
682
+ `[attachment ${r.name} (${r.mime.mimeType}) — your model cannot see ${r.mime.kind} files, ` +
683
+ `so somora had the vision worker ${described.worker} look at it and report back:\n` +
684
+ `${described.analysis}\n` +
685
+ `This is a description, not the file. Say so when the exact detail matters.]`,
686
+ );
687
+ logger.info({
688
+ msg: 'chat.attachment.described',
689
+ agent,
690
+ session,
691
+ file: r.name,
692
+ kind: r.mime.kind,
693
+ model: modelLabel,
694
+ worker: described.worker,
695
+ ms: described.ms,
696
+ });
697
+ }
698
+ // The engine must not receive what it cannot read.
699
+ for (const r of unseeable) {
700
+ const i = resolvedAttachments.indexOf(r);
701
+ if (i >= 0) resolvedAttachments.splice(i, 1);
702
+ }
703
+ }
704
+ logger.info({
705
+ msg: 'chat.attachments.resolved',
706
+ agent,
707
+ session,
708
+ count: resolvedAttachments.length,
709
+ kinds: resolvedAttachments.map((r) => r.mime.kind),
710
+ });
711
+ }
712
+
713
+ const inputMeta =
714
+ inputModality === 'voice'
715
+ ? {
716
+ modality: 'voice' as const,
717
+ transcribed: true,
718
+ // The dictation path, not a live call — the two are separate
719
+ // features and a reader must be able to tell them apart.
720
+ source: 'stt' as const,
721
+ ...(sttProvider ? { sttProvider } : {}),
722
+ }
723
+ : undefined;
724
+
725
+ // Reply-back routing for agent_ask (see turn-origin.ts). Set here,
726
+ // after every pre-engine check has passed, so a turn that fails
727
+ // before it starts (persona missing, model unresolvable, attachment
728
+ // problem) cannot leave a stale A2A origin behind for the next turn.
729
+ // Reset with null on every non-A2A turn so a human turn following
730
+ // an A2A one never inherits it. Cleared again at the end.
731
+ setTurnOrigin(agent, session, fromAgent && fromSession ? { agent: fromAgent, session: fromSession } : null);
732
+
733
+ await appendEvent(agent, session, {
734
+ kind: 'user_message',
735
+ ts: Date.now(),
736
+ engine: engine.name,
737
+ text,
738
+ ...(fromAgent ? { from_agent: fromAgent } : {}),
739
+ ...(fromAgent && fromSession ? { from_session: fromSession } : {}),
740
+ ...(fromSystem ? { from_system: fromSystem } : {}),
741
+ ...(agentAskCallId ? { agent_ask_call_id: agentAskCallId } : {}),
742
+ ...(origin ? { origin } : {}),
743
+ ...(ephemeralContext ? { ephemeral: ephemeralContext } : {}),
744
+ ...(attachments && attachments.length > 0 ? { attachments } : {}),
745
+ ...(inputMeta ? { input: inputMeta } : {}),
746
+ ...(autoPlayRequested ? { autoPlayRequested: true } : {}),
747
+ });
748
+
749
+ // Live broadcast user_message to ALL session subscribers — A2A
750
+ // inbounds AND self-typed turns. This matters when multiple
751
+ // clients watch the same session (a TUI tail + a web window
752
+ // open at once), or when one client wrote the message and the
753
+ // others should see it appear live. Senders dedupe their own
754
+ // optimistic-local copy by recent-text or local id; receivers
755
+ // just render it.
756
+ if (publishSse) {
757
+ await publishSse({
758
+ event: 'user_message',
759
+ data: {
760
+ text,
761
+ ts: Date.now(),
762
+ turnId,
763
+ ...(fromAgent ? { from_agent: fromAgent } : {}),
764
+ ...(fromAgent && fromSession ? { from_session: fromSession } : {}),
765
+ ...(fromSystem ? { from_system: fromSystem } : {}),
766
+ ...(agentAskCallId ? { agent_ask_call_id: agentAskCallId } : {}),
767
+ ...(origin ? { origin } : {}),
768
+ // Dictated, not typed. History carries this; without it here the
769
+ // live bubble loses its microphone until the page is reloaded.
770
+ ...(inputMeta ? { input: { modality: inputMeta.modality, source: inputMeta.source } } : {}),
771
+ },
772
+ });
773
+ }
774
+
775
+ // Reset the agent's auto-dream timer — sub-flows count as activity.
776
+ deps.onActivity(agent);
777
+
778
+ const modelSupportsReasoning = resolvedModel.model.capabilities.includes('reasoning');
779
+ const effectiveThinking = resolveEffectiveThinking(persona, sessionMeta);
780
+ const effectiveSampling = resolveEffectiveSampling(resolvedModel.model, persona, sessionMeta);
781
+ // What the openai-compatible engine will actually put on the wire for
782
+ // this level (per-model `reasoning.levels`). Only sent to clients when
783
+ // it differs from the level itself, so the badge can read `high→xhigh`.
784
+ const thinkingWire =
785
+ effectiveThinking && modelSupportsReasoning && resolvedModel.provider.engine === 'openai-compatible'
786
+ ? (resolveOpenAiReasoning(effectiveThinking, resolvedModel.model).value ?? 'off')
787
+ : undefined;
788
+ const thinkingWireField =
789
+ thinkingWire !== undefined && thinkingWire !== effectiveThinking ? { wire: thinkingWire } : {};
790
+ if (publishSse) {
791
+ const startThinkingPayload = effectiveThinking
792
+ ? { level: effectiveThinking, active: modelSupportsReasoning, ...thinkingWireField }
793
+ : undefined;
794
+ await publishSse({
795
+ event: 'agent',
796
+ data: {
797
+ phase: 'start',
798
+ provider: resolvedModel.providerName,
799
+ model: resolvedModel.modelId,
800
+ ...(startThinkingPayload ? { thinking: startThinkingPayload } : {}),
801
+ },
802
+ });
803
+ }
804
+
805
+ // Surface the memory inject to SSE subscribers AFTER the agent_start
806
+ // event so the chat-stream order stays sensible (agent starting →
807
+ // what memory it pulled → tool calls → final answer).
808
+ if (publishSse && memoryInjectedCount >= 0) {
809
+ const refs = memoryHits.map((h) => `${h.source}/${h.slug}`);
810
+ const topScore = memoryHits[0]?.score;
811
+ await publishSse({
812
+ event: 'memory',
813
+ data: {
814
+ count: memoryInjectedCount,
815
+ ...(topScore !== undefined ? { topScore } : {}),
816
+ refs,
817
+ fullText: ephemeralContext ?? '',
818
+ },
819
+ });
820
+ }
821
+
822
+ let lastUsage:
823
+ | {
824
+ tokens_in: number;
825
+ tokens_out: number;
826
+ tokens_in_cached?: number;
827
+ tokens_out_reasoning?: number;
828
+ /** Window the engine reports for itself, when it does. */
829
+ context_window?: number;
830
+ }
831
+ | undefined;
832
+ let finalText = '';
833
+ let turnMedia: ChatTurnMedia[] = [];
834
+ // Outcome bookkeeping (ChatTurnResult.outcome / tool_calls / rounds /
835
+ // files_written) — all from events, none from model text.
836
+ let toolCallCount = 0;
837
+ let turnRounds: number | undefined;
838
+ let forcedFinal: string | undefined;
839
+ let degradedReason: string | undefined;
840
+ const pendingWrites = new Map<string, string>();
841
+ const filesWritten: string[] = [];
842
+ let errorMessage: string | undefined;
843
+ // The engine's own turn id (`t-…`), learned from its turn_start. Kept
844
+ // outside the try so the failure path can stamp its turn_error with
845
+ // it — the client pairs the error block to the right turn by this.
846
+ let streamTurnId: string | undefined;
847
+
848
+ try {
849
+ // Re-read history NOW (after we just appended the user_message
850
+ // with its ephemeral block) so the engine sees the current turn
851
+ // as the last entry — engines that reconstruct from history
852
+ // (openai-compatible) get correct turn-order, and the persistent
853
+ // ephemeral on the just-appended event flows naturally through
854
+ // buildMessages without a separate inject step.
855
+ const history = await getHistory(agent, session);
856
+
857
+ const toolCtx = {
858
+ agent,
859
+ session,
860
+ turnId,
861
+ subagentDepth,
862
+ ...(args.signal ? { signal: args.signal } : {}),
863
+ getMemoryManager: () =>
864
+ getMemoryManager(agent, {
865
+ config: deps.config.memory,
866
+ wiki: deps.config.wiki,
867
+ obsidian: deps.config.obsidian,
868
+ }),
869
+ config: deps.config,
870
+ // Surface the resolved model so capability-gated tools (file_read
871
+ // polymorph) can check `image`/`pdf` capability before deciding
872
+ // whether to return content blocks. Stays consistent across the
873
+ // whole turn — even tool calls happening late in the loop see
874
+ // the same active model.
875
+ activeModel: resolvedModel,
876
+ };
877
+ // Per-agent gating (agent.yaml tools:) filters the LIST the model
878
+ // sees; invoke() stays unfiltered by design — a queued call for a
879
+ // just-denied tool failing mid-turn would be more confusing than
880
+ // letting it finish. The MCP child applies the same filter for the
881
+ // CLI engines (src/tools/gating.ts is the single matcher).
882
+ // A builder session also carries mode and phase (builder-session.ts):
883
+ // set on its first turn from where that turn came from, then a
884
+ // switch in the task panel. They hide ask_user (unattended) and the
885
+ // repository-changing tools (plan phase) from the list.
886
+ let builderState: BuilderSessionState | null = null;
887
+ if (persona.kind === 'builder') {
888
+ builderState = await ensureBuilderState(
889
+ deps.sessionMetaStore,
890
+ agent,
891
+ session,
892
+ origin ?? { kind: 'human', via: 'chat' },
893
+ workdirFromMeta(sessionMeta as Record<string, unknown>, persona, deps.config).path,
894
+ );
895
+ sessionMeta = await deps.sessionMetaStore.get(agent, session);
896
+ // One builder per folder: this turn claims its working directory
897
+ // (released in start-turn's finally). Dispatch and Go refuse a
898
+ // claimed folder before they get here.
899
+ const folder = workdirFromMeta(sessionMeta as Record<string, unknown>, persona, deps.config).path;
900
+ // A direct message (composer, POST /chat/send) used to bypass the
901
+ // folder claim that dispatch and Go respect: two builders in one
902
+ // working copy. Refuse here, where every builder turn passes.
903
+ const held = workdirClaimedBy(folder, { exceptTurnId: turnId });
904
+ if (held && !(held.agent === agent && held.session === session)) {
905
+ throw new Error(`folder busy: ${describeClaim(held)}`);
906
+ }
907
+ claimWorkdir({ agent, session, turnId, workdir: folder });
908
+ }
909
+ const availableTools = (await deps.tools.listAvailable(toolCtx))
910
+ .filter((t) => isToolAllowed(t.name, t.toolset, persona.toolGating) && builderSessionAllows(builderState, t.name))
911
+ // A builder's model sees the short descriptions (its harness prompt
912
+ // carries the policy); the registry and every chat agent keep the
913
+ // long ones.
914
+ .map((t) => (persona.kind === 'builder' ? { ...t, description: builderToolDescription(t.name, t.description) } : t));
915
+ const toolInvoker = {
916
+ list: () => availableTools,
917
+ invoke: (name: string, input: unknown) => deps.tools.invoke(name, input, toolCtx),
918
+ };
919
+
920
+ // One assembly for the real turn and for GET /agents/:agent/prompt-
921
+ // preview (web Agent window) — see prompt-assembly.ts for the order
922
+ // and the cache rationale per block.
923
+ const assembled = await assembleSystemPrompt({
924
+ agent,
925
+ session,
926
+ persona,
927
+ sessionMeta,
928
+ deps,
929
+ subagentDepth,
930
+ toolCount: availableTools.length,
931
+ toolNames: availableTools.map((t) => t.name),
932
+ });
933
+ const projectBlock = assembled.projectBlock;
934
+ const systemPromptForTurn = assembled.text;
935
+
936
+ logger.info({
937
+ msg: 'turn.engine_init',
938
+ turnId,
939
+ agent,
940
+ session,
941
+ provider: resolvedModel.providerName,
942
+ model: resolvedModel.modelId,
943
+ engine: resolvedModel.provider.engine,
944
+ historyEvents: history.length,
945
+ memoryInjectedCount,
946
+ });
947
+ // From here on a message posted with `steer: true` reaches this turn
948
+ // instead of the queue (engines that read the letterbox only).
949
+ markSteerable(agent, session, resolvedModel.provider.engine, turnId);
950
+
951
+ const stream = runTurnWithFallback({
952
+ primary: resolvedModel,
953
+ fallbackRefs: persona.fallback,
954
+ config: deps.config,
955
+ baseInput: {
956
+ agent,
957
+ session,
958
+ systemPrompt: systemPromptForTurn,
959
+ ephemeralContext,
960
+ // Pass the project block separately so codex-cli (which drops
961
+ // systemPrompt on resumed sessions) can inline it via the
962
+ // user-message-prefix path. claude-cli + openai-compatible
963
+ // already see it via systemPrompt and ignore this field.
964
+ ...(projectBlock ? { projectContext: projectBlock } : {}),
965
+ userMessage: describedAttachments.length > 0 ? `${text}\n\n${describedAttachments.join('\n\n')}` : text,
966
+ ...(fromAgent ? { fromAgent } : {}),
967
+ ...(fromAgent && fromSession ? { fromSession } : {}),
968
+ ...(subagentDepth > 0 ? { subagentDepth } : {}),
969
+ history,
970
+ agentKind: persona.kind,
971
+ // Steering: the engine reads the session's letterbox between steps.
972
+ steer: {
973
+ drain: () => drainSteer(agent, session),
974
+ frame: frameSteerMessage,
975
+ requeue: (msgs) => requeueSteer(agent, session, msgs),
976
+ },
977
+ metaStore: deps.sessionMetaStore,
978
+ availableModels: listAllModels(deps.config),
979
+ compactionConfig: resolveCompactionConfig(deps.config),
980
+ tools: toolInvoker,
981
+ // External MCP servers → CLI engines add one somora-<name>
982
+ // proxy child per entry (design §4.4). Per-agent gating happens
983
+ // inside the child (same matcher as the toolInvoker filter
984
+ // above), so the entry list itself is agent-independent.
985
+ externalMcpServers: Object.entries(deps.config.mcp.servers)
986
+ .filter(([, cfg]) => cfg.enabled)
987
+ .map(([name, cfg]) => ({ name, timeoutMs: cfg.timeoutMs })),
988
+ // Loop caps, most specific last: server config → the kind's
989
+ // defaults (a builder turn is a build, not a chat) → the agent's
990
+ // own agentLoop block → what this one call asked for.
991
+ agentLoopConfig: {
992
+ ...deps.config.agentLoop,
993
+ ...(persona.kind === 'builder' ? BUILDER_LOOP_DEFAULTS : {}),
994
+ ...(persona.agentLoop ?? {}),
995
+ ...(agentLoopOverride ?? {}),
996
+ },
997
+ idleTimeoutMs: pickIdleTimeoutForEngine(
998
+ deps.config.engineWatchdog,
999
+ resolvedModel.provider.engine,
1000
+ ),
1001
+ ...(() => {
1002
+ const t = pickToolIdleTimeoutForEngine(deps.config, resolvedModel.provider.engine);
1003
+ return t !== undefined ? { toolIdleTimeoutMs: t } : {};
1004
+ })(),
1005
+ ...(effectiveThinking ? { thinking: effectiveThinking } : {}),
1006
+ ...(effectiveSampling ? { sampling: effectiveSampling } : {}),
1007
+ captureThinking: deps.config.thinkingContent.capture,
1008
+ ...(signal ? { signal } : {}),
1009
+ ...(resolvedAttachments.length > 0 ? { attachments: resolvedAttachments } : {}),
1010
+ },
1011
+ });
1012
+
1013
+ const serialize = publishSse ? createTurnSerializer() : null;
1014
+ let firstEventLogged = false;
1015
+ let sawTurnEnd = false;
1016
+ let lastSeenEngine: string = resolvedModel.provider.engine;
1017
+ let fallbackInfo: ChatTurnResult['fallback'];
1018
+ for await (const ev of stream) {
1019
+ if (!firstEventLogged) {
1020
+ firstEventLogged = true;
1021
+ logger.info({
1022
+ msg: 'turn.first_event',
1023
+ turnId,
1024
+ agent,
1025
+ session,
1026
+ kind: ev.kind,
1027
+ msSinceStart: Date.now() - start,
1028
+ });
1029
+ }
1030
+ if ('engine' in ev && typeof ev.engine === 'string' && ev.engine.length > 0) {
1031
+ lastSeenEngine = ev.engine;
1032
+ }
1033
+ // Bug 2026-05-17 Rene: some engines/models hallucinate
1034
+ // text-format `<tool_call>{…}</tool_call>` markup inside
1035
+ // assistant text (instead of going through the engine's
1036
+ // structured tool_use channel). That XML survives the wire and
1037
+ // the JSON body lands in the chat bubble as a wall of text.
1038
+ // Normalize on the final assistant_message; deltas pass through
1039
+ // unchanged because XML boundaries can split across delta chunks
1040
+ // (the bubble flips to the final-message text on turn_end so a
1041
+ // brief streaming flicker is fine).
1042
+ if (ev.kind === 'assistant_message') {
1043
+ const sanitized = sanitizeAssistantText(ev.text);
1044
+ if (sanitized.matches > 0) {
1045
+ logger.warn({
1046
+ msg: 'turn.hallucinated_tool_call_xml',
1047
+ turnId,
1048
+ agent,
1049
+ session,
1050
+ engine: lastSeenEngine,
1051
+ model: resolvedModel.modelId,
1052
+ matches: sanitized.matches,
1053
+ originalLength: ev.text.length,
1054
+ sanitizedLength: sanitized.text.length,
1055
+ });
1056
+ ev.text = sanitized.text;
1057
+ }
1058
+ }
1059
+ // Thinking content: one server-side gate for SSE + JSONL (three
1060
+ // gates rule — clients need no switch of their own), and a cap on
1061
+ // what is persisted. Deltas are never persisted, like assistant
1062
+ // deltas.
1063
+ if (ev.kind === 'thinking_delta' || ev.kind === 'thinking_message') {
1064
+ if (!deps.config.thinkingContent.capture) continue;
1065
+ if (ev.kind === 'thinking_message') {
1066
+ const cap = deps.config.thinkingContent.maxChars;
1067
+ if (ev.text.length > cap) {
1068
+ ev.text = ev.text.slice(0, cap).trimEnd() + '…';
1069
+ ev.truncated = true;
1070
+ }
1071
+ }
1072
+ }
1073
+ if (ev.kind === 'turn_end' && !ev.model) {
1074
+ ev.model = turnFallback?.actual ?? `${resolvedModel.providerName}/${resolvedModel.modelId}`;
1075
+ }
1076
+ if (ev.kind === 'steer_applied') {
1077
+ // Each steered message becomes an ordinary user_message record at
1078
+ // the point in the turn where the model actually read it, and
1079
+ // every open window sees it land there.
1080
+ for (const m of ev.messages) {
1081
+ const record = {
1082
+ kind: 'user_message' as const,
1083
+ ts: ev.ts,
1084
+ engine: ev.engine,
1085
+ text: m.text,
1086
+ steer: true as const,
1087
+ steer_id: m.id,
1088
+ origin: m.origin,
1089
+ ...(m.from_agent ? { from_agent: m.from_agent } : {}),
1090
+ ...(m.from_agent && m.from_session ? { from_session: m.from_session } : {}),
1091
+ };
1092
+ await appendEvent(agent, session, record);
1093
+ logger.info({ msg: 'turn.steered', turnId, agent, session, steerId: m.id, engine: ev.engine });
1094
+ if (publishSse) {
1095
+ await publishSse({
1096
+ event: 'user_message',
1097
+ data: {
1098
+ text: m.text,
1099
+ ts: ev.ts,
1100
+ turnId,
1101
+ steer: true,
1102
+ steer_id: m.id,
1103
+ origin: m.origin,
1104
+ ...(m.from_agent ? { from_agent: m.from_agent } : {}),
1105
+ ...(m.from_agent && m.from_session ? { from_session: m.from_session } : {}),
1106
+ },
1107
+ });
1108
+ }
1109
+ }
1110
+ continue;
1111
+ }
1112
+ if (ev.kind !== 'assistant_delta' && ev.kind !== 'thinking_delta') {
1113
+ await appendEvent(agent, session, ev);
1114
+ }
1115
+ // An error event that survives the fallback chain is this turn's
1116
+ // outcome. Without this the variable was only ever set by the
1117
+ // outer catch, so a turn that ended on a streamed provider error
1118
+ // was logged as turn.completed and reported success to whoever
1119
+ // asked for it — a subagent caller, the A2A result, the audit
1120
+ // (2026-09-09 and 2026-09-10 reports). First one wins: later
1121
+ // errors are usually consequences of the first.
1122
+ if (ev.kind === 'error' && !errorMessage) {
1123
+ errorMessage = ev.message;
1124
+ logger.warn({
1125
+ msg: 'turn.engine_error',
1126
+ turnId,
1127
+ agent,
1128
+ session,
1129
+ engine: ev.engine,
1130
+ providerError: ev.providerError === true,
1131
+ err: ev.message,
1132
+ });
1133
+ }
1134
+ if (ev.kind === 'turn_start' && typeof ev.turnId === 'string') {
1135
+ streamTurnId = ev.turnId;
1136
+ if (publishSse) {
1137
+ await publishSse({ event: 'turn_started', data: { turnId: ev.turnId } });
1138
+ }
1139
+ }
1140
+ if (ev.kind === 'model_fallback') {
1141
+ fallbackInfo = {
1142
+ requested: ev.requested,
1143
+ actual: ev.actual,
1144
+ reason: ev.reason,
1145
+ ...(ev.hops ? { hops: ev.hops } : {}),
1146
+ };
1147
+ turnFallback = fallbackInfo;
1148
+ }
1149
+ if (ev.kind === 'turn_end') {
1150
+ sawTurnEnd = true;
1151
+ if (ev.usage) lastUsage = ev.usage;
1152
+ if (typeof ev.turnId === 'string') streamTurnId = ev.turnId;
1153
+ if (typeof ev.rounds === 'number') turnRounds = ev.rounds;
1154
+ if (ev.forced_final) forcedFinal = ev.forced_final;
1155
+ if (ev.degraded) degradedReason = ev.degraded.reason;
1156
+ }
1157
+ if (ev.kind === 'tool_call') {
1158
+ toolCallCount += 1;
1159
+ noteToolCall(turnId, ev.tool);
1160
+ if (ev.tool === 'file_write' || ev.tool === 'file_patch') {
1161
+ const inp = ev.input as { path?: unknown; target?: unknown } | null;
1162
+ if (inp && typeof inp.path === 'string') {
1163
+ const target = typeof inp.target === 'string' && inp.target !== 'local' ? `${inp.target}:` : '';
1164
+ pendingWrites.set(ev.callId, `${target}${inp.path}`);
1165
+ }
1166
+ }
1167
+ }
1168
+ if (ev.kind === 'tool_result') {
1169
+ const requested = pendingWrites.get(ev.callId);
1170
+ if (requested !== undefined) {
1171
+ pendingWrites.delete(ev.callId);
1172
+ // Prefer the path the tool resolved (absolute, workspace-
1173
+ // relative input expanded) over the one the model typed.
1174
+ const out = ev.output as { path?: unknown } | null;
1175
+ const resolved = out && typeof out.path === 'string' ? out.path : undefined;
1176
+ const remotePrefix = requested.includes(':') ? requested.slice(0, requested.indexOf(':') + 1) : '';
1177
+ const path = resolved ? `${remotePrefix}${resolved}` : requested;
1178
+ if (!ev.error && !filesWritten.includes(path)) filesWritten.push(path);
1179
+ }
1180
+ }
1181
+ if (ev.kind === 'assistant_message') {
1182
+ finalText = ev.text;
1183
+ } else if (ev.kind === 'assistant_delta' && !finalText) {
1184
+ // Fallback for engines that don't emit a final assistant_message
1185
+ finalText = ev.text;
1186
+ }
1187
+ if (serialize && publishSse) {
1188
+ const sse = serialize(ev);
1189
+ if (sse) await publishSse(sse);
1190
+ if (ev.kind === 'error') {
1191
+ // The serializer keeps the `status` line for older clients;
1192
+ // this adds the turn id so the failure lands in its turn.
1193
+ await publishSse({
1194
+ event: 'turn_error',
1195
+ data: {
1196
+ ...(streamTurnId ? { turnId: streamTurnId } : {}),
1197
+ message: ev.message,
1198
+ engine: ev.engine,
1199
+ },
1200
+ });
1201
+ }
1202
+ }
1203
+ }
1204
+ // Defense in depth: if the stream ended cleanly but no turn_end was
1205
+ // ever yielded, the session JSONL would be left with an orphan
1206
+ // turn_start. healOrphanToolCalls fixes the tool-call case; this
1207
+ // covers the turn_start case symmetrically.
1208
+ if (!sawTurnEnd) {
1209
+ logger.warn({
1210
+ msg: 'turn.missing_turn_end',
1211
+ turnId,
1212
+ agent,
1213
+ session,
1214
+ engine: lastSeenEngine,
1215
+ hint: 'engine stream ended without yielding turn_end; persisting synthetic close',
1216
+ });
1217
+ await appendEvent(agent, session, {
1218
+ kind: 'error',
1219
+ ts: Date.now(),
1220
+ engine: lastSeenEngine,
1221
+ message: 'engine stream ended without turn_end (synthetic close)',
1222
+ });
1223
+ await appendEvent(agent, session, {
1224
+ kind: 'turn_end',
1225
+ ts: Date.now(),
1226
+ engine: lastSeenEngine,
1227
+ turnId: `t-${Date.now()}`,
1228
+ model: turnFallback?.actual ?? `${resolvedModel.providerName}/${resolvedModel.modelId}`,
1229
+ });
1230
+ }
1231
+
1232
+ // ── Generated-media hook ──────────────────────────────────────────
1233
+ // Anything produced during this turn — an image made in it, or a
1234
+ // video whose render finished and brought us back here — goes to
1235
+ // the client as an append-only event paired to the bubble.
1236
+ // Runs regardless of whether the agent mentioned the image in its
1237
+ // reply: the user asked for a picture, so the picture belongs in
1238
+ // the conversation, and depending on the agent to remember makes
1239
+ // "Done!" with nothing to look at the failure mode.
1240
+ //
1241
+ // Awaited (an index read, milliseconds) so the list lands on the
1242
+ // ChatTurnResult for spawn callers — but non-fatal: a turn that
1243
+ // produced a real image must not be reported as failed because the
1244
+ // gallery index couldn't be read.
1245
+ // Gated on EITHER surface: a setup with video but no images still
1246
+ // has media to publish, and gating on images alone meant a
1247
+ // finished video never reached the chat at all.
1248
+ if ((deps.config.imageGen?.enabled || deps.config.videoGen?.enabled) && streamTurnId) {
1249
+ const capturedMediaTurnId = streamTurnId;
1250
+ turnMedia = await publishTurnMedia({
1251
+ agent,
1252
+ session,
1253
+ turnId: capturedMediaTurnId,
1254
+ engine: lastSeenEngine,
1255
+ startedAt: turnStartedAt,
1256
+ ...(attachMediaIds ? { attachMediaIds } : {}),
1257
+ publishSse,
1258
+ }).catch((err) => {
1259
+ logger.warn({
1260
+ msg: 'turn.media_publish_failed',
1261
+ turnId,
1262
+ agent,
1263
+ session,
1264
+ err: (err as Error).message,
1265
+ });
1266
+ return [] as ChatTurnMedia[];
1267
+ });
1268
+ }
1269
+
1270
+ // ── Auto-TTS hook ─────────────────────────────────────────────────
1271
+ // Gates (all must hold):
1272
+ // (1) config.tts.enabled
1273
+ // (2) input modality was voice
1274
+ // (3) client requested auto-play for this turn
1275
+ // (4) finalText is present + sanitizer doesn't skip
1276
+ // Fire-and-forget: TTS generation can take 1-3s, we don't block
1277
+ // the turn return. The audio arrives over SSE as assistant_audio
1278
+ // when ready (and is appended to JSONL).
1279
+ const ttsCfg = deps.config.tts;
1280
+ if (
1281
+ ttsCfg?.enabled &&
1282
+ inputModality === 'voice' &&
1283
+ autoPlayRequested &&
1284
+ finalText.length > 0 &&
1285
+ streamTurnId
1286
+ ) {
1287
+ const capturedTurnId = streamTurnId;
1288
+ void generateAutoTts({
1289
+ agent,
1290
+ session,
1291
+ turnId: capturedTurnId,
1292
+ text: finalText,
1293
+ engine: lastSeenEngine,
1294
+ config: deps.config,
1295
+ publishSse,
1296
+ parentTurnId: turnId,
1297
+ }).catch((err) => {
1298
+ logger.warn({
1299
+ msg: 'turn.auto_tts_failed',
1300
+ turnId,
1301
+ agent,
1302
+ session,
1303
+ err: (err as Error).message,
1304
+ });
1305
+ });
1306
+ }
1307
+ } catch (err) {
1308
+ errorMessage = (err as Error).message;
1309
+ logger.error({
1310
+ msg: 'turn.failed',
1311
+ turnId,
1312
+ agent,
1313
+ session,
1314
+ err: errorMessage,
1315
+ msSinceStart: Date.now() - start,
1316
+ });
1317
+ // Persist the failure into the session JSONL so the next turn can
1318
+ // run cleanly. Without these synthetic records, an engine that
1319
+ // throws mid-stream (claude-cli watchdog escape, codex SIGTERM,
1320
+ // openai-compat fetch-abort, …) leaves the session log dangling at
1321
+ // an unmatched turn_start or tool_call — the queue/lock release
1322
+ // happens in the outer finally but the persisted state stays broken
1323
+ // until healOrphanToolCalls fires on the next user turn. Surfacing
1324
+ // an explicit `error` + `turn_end` here makes the failure visible
1325
+ // and ends the turn properly. Best-effort: any append failure is
1326
+ // logged but does not re-throw so the outer finally still releases.
1327
+ try {
1328
+ await appendEvent(agent, session, {
1329
+ kind: 'error',
1330
+ ts: Date.now(),
1331
+ engine: resolvedModel.provider.engine,
1332
+ message: `turn aborted: ${errorMessage}`,
1333
+ });
1334
+ await appendEvent(agent, session, {
1335
+ kind: 'turn_end',
1336
+ ts: Date.now(),
1337
+ engine: resolvedModel.provider.engine,
1338
+ turnId: `t-failed-${Date.now()}`,
1339
+ model: `${resolvedModel.providerName}/${resolvedModel.modelId}`,
1340
+ });
1341
+ } catch (persistErr) {
1342
+ logger.error({
1343
+ msg: 'turn.failed_persist_failed',
1344
+ turnId,
1345
+ agent,
1346
+ session,
1347
+ err: String(persistErr),
1348
+ hint: 'could not append synthetic error+turn_end on turn failure; healOrphanToolCalls will run on next user turn',
1349
+ });
1350
+ }
1351
+ if (publishSse) {
1352
+ await publishSse({
1353
+ event: 'status',
1354
+ data: { msg: `turn failed: ${errorMessage}` },
1355
+ });
1356
+ await publishSse({
1357
+ event: 'turn_error',
1358
+ data: {
1359
+ ...(streamTurnId ? { turnId: streamTurnId } : {}),
1360
+ message: `turn aborted: ${errorMessage}`,
1361
+ engine: resolvedModel.provider.engine,
1362
+ },
1363
+ });
1364
+ }
1365
+ }
1366
+
1367
+ // Project-focus diff broadcast. The HTTP routes (POST/DELETE /project)
1368
+ // publish a 'project' SSE event immediately because they own the
1369
+ // write. The tool path (agent calls project_focus via MCP child)
1370
+ // can't publish — the child has no SSE access — so we'd otherwise
1371
+ // rely on each client refetching after every chat:final. That
1372
+ // refetch is fragile (timing, projectsEnabled flag, race against
1373
+ // header re-render); reports from 2026-05-19 showed the TUI chip
1374
+ // staying stale until agent/session switch. Compare turn-start vs
1375
+ // turn-end projectSlug here and emit the SSE event ourselves when
1376
+ // they differ — covers tool-path unpins/pins reliably for any
1377
+ // engine (claude-cli, codex-cli, openai-compatible).
1378
+ try {
1379
+ const startSlug =
1380
+ typeof sessionMeta.projectSlug === 'string' ? sessionMeta.projectSlug : null;
1381
+ const freshMeta = await deps.sessionMetaStore.get(agent, session);
1382
+ const endSlug =
1383
+ typeof freshMeta.projectSlug === 'string' ? freshMeta.projectSlug : null;
1384
+ if (startSlug !== endSlug && publishSse) {
1385
+ await publishSse({
1386
+ event: 'project',
1387
+ data: { from: startSlug, to: endSlug, via: 'tool' },
1388
+ });
1389
+ }
1390
+ } catch (err) {
1391
+ logger.warn({
1392
+ msg: 'turn.project_diff_publish_failed',
1393
+ turnId,
1394
+ agent,
1395
+ session,
1396
+ err: (err as Error).message,
1397
+ });
1398
+ }
1399
+
1400
+ if (publishSse) {
1401
+ const thinkingPayload = effectiveThinking
1402
+ ? { level: effectiveThinking, active: modelSupportsReasoning, ...thinkingWireField }
1403
+ : undefined;
1404
+ const actualRef = turnFallback ? splitModelRef(turnFallback.actual) : undefined;
1405
+ await publishSse({
1406
+ event: 'agent',
1407
+ data: {
1408
+ phase: 'end',
1409
+ ...(lastUsage ? { usage: lastUsage } : {}),
1410
+ // A CLI engine knows its own window; the configured value is
1411
+ // somora's guess at a cap it does not enforce (2026-09-11).
1412
+ contextWindow: lastUsage?.context_window ?? resolvedModel.model.contextWindow,
1413
+ provider: actualRef?.provider ?? resolvedModel.providerName,
1414
+ model: actualRef?.model ?? resolvedModel.modelId,
1415
+ ...(thinkingPayload ? { thinking: thinkingPayload } : {}),
1416
+ ...(turnFallback ? { fallback: turnFallback } : {}),
1417
+ },
1418
+ });
1419
+ }
1420
+
1421
+ logger.info({
1422
+ msg: errorMessage ? 'turn.ended_degraded' : 'turn.completed',
1423
+ turnId,
1424
+ agent,
1425
+ session,
1426
+ ms: Date.now() - start,
1427
+ finalTextLen: finalText.length,
1428
+ tokensIn: lastUsage?.tokens_in,
1429
+ tokensOut: lastUsage?.tokens_out,
1430
+ ...(errorMessage ? { err: errorMessage } : {}),
1431
+ });
1432
+
1433
+ clearTurnOrigin(agent, session);
1434
+ const actualForResult = turnFallback ? splitModelRef(turnFallback.actual) : undefined;
1435
+ const outcome: ChatTurnOutcome = errorMessage
1436
+ ? 'failed'
1437
+ : degradedReason
1438
+ ? 'degraded'
1439
+ : finalText.trim().length === 0
1440
+ ? 'degraded'
1441
+ : forcedFinal
1442
+ ? 'partial'
1443
+ : 'completed';
1444
+ const outcomeReason =
1445
+ outcome === 'failed'
1446
+ ? undefined
1447
+ : (degradedReason ?? (finalText.trim().length === 0 ? 'empty_answer' : forcedFinal));
1448
+ return {
1449
+ finalText,
1450
+ outcome,
1451
+ ...(outcomeReason ? { outcome_reason: outcomeReason } : {}),
1452
+ tool_calls: toolCallCount,
1453
+ ...(turnRounds !== undefined ? { rounds: turnRounds } : {}),
1454
+ ...(filesWritten.length > 0 ? { files_written: filesWritten } : {}),
1455
+ ...(turnMedia.length > 0 ? { media: turnMedia } : {}),
1456
+ usage: lastUsage,
1457
+ contextWindow: lastUsage?.context_window ?? resolvedModel.model.contextWindow,
1458
+ provider: actualForResult?.provider ?? resolvedModel.providerName,
1459
+ model: actualForResult?.model ?? resolvedModel.modelId,
1460
+ thinkingActive: modelSupportsReasoning && Boolean(effectiveThinking),
1461
+ thinkingLevel: effectiveThinking,
1462
+ ms: Date.now() - start,
1463
+ ...(turnFallback ? { fallback: turnFallback } : {}),
1464
+ ...(errorMessage ? { error: errorMessage } : {}),
1465
+ };
1466
+ }
1467
+
1468
+ /** `provider/modelId` → parts (modelIds may themselves contain '/'). */
1469
+ function splitModelRef(ref: string): { provider: string; model: string } {
1470
+ const slash = ref.indexOf('/');
1471
+ return slash < 0 ? { provider: '', model: ref } : { provider: ref.slice(0, slash), model: ref.slice(slash + 1) };
1472
+ }
1473
+
1474
+ export type { ChatTurnResult } from './run-turn-types.ts';