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,2464 @@
1
+ // openai-compatible engine: speaks /v1/chat/completions against any provider
2
+ // configured with baseUrl + apiKey. Stateless — we feed full message history
3
+ // each turn (no thread management on the server side, by design).
4
+ //
5
+ // Compaction (DECISIONS #21): before each turn we estimate the prompt
6
+ // size and, if it crosses the configured threshold, run a compaction
7
+ // pass via the same provider. The result is persisted to
8
+ // `meta.compactions[]` (non-destructive — JSONL stays untouched) and
9
+ // the next message-build uses the summary in place of compacted events.
10
+ //
11
+ // Agent-loop (Phase 2-Stufe-C): when TurnInput.tools is present, we run
12
+ // chat.completions in a loop. The model can request tool calls; we
13
+ // execute them via the registry and feed results back. Loop exits when
14
+ // the model returns a final response without tool_calls, or when we hit
15
+ // MAX_TOOL_ROUNDS (defensive cap, prevents runaway models). claude-cli
16
+ // and codex-cli ignore TurnInput.tools — they configure the somora
17
+ // MCP server out-of-process and let their CLI handle dispatch.
18
+
19
+ import OpenAI from 'openai';
20
+ import { createPatientOpenAIClient } from '../server/openai-client.ts';
21
+ import { userTagParam } from './user-tag.ts';
22
+ import {
23
+ pickLatest,
24
+ runCompaction,
25
+ shouldCompact,
26
+ type Compaction,
27
+ } from '../compaction/index.ts';
28
+ import { logger } from '../server/logger.ts';
29
+ import { compactTurnMidway, type LoopMessage } from '../compaction/midturn.ts';
30
+ import {
31
+ calibratedEstimate,
32
+ estimateRequestTokens,
33
+ parseProviderLimits,
34
+ promptBudget,
35
+ trimToolResults,
36
+ } from './context-budget.ts';
37
+ import { sanitizeAssistantText } from '../server/sanitize-assistant-text.ts';
38
+ import type { ToolDefinition, ToolInvoker } from '../tools/types.ts';
39
+ import type { NormalizedEvent } from '../types/events.ts';
40
+ import type { ModelCapability } from '../config/types.ts';
41
+ import { withFromAgentHeader } from './a2a.ts';
42
+ import type { AgentEngine, ResolvedAttachment, TurnInput } from './types.ts';
43
+ import { buildOpenAiUserContent } from '../multimodal/user-content.ts';
44
+ import { resolveAttachmentByHash } from '../attachments/store.ts';
45
+ import { openAiReasoningState, withReasoningRetry } from './reasoning-retry.ts';
46
+ import { formatSampling, isSamplingParamError, samplingBody } from './sampling.ts';
47
+ import { insideOpenThink, splitInlineThink } from './inline-think.ts';
48
+
49
+ const ENGINE = 'openai-compatible';
50
+
51
+ /** Quiet re-attempts for tool arguments that came back as invalid JSON.
52
+ * Hermes Agent retries twice before telling the model; a cut-off call is
53
+ * never retried this way, it comes back identical. */
54
+ const MAX_ARG_REROLLS = 2;
55
+ // A round that produced reasoning but neither text nor a tool call was
56
+ // cut off while thinking (the output cap; routers do not say so). It gets
57
+ // this many nudges per turn before the empty answer stands.
58
+ const MAX_REASONING_ONLY_NUDGES = 2;
59
+ // A builder that has not touched its task list for this many tool rounds
60
+ // while items are open is reminded (the person watches that list).
61
+ const TODO_STALE_ROUNDS = 12;
62
+ /** Rounds of a builder turn kept verbatim when it compacts itself. */
63
+ const MIDTURN_KEEP_ROUNDS = 6;
64
+
65
+ // Hard fallbacks if the server forgot to pass an agent-loop config.
66
+ // Should never fire in practice — `config.agentLoop` is non-optional in
67
+ // the Zod schema and defaults itself.
68
+ const DEFAULT_MAX_TOOL_ROUNDS = 8;
69
+ const DEFAULT_MAX_TOOL_CALLS_PER_TURN = 30;
70
+ const DEFAULT_TOOL_CALL_TIMEOUT_MS = 30_000;
71
+
72
+ type ChatMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
73
+ type ChatTool = OpenAI.Chat.Completions.ChatCompletionTool;
74
+ type StreamingToolCall = {
75
+ id: string;
76
+ name: string;
77
+ argsJson: string; // accumulated as fragments arrive
78
+ };
79
+
80
+ interface OpenAiCompatibleMeta {
81
+ engine?: string;
82
+ compactions?: Compaction[];
83
+ /**
84
+ * What the provider counted for the last request of this session, and
85
+ * for which model. The compaction trigger trusts this over any
86
+ * estimate — the same design OpenClaw and Hermes Agent use, and the
87
+ * reason a session made of tool traffic no longer looks tiny.
88
+ * A model switch invalidates it: tokenizers differ.
89
+ */
90
+ contextTokens?: { tokens: number; model: string; ts: number };
91
+ /**
92
+ * measured ÷ estimated for the last request. Character heuristics are
93
+ * built for prose; code and JSON run near 2.5 chars per token, and a
94
+ * turn measured on 2026-09-10 was 36 % denser than the estimate said.
95
+ * Mid-turn, where only an estimate exists for what was appended since
96
+ * the last reading, this factor carries the correction.
97
+ */
98
+ tokenRatio?: { ratio: number; model: string };
99
+ /** Provider never sent usage — fall back to estimates with more room. */
100
+ providerOmitsUsage?: boolean;
101
+ }
102
+
103
+ /** Per-result cap when replaying tool output into rebuilt history.
104
+ * Unbounded results are what bloat the context; the model can re-read
105
+ * anything it genuinely needs by calling the tool again. */
106
+ export const MAX_REPLAYED_TOOL_RESULT_CHARS = 800;
107
+
108
+ interface ApiToolCall {
109
+ id: string;
110
+ type: 'function';
111
+ function: { name: string; arguments: string };
112
+ }
113
+
114
+ /**
115
+ * Collapse identical tool calls within one round to a single execution.
116
+ *
117
+ * Weak/local models — deepseek via OpenRouter, which ignores
118
+ * `parallel_tool_calls` — fan out the SAME call many times in one round
119
+ * (77 identical `df` calls, then 116, observed 2026-07-23). Two calls are
120
+ * "identical" when name AND arguments match byte-for-byte; the first is
121
+ * kept, later repeats dropped. The model still gets a result for every
122
+ * DISTINCT call it asked for, and since the assistant message we push
123
+ * lists only the kept calls, the assistant/tool pairing the OpenAI API
124
+ * requires stays intact. Order is preserved. Mirrors Hermes
125
+ * `_deduplicate_tool_calls`. Exported for the regression test.
126
+ */
127
+ export function dedupeToolCalls(calls: ApiToolCall[]): ApiToolCall[] {
128
+ const seen = new Set<string>();
129
+ const out: ApiToolCall[] = [];
130
+ for (const c of calls) {
131
+ const sig = `${c.function.name} ${c.function.arguments}`;
132
+ if (seen.has(sig)) continue;
133
+ seen.add(sig);
134
+ out.push(c);
135
+ }
136
+ return out;
137
+ }
138
+
139
+ /**
140
+ * Race a tool invocation against (a) a wall-clock timeout and (b) an
141
+ * optional user AbortSignal.
142
+ *
143
+ * - Timeout resolves with `timeoutResult` so the model sees a normal
144
+ * tool error and can retry with a higher budget.
145
+ * - Abort rejects with AbortError so the engine's outer catch ends the
146
+ * turn immediately (`[somora] aborted by user`) instead of waiting
147
+ * for the tool's own timeout (often 30s–minutes for exec/agent_ask).
148
+ *
149
+ * Residual limit: the underlying `invoke` promise is not cancelled —
150
+ * ToolInvoker has no signal today, so long tools may keep running in
151
+ * the background until their internal timeout. The turn itself stops
152
+ * waiting and releases the session lock. Follow-up: plumb AbortSignal
153
+ * into ToolContext + exec kill if orphaned work becomes a problem.
154
+ *
155
+ * Exported for the stop-button regression test.
156
+ */
157
+ export function raceToolInvoke<T>(
158
+ invoke: Promise<T>,
159
+ opts: {
160
+ timeoutMs: number;
161
+ signal?: AbortSignal;
162
+ timeoutResult: T;
163
+ },
164
+ ): Promise<T> {
165
+ const { timeoutMs, signal, timeoutResult } = opts;
166
+ return new Promise<T>((resolve, reject) => {
167
+ if (signal?.aborted) {
168
+ reject(new DOMException('Aborted', 'AbortError'));
169
+ return;
170
+ }
171
+ let settled = false;
172
+ const settle = (fn: () => void): void => {
173
+ if (settled) return;
174
+ settled = true;
175
+ clearTimeout(timer);
176
+ if (signal) signal.removeEventListener('abort', onAbort);
177
+ fn();
178
+ };
179
+ const timer = setTimeout(() => {
180
+ settle(() => resolve(timeoutResult));
181
+ }, timeoutMs);
182
+ const onAbort = (): void => {
183
+ settle(() => reject(new DOMException('Aborted', 'AbortError')));
184
+ };
185
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
186
+ invoke.then(
187
+ (value) => settle(() => resolve(value)),
188
+ (err: unknown) =>
189
+ settle(() => reject(err instanceof Error ? err : new Error(String(err)))),
190
+ );
191
+ });
192
+ }
193
+
194
+ /**
195
+ * Provider tool-scaffold templates that weak models echo as their answer
196
+ * instead of following. The canonical one is DeepSeek-V3's tool chat
197
+ * template (shipped by SGLang/vLLM), which writes this sentence into the
198
+ * prompt right before the first tool result — a confused model reproduces
199
+ * it verbatim as its reply (observed live 2026-07-23). The phrasing is so
200
+ * specific that no genuine answer contains it, so a substring match is
201
+ * safe. Case-insensitive; the DeepSeek variant capitalises differently.
202
+ */
203
+ const SCAFFOLD_MARKERS = [
204
+ 'use the results below to formulate an answer',
205
+ 'formulate an answer to the user question unless additional information',
206
+ ];
207
+
208
+ /** True when the text carries a provider tool-scaffold template (see above). */
209
+ export function containsScaffold(text: string): boolean {
210
+ const lower = text.toLowerCase();
211
+ return SCAFFOLD_MARKERS.some((m) => lower.includes(m));
212
+ }
213
+
214
+ const PARTIAL_DIGEST_MAX_RESULTS = 12;
215
+ const PARTIAL_DIGEST_PER_RESULT = 500;
216
+ const PARTIAL_DIGEST_MAX_CHARS = 8000;
217
+
218
+ /**
219
+ * "Half a synthesis beats none": when the loop stopped at a cap AND the
220
+ * forced no-tools summary call failed too, hand the caller a compact
221
+ * digest of what the turn gathered instead of only an error string.
222
+ * Before 2026-09-04 a capped research sub returned nothing but
223
+ * "Inspect the sub-session JSONL" — unusable for a parent agent
224
+ * (other agents' session dirs are read-blacklisted) and a total loss of
225
+ * 20–40 min / 1.5M-token turns (three reports, 2026-09-03/04).
226
+ *
227
+ * Takes the last assistant text (if any) plus the tail of the tool
228
+ * results, each truncated, hard-capped in total. Tool names come from
229
+ * the assistant tool_calls that requested them.
230
+ */
231
+ export function buildPartialDigest(messages: readonly ChatMessage[]): string {
232
+ const nameByCallId = new Map<string, string>();
233
+ let lastAssistantText = '';
234
+ for (const m of messages) {
235
+ if (m.role !== 'assistant') continue;
236
+ const calls = (m as { tool_calls?: Array<{ id?: string; function?: { name?: string } }> })
237
+ .tool_calls;
238
+ for (const c of calls ?? []) {
239
+ if (c.id && c.function?.name) nameByCallId.set(c.id, c.function.name);
240
+ }
241
+ if (typeof m.content === 'string' && m.content.trim()) lastAssistantText = m.content.trim();
242
+ }
243
+ const toolMsgs = messages.filter((m) => m.role === 'tool');
244
+ const tail = toolMsgs.slice(-PARTIAL_DIGEST_MAX_RESULTS);
245
+ const lines: string[] = [];
246
+ if (lastAssistantText) {
247
+ lines.push('Last assistant text before the cap:', lastAssistantText.slice(0, 1500), '');
248
+ }
249
+ lines.push(
250
+ `Last ${tail.length} of ${toolMsgs.length} tool results (each truncated to ${PARTIAL_DIGEST_PER_RESULT} chars):`,
251
+ );
252
+ for (const m of tail) {
253
+ const id = (m as { tool_call_id?: string }).tool_call_id ?? '';
254
+ const name = nameByCallId.get(id) ?? 'tool';
255
+ const raw =
256
+ typeof m.content === 'string'
257
+ ? m.content
258
+ : Array.isArray(m.content)
259
+ ? m.content
260
+ .map((b) => ('text' in b && typeof b.text === 'string' ? b.text : `[${b.type}]`))
261
+ .join(' ')
262
+ : '';
263
+ const oneLine = raw.replace(/\s+/g, ' ').trim();
264
+ lines.push(
265
+ `- ${name}: ${oneLine.slice(0, PARTIAL_DIGEST_PER_RESULT)}${oneLine.length > PARTIAL_DIGEST_PER_RESULT ? '…' : ''}`,
266
+ );
267
+ }
268
+ const out = lines.join('\n');
269
+ return out.length > PARTIAL_DIGEST_MAX_CHARS ? `${out.slice(0, PARTIAL_DIGEST_MAX_CHARS)}…` : out;
270
+ }
271
+
272
+ /**
273
+ * True when the tail of the text is the same chunk repeated over and over
274
+ * — a degenerate loop, regardless of WHAT is repeating. Catches walls that
275
+ * aren't the known scaffold string (weak models loop on all sorts of
276
+ * phrases). Cheap and bounded: only looks once the text is long enough to
277
+ * be suspicious, and by then the stream is cut so `text` never grows huge.
278
+ */
279
+ export function looksRepetitive(text: string): boolean {
280
+ if (text.length < 240) return false;
281
+ // A 60-char probe taken from near the end. If it recurs ≥4×, it's a loop.
282
+ const probe = text.slice(-80, -20);
283
+ if (probe.length < 40) return false;
284
+ let count = 0;
285
+ let idx = text.indexOf(probe);
286
+ while (idx !== -1 && count < 4) {
287
+ count++;
288
+ idx = text.indexOf(probe, idx + probe.length);
289
+ }
290
+ return count >= 4;
291
+ }
292
+
293
+ /**
294
+ * Remove scaffold sentences (and lines dominated by them) from an answer.
295
+ * Last-resort cleanup for when even a no-tools finalisation still leaks
296
+ * the template: strip the offending lines rather than show them.
297
+ */
298
+ export function stripScaffold(text: string): string {
299
+ return text
300
+ .split('\n')
301
+ .filter((line) => !containsScaffold(line))
302
+ .join('\n')
303
+ .replace(/\n{3,}/g, '\n\n')
304
+ .trim();
305
+ }
306
+
307
+ // Exported for the history-rebuild regression tests
308
+ // (./tool-trace.test.mts) — the shape of what we hand a stateless
309
+ // backend is load-bearing enough to assert on directly.
310
+ export async function buildMessages(
311
+ systemPrompt: string,
312
+ history: NormalizedEvent[],
313
+ compactions: Compaction[] | undefined,
314
+ pdfMode: 'native' | 'rasterize',
315
+ /** Capabilities of the model this history is being packed FOR.
316
+ * Required, not optional: a caller that forgets it would silently
317
+ * reintroduce the bug this parameter exists to prevent — replaying
318
+ * image blocks at a model that cannot accept them. */
319
+ caps: readonly ModelCapability[],
320
+ ): Promise<ChatMessage[]> {
321
+ // The latest compaction summary is appended to the ONE leading system
322
+ // message instead of travelling as a second `system` entry. Strict
323
+ // chat templates (vLLM + Qwen 3.x) accept `role: system` only at
324
+ // index 0 — "System message must be at the beginning" (400) — and the
325
+ // force-summary path already paid for that assumption once
326
+ // (2026-09-04). One system message is valid everywhere; the
327
+ // <conversation-summary> block keeps its own delimiters so the
328
+ // model still sees where the prompt ends and the summary starts.
329
+ const latest = pickLatest(compactions);
330
+ const systemContent = latest
331
+ ? [
332
+ systemPrompt,
333
+ '',
334
+ '<conversation-summary>',
335
+ 'An earlier compaction summarised the older part of this',
336
+ 'session. Treat the following block as reliable context for',
337
+ 'every fact that is not explicitly repeated further below:',
338
+ '',
339
+ latest.summary,
340
+ '</conversation-summary>',
341
+ ].join('\n')
342
+ : systemPrompt;
343
+ const messages: ChatMessage[] = [{ role: 'system', content: systemContent }];
344
+ const sinceTs = latest?.throughTs ?? 0;
345
+
346
+ let pendingRole: 'user' | 'assistant' | null = null;
347
+ let pendingText = '';
348
+
349
+ const flush = () => {
350
+ if (pendingRole && pendingText) {
351
+ messages.push({ role: pendingRole, content: pendingText });
352
+ }
353
+ pendingRole = null;
354
+ pendingText = '';
355
+ };
356
+
357
+ // Tool history. Turns that used tools are replayed in the NATIVE
358
+ // OpenAI shape — an assistant message carrying `tool_calls`, followed
359
+ // by one `role:'tool'` message per result — rather than as prose.
360
+ //
361
+ // Why it matters (measured 2026-07-22, N=20 per cell): with tool turns
362
+ // flattened to text, deepseek-chat produced 0/20 tool calls on a real
363
+ // session history and deepseek-r1 1/20. Replaying the native shape
364
+ // lifted them to 14/20 and 10/20. The model has no memory beyond what
365
+ // we hand it, so a transcript in which the assistant never calls tools
366
+ // is a demonstration that here, one does not call tools.
367
+ //
368
+ // An earlier attempt used a prose `<somora-tool-log>` summary instead.
369
+ // It measured as useless (85%→90% on kimi, 0%→0% on deepseek) and,
370
+ // while it briefly sat in the assistant role, actively harmful: models
371
+ // began writing the block themselves with invented commands and
372
+ // outputs. The sanitizer still strips it (src/server/sanitize-assistant-text.ts)
373
+ // because sessions recorded during that window carry fabricated ones.
374
+ //
375
+ // Full investigation: private/toolcall-investigation.md.
376
+ const pendingCalls: Array<{ id: string; name: string; args: string }> = [];
377
+ const pendingResults = new Map<string, string>();
378
+
379
+ /** Emit the collected tool activity of one turn, ahead of that turn's
380
+ * assistant text. Calls without a matching result are dropped: an
381
+ * assistant `tool_calls` entry whose result never arrives is a hard
382
+ * 400 on most backends, and a crashed turn can leave exactly that. */
383
+ const flushToolTurn = () => {
384
+ if (pendingCalls.length === 0) return;
385
+ const paired = pendingCalls.filter((c) => pendingResults.has(c.id));
386
+ pendingCalls.length = 0;
387
+ if (paired.length === 0) { pendingResults.clear(); return; }
388
+ flush(); // close any open text message first — ordering is load-bearing
389
+ messages.push({
390
+ role: 'assistant',
391
+ content: null,
392
+ tool_calls: paired.map((c) => ({
393
+ id: c.id,
394
+ type: 'function' as const,
395
+ function: { name: c.name, arguments: c.args || '{}' },
396
+ })),
397
+ } as unknown as ChatMessage);
398
+ for (const c of paired) {
399
+ messages.push({
400
+ role: 'tool',
401
+ tool_call_id: c.id,
402
+ content: pendingResults.get(c.id)!,
403
+ } as unknown as ChatMessage);
404
+ }
405
+ pendingResults.clear();
406
+ };
407
+
408
+ for (const ev of history) {
409
+ if (ev.ts <= sinceTs) continue; // skip events covered by compaction
410
+ if (ev.kind === 'user_message') {
411
+ // A2A attribution: prepend a header when this user-message was
412
+ // written by another agent so the model sees the provenance
413
+ // even after replay across engines.
414
+ // A turn that never produced an assistant_message (crash, abort)
415
+ // still has its tool activity replayed, ahead of the next user turn.
416
+ flushToolTurn();
417
+ // A turn recorded with an `origin` (2026-09-13 onwards) carries the
418
+ // header inside its stored ephemeral block; an older one never
419
+ // stored it anywhere, so it is added here as the engine added it
420
+ // live back then (src/server/turn-framing.ts).
421
+ const headed = ev.origin ? ev.text : withFromAgentHeader(ev.text, ev.from_agent, ev.from_session);
422
+ // Memory-recall block (if any) was persisted on the event when
423
+ // this turn was originally sent; reconstruct it here so the
424
+ // byte sequence matches what the backend already cached. This
425
+ // is what makes prefix-cache hold across turns for stateless
426
+ // openai-compatible backends. Engines with stateful resumed
427
+ // sessions (claude-cli/codex-cli) don't reconstruct full
428
+ // history so they ignore this code path.
429
+ const composed = ev.ephemeral ? `${ev.ephemeral}\n\n${headed}` : headed;
430
+ // Phase Y.B — when this past turn carried attachments, it must
431
+ // become its own array-content message (can't be collapsed with
432
+ // siblings). Resolve refs from disk and build the content parts;
433
+ // missing files degrade to a text marker so a long-deleted
434
+ // attachment doesn't kill the turn replay.
435
+ if (ev.attachments && ev.attachments.length > 0) {
436
+ flush();
437
+ const resolved: ResolvedAttachment[] = [];
438
+ for (const a of ev.attachments) {
439
+ try {
440
+ const r = await resolveAttachmentByHash({ hash: a.hash, expectedMime: a.mime });
441
+ resolved.push({
442
+ hash: a.hash,
443
+ path: r.path,
444
+ name: a.name,
445
+ mime: r.mime,
446
+ size: r.size,
447
+ });
448
+ } catch (err) {
449
+ logger.warn({
450
+ msg: 'engine.replay.attachment_missing',
451
+ hash: a.hash,
452
+ name: a.name,
453
+ err: (err as Error).message,
454
+ });
455
+ }
456
+ }
457
+ if (resolved.length === 0) {
458
+ // All refs were stale — fall back to text-only with a marker
459
+ // so the model sees that something *was* attached at this turn.
460
+ const lostNames = ev.attachments.map((a) => a.name).join(', ');
461
+ messages.push({
462
+ role: 'user',
463
+ content: `[Attachments lost from disk: ${lostNames}]\n\n${composed}`,
464
+ });
465
+ } else {
466
+ const notShown = resolved.filter(
467
+ (r) =>
468
+ (r.mime.kind === 'image' && !caps.includes('image')) ||
469
+ (r.mime.kind === 'pdf' && !caps.includes('pdf') && !caps.includes('image')),
470
+ );
471
+ if (notShown.length > 0) {
472
+ logger.info({
473
+ msg: 'engine.history.attachments_not_shown',
474
+ count: notShown.length,
475
+ kinds: notShown.map((r) => r.mime.kind),
476
+ names: notShown.map((r) => r.name),
477
+ capabilities: [...caps],
478
+ hint: 'active model lacks the capability — replayed as text markers so the turn still packs',
479
+ });
480
+ }
481
+ const content = await buildOpenAiUserContent(composed, resolved, pdfMode, caps);
482
+ messages.push({
483
+ role: 'user',
484
+ content: content as OpenAI.Chat.Completions.ChatCompletionUserMessageParam['content'],
485
+ });
486
+ }
487
+ continue;
488
+ }
489
+ if (pendingRole !== 'user') flush();
490
+ pendingRole = 'user';
491
+ pendingText = pendingText ? `${pendingText}\n\n${composed}` : composed;
492
+ } else if (ev.kind === 'assistant_message') {
493
+ // This turn's tool activity happened BEFORE the model's closing
494
+ // text, so it goes out first.
495
+ flushToolTurn();
496
+ // Historical poison: sessions recorded while the prose tool-log
497
+ // block sat in the assistant role contain models' own fabricated
498
+ // <somora-tool-log> blocks. Strip them on the way back in so a
499
+ // poisoned session heals instead of compounding.
500
+ const cleaned = sanitizeAssistantText(ev.text).text;
501
+ if (pendingRole !== 'assistant') flush();
502
+ pendingRole = 'assistant';
503
+ pendingText = pendingText ? `${pendingText}\n\n${cleaned}` : cleaned;
504
+ } else if (ev.kind === 'tool_call') {
505
+ pendingCalls.push({
506
+ id: ev.callId,
507
+ name: ev.tool,
508
+ args: JSON.stringify(ev.input ?? {}),
509
+ });
510
+ } else if (ev.kind === 'tool_result') {
511
+ const payload = ev.error !== undefined ? { error: ev.error } : (ev.output ?? null);
512
+ let text: string;
513
+ try {
514
+ text = JSON.stringify(payload) ?? 'null';
515
+ } catch {
516
+ text = '"[unserializable tool result]"';
517
+ }
518
+ // Cap per result. Full outputs are what blew the context in the
519
+ // first place; the model can re-read anything it actually needs.
520
+ pendingResults.set(
521
+ ev.callId,
522
+ text.length > MAX_REPLAYED_TOOL_RESULT_CHARS
523
+ ? `${text.slice(0, MAX_REPLAYED_TOOL_RESULT_CHARS)}… [truncated]`
524
+ : text,
525
+ );
526
+ }
527
+ // deltas / turn_start / turn_end → ignore for chat.completions
528
+ }
529
+ // Trailing tool activity from a turn still in flight.
530
+ flushToolTurn();
531
+ flush();
532
+ return messages;
533
+ }
534
+
535
+ /** Soft-warning estimate over the built messages. Uses the same counter
536
+ * as the per-request budget check: the old local version summed string
537
+ * content only, so tool arguments and multimodal parts were invisible
538
+ * and the warning never fired on the sessions that needed it. */
539
+ function estimateTokens(messages: ChatMessage[]): number {
540
+ return estimateRequestTokens(messages as never);
541
+ }
542
+
543
+ /**
544
+ * Convert our ToolDefinition[] to OpenAI's `tools` parameter shape.
545
+ * Each tool's `jsonSchema` is already a complete JSON Schema object
546
+ * matching what `parameters:` expects.
547
+ */
548
+ function toOpenAiTools(defs: ToolDefinition[]): ChatTool[] {
549
+ return defs.map((d) => ({
550
+ type: 'function',
551
+ function: {
552
+ name: d.name,
553
+ description: d.description,
554
+ parameters: d.jsonSchema as Record<string, unknown>,
555
+ },
556
+ }));
557
+ }
558
+
559
+ /**
560
+ * Backend refused the prompt because it doesn't fit the model. The
561
+ * pre-turn `shouldCompact` check works off somora's own token
562
+ * ESTIMATE, which can sit far below the backend's count (26k estimated
563
+ * vs 251k counted on 2026-08-22 — images, tool payloads, chars/4). So
564
+ * the estimate is a hint; the backend's 400 is the truth. Matches the
565
+ * wordings seen in the wild: LiteLLM/sglang "Prompt too long: N tokens
566
+ * exceeds max context window", OpenAI "maximum context length is N
567
+ * tokens", `context_length_exceeded`, and oMLX's "prefill memory guard
568
+ * rejected this prompt".
569
+ */
570
+ export function isContextLengthError(err: unknown): boolean {
571
+ const msg = String((err as Error)?.message ?? err);
572
+ return /prompt too long|context[_ ]length|maximum context|max(imum)? context window|context window of|prefill memory guard|too many tokens|reduce the length of the messages|input is too long|exceeds the (model'?s? )?(context|token)/i.test(
573
+ msg,
574
+ );
575
+ }
576
+
577
+ /** Turns that already got one reactive compaction+retry — never loop. */
578
+ const CONTEXT_RETRIED = new WeakSet<TurnInput>();
579
+
580
+ export const openAiCompatibleEngine: AgentEngine = {
581
+ name: ENGINE,
582
+
583
+ async *runTurn(input: TurnInput): AsyncIterable<NormalizedEvent> {
584
+ const {
585
+ agent,
586
+ session,
587
+ systemPrompt,
588
+ ephemeralContext,
589
+ history,
590
+ metaStore,
591
+ resolvedModel,
592
+ availableModels,
593
+ thinking,
594
+ sampling,
595
+ signal,
596
+ } = input;
597
+ if (resolvedModel.provider.engine !== ENGINE) {
598
+ throw new Error(`openai-compatible engine called with non-matching provider engine: ${resolvedModel.provider.engine}`);
599
+ }
600
+
601
+ const turnId = `t-${Date.now()}`;
602
+ const ts = () => Date.now();
603
+
604
+ // Idle watchdog — bridges the upstream user-abort signal with an
605
+ // event-idle timer. If the local LLM stops streaming chunks for the
606
+ // configured window we abort the fetch so the per-session lock
607
+ // releases cleanly instead of a Node process hanging forever.
608
+ // Threshold from config.engineWatchdog.openaiCompatibleIdleMs
609
+ // (default 1200s = 20min). Local-LLM workloads can legitimately
610
+ // take many minutes per turn; the timer resets on every received
611
+ // chunk so a slow-but-streaming model never trips this.
612
+ const IDLE_TIMEOUT_MS = input.idleTimeoutMs ?? 1_200_000;
613
+ const watchdogAbort = new AbortController();
614
+ let watchdogFired = false;
615
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
616
+ const armIdleTimer = () => {
617
+ if (idleTimer) clearTimeout(idleTimer);
618
+ idleTimer = setTimeout(() => {
619
+ watchdogFired = true;
620
+ logger.error({
621
+ msg: 'engine.watchdog_idle_timeout',
622
+ engine: ENGINE,
623
+ agent,
624
+ session,
625
+ idleMs: IDLE_TIMEOUT_MS,
626
+ hint: 'no stream chunks received from openai-compatible backend; aborting',
627
+ });
628
+ watchdogAbort.abort();
629
+ }, IDLE_TIMEOUT_MS);
630
+ };
631
+ const disarmIdleTimer = () => {
632
+ if (idleTimer) {
633
+ clearTimeout(idleTimer);
634
+ idleTimer = undefined;
635
+ }
636
+ };
637
+ // Forward upstream user-abort to the same controller, so create()
638
+ // sees a single combined signal.
639
+ const onUpstreamAbort = () => watchdogAbort.abort();
640
+ if (signal) {
641
+ if (signal.aborted) watchdogAbort.abort();
642
+ else signal.addEventListener('abort', onUpstreamAbort, { once: true });
643
+ }
644
+ const effectiveSignal = watchdogAbort.signal;
645
+
646
+ // Race iter.next() against the abort signal. Mirrors the main
647
+ // streaming loop's inline race (see its rationale ~line 652): some
648
+ // openai-compatible backends hold the connection open without
649
+ // emitting bytes and ignore the fetch-level abort, so a plain
650
+ // for-await wedges on the body reader and neither user-cancel nor the
651
+ // idle watchdog can escape. Used by the force-summary finish below.
652
+ async function nextOrAbort<T>(iter: AsyncIterator<T>): Promise<IteratorResult<T>> {
653
+ return await new Promise<IteratorResult<T>>((resolve, reject) => {
654
+ if (effectiveSignal.aborted) {
655
+ reject(new DOMException('Aborted', 'AbortError'));
656
+ return;
657
+ }
658
+ const onAbort = (): void => reject(new DOMException('Aborted', 'AbortError'));
659
+ effectiveSignal.addEventListener('abort', onAbort, { once: true });
660
+ iter.next().then(
661
+ (r) => {
662
+ effectiveSignal.removeEventListener('abort', onAbort);
663
+ resolve(r);
664
+ },
665
+ (err: unknown) => {
666
+ effectiveSignal.removeEventListener('abort', onAbort);
667
+ reject(err instanceof Error ? err : new Error(String(err)));
668
+ },
669
+ );
670
+ });
671
+ }
672
+
673
+ yield { kind: 'turn_start', ts: ts(), engine: ENGINE, turnId };
674
+
675
+ /** measured ÷ estimated, carried from the session and refreshed after
676
+ * every request of this turn. See calibratedEstimate(). */
677
+ let tokenRatio: number | undefined;
678
+ /** What we estimated for the request currently in flight, so the
679
+ * provider's answer can be compared against it. */
680
+ let estimateInFlight: number | undefined;
681
+ /** A compaction just ran: check the next real reading against the
682
+ * trigger instead of assuming it helped. */
683
+ let verifyCompaction = false;
684
+ /** The trigger this turn was measured against, for that check. */
685
+ let compactionTrigger = Number.POSITIVE_INFINITY;
686
+
687
+ let meta = (await metaStore.get(agent, session)) as OpenAiCompatibleMeta;
688
+ let compactions = meta.compactions;
689
+
690
+ // Compaction tunables come from the server-resolved config (env > yaml > defaults).
691
+ const compactionConfig = input.compactionConfig;
692
+ // The provider's own count for this session's last request, when it
693
+ // is still valid for the model about to answer. A model switch drops
694
+ // it: tokenizers differ, and a stale number is worse than none.
695
+ const measured =
696
+ meta.contextTokens && meta.contextTokens.model === resolvedModel.modelId
697
+ ? meta.contextTokens.tokens
698
+ : undefined;
699
+ if (meta.tokenRatio && meta.tokenRatio.model === resolvedModel.modelId) {
700
+ tokenRatio = meta.tokenRatio.ratio;
701
+ }
702
+ const decision = shouldCompact({
703
+ systemPrompt,
704
+ history,
705
+ compactions,
706
+ contextWindow: resolvedModel.model.contextWindow,
707
+ config: compactionConfig,
708
+ ...(resolvedModel.model.maxTokens ? { maxOutputTokens: resolvedModel.model.maxTokens } : {}),
709
+ ...(measured !== undefined ? { measuredTokens: measured } : {}),
710
+ ...(tokenRatio !== undefined ? { tokenRatio } : {}),
711
+ });
712
+ compactionTrigger = decision.triggerTokens;
713
+ if (decision.shouldCompact) {
714
+ logger.info({
715
+ msg: 'engine.compaction_trigger',
716
+ engine: ENGINE,
717
+ agent,
718
+ session,
719
+ estimatedTokens: decision.estimatedTokens,
720
+ source: decision.source,
721
+ triggerTokens: decision.triggerTokens,
722
+ ratio: Math.round(decision.ratio * 100) / 100,
723
+ existingCompactions: compactions?.length ?? 0,
724
+ });
725
+ try {
726
+ const newCompaction = await runCompaction({
727
+ systemPrompt,
728
+ history,
729
+ resolvedModel,
730
+ availableModels,
731
+ compactions,
732
+ config: compactionConfig,
733
+ });
734
+ if (newCompaction) {
735
+ verifyCompaction = true;
736
+ compactions = [...(compactions ?? []), newCompaction];
737
+ await metaStore.set(agent, session, {
738
+ ...meta,
739
+ compactions,
740
+ });
741
+ meta = { ...meta, compactions };
742
+ logger.info({
743
+ msg: 'engine.compaction_done',
744
+ engine: ENGINE,
745
+ agent,
746
+ session,
747
+ throughTs: newCompaction.throughTs,
748
+ tokensBefore: newCompaction.tokensBefore,
749
+ tokensAfter: newCompaction.tokensAfter,
750
+ summaryChars: newCompaction.summary.length,
751
+ });
752
+ } else {
753
+ // Nothing to summarise under the normal cushion. That is fine
754
+ // when the session is short — and fatal when it is short but
755
+ // already too big for the window (a large system prompt plus a
756
+ // few long exchanges). Try once more keeping only the last
757
+ // exchange: an aggressive summary beats a turn that cannot run.
758
+ // Hermes Agent bounds its compression attempts the same way.
759
+ const tight = await runCompaction({
760
+ systemPrompt,
761
+ history,
762
+ resolvedModel,
763
+ availableModels,
764
+ compactions,
765
+ config: { ...compactionConfig, safetyCushionPairs: 1 },
766
+ }).catch(() => null);
767
+ if (tight) {
768
+ verifyCompaction = true;
769
+ compactions = [...(compactions ?? []), tight];
770
+ await metaStore.update(agent, session, (current) => ({ ...current, compactions }));
771
+ meta = { ...meta, compactions };
772
+ logger.info({
773
+ msg: 'engine.compaction_done',
774
+ engine: ENGINE,
775
+ agent,
776
+ session,
777
+ cushion: 1,
778
+ throughTs: tight.throughTs,
779
+ tokensBefore: tight.tokensBefore,
780
+ tokensAfter: tight.tokensAfter,
781
+ reason: 'normal cushion covered everything; compacted down to the last exchange',
782
+ });
783
+ } else {
784
+ logger.info({
785
+ msg: 'engine.compaction_skip',
786
+ engine: ENGINE,
787
+ agent,
788
+ session,
789
+ reason: 'nothing left to compact even at cushion 1 (one exchange is already too big)',
790
+ });
791
+ }
792
+ }
793
+ } catch (err) {
794
+ // Don't kill the turn if compaction itself fails — degrade gracefully.
795
+ logger.warn({
796
+ msg: 'engine.compaction_fail',
797
+ engine: ENGINE,
798
+ agent,
799
+ session,
800
+ err: String(err),
801
+ });
802
+ }
803
+ }
804
+
805
+ // Memory inject placement controls prefix-cache hit-rate. Default
806
+ // ('inline-user') relies on persistence: ephemeralContext is stored
807
+ // alongside each user_message in JSONL (see run-turn.ts), and
808
+ // buildMessages reconstructs each prior user message with its own
809
+ // memory block included. Result: the byte sequence sent for turn
810
+ // N+1 matches what the backend cached for turn N up to (but not
811
+ // including) the new user message — full prefix cache hit on
812
+ // system + tools + entire prior conversation.
813
+ //
814
+ // 'system' is the legacy concat-onto-system mode. Opt-in via config
815
+ // for backends that mishandle multi-pair user/assistant histories
816
+ // with embedded memory blocks. Cache-destructive (memory landing
817
+ // in the system prefix changes per turn) — only use as a fallback.
818
+ const memoryInjectMode =
819
+ (resolvedModel.provider as { memoryInjectMode?: 'inline-user' | 'system' })
820
+ .memoryInjectMode ?? 'inline-user';
821
+ const useLegacySystemConcat = memoryInjectMode === 'system';
822
+ const effectiveSystemPrompt =
823
+ useLegacySystemConcat && ephemeralContext
824
+ ? `${systemPrompt}\n\n---\n\n${ephemeralContext}`
825
+ : systemPrompt;
826
+ const pdfMode =
827
+ (resolvedModel.provider as { pdfMode?: 'native' | 'rasterize' }).pdfMode ?? 'rasterize';
828
+ const messages = await buildMessages(
829
+ effectiveSystemPrompt,
830
+ history,
831
+ compactions,
832
+ pdfMode,
833
+ resolvedModel.model.capabilities,
834
+ );
835
+ const estTokens = estimateTokens(messages);
836
+ const ctxRatio = estTokens / resolvedModel.model.contextWindow;
837
+ if (ctxRatio > 0.7) {
838
+ logger.warn({
839
+ msg: 'engine.context_warn',
840
+ engine: ENGINE,
841
+ provider: resolvedModel.providerName,
842
+ model: resolvedModel.modelId,
843
+ agent,
844
+ session,
845
+ estimatedTokens: estTokens,
846
+ contextWindow: resolvedModel.model.contextWindow,
847
+ ratio: Math.round(ctxRatio * 100) / 100,
848
+ hint: 'history is approaching the context-window limit even after compaction. Lower triggerRatio for more headroom.',
849
+ });
850
+ }
851
+
852
+ const client = createPatientOpenAIClient({
853
+ baseURL: resolvedModel.provider.baseUrl,
854
+ apiKey: resolvedModel.provider.apiKey,
855
+ });
856
+
857
+ // Cumulative content across ALL tool-rounds. The model may speak in
858
+ // round 1 ("Let me check..."), call tools, then continue in round 2
859
+ // ("Based on what I found, …"). We concat with a blank line between
860
+ // round-segments so the streamed view to the user keeps growing
861
+ // monotonically — matches how claude-cli's SDK presents
862
+ // tool-using turns to us (one final assistant_message at the end).
863
+ let cumulative = '';
864
+ // Reasoning text across rounds of this turn — see roundThinking.
865
+ let turnThinking = '';
866
+ /** Rounds whose request was sent — the reactive context retry is only
867
+ * safe before anything happened (round 1, nothing emitted). */
868
+ let roundsStarted = 0;
869
+ /** Outcome signals for turn_end (ChatTurnResult.outcome): set when a
870
+ * forced no-tools finish was needed, and when the final text ended
871
+ * up as a somora marker instead of a model answer. */
872
+ let forcedFinalReason: string | undefined;
873
+ let degradedReason: string | undefined;
874
+ let totalUsage:
875
+ | {
876
+ tokens_in: number;
877
+ tokens_out: number;
878
+ tokens_out_reasoning?: number;
879
+ tokens_out_reasoning_estimated?: boolean;
880
+ }
881
+ | undefined;
882
+ let tokensInCached: number | undefined;
883
+ /** Prompt size of the most recent request — see usage.context_tokens. */
884
+ let lastPromptTokens: number | undefined;
885
+ /** Output tokens of the most recent request. Compared against the
886
+ * model's declared cap this is the only trustworthy evidence that a
887
+ * round ran out of room: the provider's stop reason is rewritten by
888
+ * routers (vLLM turns 'length' into 'tool_calls'). */
889
+ let lastCompletionTokens: number | undefined;
890
+ /** Quiet retries spent on malformed tool arguments this turn. */
891
+ let argRerolls = 0;
892
+ let reasoningOnlyNudges = 0;
893
+ let lastTodoRound = 1;
894
+
895
+ const tools = input.tools;
896
+ const toolList = tools ? tools.list() : [];
897
+ // An EMPTY array is not "no tools" to a backend: LiteLLM answers
898
+ // `400 "tools must not be an empty array. Either provide at least one
899
+ // tool or omit the field entirely"`. An agent with every tool denied
900
+ // hit that on every single turn (found while testing 2026-09-10).
901
+ const advertised: ChatTool[] | undefined = tools ? toOpenAiTools(toolList) : undefined;
902
+ const openAiTools: ChatTool[] | undefined = advertised && advertised.length > 0 ? advertised : undefined;
903
+ const toolByName = new Map(toolList.map((t) => [t.name, t]));
904
+ const loopMessages = [...messages]; // mutable copy; tool rounds append
905
+ // Where this turn begins in loopMessages: its user message (the
906
+ // last one built) — the mid-turn compaction of a builder turn keeps
907
+ // everything before it and summarises the rounds after it.
908
+ let turnStartIdx = loopMessages.length - 1;
909
+ while (turnStartIdx > 0 && loopMessages[turnStartIdx]?.role !== 'user') turnStartIdx--;
910
+ const isBuilderTurn = input.agentKind === 'builder';
911
+ const maxRounds = input.agentLoopConfig?.maxRounds ?? DEFAULT_MAX_TOOL_ROUNDS;
912
+ const maxToolCallsPerTurn =
913
+ input.agentLoopConfig?.maxToolCallsPerTurn ?? DEFAULT_MAX_TOOL_CALLS_PER_TURN;
914
+ const globalToolTimeoutMs =
915
+ input.agentLoopConfig?.toolCallTimeoutMs ?? DEFAULT_TOOL_CALL_TIMEOUT_MS;
916
+
917
+ try {
918
+ logger.info({
919
+ msg: 'engine.init',
920
+ engine: ENGINE,
921
+ provider: resolvedModel.providerName,
922
+ model: resolvedModel.modelId,
923
+ baseUrl: resolvedModel.provider.baseUrl,
924
+ estimatedTokens: estTokens,
925
+ compactionsApplied: compactions?.length ?? 0,
926
+ toolsAdvertised: openAiTools?.length ?? 0,
927
+ });
928
+
929
+ // Cross-engine thinking knob → OpenAI's `reasoning_effort` body param
930
+ // via shared helper. Helper internally guards on the model's
931
+ // 'reasoning' capability — for opaque local endpoints (Gemma etc.)
932
+ // it returns {} so the request stays clean and the user sees the
933
+ // dormant state in the header.
934
+ const reasoning = openAiReasoningState(thinking, resolvedModel.model);
935
+ type CreateParams = OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;
936
+ // One retry when the backend rejects the effort value — see
937
+ // src/engine/reasoning-retry.ts. The adjusted value sticks for the
938
+ // remaining rounds of this turn; `reasoning.adjustment` is yielded
939
+ // once as engine_meta below so the user sees what was sent.
940
+ // Sampling (temperature, top_p, …): model default < agent.yaml <
941
+ // session override, merged by run-turn. A backend that rejects a
942
+ // key answers 400 → retry ONCE without any sampling and say so via
943
+ // engine_meta; the drop sticks for the rest of the turn.
944
+ let samplingParam: Record<string, unknown> = samplingBody(sampling);
945
+ // `user: "<agent>/<session>"` — standard field, lets a gateway
946
+ // attribute cost per agent and group a session's requests.
947
+ const userTag = userTagParam(resolvedModel, agent, session);
948
+ let samplingDropped: { sent: Record<string, unknown>; backend: string } | null = null;
949
+ const logCtx = { engine: ENGINE, provider: resolvedModel.providerName, model: resolvedModel.modelId, agent, session };
950
+ const createChatStream = async (params: CreateParams) => {
951
+ const send = () =>
952
+ withReasoningRetry(
953
+ reasoning,
954
+ (body) =>
955
+ client.chat.completions.create({ ...params, ...samplingParam, ...userTag, ...body } as CreateParams, {
956
+ signal: effectiveSignal,
957
+ }),
958
+ logCtx,
959
+ );
960
+ try {
961
+ return await send();
962
+ } catch (err) {
963
+ if (Object.keys(samplingParam).length === 0 || !isSamplingParamError(err)) throw err;
964
+ const backend = String((err as Error).message ?? err).slice(0, 300);
965
+ logger.warn({ msg: 'engine.sampling_rejected', ...logCtx, sent: samplingParam, backend });
966
+ samplingDropped = { sent: samplingParam, backend };
967
+ samplingParam = {};
968
+ return await send();
969
+ }
970
+ };
971
+
972
+ let round = 0;
973
+ // Did the LAST executed round still want tools? Distinguishes
974
+ // "model gave its final answer" (breaks below) from "hit the cap
975
+ // mid-runaway" — only the latter needs the forced no-tools finish.
976
+ let lastRoundHadTools = false;
977
+ // Set when the stream guard aborted a round mid-scaffold. The content
978
+ // is discarded, so the post-loop containsScaffold(cumulative) check
979
+ // wouldn't see it — this flag carries the signal to force a clean finish.
980
+ let sawScaffoldLeak = false;
981
+ // Total tool calls executed this turn, across all rounds. Bounds the
982
+ // within-round fan-out that maxRounds can't (a weak model emitting 77
983
+ // calls in one round). When it trips we force a clean final answer.
984
+ let totalToolCalls = 0;
985
+ let hitToolBudget = false;
986
+ let softWarned = false;
987
+ // Wall-clock cap (agentLoop.maxTurnMs, builders): a night build
988
+ // must end with a report, not run into the next day unseen.
989
+ const maxTurnMs = input.agentLoopConfig?.maxTurnMs;
990
+ const turnStartedAt = Date.now();
991
+ let hitTimeCap = false;
992
+ // Doom loop: the same round of tool calls (names + arguments)
993
+ // repeated back to back. Three times → a notice the model can act
994
+ // on; five times → stop and ask for the report instead of burning
995
+ // the budget on identical results.
996
+ let lastRoundSig = '';
997
+ let repeatRounds = 0;
998
+ let hitDoomLoop = false;
999
+ while (round < maxRounds) {
1000
+ round++;
1001
+ roundsStarted = round;
1002
+ if (effectiveSignal.aborted) throw new DOMException('Aborted', 'AbortError');
1003
+ if (maxTurnMs && Date.now() - turnStartedAt > maxTurnMs) {
1004
+ hitTimeCap = true;
1005
+ round--;
1006
+ break;
1007
+ }
1008
+
1009
+ // Steering: what the person (or an agent) sent while the previous
1010
+ // round ran reaches the model now, before the next call, as user
1011
+ // messages. run-turn persists them from the event, in this order.
1012
+ const steered = input.steer?.drain() ?? [];
1013
+ if (steered.length > 0) {
1014
+ for (const m of steered) {
1015
+ loopMessages.push({ role: 'user', content: input.steer!.frame(m) });
1016
+ }
1017
+ yield { kind: 'steer_applied', ts: ts(), engine: ENGINE, messages: steered };
1018
+ }
1019
+ // Builder checkpoint: every 100 rounds the model refreshes its task
1020
+ // list and appends a short status to its report file, so a crash
1021
+ // in hour six loses minutes, not the night.
1022
+ if (isBuilderTurn && round > 1 && round % 100 === 1 && toolList.some((t) => t.name === 'todo_write')) {
1023
+ logger.info({ msg: 'engine.builder_checkpoint', engine: ENGINE, agent, session, round });
1024
+ loopMessages.push({
1025
+ role: 'user',
1026
+ content:
1027
+ `[somora] Checkpoint after ${round - 1} tool rounds: refresh your task list with todo_write (what is done, what is next), ` +
1028
+ 'append a short status (done / in progress / next) to your report file with file_write mode append if the task named one, ' +
1029
+ 'then continue where you were.',
1030
+ } as ChatMessage);
1031
+ }
1032
+
1033
+ // A stale task list: the list is what the person watches, and a
1034
+ // model deep in its work stops writing it (measured 2026-09-23:
1035
+ // one todo_write at round 1, none in the next 80 rounds, five
1036
+ // compactions with the list in the block did not change that).
1037
+ // Every TODO_STALE_ROUNDS rounds without a todo_write while items
1038
+ // are open, one line asks for it.
1039
+ if (isBuilderTurn && round - lastTodoRound >= TODO_STALE_ROUNDS && toolList.some((t) => t.name === 'todo_write')) {
1040
+ lastTodoRound = round;
1041
+ const todosNow = ((await metaStore.get(agent, session)) as { todos?: { content?: string; status?: string }[] }).todos;
1042
+ const open = Array.isArray(todosNow) ? todosNow.filter((t) => t.status === 'pending' || t.status === 'in_progress') : [];
1043
+ if (open.length > 0) {
1044
+ logger.info({ msg: 'engine.todo_stale_nudge', engine: ENGINE, agent, session, round, open: open.length });
1045
+ loopMessages.push({
1046
+ role: 'user',
1047
+ content:
1048
+ `[somora] Your task list has not changed for ${TODO_STALE_ROUNDS} tool rounds and ${open.length} item(s) are still open ` +
1049
+ `(in progress: ${open.filter((t) => t.status === 'in_progress').map((t) => t.content).join('; ') || 'none'}). ` +
1050
+ 'Bring it up to date with todo_write now — completed for what is verified, in_progress for the step you are on — then continue, ' +
1051
+ 'and from here on update the list in the round an item changes, not in a batch later.',
1052
+ } as ChatMessage);
1053
+ }
1054
+ }
1055
+
1056
+ // Does what we are about to send still fit? The pre-turn
1057
+ // compaction sized the conversation before any tool ran, and a
1058
+ // turn grows with every round: tool results, images, the tool
1059
+ // schemas that ride along each time. Checking once was how a
1060
+ // turn estimated at 58k tokens reached the backend at 507k and
1061
+ // died on a raw 400 (2026-09-10 report).
1062
+ //
1063
+ // The remedy has to work INSIDE the running turn: the tools have
1064
+ // already run, and re-running them is not an option. So the
1065
+ // oldest tool results are shortened, which keeps every
1066
+ // tool_call/result pair intact and keeps the model's record of
1067
+ // what it already did.
1068
+ const budget = promptBudget({
1069
+ contextWindow: resolvedModel.model.contextWindow,
1070
+ ...(resolvedModel.model.maxTokens ? { maxOutputTokens: resolvedModel.model.maxTokens } : {}),
1071
+ // A provider that never reports usage leaves us with the
1072
+ // estimate alone, and an estimate that cannot be corrected
1073
+ // deserves more room under it.
1074
+ ...(meta.providerOmitsUsage === true ? { safetyRatio: 0.15 } : {}),
1075
+ });
1076
+ let rawEstimate = estimateRequestTokens(loopMessages, openAiTools);
1077
+ let estimated = calibratedEstimate(rawEstimate, tokenRatio);
1078
+ estimateInFlight = rawEstimate;
1079
+ // A builder turn compacts its own older rounds first (a work-state
1080
+ // summary from a worker model, the last rounds verbatim —
1081
+ // compaction/midturn.ts); the tool-result trim below stays the
1082
+ // fallback, and the only path for chat agents.
1083
+ if (estimated > budget && isBuilderTurn && round > 1) {
1084
+ try {
1085
+ // The task list is read fresh: todo_write updated the meta
1086
+ // during this very turn.
1087
+ const todosNow = ((await metaStore.get(agent, session)) as { todos?: unknown }).todos;
1088
+ const c = await compactTurnMidway({
1089
+ messages: loopMessages as LoopMessage[],
1090
+ turnStartIdx,
1091
+ keepRounds: MIDTURN_KEEP_ROUNDS,
1092
+ resolvedModel,
1093
+ availableModels: input.availableModels,
1094
+ config: input.compactionConfig,
1095
+ agent,
1096
+ ...(Array.isArray(todosNow) ? { todos: todosNow as { content: string; status: string }[] } : {}),
1097
+ });
1098
+ if (c) {
1099
+ loopMessages.splice(0, loopMessages.length, ...(c.messages as ChatMessage[]));
1100
+ rawEstimate = estimateRequestTokens(loopMessages, openAiTools);
1101
+ estimated = calibratedEstimate(rawEstimate, tokenRatio);
1102
+ estimateInFlight = rawEstimate;
1103
+ logger.info({ msg: 'engine.midturn_compacted', engine: ENGINE, agent, session, round, replaced: c.compactedMessages, worker: c.worker, estimated, budget });
1104
+ yield {
1105
+ kind: 'engine_meta',
1106
+ ts: ts(),
1107
+ engine: ENGINE,
1108
+ itemType: 'context_compacted',
1109
+ payload: {
1110
+ text: `Earlier rounds of this turn were summarised into a work-state block (${c.compactedMessages} messages, worker ${c.worker}) to stay inside the context window.`,
1111
+ replaced: c.compactedMessages,
1112
+ worker: c.worker,
1113
+ },
1114
+ };
1115
+ }
1116
+ } catch (err) {
1117
+ logger.warn({ msg: 'engine.midturn_compaction_failed', engine: ENGINE, agent, session, round, err: (err as Error).message });
1118
+ }
1119
+ }
1120
+ if (estimated > budget) {
1121
+ const trim = trimToolResults(loopMessages, {
1122
+ budget,
1123
+ tools: openAiTools,
1124
+ ...(tokenRatio !== undefined ? { ratio: tokenRatio } : {}),
1125
+ });
1126
+ logger.warn({
1127
+ msg: 'engine.context_trim',
1128
+ engine: ENGINE,
1129
+ agent,
1130
+ session,
1131
+ round,
1132
+ estimated,
1133
+ rawEstimate,
1134
+ tokenRatio,
1135
+ budget,
1136
+ contextWindow: resolvedModel.model.contextWindow,
1137
+ trimmed: trim.trimmed,
1138
+ after: trim.estimate,
1139
+ fits: trim.fits,
1140
+ });
1141
+ if (trim.trimmed > 0) {
1142
+ loopMessages.length = 0;
1143
+ loopMessages.push(...(trim.messages as ChatMessage[]));
1144
+ yield {
1145
+ kind: 'engine_meta',
1146
+ ts: ts(),
1147
+ engine: ENGINE,
1148
+ itemType: 'context_trimmed',
1149
+ payload: {
1150
+ text:
1151
+ `The conversation reached ${resolvedModel.modelId}'s context window, so somora shortened ` +
1152
+ `${trim.trimmed} older tool result${trim.trimmed === 1 ? '' : 's'} to keep this turn going. ` +
1153
+ 'Nothing was run twice.',
1154
+ trimmed: trim.trimmed,
1155
+ estimated,
1156
+ budget,
1157
+ },
1158
+ };
1159
+ }
1160
+ if (!trim.fits) {
1161
+ // Even trimmed it does not fit. Stop with an explanation
1162
+ // instead of letting the backend answer with a raw 400 —
1163
+ // and stop AFTER the tool results are persisted, so the work
1164
+ // of this turn is on the record.
1165
+ logger.error({
1166
+ msg: 'engine.fail',
1167
+ engine: ENGINE,
1168
+ agent,
1169
+ session,
1170
+ err: `context budget exceeded mid-turn (${trim.estimate} > ${budget})`,
1171
+ });
1172
+ yield {
1173
+ kind: 'error',
1174
+ ts: ts(),
1175
+ engine: ENGINE,
1176
+ message:
1177
+ round === 1
1178
+ ? `This conversation does not fit ${resolvedModel.modelId}'s context window ` +
1179
+ `(${resolvedModel.model.contextWindow.toLocaleString('en-US')} tokens): about ` +
1180
+ `${trim.estimate.toLocaleString('en-US')} tokens of prompt against a budget of ` +
1181
+ `${budget.toLocaleString('en-US')}, and there is nothing left to shorten. Start a new session ` +
1182
+ '(/reset) or switch to a model with a larger window (/model).'
1183
+ : `This turn no longer fits ${resolvedModel.modelId}'s context window ` +
1184
+ `(${resolvedModel.model.contextWindow.toLocaleString('en-US')} tokens) after ${round - 1} tool ` +
1185
+ `round${round === 2 ? '' : 's'}: about ${trim.estimate.toLocaleString('en-US')} tokens of prompt ` +
1186
+ `against a budget of ${budget.toLocaleString('en-US')}. The tool results so far are in the ` +
1187
+ 'session — ask for the next step in a new message, or switch to a model with a larger window (/model).',
1188
+ providerError: false,
1189
+ };
1190
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
1191
+ return;
1192
+ }
1193
+ }
1194
+ armIdleTimer();
1195
+ const stream = await createChatStream({
1196
+ model: resolvedModel.modelId,
1197
+ messages: loopMessages,
1198
+ stream: true,
1199
+ stream_options: { include_usage: true },
1200
+ ...(openAiTools
1201
+ ? {
1202
+ tools: openAiTools,
1203
+ tool_choice: 'auto',
1204
+ // Default to one tool call per round. Weak/local models
1205
+ // (deepseek, kimi) fan out into large parallel batches of
1206
+ // identical calls and lose track of what they've run — the
1207
+ // 123×-`df` runaway. Sequential = one call, one result,
1208
+ // clear state. A model set `parallelToolCalls: true` opts
1209
+ // back into the provider's parallel default.
1210
+ ...(resolvedModel.model.parallelToolCalls === true
1211
+ ? {}
1212
+ : { parallel_tool_calls: false }),
1213
+ }
1214
+ : {}),
1215
+ ...(resolvedModel.model.maxTokens ? { max_tokens: resolvedModel.model.maxTokens } : {}),
1216
+ });
1217
+ if (samplingDropped) {
1218
+ const dropped: { sent: Record<string, unknown>; backend: string } = samplingDropped;
1219
+ samplingDropped = null;
1220
+ yield {
1221
+ kind: 'engine_meta',
1222
+ ts: ts(),
1223
+ engine: ENGINE,
1224
+ itemType: 'sampling_dropped',
1225
+ payload: {
1226
+ text:
1227
+ `${resolvedModel.modelId} rejected the sampling parameters (${formatSampling(dropped.sent as never)}) — ` +
1228
+ 'sent without them for this turn. Remove the offending key from the model, agent or session sampling to make this permanent.',
1229
+ sent: dropped.sent,
1230
+ backend: dropped.backend,
1231
+ },
1232
+ };
1233
+ }
1234
+ if (reasoning.adjustment) {
1235
+ const adj = reasoning.adjustment;
1236
+ reasoning.adjustment = null;
1237
+ yield {
1238
+ kind: 'engine_meta',
1239
+ ts: ts(),
1240
+ engine: ENGINE,
1241
+ itemType: 'reasoning_effort_adjusted',
1242
+ payload: {
1243
+ text:
1244
+ `${resolvedModel.modelId} rejected reasoning effort '${adj.requested}' — ` +
1245
+ (adj.sent ? `sent '${adj.sent}' instead` : 'sent without the parameter (model default)') +
1246
+ '. Map the level in the model\'s `reasoning.levels` config to make this permanent.',
1247
+ requested: adj.requested,
1248
+ sent: adj.sent,
1249
+ backend: adj.backend,
1250
+ },
1251
+ };
1252
+ }
1253
+
1254
+ // Per-round accumulators
1255
+ let roundContent = '';
1256
+ // Chars of `reasoning_content` / `reasoning` deltas seen this round.
1257
+ // Only used when the backend's usage reports no reasoning_tokens
1258
+ // (SGLang/vLLM builds vary) — then the 🧠 counter is estimated
1259
+ // from the streamed text at 4 chars/token and flagged as such.
1260
+ let roundReasoningChars = 0;
1261
+ // Reasoning TEXT of this round (reasoning_content / reasoning
1262
+ // deltas). Streamed as cumulative thinking_delta (turn-wide),
1263
+ // folded into turnThinking at round end, emitted once as
1264
+ // thinking_message before the final assistant_message.
1265
+ let roundThinking = '';
1266
+ // Inline-think text already surfaced as thinking_delta this round
1267
+ // (dedupes the cumulative re-split on every content delta).
1268
+ let roundInlineThinkingSeen = '';
1269
+ const roundToolCalls = new Map<number, StreamingToolCall>();
1270
+ let finishReason: string | null = null;
1271
+
1272
+ // Manual iteration with abort-race instead of plain `for await
1273
+ // (const chunk of stream)`. The OpenAI SDK passes our
1274
+ // effectiveSignal down to the underlying fetch, and undici is
1275
+ // supposed to abort the body-stream read when the signal fires.
1276
+ // Some openai-compatible backends (omlx in particular, but also
1277
+ // local ollama under load) hold the HTTP connection open without
1278
+ // emitting bytes and don't react to the abort — the for-await
1279
+ // just hangs on the body reader. Racing iter.next() against the
1280
+ // signal guarantees the watchdog can escape regardless.
1281
+ const chunkIter = (stream as AsyncIterable<typeof stream extends AsyncIterable<infer C> ? C : never>)[Symbol.asyncIterator]();
1282
+ while (true) {
1283
+ let next: IteratorResult<typeof stream extends AsyncIterable<infer C> ? C : never>;
1284
+ try {
1285
+ next = await new Promise<typeof next>((resolve, reject) => {
1286
+ if (effectiveSignal.aborted) {
1287
+ reject(new DOMException('Aborted', 'AbortError'));
1288
+ return;
1289
+ }
1290
+ const onAbort = (): void => {
1291
+ reject(new DOMException('Aborted', 'AbortError'));
1292
+ };
1293
+ effectiveSignal.addEventListener('abort', onAbort, { once: true });
1294
+ chunkIter.next().then(
1295
+ (r) => {
1296
+ effectiveSignal.removeEventListener('abort', onAbort);
1297
+ resolve(r);
1298
+ },
1299
+ (err: unknown) => {
1300
+ effectiveSignal.removeEventListener('abort', onAbort);
1301
+ reject(err instanceof Error ? err : new Error(String(err)));
1302
+ },
1303
+ );
1304
+ });
1305
+ } catch (err) {
1306
+ // Fire-and-forget cleanup — do NOT await. On a wedged native
1307
+ // async generator, return() is queued behind the pending
1308
+ // next() and never settles when that next() never settles, so
1309
+ // awaiting it re-hangs the turn in exactly the stuck-stream
1310
+ // case this race exists to escape (Juni-Audit 2026-06).
1311
+ // Detach it and surface the error immediately.
1312
+ void Promise.resolve(chunkIter.return?.(undefined)).catch(() => {});
1313
+ throw err;
1314
+ }
1315
+ if (next.done) break;
1316
+ const chunk = next.value;
1317
+ // Some openai-compatible backends (omlx in particular) close
1318
+ // the stream on signal-abort *without* throwing — the iterator
1319
+ // just terminates. Detect that here so we don't silently emit
1320
+ // a truncated assistant_message as if it were a clean completion.
1321
+ if (effectiveSignal.aborted) throw new DOMException('Aborted', 'AbortError');
1322
+ armIdleTimer();
1323
+ const choice = chunk.choices[0];
1324
+ const delta = choice?.delta;
1325
+ {
1326
+ const r = delta as { reasoning_content?: unknown; reasoning?: unknown } | undefined;
1327
+ const rtext =
1328
+ typeof r?.reasoning_content === 'string'
1329
+ ? r.reasoning_content
1330
+ : typeof r?.reasoning === 'string'
1331
+ ? r.reasoning
1332
+ : '';
1333
+ if (rtext) {
1334
+ roundReasoningChars += rtext.length;
1335
+ roundThinking += rtext;
1336
+ yield {
1337
+ kind: 'thinking_delta',
1338
+ ts: ts(),
1339
+ engine: ENGINE,
1340
+ text: turnThinking ? `${turnThinking}\n\n${roundThinking}` : roundThinking,
1341
+ };
1342
+ }
1343
+ }
1344
+ if (delta?.content && typeof delta.content === 'string') {
1345
+ roundContent += delta.content;
1346
+ // Inline `<think>…</think>` in content (backend without a
1347
+ // reasoning parser — DeepSeek V4 on SGLang): route the
1348
+ // reasoning part to thinking_delta and stream only the
1349
+ // answer part as assistant text. Without an opening tag the
1350
+ // block is only recognisable once `</think>` arrives, so the
1351
+ // first deltas of such a round may stream as assistant text;
1352
+ // the round-end split below and the final assistant_message
1353
+ // are always clean.
1354
+ const inline = splitInlineThink(roundContent);
1355
+ if (inline.thinking && inline.thinking !== roundInlineThinkingSeen) {
1356
+ roundInlineThinkingSeen = inline.thinking;
1357
+ roundReasoningChars += inline.thinking.length;
1358
+ yield {
1359
+ kind: 'thinking_delta',
1360
+ ts: ts(),
1361
+ engine: ENGINE,
1362
+ text: turnThinking ? `${turnThinking}\n\n${inline.thinking}` : inline.thinking,
1363
+ };
1364
+ }
1365
+ if (insideOpenThink(roundContent)) continue;
1366
+ const visibleRound = inline.content;
1367
+ // Scaffold guard AT THE STREAM. A confused model emits the
1368
+ // provider's tool-result template ("Use the results below to
1369
+ // formulate an answer…") as content and repeats it hundreds of
1370
+ // times. Cleaning only the final text (below) is too late — the
1371
+ // deltas already streamed the wall into the user's window live.
1372
+ // The moment the running content becomes scaffold, stop: discard
1373
+ // it, close the upstream stream so the model stops generating,
1374
+ // and let the forced no-tools finish (below) produce a clean
1375
+ // answer. The user sees at most one partial sentence, not 100.
1376
+ if (containsScaffold(visibleRound) || looksRepetitive(visibleRound)) {
1377
+ sawScaffoldLeak = true;
1378
+ roundContent = '';
1379
+ void Promise.resolve(chunkIter.return?.(undefined)).catch(() => {});
1380
+ break;
1381
+ }
1382
+ if (!visibleRound) continue;
1383
+ // Stream the running cumulative (existing rounds + this round so far).
1384
+ const runningCumulative = cumulative
1385
+ ? `${cumulative}\n\n${visibleRound}`
1386
+ : visibleRound;
1387
+ yield { kind: 'assistant_delta', ts: ts(), engine: ENGINE, text: runningCumulative };
1388
+ }
1389
+ if (delta?.tool_calls) {
1390
+ // tool_calls stream as fragments indexed by `index`. Accumulate
1391
+ // name and arguments-JSON across chunks.
1392
+ for (const tc of delta.tool_calls) {
1393
+ const idx = tc.index ?? 0;
1394
+ const slot =
1395
+ roundToolCalls.get(idx) ?? { id: '', name: '', argsJson: '' };
1396
+ if (tc.id && !slot.id) slot.id = tc.id;
1397
+ if (tc.function?.name && !slot.name) slot.name = tc.function.name;
1398
+ if (tc.function?.arguments) slot.argsJson += tc.function.arguments;
1399
+ roundToolCalls.set(idx, slot);
1400
+ }
1401
+ }
1402
+ if (choice?.finish_reason) finishReason = choice.finish_reason;
1403
+ if (chunk.usage) {
1404
+ const rawUsage = chunk.usage as {
1405
+ prompt_tokens_details?: { cached_tokens?: number };
1406
+ completion_tokens_details?: { reasoning_tokens?: number };
1407
+ };
1408
+ // Accumulate across rounds like tokens_in below — plain
1409
+ // assignment kept only the LAST round's cached count while
1410
+ // tokens_in summed all rounds, so the cached/uncached split
1411
+ // shown to the user was inconsistent on multi-round tool
1412
+ // turns (Juni-Audit 2026-06).
1413
+ const roundCached = rawUsage.prompt_tokens_details?.cached_tokens;
1414
+ if (roundCached !== undefined) {
1415
+ tokensInCached = (tokensInCached ?? 0) + roundCached;
1416
+ }
1417
+ // OpenAI returns reasoning_tokens inside completion_tokens_details
1418
+ // for reasoning models (gpt-5/o-series). It's already INCLUDED in
1419
+ // the top-level completion_tokens, so we surface it as a separate
1420
+ // counter for the UI's (N🧠) display without double-counting in
1421
+ // tokens_out.
1422
+ const reportedReasoning = rawUsage.completion_tokens_details?.reasoning_tokens;
1423
+ const reasoningEstimated = reportedReasoning == null && roundReasoningChars > 0;
1424
+ const reasoningTokens = reasoningEstimated
1425
+ ? Math.ceil(roundReasoningChars / 4)
1426
+ : (reportedReasoning ?? undefined);
1427
+ // Occupancy, not spend: the prompt of THIS request, replaced
1428
+ // each round rather than summed. The sum below is what the
1429
+ // turn cost; this is how full the window actually got.
1430
+ lastPromptTokens = chunk.usage.prompt_tokens ?? lastPromptTokens;
1431
+ lastCompletionTokens = chunk.usage.completion_tokens ?? lastCompletionTokens;
1432
+ // Calibrate: what did the provider count for what we sent?
1433
+ if (chunk.usage.prompt_tokens && estimateInFlight && estimateInFlight > 0) {
1434
+ tokenRatio = chunk.usage.prompt_tokens / estimateInFlight;
1435
+ }
1436
+ // Did the compaction that just ran actually clear the
1437
+ // threshold? Believing "we compacted, so it fits" is how a
1438
+ // session compacts every turn and still dies (Hermes checks
1439
+ // the same thing against the provider's real count).
1440
+ if (verifyCompaction && chunk.usage.prompt_tokens) {
1441
+ verifyCompaction = false;
1442
+ if (chunk.usage.prompt_tokens >= compactionTrigger) {
1443
+ logger.warn({
1444
+ msg: 'engine.compaction_ineffective',
1445
+ engine: ENGINE,
1446
+ agent,
1447
+ session,
1448
+ measured: chunk.usage.prompt_tokens,
1449
+ trigger: compactionTrigger,
1450
+ hint: 'compaction ran and the prompt is still above the trigger — the uncompacted tail is too big on its own',
1451
+ });
1452
+ }
1453
+ }
1454
+ const u = {
1455
+ tokens_in: chunk.usage.prompt_tokens ?? 0,
1456
+ tokens_out: chunk.usage.completion_tokens ?? 0,
1457
+ ...(reasoningTokens !== undefined
1458
+ ? { tokens_out_reasoning: reasoningTokens }
1459
+ : {}),
1460
+ ...(reasoningEstimated ? { tokens_out_reasoning_estimated: true } : {}),
1461
+ };
1462
+ // Accumulate across rounds for the final turn_end usage.
1463
+ totalUsage = totalUsage
1464
+ ? {
1465
+ tokens_in: totalUsage.tokens_in + u.tokens_in,
1466
+ tokens_out: totalUsage.tokens_out + u.tokens_out,
1467
+ ...(u.tokens_out_reasoning !== undefined ||
1468
+ totalUsage.tokens_out_reasoning !== undefined
1469
+ ? {
1470
+ tokens_out_reasoning:
1471
+ (totalUsage.tokens_out_reasoning ?? 0) +
1472
+ (u.tokens_out_reasoning ?? 0),
1473
+ }
1474
+ : {}),
1475
+ ...(u.tokens_out_reasoning_estimated || totalUsage.tokens_out_reasoning_estimated
1476
+ ? { tokens_out_reasoning_estimated: true }
1477
+ : {}),
1478
+ }
1479
+ : u;
1480
+ }
1481
+ }
1482
+
1483
+ // Streaming for this round is done — disarm the idle watchdog so
1484
+ // it doesn't count the upcoming tool-execution phase as "dead
1485
+ // backend, no chunks" and abort a healthy turn (a single
1486
+ // agent_ask / subagent_result wait_until_done can legitimately
1487
+ // run past the idle threshold). The next round re-arms at
1488
+ // round-top before the next create() call (Juni-Audit 2026-06).
1489
+ disarmIdleTimer();
1490
+
1491
+ // Inline think block (see the delta handler): move it out of the
1492
+ // content for good so neither the persisted assistant_message nor
1493
+ // a subagent `result` carries raw reasoning + a bare `</think>`.
1494
+ if (roundContent) {
1495
+ const inline = splitInlineThink(roundContent);
1496
+ if (inline.thinking) {
1497
+ logger.info({
1498
+ msg: 'engine.inline_think_split',
1499
+ engine: ENGINE,
1500
+ agent,
1501
+ session,
1502
+ thinkingChars: inline.thinking.length,
1503
+ contentChars: inline.content.length,
1504
+ });
1505
+ roundThinking = roundThinking ? `${roundThinking}\n\n${inline.thinking}` : inline.thinking;
1506
+ roundContent = inline.content;
1507
+ }
1508
+ }
1509
+ // Leading whitespace is never meaningful in an answer; DeepSeek V4
1510
+ // with reasoning off opens every reply with the blank lines of an
1511
+ // empty think block ("\n\n\n\n\n391", 2026-09-05).
1512
+ roundContent = roundContent.replace(/^\s+/, '');
1513
+ // Merge the round's content into the cumulative (separator only when
1514
+ // there's previous content AND new content).
1515
+ if (roundContent) {
1516
+ cumulative = cumulative ? `${cumulative}\n\n${roundContent}` : roundContent;
1517
+ }
1518
+ if (roundThinking) {
1519
+ turnThinking = turnThinking ? `${turnThinking}\n\n${roundThinking}` : roundThinking;
1520
+ roundThinking = '';
1521
+ }
1522
+
1523
+ // Also catch silent abort-close: if the stream ended without a
1524
+ // throw but the upstream signal (or watchdog) fired, treat as
1525
+ // user-cancel / wedge.
1526
+ if (effectiveSignal.aborted) throw new DOMException('Aborted', 'AbortError');
1527
+
1528
+ lastRoundHadTools = roundToolCalls.size > 0;
1529
+ if (roundToolCalls.size === 0) {
1530
+ // Nothing visible and nothing to run, but the model was
1531
+ // thinking: the output cap ended the response inside the
1532
+ // reasoning (DeepSeek on a builder task, 2026-09-23: seven
1533
+ // rounds of reading, then 8k tokens of planning and silence).
1534
+ // The stop reason cannot be trusted (routers rewrite it), so
1535
+ // the test is structural. Ending the turn here would present
1536
+ // the silence as the answer; a nudge lets it continue.
1537
+ if (!roundContent && roundReasoningChars > 0 && reasoningOnlyNudges < MAX_REASONING_ONLY_NUDGES) {
1538
+ reasoningOnlyNudges++;
1539
+ logger.warn({
1540
+ msg: 'engine.reasoning_only_round',
1541
+ engine: ENGINE,
1542
+ agent,
1543
+ session,
1544
+ round,
1545
+ attempt: reasoningOnlyNudges,
1546
+ reasoningChars: roundReasoningChars,
1547
+ finishReason,
1548
+ outputTokens: lastCompletionTokens,
1549
+ outputCap: resolvedModel.model.maxTokens,
1550
+ });
1551
+ loopMessages.push({
1552
+ role: 'user',
1553
+ content:
1554
+ '[somora] Your last response ended while you were still thinking: it contained no answer and no tool call ' +
1555
+ '(the output limit cut it off). Continue from where you were — keep the thinking short, then call the ' +
1556
+ 'next tool or write the answer.',
1557
+ });
1558
+ continue;
1559
+ }
1560
+ // No tools requested — model gave its final answer this round.
1561
+ break;
1562
+ }
1563
+
1564
+ // Persist the assistant turn (with tool_calls) to the chat history.
1565
+ // The OpenAI API requires the tool_call message before the tool
1566
+ // results, so we add both before the next round.
1567
+ const rawToolCalls = [...roundToolCalls.entries()]
1568
+ .sort(([a], [b]) => a - b)
1569
+ .map(([, c]) => ({
1570
+ id: c.id || `call-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
1571
+ type: 'function' as const,
1572
+ function: { name: c.name, arguments: c.argsJson || '{}' },
1573
+ }));
1574
+
1575
+ // Within-round dedup — see dedupeToolCalls at module top. Collapses
1576
+ // the weak-model "same call 77×" fan-out to one execution per
1577
+ // distinct call.
1578
+ const toolCallsForApi = dedupeToolCalls(rawToolCalls);
1579
+ if (toolCallsForApi.length < rawToolCalls.length) {
1580
+ logger.warn({
1581
+ msg: 'engine.tool_calls_deduped',
1582
+ engine: ENGINE,
1583
+ agent,
1584
+ session,
1585
+ round,
1586
+ emitted: rawToolCalls.length,
1587
+ executed: toolCallsForApi.length,
1588
+ });
1589
+ }
1590
+
1591
+ // Arguments are classified BEFORE the assistant message is built,
1592
+ // because a call whose arguments are not valid JSON must never go
1593
+ // back on the wire.
1594
+ //
1595
+ // 2026-09-10, spielberg/main: a call arrived cut off after 64
1596
+ // characters (`{"project_id": "…", "files": `). somora ran it
1597
+ // anyway, got a confusing "project_id is required", and then sent
1598
+ // the same fragment back in the next round. The backend parses
1599
+ // tool-call arguments while building the prompt, so it answered
1600
+ // 400 "Expecting value: line 1 column 65 (char 64)" — and every
1601
+ // further round of that turn failed the same way, because the
1602
+ // fragment sits in the running conversation. The turn was lost.
1603
+ //
1604
+ // Truncation like this is what an output limit hit mid-call looks
1605
+ // like, so the model is told exactly that and can retry smaller.
1606
+ // Two different faults, two different answers (Hermes Agent's
1607
+ // turn_tool_validation.py is the template here):
1608
+ //
1609
+ // cut off — the text stops mid-value. Retrying the same
1610
+ // request reproduces it, because the model writes
1611
+ // the same thing again and it dies at the same
1612
+ // place. Measured five times in one day, always
1613
+ // exactly where the big `files` value began.
1614
+ // malformed — complete but invalid JSON. That is the kind of
1615
+ // slip a second attempt usually does not repeat.
1616
+ //
1617
+ // Telling them apart by the provider's stop reason does NOT work:
1618
+ // routers rewrite it. vLLM overwrites finish_reason with
1619
+ // 'tool_calls' whenever a tool call was parsed, even when the
1620
+ // real reason was the output limit (measured on cerebro,
1621
+ // 2026-09-10). Hermes documents the same thing. So the test is
1622
+ // structural: a complete JSON value ends on its closing bracket.
1623
+ const calls = toolCallsForApi.map((call) => {
1624
+ const raw = call.function.arguments ?? '';
1625
+ try {
1626
+ return { call, args: JSON.parse(raw || '{}') as unknown, fault: null as null | 'cut_off' | 'malformed', why: '' };
1627
+ } catch (err) {
1628
+ const looksComplete = /[}\]]$/.test(raw.trimEnd());
1629
+ return {
1630
+ call,
1631
+ args: { _raw: raw } as unknown,
1632
+ fault: (looksComplete ? 'malformed' : 'cut_off') as 'cut_off' | 'malformed',
1633
+ why: (err as Error).message,
1634
+ };
1635
+ }
1636
+ });
1637
+ const badCalls = calls.filter((c) => c.fault !== null);
1638
+ if (badCalls.length > 0) {
1639
+ logger.warn({
1640
+ msg: 'engine.tool_args_unparseable',
1641
+ engine: ENGINE,
1642
+ agent,
1643
+ session,
1644
+ round,
1645
+ // Kept for forensics, not for the decision — see above.
1646
+ finishReason,
1647
+ outputTokens: lastCompletionTokens,
1648
+ outputCap: resolvedModel.model.maxTokens,
1649
+ calls: badCalls.map((c) => ({
1650
+ tool: c.call.function.name,
1651
+ fault: c.fault,
1652
+ chars: c.call.function.arguments.length,
1653
+ head: c.call.function.arguments.slice(0, 120),
1654
+ })),
1655
+ });
1656
+ }
1657
+
1658
+ // A malformed-but-complete call is worth one quiet second
1659
+ // attempt: same request, nothing appended, the model usually
1660
+ // gets it right. Only when this round did nothing else — text
1661
+ // already streamed, or another call about to run, would be
1662
+ // duplicated. A cut-off call is never retried this way; it comes
1663
+ // back identical.
1664
+ if (
1665
+ badCalls.length === calls.length &&
1666
+ calls.every((c) => c.fault === 'malformed') &&
1667
+ !roundContent &&
1668
+ argRerolls < MAX_ARG_REROLLS
1669
+ ) {
1670
+ argRerolls++;
1671
+ logger.info({
1672
+ msg: 'engine.tool_args_reroll',
1673
+ engine: ENGINE,
1674
+ agent,
1675
+ session,
1676
+ round,
1677
+ attempt: argRerolls,
1678
+ calls: calls.map((c) => c.call.function.name),
1679
+ });
1680
+ continue;
1681
+ }
1682
+
1683
+ // Doom-loop check BEFORE the assistant message is appended: a
1684
+ // stop here leaves the history consistent (the previous round's
1685
+ // tool results are the last messages), so the forced final
1686
+ // answer below can run.
1687
+ const roundSig = calls.map((c) => `${c.call.function.name}:${c.call.function.arguments}`).join('\n');
1688
+ repeatRounds = roundSig === lastRoundSig ? repeatRounds + 1 : 1;
1689
+ lastRoundSig = roundSig;
1690
+ if (repeatRounds >= 5) {
1691
+ hitDoomLoop = true;
1692
+ logger.warn({ msg: 'engine.doom_loop_stop', engine: ENGINE, agent, session, round, calls: calls.map((c) => c.call.function.name) });
1693
+ // Persisted like the notice, so the record shows WHY the turn
1694
+ // was cut short, not only that it was (hardening test 2026-09-23).
1695
+ yield {
1696
+ kind: 'engine_meta',
1697
+ ts: ts(),
1698
+ engine: ENGINE,
1699
+ itemType: 'doom_loop_stop',
1700
+ payload: {
1701
+ text: `Stopped after ${repeatRounds} identical tool rounds (${calls.map((c) => c.call.function.name).join(', ')}); the turn is forced to a final answer.`,
1702
+ round,
1703
+ repeats: repeatRounds,
1704
+ calls: calls.map((c) => c.call.function.name),
1705
+ },
1706
+ };
1707
+ break;
1708
+ }
1709
+
1710
+ loopMessages.push({
1711
+ role: 'assistant',
1712
+ // OpenAI accepts content=null when only tool_calls are present.
1713
+ content: roundContent || null,
1714
+ // A cut-off argument string is replaced by an empty object here.
1715
+ // The call itself stays: dropping it would leave a `tool` reply
1716
+ // without its call, which backends refuse just as hard.
1717
+ tool_calls: calls.map(({ call, fault }) =>
1718
+ fault ? { ...call, function: { ...call.function, arguments: '{}' } } : call,
1719
+ ),
1720
+ } as ChatMessage);
1721
+
1722
+ // Run each tool call, emit normalized events, append a `tool` message
1723
+ // per result for the next round.
1724
+ if (!tools) {
1725
+ // Should never happen — if there are no tools advertised the model
1726
+ // shouldn't request them. Bail with a clear error.
1727
+ throw new Error('model requested tool_calls but no tool registry was passed to the engine');
1728
+ }
1729
+ for (const { call, args: parsedArgs, fault, why } of calls) {
1730
+ yield {
1731
+ kind: 'tool_call',
1732
+ ts: ts(),
1733
+ engine: ENGINE,
1734
+ callId: call.id,
1735
+ tool: call.function.name,
1736
+ // The fragment is kept HERE, in the session record, because it
1737
+ // is the evidence of what went wrong. It never reaches the wire.
1738
+ input: parsedArgs,
1739
+ };
1740
+ if (fault) {
1741
+ // Not run: with half its arguments the call would either fail
1742
+ // in a confusing way or, worse, do something partial. The two
1743
+ // faults need different advice — "write less" is useless for
1744
+ // a typo, "retry" is useless for an output limit.
1745
+ const chars = call.function.arguments.length;
1746
+ const cap = resolvedModel.model.maxTokens;
1747
+ const spentItsAllowance = cap !== undefined && lastCompletionTokens !== undefined && lastCompletionTokens >= cap;
1748
+ const message =
1749
+ fault === 'cut_off'
1750
+ ? `Your call to ${call.function.name} arrived cut off after ${chars} characters — the arguments stop mid-value, so it was not run. ` +
1751
+ (spentItsAllowance
1752
+ ? `That round used its whole output allowance (${lastCompletionTokens} of ${cap} tokens). `
1753
+ : '') +
1754
+ 'Call it again with less in one go: fewer items, shorter values, or split across several calls.'
1755
+ : `Your call to ${call.function.name} was complete but its arguments are not valid JSON (${why}), so it was not run. ` +
1756
+ 'For a tool with no required parameters use {}. Call it again with valid JSON.';
1757
+ yield {
1758
+ kind: 'tool_result',
1759
+ ts: ts(),
1760
+ engine: ENGINE,
1761
+ callId: call.id,
1762
+ output: null,
1763
+ error: message,
1764
+ };
1765
+ loopMessages.push({
1766
+ role: 'tool',
1767
+ tool_call_id: call.id,
1768
+ content: message,
1769
+ } as ChatMessage);
1770
+ continue;
1771
+ }
1772
+ // Resolve the per-call timeout. Tools that declare themselves
1773
+ // long-running (subagent_result with wait_until_done, agent_ask,
1774
+ // exec, etc.) override the global cap via timeoutFromInput
1775
+ // (dynamic, per-call) or defaultTimeoutMs (static). maxTimeoutMs
1776
+ // hard-caps both so a malformed model-supplied timeout_ms can't
1777
+ // pin a slot indefinitely. Pattern adapted from OpenClaw's
1778
+ // waitForAgentRun — engine itself has no fixed cap, the caller
1779
+ // declares the budget.
1780
+ const toolDef = toolByName.get(call.function.name);
1781
+ const dynamicTimeout = toolDef?.timeoutFromInput?.(parsedArgs as never);
1782
+ const staticTimeout = toolDef?.defaultTimeoutMs;
1783
+ const hardCap = toolDef?.maxTimeoutMs;
1784
+ let toolTimeoutMs = dynamicTimeout ?? staticTimeout ?? globalToolTimeoutMs;
1785
+ if (hardCap !== undefined) toolTimeoutMs = Math.min(toolTimeoutMs, hardCap);
1786
+ // Race the tool invocation against timeout AND user abort.
1787
+ // Timeout → error-shaped result the model can retry against.
1788
+ // Abort → AbortError so the turn ends without waiting out the
1789
+ // full tool budget (stop-button felt broken during long exec).
1790
+ if (call.function.name === 'todo_write') lastTodoRound = round;
1791
+ const result = await raceToolInvoke(tools.invoke(call.function.name, parsedArgs), {
1792
+ timeoutMs: toolTimeoutMs,
1793
+ signal: effectiveSignal,
1794
+ timeoutResult: {
1795
+ ok: false as const,
1796
+ error:
1797
+ `tool '${call.function.name}' timed out after ${toolTimeoutMs}ms` +
1798
+ (dynamicTimeout !== undefined
1799
+ ? ` — call again with a higher timeout_ms if more time is needed`
1800
+ : ''),
1801
+ },
1802
+ });
1803
+ // Multimodal results (file_read polymorph on image/PDF) carry
1804
+ // contentBlocks instead of a JSON-able payload. OpenAI's API
1805
+ // accepts a content-array in tool messages with text and
1806
+ // image_url entries — local openai-compatible servers (omlx,
1807
+ // ollama) may reject this; the failure surfaces as an API
1808
+ // error visible to the operator. The model side: gpt-5+,
1809
+ // openrouter-claude, gemma-vision all accept it.
1810
+ const isMultimodalOk = result.ok && result.contentBlocks !== undefined;
1811
+ if (isMultimodalOk) {
1812
+ const blocks = result.contentBlocks!;
1813
+ const contentArray = blocks.map((b) => {
1814
+ if (b.type === 'image') {
1815
+ return {
1816
+ type: 'image_url' as const,
1817
+ image_url: {
1818
+ url: `data:${b.source.mediaType};base64,${b.source.data}`,
1819
+ },
1820
+ };
1821
+ }
1822
+ if (b.type === 'text') {
1823
+ return { type: 'text' as const, text: b.text };
1824
+ }
1825
+ return {
1826
+ type: 'text' as const,
1827
+ text: `[document content block (${b.source.mediaType}) — not delivered as inline content; use analyze_file]`,
1828
+ };
1829
+ });
1830
+ yield {
1831
+ kind: 'tool_result',
1832
+ ts: ts(),
1833
+ engine: ENGINE,
1834
+ callId: call.id,
1835
+ output: {
1836
+ multimodal: true,
1837
+ blocks: blocks.length,
1838
+ kinds: blocks.map((b) => b.type),
1839
+ },
1840
+ };
1841
+ loopMessages.push({
1842
+ role: 'tool',
1843
+ tool_call_id: call.id,
1844
+ // The OpenAI SDK type accepts string | ContentArray for tool
1845
+ // messages; ts narrows tightly here so we cast.
1846
+ content: contentArray,
1847
+ } as ChatMessage);
1848
+ } else {
1849
+ const outputText = result.ok
1850
+ ? JSON.stringify(result.data)
1851
+ : (result.error ?? 'tool failed');
1852
+ yield {
1853
+ kind: 'tool_result',
1854
+ ts: ts(),
1855
+ engine: ENGINE,
1856
+ callId: call.id,
1857
+ output: result.ok ? result.data : null,
1858
+ ...(result.ok ? {} : { error: result.error ?? 'tool failed' }),
1859
+ };
1860
+ loopMessages.push({
1861
+ role: 'tool',
1862
+ tool_call_id: call.id,
1863
+ content: outputText,
1864
+ } as ChatMessage);
1865
+ }
1866
+ }
1867
+
1868
+ // Total-tool-call budget. Bounds within-round fan-out that the
1869
+ // round cap can't see: after dedup a runaway still emits many
1870
+ // DISTINCT calls per round, and enough rounds of that runs up a
1871
+ // three-digit total. Once the budget is spent, stop and force a
1872
+ // clean final answer (below) instead of executing more.
1873
+ totalToolCalls += toolCallsForApi.length;
1874
+ if (repeatRounds === 3) {
1875
+ logger.info({ msg: 'engine.doom_loop_notice', engine: ENGINE, agent, session, round });
1876
+ // The nudge the model gets is also written to the session, so
1877
+ // a reviewer sees that the loop was noticed and what was said.
1878
+ yield {
1879
+ kind: 'engine_meta',
1880
+ ts: ts(),
1881
+ engine: ENGINE,
1882
+ itemType: 'doom_loop_notice',
1883
+ payload: {
1884
+ text: `Same tool call(s) three rounds in a row (${calls.map((c) => c.call.function.name).join(', ')}); the model was told to change course — two more identical rounds end the turn.`,
1885
+ round,
1886
+ calls: calls.map((c) => c.call.function.name),
1887
+ },
1888
+ };
1889
+ loopMessages.push({
1890
+ role: 'user',
1891
+ content:
1892
+ '[somora] You have now made the same tool call(s) with the same arguments three times in a row. ' +
1893
+ 'The result will not change. Do something different — a different query, another file, a different ' +
1894
+ 'command — or stop and explain what is blocking you. Two more identical rounds end this turn.',
1895
+ } as ChatMessage);
1896
+ }
1897
+ // Soft warning at ~75 % of either budget, once per turn: the
1898
+ // model cannot see the caps, so a "read N things and summarise"
1899
+ // task ran straight into the hard stop and then into the
1900
+ // force-summary path (three reports 2026-09-03/04, 1–2.5M-token
1901
+ // turns lost). A plain user-role notice is accepted by every
1902
+ // backend (a second `system` entry is not — see below) and
1903
+ // models reliably wrap up on it.
1904
+ const roundsLeft = maxRounds - round;
1905
+ const callsLeft = maxToolCallsPerTurn - totalToolCalls;
1906
+ if (
1907
+ !softWarned &&
1908
+ roundsLeft > 0 &&
1909
+ callsLeft > 0 &&
1910
+ (round >= Math.ceil(maxRounds * 0.75) ||
1911
+ totalToolCalls >= Math.ceil(maxToolCallsPerTurn * 0.75))
1912
+ ) {
1913
+ softWarned = true;
1914
+ logger.info({
1915
+ msg: 'engine.budget_soft_warn',
1916
+ engine: ENGINE,
1917
+ agent,
1918
+ session,
1919
+ round,
1920
+ maxRounds,
1921
+ totalToolCalls,
1922
+ maxToolCallsPerTurn,
1923
+ });
1924
+ loopMessages.push({
1925
+ role: 'user',
1926
+ content:
1927
+ `[somora] Budget notice: ${roundsLeft} tool-call round(s) and ${callsLeft} tool call(s) ` +
1928
+ 'remain in this turn before the loop is stopped. Wrap up now: write your final answer ' +
1929
+ 'from what you already have. Call a tool only if it is essential for the answer.',
1930
+ });
1931
+ }
1932
+ if (totalToolCalls >= maxToolCallsPerTurn) {
1933
+ hitToolBudget = true;
1934
+ logger.warn({
1935
+ msg: 'engine.tool_budget_cap',
1936
+ engine: ENGINE,
1937
+ agent,
1938
+ session,
1939
+ totalToolCalls,
1940
+ maxToolCallsPerTurn,
1941
+ hint: 'turn exceeded agentLoop.maxToolCallsPerTurn; forcing a final answer to stop a runaway.',
1942
+ });
1943
+ break;
1944
+ }
1945
+
1946
+ // Defensive: if we hit the round cap with tools still pending, log
1947
+ // and stop. The loop guard at the top will exit on the next check.
1948
+ if (round >= maxRounds) {
1949
+ logger.warn({
1950
+ msg: 'engine.tool_loop_cap',
1951
+ engine: ENGINE,
1952
+ agent,
1953
+ session,
1954
+ rounds: round,
1955
+ maxRounds,
1956
+ hint: 'model still wanted to call tools at agentLoop.maxRounds; stopping to prevent runaway. Increase via config.yaml agentLoop.maxRounds.',
1957
+ });
1958
+ }
1959
+ }
1960
+
1961
+ // Force a clean final answer whenever the loop exited at the round
1962
+ // cap while the model still wanted tools. One last call WITHOUT the
1963
+ // `tools` param: a model that is offered no tools cannot keep calling
1964
+ // them, and — crucially — cannot echo a provider's tool-scaffold
1965
+ // template as its "answer" (DeepSeek's "Use the results below to
1966
+ // formulate an answer…" leak, 2026-07-23). Any partial content from
1967
+ // the capped round is discarded first: at a runaway cap it is
1968
+ // unreliable (scaffold text / half-thoughts), and the model has every
1969
+ // tool result in loopMessages to summarise from cleanly.
1970
+ // Originally this only fired when cumulative was empty (2026-05-03
1971
+ // silent-"" bug); broadened so garbage content at the cap is replaced
1972
+ // too, and to also cover the tool-call-budget stop (2026-07-23).
1973
+ // Scaffold leak: the model echoed a provider tool-result template
1974
+ // (DeepSeek's "Use the results below to formulate an answer…") as its
1975
+ // reply instead of answering. Surfaces on a normal (tool-less) final
1976
+ // round, so the cap conditions above miss it — detect it on the
1977
+ // accumulated text and force the same clean no-tools finish.
1978
+ const scaffoldLeak =
1979
+ sawScaffoldLeak || containsScaffold(cumulative) || looksRepetitive(cumulative);
1980
+ const forcedByCap = (round >= maxRounds && lastRoundHadTools) || hitToolBudget || hitTimeCap || hitDoomLoop;
1981
+ if (forcedByCap || scaffoldLeak) {
1982
+ cumulative = '';
1983
+ forcedFinalReason = scaffoldLeak
1984
+ ? 'scaffold_leak'
1985
+ : hitDoomLoop
1986
+ ? 'doom_loop'
1987
+ : hitTimeCap
1988
+ ? 'time_cap'
1989
+ : hitToolBudget
1990
+ ? 'tool_budget'
1991
+ : 'round_cap';
1992
+ logger.warn({
1993
+ msg: 'engine.force_final_answer',
1994
+ engine: ENGINE,
1995
+ agent,
1996
+ session,
1997
+ rounds: round,
1998
+ reason: forcedFinalReason,
1999
+ });
2000
+ // The stop reason, spelled out: the old text always said
2001
+ // "maximum number of tool-call rounds (maxRounds)" even when the
2002
+ // TOOL-CALL BUDGET fired (2026-09-04: "cap of 50" reported on
2003
+ // sessions with 30 calls — a diagnosis detour).
2004
+ const capDescription = hitDoomLoop
2005
+ ? 'a loop: the same tool call(s) with the same arguments five times in a row'
2006
+ : hitTimeCap
2007
+ ? `the time cap of ${Math.round((maxTurnMs ?? 0) / 60_000)} minutes for this turn (agentLoop.maxTurnMs)`
2008
+ : hitToolBudget
2009
+ ? `the tool-call budget of ${maxToolCallsPerTurn} calls for this turn (agentLoop.maxToolCallsPerTurn)`
2010
+ : `the agent-loop cap of ${maxRounds} tool-call rounds for this turn (agentLoop.maxRounds)`;
2011
+ // USER role, not a trailing `system` entry: strict chat templates
2012
+ // (vLLM + Qwen 3.x behind LiteLLM) reject any system message
2013
+ // after index 0 with 400 "System message must be at the
2014
+ // beginning" — which killed exactly this rescue on every Qwen
2015
+ // backend since at least 2026-08-23 (six losses on 2026-09-03
2016
+ // alone). A user message is valid on every backend.
2017
+ loopMessages.push({
2018
+ role: 'user',
2019
+ content: scaffoldLeak
2020
+ ? '[somora] Your previous draft repeated an internal tool-result instruction ' +
2021
+ 'instead of answering. Answer the question directly NOW, ' +
2022
+ 'in your own words, using the tool results already gathered above. ' +
2023
+ 'Do not call any tools and do not repeat any instruction text.'
2024
+ : `[somora] You have reached ${capDescription}. Respond NOW without further ` +
2025
+ 'tool calls — summarize what you have learned from the tool results so far, ' +
2026
+ 'even partially. Do not call any tools.',
2027
+ } as ChatMessage);
2028
+ try {
2029
+ // Re-arm the idle watchdog: it was disarmed at the end of the
2030
+ // last streaming round (~line 785), and this forced finish is a
2031
+ // fresh model call that can wedge like any other. Without the
2032
+ // re-arm AND the abort-race below, a backend that holds the
2033
+ // connection open without emitting bytes would hang the turn
2034
+ // forever — a disarmed timer can't rescue it and some backends
2035
+ // ignore the fetch-level abort (Juni-Audit 2026-06).
2036
+ armIdleTimer();
2037
+ const summaryStream = await createChatStream({
2038
+ model: resolvedModel.modelId,
2039
+ messages: loopMessages,
2040
+ stream: true,
2041
+ stream_options: { include_usage: true },
2042
+ ...(resolvedModel.model.maxTokens
2043
+ ? { max_tokens: resolvedModel.model.maxTokens }
2044
+ : {}),
2045
+ // No tools, no tool_choice — pure text response.
2046
+ });
2047
+ const summaryIter = (
2048
+ summaryStream as AsyncIterable<
2049
+ typeof summaryStream extends AsyncIterable<infer C> ? C : never
2050
+ >
2051
+ )[Symbol.asyncIterator]();
2052
+ while (true) {
2053
+ let next: IteratorResult<
2054
+ typeof summaryStream extends AsyncIterable<infer C> ? C : never
2055
+ >;
2056
+ try {
2057
+ next = await nextOrAbort(summaryIter);
2058
+ } catch (raceErr) {
2059
+ // Fire-and-forget cleanup (do NOT await — a wedged native
2060
+ // generator never settles return() behind a pending next()).
2061
+ void Promise.resolve(summaryIter.return?.(undefined)).catch(() => {});
2062
+ throw raceErr;
2063
+ }
2064
+ if (next.done) break;
2065
+ const chunk = next.value;
2066
+ if (effectiveSignal.aborted) throw new DOMException('Aborted', 'AbortError');
2067
+ armIdleTimer();
2068
+ const choice = chunk.choices[0];
2069
+ const delta = choice?.delta;
2070
+ if (delta?.content && typeof delta.content === 'string') {
2071
+ cumulative += delta.content;
2072
+ // Same stream guard: a deeply-confused model can leak the
2073
+ // scaffold — or loop on any phrase — even when offered no
2074
+ // tools. Stop before it repeats; stripScaffold (below) cleans
2075
+ // the partial, and if nothing survives the honest fallback
2076
+ // message is emitted.
2077
+ if (containsScaffold(cumulative) || looksRepetitive(cumulative)) {
2078
+ void Promise.resolve(summaryIter.return?.(undefined)).catch(() => {});
2079
+ break;
2080
+ }
2081
+ if (insideOpenThink(cumulative)) continue;
2082
+ const visible = splitInlineThink(cumulative).content;
2083
+ if (!visible) continue;
2084
+ yield {
2085
+ kind: 'assistant_delta',
2086
+ ts: ts(),
2087
+ engine: ENGINE,
2088
+ text: visible,
2089
+ };
2090
+ }
2091
+ const usage = chunk.usage;
2092
+ if (usage) {
2093
+ const reasoningTokens = (
2094
+ usage as { completion_tokens_details?: { reasoning_tokens?: number } }
2095
+ ).completion_tokens_details?.reasoning_tokens;
2096
+ // Keep the cached counter consistent with the main loop's
2097
+ // accumulation (Juni-Audit 2026-06).
2098
+ const summaryCached = (
2099
+ usage as { prompt_tokens_details?: { cached_tokens?: number } }
2100
+ ).prompt_tokens_details?.cached_tokens;
2101
+ if (summaryCached !== undefined) {
2102
+ tokensInCached = (tokensInCached ?? 0) + summaryCached;
2103
+ }
2104
+ const prevIn = totalUsage?.tokens_in ?? 0;
2105
+ const prevOut = totalUsage?.tokens_out ?? 0;
2106
+ const prevReasoning = totalUsage?.tokens_out_reasoning;
2107
+ totalUsage = {
2108
+ tokens_in: prevIn + (usage.prompt_tokens ?? 0),
2109
+ tokens_out: prevOut + (usage.completion_tokens ?? 0),
2110
+ ...(reasoningTokens !== undefined || prevReasoning !== undefined
2111
+ ? {
2112
+ tokens_out_reasoning:
2113
+ (prevReasoning ?? 0) + (reasoningTokens ?? 0),
2114
+ }
2115
+ : {}),
2116
+ };
2117
+ }
2118
+ }
2119
+ disarmIdleTimer();
2120
+ {
2121
+ const inline = splitInlineThink(cumulative);
2122
+ if (inline.thinking) {
2123
+ turnThinking = turnThinking ? `${turnThinking}\n\n${inline.thinking}` : inline.thinking;
2124
+ cumulative = inline.content;
2125
+ }
2126
+ cumulative = cumulative.replace(/^\s+/, '');
2127
+ }
2128
+ } catch (err) {
2129
+ disarmIdleTimer();
2130
+ // A watchdog timeout or user-cancel during the forced finish
2131
+ // must propagate to the turn-level handler (which emits the
2132
+ // proper timeout/abort error + turn_end), exactly as an abort
2133
+ // in the main loop does — NOT be swallowed into the synthetic
2134
+ // "fallback also failed" message below.
2135
+ if (
2136
+ effectiveSignal.aborted ||
2137
+ (err instanceof Error && err.name === 'AbortError')
2138
+ ) {
2139
+ throw err;
2140
+ }
2141
+ logger.error({
2142
+ msg: 'engine.force_summary_failed',
2143
+ engine: ENGINE,
2144
+ agent,
2145
+ session,
2146
+ reason: scaffoldLeak ? 'scaffold_leak' : hitToolBudget ? 'tool_budget' : 'round_cap',
2147
+ rounds: round,
2148
+ totalToolCalls,
2149
+ err: (err as Error).message,
2150
+ });
2151
+ // Fallback: an honest marker PLUS a digest of what the turn
2152
+ // gathered, so the caller (user or parent agent) gets the
2153
+ // partial result instead of a pointer to a JSONL it cannot
2154
+ // read.
2155
+ const errText = (err as Error).message.replace(/\.+$/, '');
2156
+ degradedReason = 'force_summary_failed';
2157
+ cumulative =
2158
+ `[somora] Agent loop stopped at ${capDescription} without a final answer, and the ` +
2159
+ `forced summary call also failed: ${errText}. ` +
2160
+ `Partial results follow (session ${agent}/${session}).\n\n` +
2161
+ buildPartialDigest(loopMessages);
2162
+ }
2163
+ }
2164
+
2165
+ // Last-resort safety net: if the forced no-tools finish ITSELF still
2166
+ // leaked the scaffold template (a deeply-confused model can), strip
2167
+ // the offending lines rather than show them. If nothing meaningful
2168
+ // survives, fall back to an honest marker instead of empty text.
2169
+ if (cumulative && (containsScaffold(cumulative) || looksRepetitive(cumulative))) {
2170
+ const cleaned = containsScaffold(cumulative) ? stripScaffold(cumulative) : '';
2171
+ logger.warn({
2172
+ msg: 'engine.scaffold_stripped',
2173
+ engine: ENGINE,
2174
+ agent,
2175
+ session,
2176
+ before: cumulative.length,
2177
+ after: cleaned.length,
2178
+ });
2179
+ if (cleaned.length < 20 || looksRepetitive(cleaned)) degradedReason = 'scaffold_stripped';
2180
+ cumulative =
2181
+ cleaned.length >= 20 && !looksRepetitive(cleaned)
2182
+ ? cleaned
2183
+ : '[somora] The model could not produce a clean answer for this turn ' +
2184
+ '(it looped on repeated text). The tool results are in the session; ' +
2185
+ 'try rephrasing or a stronger model.';
2186
+ }
2187
+
2188
+ if (cumulative) {
2189
+ if (turnThinking) {
2190
+ yield { kind: 'thinking_message', ts: ts(), engine: ENGINE, text: turnThinking };
2191
+ turnThinking = '';
2192
+ }
2193
+ yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: cumulative };
2194
+ } else if (round >= maxRounds) {
2195
+ // Loop ended at the cap and the force-summary path didn't
2196
+ // populate cumulative either — synthesize a marker so the
2197
+ // caller doesn't get `result: ""` silently.
2198
+ degradedReason = 'round_cap_no_answer';
2199
+ cumulative =
2200
+ `[somora] Agent loop reached the cap of ${maxRounds} tool-call rounds ` +
2201
+ 'and produced no final message. Increase agentLoop.maxRounds in config.yaml or ' +
2202
+ 'pass maxRounds in spawn_subagent input if more rounds are needed.';
2203
+ if (turnThinking) {
2204
+ yield { kind: 'thinking_message', ts: ts(), engine: ENGINE, text: turnThinking };
2205
+ turnThinking = '';
2206
+ }
2207
+ yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: cumulative };
2208
+ }
2209
+
2210
+ logger.info({
2211
+ msg: 'engine.turn',
2212
+ engine: ENGINE,
2213
+ provider: resolvedModel.providerName,
2214
+ model: resolvedModel.modelId,
2215
+ agent,
2216
+ session,
2217
+ tokens_in: totalUsage?.tokens_in,
2218
+ tokens_in_cached: tokensInCached,
2219
+ context_tokens: lastPromptTokens,
2220
+ tokens_out: totalUsage?.tokens_out,
2221
+ toolRounds: round,
2222
+ });
2223
+
2224
+ yield {
2225
+ kind: 'turn_end',
2226
+ ts: ts(),
2227
+ engine: ENGINE,
2228
+ turnId,
2229
+ rounds: round,
2230
+ ...(forcedFinalReason ? { forced_final: forcedFinalReason } : {}),
2231
+ ...(degradedReason ? { degraded: { reason: degradedReason } } : {}),
2232
+ ...(totalUsage
2233
+ ? {
2234
+ usage: {
2235
+ ...totalUsage,
2236
+ ...(tokensInCached !== undefined ? { tokens_in_cached: tokensInCached } : {}),
2237
+ ...(lastPromptTokens !== undefined ? { context_tokens: lastPromptTokens } : {}),
2238
+ },
2239
+ }
2240
+ : {}),
2241
+ };
2242
+
2243
+ // Tag the session with the engine that owns it now (for future routing logic)
2244
+ // and hand the next turn what this one measured. Merge under the store's
2245
+ // lock — compaction and the turn-end write race otherwise.
2246
+ await metaStore.update(agent, session, (current) => {
2247
+ const next = { ...current } as OpenAiCompatibleMeta;
2248
+ next.engine = ENGINE;
2249
+ if (lastPromptTokens !== undefined) {
2250
+ next.contextTokens = { tokens: lastPromptTokens, model: resolvedModel.modelId, ts: ts() };
2251
+ next.providerOmitsUsage = false;
2252
+ } else {
2253
+ // No usage in the whole turn: this provider does not report it,
2254
+ // so future turns lean on the estimate with more headroom.
2255
+ next.providerOmitsUsage = true;
2256
+ }
2257
+ if (tokenRatio !== undefined && Number.isFinite(tokenRatio)) {
2258
+ next.tokenRatio = { ratio: tokenRatio, model: resolvedModel.modelId };
2259
+ }
2260
+ return next as never;
2261
+ });
2262
+ } catch (err) {
2263
+ if (watchdogFired) {
2264
+ const message = `openai-compatible backend timed out (${IDLE_TIMEOUT_MS / 1000}s idle, no chunks)`;
2265
+ logger.error({
2266
+ msg: 'engine.fail',
2267
+ engine: ENGINE,
2268
+ agent,
2269
+ session,
2270
+ err: 'idle watchdog timeout',
2271
+ idleMs: IDLE_TIMEOUT_MS,
2272
+ });
2273
+ yield { kind: 'error', ts: ts(), engine: ENGINE, message, providerError: true };
2274
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
2275
+ } else if (signal?.aborted) {
2276
+ logger.info({ msg: 'engine.aborted', engine: ENGINE, agent, session });
2277
+ const partial = cumulative
2278
+ ? `${cumulative}\n\n[somora] aborted by user`
2279
+ : '[somora] aborted by user';
2280
+ yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: partial };
2281
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
2282
+ } else if (isContextLengthError(err)) {
2283
+ // A refusal is the one moment the backend states its truth. Read
2284
+ // it before anything else: the window it really enforces, and how
2285
+ // big our prompt actually was. Hermes Agent adopts the reported
2286
+ // limit from here for the same reason — a configured window can
2287
+ // simply be wrong, and guessing again after every refusal is how
2288
+ // a session wedges.
2289
+ const limits = parseProviderLimits((err as Error).message);
2290
+ if (limits.promptTokens && estimateInFlight && estimateInFlight > 0) {
2291
+ tokenRatio = limits.promptTokens / estimateInFlight;
2292
+ }
2293
+ if (limits.contextWindow || limits.promptTokens) {
2294
+ logger.warn({
2295
+ msg: 'engine.context_limit_learned',
2296
+ engine: ENGINE,
2297
+ agent,
2298
+ session,
2299
+ model: resolvedModel.modelId,
2300
+ configuredWindow: resolvedModel.model.contextWindow,
2301
+ reportedWindow: limits.contextWindow,
2302
+ reportedPromptTokens: limits.promptTokens,
2303
+ ourEstimate: estimateInFlight,
2304
+ tokenRatio,
2305
+ ...(limits.contextWindow && limits.contextWindow < resolvedModel.model.contextWindow
2306
+ ? { hint: `config.yaml declares a larger window than ${resolvedModel.modelId} enforces — lower contextWindow to ${limits.contextWindow}` }
2307
+ : {}),
2308
+ });
2309
+ }
2310
+ // Remember it for the next turn even though this one is failing:
2311
+ // a rate limit or a crash must not throw the reading away.
2312
+ if (tokenRatio !== undefined && Number.isFinite(tokenRatio)) {
2313
+ await metaStore
2314
+ .update(agent, session, (current) => ({
2315
+ ...current,
2316
+ tokenRatio: { ratio: tokenRatio!, model: resolvedModel.modelId },
2317
+ ...(limits.promptTokens
2318
+ ? { contextTokens: { tokens: limits.promptTokens, model: resolvedModel.modelId, ts: ts() } }
2319
+ : {}),
2320
+ }))
2321
+ .catch(() => {
2322
+ /* a failed note must not replace the error the caller needs */
2323
+ });
2324
+ }
2325
+ if (!(roundsStarted <= 1 && !cumulative)) {
2326
+ // Mid-turn: tools have run, so the turn cannot be replayed.
2327
+ // The budget check with the corrected ratio catches this on the
2328
+ // next round; here the honest move is a clear ending.
2329
+ logger.error({
2330
+ msg: 'engine.fail',
2331
+ engine: ENGINE,
2332
+ agent,
2333
+ session,
2334
+ err: `context overflow after ${roundsStarted} round(s), no replay possible`,
2335
+ });
2336
+ yield {
2337
+ kind: 'error',
2338
+ ts: ts(),
2339
+ engine: ENGINE,
2340
+ message:
2341
+ `The conversation stopped fitting ${resolvedModel.modelId}'s context window during this turn` +
2342
+ (limits.promptTokens ? ` (the backend counted ${limits.promptTokens.toLocaleString('en-US')} input tokens)` : '') +
2343
+ '. The work done so far is in the session — send the next step as a new message, and somora will compact first.',
2344
+ };
2345
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
2346
+ return;
2347
+ }
2348
+ // Reactive compaction: the backend says the prompt doesn't fit,
2349
+ // whatever our estimate thought. Force a compaction down to one
2350
+ // intact pair and retry the turn ONCE. Only before anything was
2351
+ // streamed or any tool ran — a mid-turn retry would replay tool
2352
+ // calls. Second failure → clear message instead of a raw 400.
2353
+ const backendMessage = (err as Error).message;
2354
+ const alreadyRetried = CONTEXT_RETRIED.has(input);
2355
+ CONTEXT_RETRIED.add(input);
2356
+ logger.warn({
2357
+ msg: 'engine.context_overflow',
2358
+ engine: ENGINE,
2359
+ provider: resolvedModel.providerName,
2360
+ model: resolvedModel.modelId,
2361
+ agent,
2362
+ session,
2363
+ contextWindow: resolvedModel.model.contextWindow,
2364
+ estimatedTokens: estTokens,
2365
+ existingCompactions: compactions?.length ?? 0,
2366
+ backend: backendMessage.slice(0, 200),
2367
+ action: 'forcing compaction, retrying once',
2368
+ });
2369
+ let forced: Compaction | null = null;
2370
+ let forceErr: string | undefined;
2371
+ if (alreadyRetried) {
2372
+ forceErr = 'the prompt still does not fit after a forced compaction';
2373
+ } else {
2374
+ try {
2375
+ forced = await runCompaction({
2376
+ systemPrompt,
2377
+ history,
2378
+ resolvedModel,
2379
+ availableModels,
2380
+ compactions,
2381
+ config: {
2382
+ ...compactionConfig,
2383
+ safetyCushionPairs: Math.min(1, compactionConfig.safetyCushionPairs),
2384
+ },
2385
+ });
2386
+ } catch (cErr) {
2387
+ forceErr = String((cErr as Error)?.message ?? cErr);
2388
+ }
2389
+ }
2390
+ if (forced) {
2391
+ const freshMeta = (await metaStore.get(agent, session)) as OpenAiCompatibleMeta;
2392
+ const nextCompactions = [...(freshMeta.compactions ?? []), forced];
2393
+ await metaStore.set(agent, session, { ...freshMeta, compactions: nextCompactions });
2394
+ logger.info({
2395
+ msg: 'engine.compaction_done',
2396
+ engine: ENGINE,
2397
+ agent,
2398
+ session,
2399
+ reason: 'context_overflow',
2400
+ throughTs: forced.throughTs,
2401
+ tokensBefore: forced.tokensBefore,
2402
+ tokensAfter: forced.tokensAfter,
2403
+ });
2404
+ yield {
2405
+ kind: 'engine_meta',
2406
+ ts: ts(),
2407
+ engine: ENGINE,
2408
+ itemType: 'context_compacted',
2409
+ payload: {
2410
+ text:
2411
+ `history compacted for ${resolvedModel.modelId} (${resolvedModel.model.contextWindow.toLocaleString('en-US')}-token window) ` +
2412
+ `after the backend rejected the prompt — retrying`,
2413
+ reason: 'context_overflow',
2414
+ backend: backendMessage.slice(0, 300),
2415
+ tokensBefore: forced.tokensBefore,
2416
+ tokensAfter: forced.tokensAfter,
2417
+ },
2418
+ };
2419
+ disarmIdleTimer();
2420
+ if (signal) signal.removeEventListener('abort', onUpstreamAbort);
2421
+ // Re-run the whole turn against the compacted history. The
2422
+ // retry re-reads meta (compactions), rebuilds messages and
2423
+ // owns its own watchdog; its turn_start is dropped so the
2424
+ // consumer sees exactly one turn.
2425
+ for await (const ev of openAiCompatibleEngine.runTurn(input)) {
2426
+ if (ev.kind === 'turn_start') continue;
2427
+ yield ev;
2428
+ }
2429
+ return;
2430
+ }
2431
+ const why = alreadyRetried
2432
+ ? forceErr
2433
+ : forceErr
2434
+ ? `compaction failed: ${forceErr}`
2435
+ : 'nothing older could be compacted (the conversation is already down to its last exchange)';
2436
+ logger.error({
2437
+ msg: 'engine.fail',
2438
+ engine: ENGINE,
2439
+ agent,
2440
+ session,
2441
+ err: `context overflow, ${why}`,
2442
+ });
2443
+ yield {
2444
+ kind: 'error',
2445
+ ts: ts(),
2446
+ engine: ENGINE,
2447
+ message:
2448
+ `The conversation no longer fits ${resolvedModel.modelId}'s context window ` +
2449
+ `(${resolvedModel.model.contextWindow.toLocaleString('en-US')} tokens) and ${why}. ` +
2450
+ `Switch to a model with a larger window (/model) or start a new session (/reset). ` +
2451
+ `Backend: ${backendMessage.slice(0, 200)}`,
2452
+ };
2453
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
2454
+ } else {
2455
+ logger.error({ msg: 'engine.fail', engine: ENGINE, agent, session, err: String(err) });
2456
+ yield { kind: 'error', ts: ts(), engine: ENGINE, message: (err as Error).message, providerError: true };
2457
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
2458
+ }
2459
+ } finally {
2460
+ disarmIdleTimer();
2461
+ if (signal) signal.removeEventListener('abort', onUpstreamAbort);
2462
+ }
2463
+ },
2464
+ };