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,969 @@
1
+ // claude-cli engine: Anthropic via the local Claude Code binary
2
+ // (Subscription auth path). The provider config has no baseUrl/apiKey —
3
+ // the binary at ~/.local/bin/claude already holds the user's session.
4
+
5
+ import { existsSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { query, type CanUseTool, type SDKMessage, type SDKUserMessage } from '@anthropic-ai/claude-agent-sdk';
9
+ import {
10
+ MCP_SERVER_NAME,
11
+ MCP_TOOL_PREFIX,
12
+ somoraMcpProxyName,
13
+ somoraMcpProxySpawn,
14
+ somoraMemoryServerSpawn,
15
+ } from '../mcp/config.ts';
16
+ import { reconcileClaudeCredentials } from '../server/claude-credential-sync.ts';
17
+ import { logger } from '../server/logger.ts';
18
+ import type { NormalizedEvent } from '../types/events.ts';
19
+ import {
20
+ computeReplayDelta,
21
+ getLastSeenTs,
22
+ renderReplayPrefix,
23
+ withLastSeenTs,
24
+ type EngineLastSeen,
25
+ capReplayDelta,
26
+ } from './replay.ts';
27
+ import type { AgentEngine, TurnInput } from './types.ts';
28
+ import { claudeCliThinkingOptions } from './thinking-params.ts';
29
+ import { buildAnthropicUserContent } from '../multimodal/user-content.ts';
30
+
31
+ /**
32
+ * The SDK's prompt input for one turn. Streaming-input mode: the first
33
+ * user message goes out at once; the iterable then stays open so a
34
+ * steer message (src/server/steer-inbox.ts) can be pushed while the
35
+ * turn runs. The SDK answers EVERY user message on the input with a
36
+ * `result` of its own (verified 2026-09-24: two messages, two results),
37
+ * so the input is closed only once a result has arrived for the first
38
+ * message and for each steer that was pushed — closing it at the first
39
+ * result left a steer pushed moments earlier running on a closed
40
+ * stream, where every somora tool failed its permission request with
41
+ * "AbortError: Stream closed" (hans, 2026-09-24). No new steer is
42
+ * pushed after the first result; from then on a message becomes a
43
+ * normal turn (start-turn.ts).
44
+ */
45
+ interface SteerableInput {
46
+ iterable: AsyncIterable<SDKUserMessage>;
47
+ push: (msg: SDKUserMessage) => void;
48
+ close: () => void;
49
+ }
50
+
51
+ function createSteerableInput(first: SDKUserMessage): SteerableInput {
52
+ const queue: SDKUserMessage[] = [first];
53
+ let closed = false;
54
+ let notify: (() => void) | undefined;
55
+ const wake = (): void => {
56
+ const n = notify;
57
+ notify = undefined;
58
+ n?.();
59
+ };
60
+ return {
61
+ iterable: {
62
+ async *[Symbol.asyncIterator]() {
63
+ while (true) {
64
+ if (queue.length > 0) {
65
+ yield queue.shift()!;
66
+ continue;
67
+ }
68
+ if (closed) return;
69
+ await new Promise<void>((resolve) => {
70
+ notify = resolve;
71
+ });
72
+ }
73
+ },
74
+ },
75
+ push: (msg) => {
76
+ if (closed) return;
77
+ queue.push(msg);
78
+ wake();
79
+ },
80
+ close: () => {
81
+ closed = true;
82
+ wake();
83
+ },
84
+ };
85
+ }
86
+
87
+ const ENGINE = 'claude-cli';
88
+
89
+ /** The text of a tool_result block's content, whatever shape it has. */
90
+ function toolResultText(content: unknown): string {
91
+ if (typeof content === 'string') return content;
92
+ if (Array.isArray(content)) {
93
+ return content
94
+ .map((b) => (b && typeof b === 'object' && 'text' in b ? String((b as { text: unknown }).text) : ''))
95
+ .join(' ');
96
+ }
97
+ return '';
98
+ }
99
+ // Legacy sessions tagged with `engine: 'anthropic'` still resume cleanly:
100
+ // we now resume on `sdkSessionId` presence alone, regardless of the
101
+ // `engine` field, so no special-case is needed.
102
+
103
+ const KNOWN_ACCOUNT_TOOLS = [
104
+ 'mcp__claude_ai_Gmail__authenticate',
105
+ 'mcp__claude_ai_Gmail__complete_authentication',
106
+ 'mcp__claude_ai_Google_Calendar__authenticate',
107
+ 'mcp__claude_ai_Google_Calendar__complete_authentication',
108
+ 'mcp__claude_ai_Google_Drive__authenticate',
109
+ 'mcp__claude_ai_Google_Drive__complete_authentication',
110
+ ];
111
+
112
+ // Allow somora's own MCP tools through; deny everything else.
113
+ // Account-MCPs and built-ins (Bash/Edit/etc.) should never be invoked
114
+ // by a somora session — that's DECISION #23.
115
+ const somoraToolGate: CanUseTool = async (toolName, input) => {
116
+ // MCP_TOOL_PREFIX (`mcp__somora__`) is our own server; `mcp__somora-`
117
+ // covers the somora-<server> proxy children for external MCP servers
118
+ // (design §4.4) — all of them are our own MCP entries with an
119
+ // already-gated tool surface.
120
+ if (toolName.startsWith(MCP_TOOL_PREFIX) || toolName.startsWith('mcp__somora-')) {
121
+ return { behavior: 'allow', updatedInput: input };
122
+ }
123
+ return {
124
+ behavior: 'deny',
125
+ message: `Tool '${toolName}' is not allowed in this somora session.`,
126
+ };
127
+ };
128
+
129
+ let toolsLeakWarned = false;
130
+ let mcpLeakWarned = false;
131
+
132
+ function resolveClaudeBin(): string | undefined {
133
+ if (process.env.SOMORA_CLAUDE_BIN) return process.env.SOMORA_CLAUDE_BIN;
134
+ const localBin = join(homedir(), '.local', 'bin', 'claude');
135
+ if (existsSync(localBin)) return localBin;
136
+ return undefined;
137
+ }
138
+
139
+ const CLAUDE_BIN = resolveClaudeBin();
140
+
141
+ import type { Compaction } from '../compaction/index.ts';
142
+
143
+ interface ClaudeCliMeta {
144
+ engine?: string;
145
+ sdkSessionId?: string;
146
+ /** MCP server name the SDK session was recorded with. The session's
147
+ * transcript holds tool_use blocks under `mcp__<name>__*`; after a
148
+ * rename the SDK would offer the tools under the new name while the
149
+ * model keeps calling the old one. A mismatch (or absence, for
150
+ * sessions from before the field existed) restarts the SDK session
151
+ * with the full history replayed. */
152
+ mcpServerName?: string;
153
+ engineLastSeen?: EngineLastSeen;
154
+ compactions?: Compaction[];
155
+ }
156
+
157
+ export const claudeCliEngine: AgentEngine = {
158
+ name: ENGINE,
159
+
160
+ async *runTurn(input: TurnInput): AsyncIterable<NormalizedEvent> {
161
+ const {
162
+ agent,
163
+ session,
164
+ systemPrompt,
165
+ ephemeralContext,
166
+ userMessage,
167
+ history,
168
+ metaStore,
169
+ resolvedModel,
170
+ thinking,
171
+ fromAgent,
172
+ fromSession,
173
+ signal,
174
+ } = input;
175
+ if (resolvedModel.provider.engine !== ENGINE) {
176
+ throw new Error(`claude-cli engine called with non-matching provider engine: ${resolvedModel.provider.engine}`);
177
+ }
178
+ const meta = (await metaStore.get(agent, session)) as ClaudeCliMeta;
179
+
180
+ // Always resume our own SDK session if one exists — even if another
181
+ // engine was last active. The internal session knows every turn that
182
+ // _claude-cli_ ever made on this somora-session; the gap (turns made
183
+ // by other engines) is bridged via delta-replay below.
184
+ //
185
+ // EXCEPT after an MCP server rename (`somora-memory` → `somora`,
186
+ // 2026-09-03): the SDK session remembers tools under the old name.
187
+ // Drop only the SDK-side session and rebuild it from ts 0 with the
188
+ // compaction-aware history replay — same shape as codex's model-
189
+ // switch re-thread. The somora session (slug, JSONL, meta) stays.
190
+ const mcpRenamed = Boolean(meta.sdkSessionId) && meta.mcpServerName !== MCP_SERVER_NAME;
191
+ const resume = mcpRenamed ? undefined : meta.sdkSessionId;
192
+ if (mcpRenamed) {
193
+ logger.info({
194
+ msg: 'engine.mcp_rename_resession',
195
+ engine: ENGINE,
196
+ agent,
197
+ session,
198
+ recordedServer: meta.mcpServerName ?? null,
199
+ currentServer: MCP_SERVER_NAME,
200
+ droppedSdkSessionId: meta.sdkSessionId,
201
+ });
202
+ }
203
+ const lastSeenTs = mcpRenamed ? 0 : getLastSeenTs(meta, ENGINE);
204
+ const rawReplayDelta = computeReplayDelta(history, lastSeenTs, meta.compactions);
205
+ // A from-zero replay without a compaction on file would be the whole
206
+ // session — cap it to the recent tail (see capReplayDelta).
207
+ const replayDelta = mcpRenamed ? capReplayDelta(rawReplayDelta) : rawReplayDelta;
208
+ const replayPrefix = renderReplayPrefix(replayDelta);
209
+ // Memory recall (ephemeralContext, already wrapped in
210
+ // <memory-context>...</memory-context>) goes BEFORE the actual user
211
+ // text so the persistent system prompt can stay stable across
212
+ // turns — Anthropic's prompt-cache cache_control breakpoint on the
213
+ // system block then holds, instead of being invalidated every turn
214
+ // by a per-turn-changing system string. The replayPrefix sits
215
+ // ahead of memory because it's an even more "outer" frame
216
+ // (cross-engine catch-up summary).
217
+ //
218
+ // Order in the user-message string:
219
+ // [replay-prefix? ][ephemeral: A2A header? + memory-recall? ][actual user text]
220
+ // (the A2A header travels in ephemeralContext since 2026-09-13 —
221
+ // src/server/turn-framing.ts — so this adapter adds nothing)
222
+ //
223
+ // claude-agent-sdk has no multi-system-message escape so we can't
224
+ // do "second system message late" like openai-compatible — inline
225
+ // is the structurally correct choice for this engine.
226
+ const memoryBlock = ephemeralContext ? `${ephemeralContext}\n\n` : '';
227
+ const effectiveUserMessage = replayPrefix + memoryBlock + userMessage;
228
+ // Phase Y.B — when the user attached files to this turn, build the
229
+ // multimodal content array. Image/PDF blocks come first, the
230
+ // composed text block last (replay + memory + user text). Anthropic's
231
+ // MessageParam.content is polymorphic (string | ContentBlockParam[])
232
+ // so we just hand the SDK either form.
233
+ const userContent =
234
+ input.attachments && input.attachments.length > 0
235
+ ? buildAnthropicUserContent(effectiveUserMessage, input.attachments)
236
+ : effectiveUserMessage;
237
+
238
+ const turnId = `t-${Date.now()}`;
239
+ const ts = () => Date.now();
240
+
241
+ yield { kind: 'turn_start', ts: ts(), engine: ENGINE, turnId };
242
+ if (mcpRenamed) {
243
+ yield {
244
+ kind: 'engine_meta',
245
+ ts: ts(),
246
+ engine: ENGINE,
247
+ itemType: 'mcp_server_renamed',
248
+ payload: {
249
+ from: meta.mcpServerName ?? null,
250
+ to: MCP_SERVER_NAME,
251
+ text: `Claude session restarted because somora's MCP server was renamed (${meta.mcpServerName ?? 'somora-memory'} → ${MCP_SERVER_NAME}) — session history carried over.`,
252
+ },
253
+ };
254
+ }
255
+
256
+ let cumulative = '';
257
+ let finalText = '';
258
+ let sawToolUse = false;
259
+ let yieldedErrorEvent = false;
260
+ let lastSdkSessionId: string | undefined;
261
+ let usage: { tokens_in: number; tokens_out: number } | undefined;
262
+ /**
263
+ * Prompt size of the LAST API call the CLI made this turn — how full
264
+ * the context got. The `result` message sums every call of the turn,
265
+ * which on a tool-using turn is a multiple of the window (measured:
266
+ * 2.28M reported against a 1M model), so it cannot be shown as
267
+ * occupancy. Each `assistant` message carries the usage of its own
268
+ * call, and the last one is the answer to "how full was it".
269
+ */
270
+ let lastCallContextTokens: number | undefined;
271
+ let tokensInCachedClaude: number | undefined;
272
+
273
+ // Bridge somora's AbortSignal into the SDK's abortController option.
274
+ // The SDK exposes only AbortController (not AbortSignal), so mirror
275
+ // the upstream signal into a fresh controller. Hoisted out of the
276
+ // try-block so the finally can remove the listener regardless of
277
+ // where the throw came from.
278
+ const sdkAbortController = new AbortController();
279
+ const onUpstreamAbort = () => sdkAbortController.abort();
280
+ // Steering (see createSteerableInput): the open input stream, the
281
+ // letterbox poll, and records waiting to be yielded from the loop.
282
+ let steerInput: SteerableInput | undefined;
283
+ let steerPoll: ReturnType<typeof setInterval> | undefined;
284
+ // Messages handed to the SDK beyond the first, and results seen:
285
+ // the input closes when results === 1 + pushedSteers.
286
+ let pushedSteers = 0;
287
+ let resultsSeen = 0;
288
+ const pendingSteerEvents: NormalizedEvent[] = [];
289
+ if (signal) {
290
+ if (signal.aborted) sdkAbortController.abort();
291
+ else signal.addEventListener('abort', onUpstreamAbort, { once: true });
292
+ }
293
+
294
+ // Idle watchdog. Catches the "SDK iterator hangs forever because the
295
+ // underlying claude-cli child died" failure mode — the SDK's stdio
296
+ // peer sometimes doesn't propagate child exit, so `for await` just
297
+ // suspends, no error is thrown, no turn_end is ever yielded, and the
298
+ // session ends up with an orphan tool_call in JSONL (jarvis 2026-05-13).
299
+ // The watchdog is reset on every received event; if N seconds pass
300
+ // without any event, we abort the SDK to surface the failure loudly.
301
+ //
302
+ // Threshold comes from config.engineWatchdog.claudeCliIdleMs (default
303
+ // 300s). Subscription-hosted claude-cli is fast; any 5min silence is
304
+ // a dead child, not slow thinking. Operator can raise via config.yaml.
305
+ const IDLE_TIMEOUT_MS = input.idleTimeoutMs ?? 300_000;
306
+ // While a tool_use is outstanding the SDK stream legitimately goes
307
+ // quiet for the tool's whole duration (it runs in the MCP child), so
308
+ // relax the watchdog to the MCP tool timeout — a healthy long tool
309
+ // (agent_ask, subagent_result wait_until_done) isn't cut off, while a
310
+ // truly dead child is still caught at the tool-timeout horizon
311
+ // (Juni-Audit 2026-06). Falls back to the normal idle threshold when
312
+ // unset, or whichever is larger so it never shortens the window.
313
+ const TOOL_IDLE_TIMEOUT_MS = Math.max(input.toolIdleTimeoutMs ?? 0, IDLE_TIMEOUT_MS);
314
+ let pendingToolCalls = 0;
315
+ let watchdogFired = false;
316
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
317
+ const armIdleTimer = () => {
318
+ if (idleTimer) clearTimeout(idleTimer);
319
+ const threshold = pendingToolCalls > 0 ? TOOL_IDLE_TIMEOUT_MS : IDLE_TIMEOUT_MS;
320
+ idleTimer = setTimeout(() => {
321
+ watchdogFired = true;
322
+ logger.error({
323
+ msg: 'engine.watchdog_idle_timeout',
324
+ engine: ENGINE,
325
+ agent,
326
+ session,
327
+ idleMs: threshold,
328
+ pendingToolCalls,
329
+ hint: 'no SDK events received — likely underlying claude-cli child died silently after tool_use; aborting to surface as error',
330
+ });
331
+ sdkAbortController.abort();
332
+ }, threshold);
333
+ };
334
+ const disarmIdleTimer = () => {
335
+ if (idleTimer) {
336
+ clearTimeout(idleTimer);
337
+ idleTimer = undefined;
338
+ }
339
+ };
340
+
341
+ try {
342
+ logger.info({
343
+ msg: 'engine.replay',
344
+ engine: ENGINE,
345
+ agent,
346
+ session,
347
+ lastSeenTs,
348
+ replayPairs: replayDelta.pairs.length,
349
+ replaySummary: Boolean(replayDelta.summary),
350
+ resumeSdkSessionId: Boolean(resume),
351
+ });
352
+ // systemPrompt stays STABLE across turns now — memory landed in
353
+ // the user-message above. Anthropic's prompt-cache marks the
354
+ // system block with cache_control by default; keeping the string
355
+ // identical across turns means we hit the cache for system+tools
356
+ // every turn after the first, saving real tokens (cache reads
357
+ // are ~10% of fresh-input cost).
358
+ const systemPromptForTurn = systemPrompt;
359
+
360
+ // Map somora's cross-engine thinking knob to the Claude Agent SDK's
361
+ // thinking/effort surface via shared helper. Helper guards on the
362
+ // model's 'reasoning' capability — otherwise the user's setting is
363
+ // dormant and the header reflects that.
364
+ const thinkingOptions = claudeCliThinkingOptions(
365
+ thinking,
366
+ resolvedModel.model,
367
+ );
368
+
369
+ // Pre-turn credential reconcile — the subprocess spawned below
370
+ // reads .credentials.json fresh, so syncing here guarantees every
371
+ // turn starts on the newest OAuth chain even if the watcher's
372
+ // debounce hasn't fired yet. Two ~500-byte reads when healthy;
373
+ // the sync module logs if it actually had to heal.
374
+ reconcileClaudeCredentials();
375
+
376
+ steerInput = createSteerableInput({
377
+ type: 'user',
378
+ parent_tool_use_id: null,
379
+ message: { role: 'user', content: userContent },
380
+ });
381
+ // Steering: poll the session's letterbox and push what arrives as
382
+ // further user messages on the open input stream. The SDK hands
383
+ // them to the model at its next step; the record for the session
384
+ // file is yielded from the main loop (pendingSteerEvents).
385
+ if (input.steer) {
386
+ const steer = input.steer;
387
+ const target = steerInput;
388
+ steerPoll = setInterval(() => {
389
+ const msgs = steer.drain();
390
+ if (msgs.length === 0) return;
391
+ for (const m of msgs) {
392
+ target.push({
393
+ type: 'user',
394
+ parent_tool_use_id: null,
395
+ message: { role: 'user', content: steer.frame(m) },
396
+ });
397
+ pushedSteers += 1;
398
+ }
399
+ pendingSteerEvents.push({ kind: 'steer_applied', ts: Date.now(), engine: ENGINE, messages: msgs });
400
+ }, 300);
401
+ steerPoll.unref?.();
402
+ }
403
+ const stream = query({
404
+ prompt: steerInput.iterable,
405
+ options: {
406
+ model: resolvedModel.modelId,
407
+ systemPrompt: systemPromptForTurn,
408
+ settingSources: [],
409
+ // claude-code 2.1.142+ surfaces MCP tools to the model only
410
+ // when the meta-tool `ToolSearch` is among the enabled
411
+ // built-ins — the SDK uses ToolSearch as the discovery
412
+ // mechanism for any MCP server with > a few tools. With
413
+ // `tools: []` (which we used pre-2026-05-16) MCP tools
414
+ // register inside the SDK but never reach the API request,
415
+ // so the model sees nothing. Whitelisting just `ToolSearch`
416
+ // restores tool visibility without re-enabling the
417
+ // Bash/Edit/Read/etc built-ins that DECISION #23 keeps off.
418
+ // See https://github.com/anthropics/claude-code/issues/38245
419
+ tools: ['ToolSearch'],
420
+ disallowedTools: KNOWN_ACCOUNT_TOOLS,
421
+ mcpServers: {
422
+ [MCP_SERVER_NAME]: somoraMemoryServerSpawn({
423
+ agent,
424
+ session,
425
+ subagentDepth: input.subagentDepth,
426
+ activeModelRef: `${resolvedModel.providerName}/${resolvedModel.modelId}`,
427
+ }),
428
+ // One proxy child per external MCP server (design §4.4):
429
+ // serves the hub's catalog snapshot, forwards calls to the
430
+ // main server. Model-visible names: mcp__somora-<name>__*.
431
+ ...Object.fromEntries(
432
+ (input.externalMcpServers ?? []).map((srv) => [
433
+ somoraMcpProxyName(srv.name),
434
+ somoraMcpProxySpawn({ server: srv.name, agent }),
435
+ ]),
436
+ ),
437
+ },
438
+ canUseTool: somoraToolGate,
439
+ // Only the MCP servers passed above exist for this session —
440
+ // ignores ~/.claude.json, project .mcp.json, plugins and the
441
+ // claude.ai account connectors (Gmail/Calendar/Drive). Before
442
+ // this (SDK 0.3.259 re-audit, 2026-09-03) those connectors
443
+ // showed up in the init message as "needs-auth" AND were
444
+ // mentioned to the model in its system prompt; the deny-list
445
+ // in KNOWN_ACCOUNT_TOOLS only kept their tools uncallable. Now
446
+ // they never reach the session; the deny-list stays as the
447
+ // second layer for whatever a future SDK adds.
448
+ strictMcpConfig: true,
449
+ abortController: sdkAbortController,
450
+ // Policy-layer settings: turn off Claude Code's auto-memory so the
451
+ // CLI doesn't inject ~/.claude/projects/<cwd>/memory/* into the
452
+ // system prompt. Without this, somora agents inherit Claude Code's
453
+ // own auto-memory for the cwd of the somora-server process — a
454
+ // privacy leak (e.g. another somora agent like another agent could read
455
+ // notes that belong to a Claude Code session in the same project
456
+ // dir). settingSources:[] alone does NOT cover this — auto-memory
457
+ // is loaded independently of settings.json files.
458
+ managedSettings: { autoMemoryEnabled: false },
459
+ includePartialMessages: true,
460
+ ...thinkingOptions,
461
+ ...(CLAUDE_BIN ? { pathToClaudeCodeExecutable: CLAUDE_BIN } : {}),
462
+ ...(resume ? { resume } : {}),
463
+ },
464
+ });
465
+
466
+ // When includePartialMessages is on, text arrives via stream_event /
467
+ // content_block_delta tokens. The trailing 'assistant' message then
468
+ // contains the same text again — we skip its text blocks to avoid
469
+ // double-emitting. Tool-use blocks still come from the assistant
470
+ // message because they're not streamed as deltas.
471
+ let receivedTextViaStream = false;
472
+ // Reasoning text. Streams as thinking_delta (content_block_delta
473
+ // type thinking_delta), falls back to the assistant message's
474
+ // thinking blocks when nothing streamed. Adaptive-thinking models
475
+ // may return summarised or redacted thinking — redacted blocks
476
+ // carry no text and are shown as a placeholder once.
477
+ let thinkingCumulative = '';
478
+ let receivedThinkingViaStream = false;
479
+ let sawRedactedThinking = false;
480
+ // A thinking block that carried no text at all: on adaptive-thinking
481
+ // models (Fable, Opus 4.7) the API streams only pings for the
482
+ // thinking phase and the block arrives empty — the model did think,
483
+ // the provider just does not disclose it. Shown as a placeholder.
484
+ let sawEmptyThinkingBlock = false;
485
+
486
+ // Manual iteration with abort-race instead of `for await (... of
487
+ // stream)`. The SDK's iterator sits on top of an stdio pipe to
488
+ // the claude-cli child; if the child dies silently the pipe
489
+ // stays half-open and the SDK's internal `read()` await never
490
+ // resolves. Calling `sdkAbortController.abort()` from the
491
+ // watchdog does NOT unblock that read on every Node/SDK version
492
+ // — observed on subscription-hosted claude-cli on linux: watchdog
493
+ // fires, logs "aborting", but the for-await loop sits there
494
+ // forever, the catch never runs, no error/turn_end is yielded,
495
+ // lock+queue stay held until server restart. Reproduced on
496
+ // 2026-05-16 morning (naxon/lisa).
497
+ //
498
+ // Fix: race each iter.next() against the abort signal ourselves.
499
+ // When the watchdog (or upstream user-abort) fires, the race
500
+ // rejects synchronously and the catch below sees `watchdogFired`
501
+ // or `signal.aborted` and emits proper terminal events.
502
+ //
503
+ // Verified independently on 2026-05-16 afternoon: when MCP-tools
504
+ // registration broke (Anthropic regression in 2.1.142+), we
505
+ // suspected this race was the cause. Reverted to plain for-await,
506
+ // bug remained. Re-added — confirmed innocent of the MCP issue
507
+ // (which was about `tools: []` missing ToolSearch).
508
+ const iter = stream[Symbol.asyncIterator]();
509
+ armIdleTimer();
510
+ while (true) {
511
+ let next: IteratorResult<SDKMessage>;
512
+ try {
513
+ next = await new Promise<IteratorResult<SDKMessage>>((resolve, reject) => {
514
+ if (sdkAbortController.signal.aborted) {
515
+ reject(new Error('claude-cli iterator aborted (watchdog or upstream)'));
516
+ return;
517
+ }
518
+ const onAbort = (): void => {
519
+ reject(new Error('claude-cli iterator aborted (watchdog or upstream)'));
520
+ };
521
+ sdkAbortController.signal.addEventListener('abort', onAbort, { once: true });
522
+ iter.next().then(
523
+ (r: IteratorResult<SDKMessage>) => {
524
+ sdkAbortController.signal.removeEventListener('abort', onAbort);
525
+ resolve(r);
526
+ },
527
+ (err: unknown) => {
528
+ sdkAbortController.signal.removeEventListener('abort', onAbort);
529
+ reject(err instanceof Error ? err : new Error(String(err)));
530
+ },
531
+ );
532
+ });
533
+ } catch (err) {
534
+ // Best-effort cleanup — fire-and-forget, do NOT await. On a
535
+ // wedged native async generator, return() queues behind the
536
+ // never-settling next() and never resolves, so awaiting it
537
+ // re-hangs the turn in exactly the stuck-pipe case this race
538
+ // exists to escape (Juni-Audit 2026-06). Detach it and surface
539
+ // the error immediately.
540
+ void Promise.resolve(iter.return?.(undefined)).catch(() => {});
541
+ throw err;
542
+ }
543
+ if (next.done) break;
544
+ const msg = next.value;
545
+ armIdleTimer();
546
+ while (pendingSteerEvents.length > 0) yield pendingSteerEvents.shift()!;
547
+ if ('session_id' in msg && typeof msg.session_id === 'string') {
548
+ lastSdkSessionId = msg.session_id;
549
+ }
550
+
551
+ if (msg.type === 'system' && msg.subtype === 'init') {
552
+ logger.info({
553
+ msg: 'engine.init',
554
+ engine: ENGINE,
555
+ provider: resolvedModel.providerName,
556
+ model: resolvedModel.modelId,
557
+ apiKeySource: msg.apiKeySource,
558
+ sessionId: msg.session_id,
559
+ resumed: Boolean(resume),
560
+ tools: msg.tools,
561
+ mcpServers: msg.mcp_servers,
562
+ });
563
+ // Strip our own somora tools/server before checking for
564
+ // leaks — they're expected and add intentional surface. Proxy
565
+ // children for external MCP servers register as
566
+ // somora-<name>, so `mcp__somora-` covers the proxies.
567
+ const unexpectedTools = msg.tools.filter(
568
+ (t: string) => !t.startsWith(MCP_TOOL_PREFIX) && !t.startsWith('mcp__somora-'),
569
+ );
570
+ if (unexpectedTools.length > 0 && !toolsLeakWarned) {
571
+ logger.warn({
572
+ msg: 'engine.tools_leaked',
573
+ engine: ENGINE,
574
+ tools: unexpectedTools,
575
+ hint: 'Tools reached Claude despite disallowedTools/mcpServers/canUseTool. Update KNOWN_ACCOUNT_TOOLS in claude-cli.ts. (Logged once per server lifetime.)',
576
+ });
577
+ toolsLeakWarned = true;
578
+ }
579
+ const expectedServers = new Set([
580
+ MCP_SERVER_NAME,
581
+ ...(input.externalMcpServers ?? []).map((srv) => somoraMcpProxyName(srv.name)),
582
+ ]);
583
+ const unexpectedServers = msg.mcp_servers.filter(
584
+ (s) => !expectedServers.has(s.name),
585
+ );
586
+ if (unexpectedServers.length > 0 && !mcpLeakWarned) {
587
+ const summary = unexpectedServers.map((s) => `${s.name}(${s.status})`).join(', ');
588
+ logger.warn({
589
+ msg: 'engine.mcp_servers_leaked',
590
+ engine: ENGINE,
591
+ servers: summary,
592
+ count: unexpectedServers.length,
593
+ hint: 'Account-MCPs sichtbar im Init-Header, aber inert (tools=[]). Einmal pro Server-Lifetime.',
594
+ });
595
+ mcpLeakWarned = true;
596
+ }
597
+ } else if (msg.type === 'stream_event') {
598
+ const ev = msg.event;
599
+ if (ev.type === 'content_block_delta' && ev.delta.type === 'text_delta') {
600
+ cumulative += ev.delta.text;
601
+ receivedTextViaStream = true;
602
+ yield { kind: 'assistant_delta', ts: ts(), engine: ENGINE, text: cumulative };
603
+ } else if (ev.type === 'content_block_delta' && ev.delta.type === 'thinking_delta') {
604
+ const t = (ev.delta as { thinking?: unknown }).thinking;
605
+ if (typeof t === 'string' && t.length > 0) {
606
+ thinkingCumulative += t;
607
+ receivedThinkingViaStream = true;
608
+ yield { kind: 'thinking_delta', ts: ts(), engine: ENGINE, text: thinkingCumulative };
609
+ }
610
+ }
611
+ } else if (msg.type === 'assistant') {
612
+ const au = (msg.message as unknown as { usage?: { input_tokens?: number; cache_read_input_tokens?: number | null; cache_creation_input_tokens?: number | null } }).usage;
613
+ if (au) {
614
+ lastCallContextTokens =
615
+ (au.input_tokens ?? 0) + (au.cache_read_input_tokens ?? 0) + (au.cache_creation_input_tokens ?? 0);
616
+ }
617
+ for (const block of msg.message.content) {
618
+ if (block.type === 'thinking' && !receivedThinkingViaStream) {
619
+ const t = (block as { thinking?: unknown }).thinking;
620
+ if (typeof t === 'string' && t.length > 0) {
621
+ thinkingCumulative += (thinkingCumulative ? '\n\n' : '') + t;
622
+ yield { kind: 'thinking_delta', ts: ts(), engine: ENGINE, text: thinkingCumulative };
623
+ } else {
624
+ sawEmptyThinkingBlock = true;
625
+ }
626
+ } else if (block.type === 'redacted_thinking') {
627
+ sawRedactedThinking = true;
628
+ } else if (block.type === 'text' && !receivedTextViaStream) {
629
+ cumulative += block.text;
630
+ yield { kind: 'assistant_delta', ts: ts(), engine: ENGINE, text: cumulative };
631
+ } else if (block.type === 'tool_use') {
632
+ // A tool is now running in the MCP child — relax the
633
+ // watchdog (re-arm with the tool threshold) so a legit
634
+ // long tool isn't killed mid-run (Juni-Audit 2026-06).
635
+ pendingToolCalls++;
636
+ sawToolUse = true;
637
+ armIdleTimer();
638
+ yield {
639
+ kind: 'tool_call',
640
+ ts: ts(),
641
+ engine: ENGINE,
642
+ callId: block.id,
643
+ tool: block.name,
644
+ input: block.input,
645
+ };
646
+ }
647
+ }
648
+ } else if (msg.type === 'user') {
649
+ for (const block of msg.message.content) {
650
+ if (typeof block === 'object' && 'type' in block && block.type === 'tool_result') {
651
+ // Tool finished — drop back toward the normal idle threshold
652
+ // once no tools are outstanding (re-armed below at loop top).
653
+ if (pendingToolCalls > 0) pendingToolCalls--;
654
+ // A permission request the SDK could not deliver (the
655
+ // input stream was closed under the turn) surfaces only
656
+ // as the tool's error text — make it visible in the log.
657
+ if (block.is_error && /Tool permission request failed/i.test(toolResultText(block.content))) {
658
+ logger.warn({
659
+ msg: 'engine.permission_request_failed',
660
+ engine: ENGINE,
661
+ agent,
662
+ session,
663
+ turnId,
664
+ callId: String(block.tool_use_id),
665
+ detail: toolResultText(block.content).slice(0, 200),
666
+ });
667
+ }
668
+ yield {
669
+ kind: 'tool_result',
670
+ ts: ts(),
671
+ engine: ENGINE,
672
+ callId: String(block.tool_use_id),
673
+ output: block.content,
674
+ ...(block.is_error ? { error: 'tool error' } : {}),
675
+ };
676
+ }
677
+ }
678
+ } else if (msg.type === 'result') {
679
+ // One result per user message on the input. No further steer
680
+ // is pushed from here on (a message that arrives now becomes
681
+ // a normal turn, start-turn.ts); the input closes — so the
682
+ // SDK child exits — once every pushed steer has its result.
683
+ // Closing earlier left the steer's leg without a control
684
+ // channel: every tool permission request failed (hans,
685
+ // 2026-09-24). Should a result never come, the idle timer
686
+ // below ends the turn as for any silent child.
687
+ resultsSeen += 1;
688
+ if (steerPoll) {
689
+ clearInterval(steerPoll);
690
+ steerPoll = undefined;
691
+ }
692
+ if (resultsSeen >= 1 + pushedSteers) {
693
+ steerInput?.close();
694
+ } else {
695
+ logger.info({
696
+ msg: 'engine.steer_leg_pending',
697
+ engine: ENGINE,
698
+ agent,
699
+ session,
700
+ turnId,
701
+ results: resultsSeen,
702
+ pushed_steers: pushedSteers,
703
+ });
704
+ }
705
+ if (msg.subtype === 'success') {
706
+ // `msg.result` from claude-agent-sdk only carries the final
707
+ // assistant text block — for multi-block turns that
708
+ // intersperse `[text A, tool_use, tool_result, text B]`,
709
+ // it equals just "B" and drops "A" on the floor. Sourcing
710
+ // finalText from there made the chat:final event clobber
711
+ // the streaming bubble to the post-tool text only, so the
712
+ // web client locked in with text-A erased (luca 2026-05-12
713
+ // bug report). `cumulative` is the running total of every
714
+ // text_delta we saw across the whole turn, so it always
715
+ // contains every text block in order — use it as the source
716
+ // of truth, and fall back to `msg.result` only when no
717
+ // streaming happened (defensive — shouldn't trigger in
718
+ // practice since claude-agent-sdk always streams).
719
+ if (!thinkingCumulative && (sawRedactedThinking || sawEmptyThinkingBlock)) {
720
+ thinkingCumulative = sawRedactedThinking
721
+ ? '(thinking redacted by the provider)'
722
+ : '(the model thought, but the provider does not disclose the thinking text for this model)';
723
+ }
724
+ if (thinkingCumulative) {
725
+ yield { kind: 'thinking_message', ts: ts(), engine: ENGINE, text: thinkingCumulative };
726
+ thinkingCumulative = '';
727
+ }
728
+ finalText = cumulative || msg.result;
729
+ // Anthropic returns input_tokens (uncached new) separate from
730
+ // cache_read_input_tokens and cache_creation_input_tokens.
731
+ // For somora's display we want TOTAL context size used this
732
+ // turn so the X/contextWindow ratio is honest and comparable
733
+ // across engines (codex-cli/openai-compatible already report
734
+ // totals in their `input_tokens`/`prompt_tokens`).
735
+ const u = msg.usage as
736
+ | {
737
+ input_tokens?: number;
738
+ output_tokens?: number;
739
+ cache_read_input_tokens?: number;
740
+ cache_creation_input_tokens?: number;
741
+ }
742
+ | undefined;
743
+ const newIn = u?.input_tokens ?? 0;
744
+ const cacheRead = u?.cache_read_input_tokens ?? 0;
745
+ const cacheCreate = u?.cache_creation_input_tokens ?? 0;
746
+ // For the cached-token display: cache_read is "served from
747
+ // cache this turn" — that's what we want to surface as
748
+ // tokens_in_cached. cache_creation is uncached (new content
749
+ // added to cache); we lump it into the "uncached / new"
750
+ // portion implicit in tokens_in - tokens_in_cached.
751
+ usage = {
752
+ tokens_in: newIn + cacheRead + cacheCreate,
753
+ tokens_out: u?.output_tokens ?? 0,
754
+ };
755
+ tokensInCachedClaude = cacheRead;
756
+ logger.info({
757
+ msg: 'engine.turn',
758
+ engine: ENGINE,
759
+ provider: resolvedModel.providerName,
760
+ model: resolvedModel.modelId,
761
+ agent,
762
+ session,
763
+ tokens_in: usage.tokens_in,
764
+ context_tokens: lastCallContextTokens,
765
+ tokens_in_new: newIn,
766
+ tokens_in_cache_read: cacheRead,
767
+ tokens_in_cache_create: cacheCreate,
768
+ tokens_out: usage.tokens_out,
769
+ cost_usd: msg.total_cost_usd,
770
+ duration_ms: msg.duration_ms,
771
+ });
772
+ } else {
773
+ yieldedErrorEvent = true;
774
+ // The provider ended the turn itself. The monthly-quota case
775
+ // arrives exactly here, right after the CLI streamed its
776
+ // notice as ordinary assistant text — that text is not an
777
+ // answer, so the fallback chain must still be allowed to run
778
+ // (2026-09-09 report).
779
+ yield {
780
+ kind: 'error',
781
+ ts: ts(),
782
+ engine: ENGINE,
783
+ message: `${msg.subtype}: ${msg.errors?.join(', ') ?? 'unknown'}`,
784
+ providerError: true,
785
+ };
786
+ }
787
+ }
788
+ }
789
+
790
+ // Auth failures surface as a NORMAL result text from the SDK
791
+ // ("Failed to authenticate: OAuth session expired…"), not as a
792
+ // thrown error. Detect them, run the credential reconcile (heals
793
+ // the symlink-drift where a token refresh materialized
794
+ // .credentials.json into a stale copy — 2026-07-21 incident), and
795
+ // surface a proper error event with an actionable hint instead of
796
+ // a fake assistant message.
797
+ if (finalText && /^Failed to authenticate/i.test(finalText.trim())) {
798
+ const healed = reconcileClaudeCredentials();
799
+ logger.warn({ msg: 'engine.auth_failure', engine: ENGINE, agent, session, healed });
800
+ const hint =
801
+ healed === 'pulled' || healed === 'pushed'
802
+ ? 'Credential drift detected and auto-healed — just resend your message.'
803
+ : 'Please run `claude login` in your terminal and resend (`somora auth status` shows the credential state).';
804
+ yield { kind: 'error', ts: ts(), engine: ENGINE, message: `${finalText.trim()} — ${hint}`, providerError: true };
805
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
806
+ return;
807
+ }
808
+
809
+ // Empty-turn defense. On 2026-07-24 an expired OAuth session
810
+ // produced turns that ended after ~4s with NO assistant text, NO
811
+ // tool_use, NO error event and nothing in the logs — the SDK
812
+ // swallowed the auth error entirely (it neither threw nor emitted
813
+ // the "Failed to authenticate" result text that the branch above
814
+ // catches). A turn that yields literally nothing is never a valid
815
+ // outcome, so surface it loudly, reconcile credentials (the most
816
+ // likely cause), and tell the user what to do — instead of the
817
+ // silent turn_start/turn_end pair that had them guessing.
818
+ if (!finalText && !cumulative && !sawToolUse && !yieldedErrorEvent) {
819
+ const healed = reconcileClaudeCredentials();
820
+ logger.warn({
821
+ msg: 'engine.empty_turn',
822
+ engine: ENGINE,
823
+ agent,
824
+ session,
825
+ healed,
826
+ hint: 'SDK stream ended without text/tools/error — likely a swallowed auth failure',
827
+ });
828
+ const hint =
829
+ healed === 'pulled' || healed === 'pushed'
830
+ ? 'Credential drift detected and auto-healed — just resend your message.'
831
+ : 'Most common cause: expired OAuth session. `somora auth status` shows the credential state; run `claude login` if needed and resend.';
832
+ yield {
833
+ kind: 'error',
834
+ ts: ts(),
835
+ engine: ENGINE,
836
+ message: `claude-cli returned an empty turn (no text, no tool call, no error event) — ${hint}`,
837
+ providerError: true,
838
+ };
839
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
840
+ return;
841
+ }
842
+
843
+ if (finalText) {
844
+ yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: finalText };
845
+ }
846
+ yield {
847
+ kind: 'turn_end',
848
+ ts: ts(),
849
+ engine: ENGINE,
850
+ turnId,
851
+ ...(usage
852
+ ? {
853
+ usage: {
854
+ ...usage,
855
+ ...(typeof tokensInCachedClaude === 'number' && tokensInCachedClaude > 0
856
+ ? { tokens_in_cached: tokensInCachedClaude }
857
+ : {}),
858
+ ...(lastCallContextTokens !== undefined ? { context_tokens: lastCallContextTokens } : {}),
859
+ },
860
+ }
861
+ : {}),
862
+ };
863
+
864
+ if (lastSdkSessionId) {
865
+ // Re-read meta from disk before merging — tools running in the
866
+ // MCP child during this turn may have mutated session-scoped
867
+ // fields (project_focus writes projectSlug + projectLinkedAt;
868
+ // future tools may write others). The `meta` snapshot above is
869
+ // from turn START and would clobber those mid-turn writes if
870
+ // we spread it directly. Refs: naxon 2026-05-13 — project_focus
871
+ // pin survived inside the turn, then vanished at turn end.
872
+ // Atomic read-merge-write — re-reads under the per-session lock
873
+ // so a concurrent /sessions stats-cache write (or activity mark)
874
+ // can't revert sdkSessionId, and our write can't revert theirs
875
+ // (Juni-Audit 2026-06).
876
+ await metaStore.update(agent, session, (freshMeta) => ({
877
+ ...freshMeta,
878
+ engine: ENGINE,
879
+ sdkSessionId: lastSdkSessionId,
880
+ mcpServerName: MCP_SERVER_NAME,
881
+ engineLastSeen: withLastSeenTs(freshMeta, ENGINE, ts()),
882
+ }));
883
+ }
884
+ } catch (err) {
885
+ // User pressed ESC mid-turn — emit whatever we streamed so far +
886
+ // a marker, no error event. Anything else is a real failure.
887
+ if (signal?.aborted) {
888
+ logger.info({ msg: 'engine.aborted', engine: ENGINE, agent, session });
889
+ const partial = cumulative
890
+ ? `${cumulative}\n\n[somora] aborted by user`
891
+ : '[somora] aborted by user';
892
+ yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: partial };
893
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
894
+ } else if (watchdogFired) {
895
+ // Idle watchdog tripped — SDK iterator was stuck. Loud surface
896
+ // beats silent stuck-session. Next user turn will hit
897
+ // healOrphanToolCalls() if a tool_use was outstanding.
898
+ logger.error({
899
+ msg: 'engine.fail',
900
+ engine: ENGINE,
901
+ agent,
902
+ session,
903
+ err: 'idle watchdog timeout',
904
+ });
905
+ yield {
906
+ kind: 'error',
907
+ ts: ts(),
908
+ engine: ENGINE,
909
+ message: `engine timed out: no SDK events for ${IDLE_TIMEOUT_MS / 1000}s (claude-cli child likely died silently)`,
910
+ providerError: true,
911
+ };
912
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
913
+ } else {
914
+ const errMsg = (err as Error).message;
915
+
916
+ // claude-cli reports "No conversation found with session ID: <uuid>"
917
+ // when its local conversation store no longer has the session we
918
+ // tried to resume (cleaned up, expired, fresh install, account
919
+ // switch, etc.). Without clearing, the fallback path on the same
920
+ // engine — and every subsequent user turn — keeps retrying the
921
+ // dead ID and forces the user to do a manual `/reset`. Drop
922
+ // the stale id from meta so the next attempt starts fresh.
923
+ if (resume && /No conversation found/i.test(errMsg)) {
924
+ try {
925
+ // Same atomic merge as the success branch — preserve any
926
+ // mid-turn meta writes from tools (project_focus, ...) while
927
+ // dropping only the stale sdkSessionId. Also drop this
928
+ // engine's lastSeen: the fresh SDK session knows nothing, so
929
+ // the next turn must replay the FULL compaction-aware
930
+ // history — keeping lastSeen would shrink the replay to the
931
+ // recent delta and silently lose the older context
932
+ // (2026-07-21, found while building the codex twin of this
933
+ // recovery).
934
+ await metaStore.update(agent, session, (freshMeta) => {
935
+ const { sdkSessionId: _drop, ...rest } = freshMeta;
936
+ const lastSeen = { ...((rest as { engineLastSeen?: Record<string, number> }).engineLastSeen ?? {}) };
937
+ delete lastSeen[ENGINE];
938
+ return { ...rest, engineLastSeen: lastSeen };
939
+ });
940
+ logger.info({
941
+ msg: 'engine.session_resume_cleared',
942
+ engine: ENGINE,
943
+ agent,
944
+ session,
945
+ stale_id: resume,
946
+ });
947
+ } catch (clearErr) {
948
+ logger.warn({
949
+ msg: 'engine.session_resume_clear_failed',
950
+ engine: ENGINE,
951
+ agent,
952
+ session,
953
+ err: String(clearErr),
954
+ });
955
+ }
956
+ }
957
+
958
+ logger.error({ msg: 'engine.fail', engine: ENGINE, agent, session, err: errMsg });
959
+ yield { kind: 'error', ts: ts(), engine: ENGINE, message: errMsg, providerError: true };
960
+ yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId };
961
+ }
962
+ } finally {
963
+ disarmIdleTimer();
964
+ if (steerPoll) clearInterval(steerPoll);
965
+ steerInput?.close();
966
+ if (signal) signal.removeEventListener('abort', onUpstreamAbort);
967
+ }
968
+ },
969
+ };