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,2292 @@
1
+ // Server config schema. Lives at ~/.somora/config.yaml (override via SOMORA_HOME).
2
+ // Engines are the protocol adapters (claude-cli, openai-compatible).
3
+ // Providers are concrete instances of an engine with baseUrl/apiKey and a model list.
4
+ // Personas reference models as `<provider>/<modelId>`.
5
+
6
+ import { DEFAULT_CODEX_DIRECT_TOOLS } from '../engine/codex-dynamic-tools.ts';
7
+ import { z } from 'zod';
8
+
9
+ // Model capabilities. `text` is universal. `image` enables Vision (image
10
+ // content blocks). `pdf` enables PDF document content blocks (Anthropic
11
+ // natively, OpenAI via file-API; most local OMX models lack it). The
12
+ // runtime gates `file_read` on these — agent gets a clear error when
13
+ // it tries to read media a model can't process. `reasoning` enables
14
+ // per-engine "thinking" effort levels.
15
+ export const ModelCapabilitySchema = z.enum(['text', 'image', 'pdf', 'reasoning']);
16
+ export type ModelCapability = z.infer<typeof ModelCapabilitySchema>;
17
+
18
+ // Cross-engine "thinking" knob. Values map per-engine in each adapter:
19
+ // claude-cli → SDK `effort: 'low'|'medium'|'high'` (or thinking: disabled)
20
+ // codex-cli → -c model_reasoning_effort=<level>
21
+ // openai-compatible → reasoning_effort: <level>
22
+ // 'off' disables thinking entirely; the level otherwise guides depth.
23
+ // Only applied when the model has the 'reasoning' capability — otherwise
24
+ // the setting is dormant (header surfaces this honestly).
25
+ export const ThinkingLevelSchema = z.enum(['off', 'low', 'medium', 'high']);
26
+ export type ThinkingLevel = z.infer<typeof ThinkingLevelSchema>;
27
+
28
+ /**
29
+ * Per-model reasoning vocabulary for the `openai-compatible` engine.
30
+ * Real models disagree on the words (OpenAI none…xhigh, Qwen only
31
+ * xhigh|medium|low, DeepSeek low|high|max) and some reject unknown
32
+ * values with HTTP 400 instead of ignoring them. This block maps
33
+ * somora's neutral levels onto what the model actually accepts, and
34
+ * says where the value goes in the request body. Unset = legacy
35
+ * behaviour (`off` omits the param, the other levels go verbatim as
36
+ * `reasoning_effort`). See docs/thinking.md → Per-model vocabulary.
37
+ */
38
+ export const ModelReasoningSchema = z.object({
39
+ /** Body shape. `reasoning_effort` (top-level, default), `reasoning`
40
+ * (OpenRouter's nested `{ reasoning: { effort } }`), or
41
+ * `chat_template_kwargs` (vLLM templates that only read kwargs). */
42
+ param: z.enum(['reasoning_effort', 'reasoning', 'chat_template_kwargs']).optional(),
43
+ /** somora level → model value. A string is sent as-is; `null` omits
44
+ * the param for that level (model default). Missing levels keep the
45
+ * legacy mapping. */
46
+ levels: z
47
+ .object({
48
+ off: z.string().min(1).nullable().optional(),
49
+ low: z.string().min(1).nullable().optional(),
50
+ medium: z.string().min(1).nullable().optional(),
51
+ high: z.string().min(1).nullable().optional(),
52
+ })
53
+ .optional(),
54
+ });
55
+ export type ModelReasoningConfig = z.infer<typeof ModelReasoningSchema>;
56
+
57
+ /**
58
+ * Sampling parameters for the `openai-compatible` engine. Set as a model
59
+ * default here, as an agent default in agent.yaml (`sampling:`), or per
60
+ * session via `/sampling` / `/temp`; later layers win per key. Every key
61
+ * goes on the wire under its own name — a backend that rejects one
62
+ * answers 400 and the engine retries once without sampling. See
63
+ * docs/sampling.md.
64
+ */
65
+ export const SamplingSchema = z
66
+ .object({
67
+ temperature: z.number().min(0).max(2).optional(),
68
+ top_p: z.number().min(0).max(1).optional(),
69
+ top_k: z.number().int().min(1).optional(),
70
+ min_p: z.number().min(0).max(1).optional(),
71
+ frequency_penalty: z.number().min(-2).max(2).optional(),
72
+ presence_penalty: z.number().min(-2).max(2).optional(),
73
+ repetition_penalty: z.number().positive().optional(),
74
+ seed: z.number().int().optional(),
75
+ stop: z.union([z.string().min(1), z.array(z.string().min(1)).max(4)]).optional(),
76
+ })
77
+ .strict();
78
+ export type SamplingConfig = z.infer<typeof SamplingSchema>;
79
+
80
+ export const ModelSchema = z.object({
81
+ id: z.string().min(1),
82
+ /**
83
+ * Optional shorthand. Must be globally unique across the whole config.
84
+ * Lets you write `model: opus` in a persona instead of
85
+ * `model: anthropic/claude-opus-4-7`.
86
+ */
87
+ alias: z
88
+ .string()
89
+ .min(1)
90
+ .regex(/^[A-Za-z0-9_-]+$/, 'alias must match [A-Za-z0-9_-]+')
91
+ .optional(),
92
+ contextWindow: z.number().int().positive(),
93
+ capabilities: z.array(ModelCapabilitySchema).default(['text']),
94
+ /**
95
+ * Output cap sent as `max_tokens` (openai-compatible only). Unset =
96
+ * not sent, the backend decides (vLLM: the rest of the context). Worth
97
+ * setting on reasoning models, where thinking and answer share one
98
+ * budget and nothing else stops a runaway thinking phase. Not to be
99
+ * confused with `memory.autoInject.maxTokens` (input-side cap on the
100
+ * injected memory block).
101
+ */
102
+ maxTokens: z.number().int().positive().optional(),
103
+ /** Reasoning vocabulary + wire shape for this model (openai-compatible only). */
104
+ reasoning: ModelReasoningSchema.optional(),
105
+ /** Vendor-recommended sampling defaults for this model (openai-compatible
106
+ * only). agent.yaml `sampling:` and the session override win per key. */
107
+ sampling: SamplingSchema.optional(),
108
+ /**
109
+ * Only read by the `openai-compatible` engine. When unset (the common
110
+ * case), that engine sends `parallel_tool_calls: false` so the model
111
+ * emits ONE tool call per round — smaller/local models (deepseek, kimi)
112
+ * otherwise fan out into large parallel batches and lose track of what
113
+ * they've already run, which fuels runaway loops. Set `true` on a model
114
+ * you trust to parallelise (a strong local model doing independent
115
+ * reads) to restore the provider's default parallel behaviour. No effect
116
+ * on claude-cli / codex-cli. See docs/setup.md → Local OpenAI-compatible.
117
+ */
118
+ parallelToolCalls: z.boolean().optional(),
119
+ });
120
+ export type Model = z.infer<typeof ModelSchema>;
121
+
122
+ export const ClaudeCliProviderSchema = z.object({
123
+ engine: z.literal('claude-cli'),
124
+ models: z.array(ModelSchema).min(1),
125
+ });
126
+
127
+ // codex-cli: auth handled by the binary itself via `codex login`
128
+ // (ChatGPT subscription preferred) or OPENAI_API_KEY env. No baseUrl /
129
+ // apiKey here — they would do nothing.
130
+ export const CodexCliProviderSchema = z.object({
131
+ engine: z.literal('codex-cli'),
132
+ models: z.array(ModelSchema).min(1),
133
+ });
134
+
135
+ // grok-cli: xAI's Grok Build CLI driven over ACP (Agent Client
136
+ // Protocol, JSON-RPC on stdio) via `grok agent stdio`. Auth is handled
137
+ // by the binary itself — `grok login` writes a session to
138
+ // ~/.grok/auth.json and the ACP handshake reports it as the
139
+ // `cached_token` auth method. That session carries a SuperGrok/Premium
140
+ // subscription, so no baseUrl / apiKey belong here; passing an
141
+ // XAI_API_KEY env var instead switches the binary to pay-per-token API
142
+ // billing (see docs/setup.md).
143
+ //
144
+ // Binary path override: SOMORA_GROK_BIN (default ~/.local/bin/grok),
145
+ // mirroring SOMORA_CODEX_BIN / SOMORA_CLAUDE_BIN.
146
+ export const GrokCliProviderSchema = z.object({
147
+ engine: z.literal('grok-cli'),
148
+ models: z.array(ModelSchema).min(1),
149
+ });
150
+
151
+ export const OpenAiCompatibleProviderSchema = z.object({
152
+ engine: z.literal('openai-compatible'),
153
+ baseUrl: z.string().url(),
154
+ apiKey: z.string().min(1),
155
+ models: z.array(ModelSchema).min(1),
156
+ /**
157
+ * How PDFs ride along on user-attachments via this provider.
158
+ * - `rasterize` (default): render PDF pages to PNG via pdf-to-img
159
+ * and pass them as image_url blocks. Works against every backend
160
+ * that supports vision (omlx, ollama, gemma, anything OpenAI-
161
+ * style image-capable). Pages × image-tokens cost-wise, but
162
+ * universally compatible.
163
+ * - `native`: pass the PDF as a `{type:'file', file:{file_data:
164
+ * 'data:application/pdf;base64,…'}}` content block. Anthropic
165
+ * via OpenRouter and OpenAI direct accept this; most local
166
+ * servers (omlx, ollama) do not. Only enable when you've
167
+ * verified the backend behind this provider supports it.
168
+ * claude-cli always uses native DocumentBlock (Anthropic SDK
169
+ * supports it), codex-cli always rasterizes (its `--image` flag
170
+ * accepts only images). The knob is intentionally limited to this
171
+ * provider type because only here does the answer vary by the
172
+ * concrete backend.
173
+ */
174
+ pdfMode: z.enum(['rasterize', 'native']).default('rasterize').optional(),
175
+ /**
176
+ * Where the per-turn memory recall block lands in the prompt sent to
177
+ * the backend. The choice matters because openai-compatible can sit
178
+ * in front of any backend (mlx-omx, ollama, vLLM, OpenAI itself,
179
+ * llama.cpp gateways, ...) and prefix-cache support varies.
180
+ *
181
+ * - `inline-user` (default): the memory block is persisted on each
182
+ * `user_message` JSONL event (`ephemeral` field), and rebuilt
183
+ * into the user-message content on every history reconstruction.
184
+ * The byte sequence at turn N+1 matches what was sent at turn N
185
+ * for the entire prior conversation, so prefix-cache holds across
186
+ * the whole history. Memory still updates per turn — only the
187
+ * LATEST user message has a freshly-computed block; older turns
188
+ * keep the block they had at their original send time.
189
+ *
190
+ * - `system`: legacy — concat the memory block onto the persistent
191
+ * system prompt. Cache-destructive (system block changes every
192
+ * turn) but maximally compatible with backends that mishandle
193
+ * embedded memory inside user-message content. Opt-in fallback.
194
+ *
195
+ * claude-cli + codex-cli intentionally don't carry this field —
196
+ * claude-cli's backend is always Anthropic so we hardcode
197
+ * inline-user there (claude-agent-sdk has no multi-system escape),
198
+ * and codex-cli's stdin payload structure puts memory in the right
199
+ * place by construction.
200
+ */
201
+ memoryInjectMode: z
202
+ .enum(['inline-user', 'system'])
203
+ .default('inline-user')
204
+ .optional(),
205
+ /**
206
+ * Send `user: "<agent>/<session>"` (chat turns) or
207
+ * `user: "<agent>/<worker>"` (REM, Deep, compaction, analyze_file)
208
+ * on every chat-completions request. `user` is a standard field of
209
+ * the OpenAI API ("unique identifier representing your end-user"),
210
+ * accepted by OpenAI, LiteLLM, vLLM, SGLang, Ollama and ignored by
211
+ * backends that don't use it. A gateway that logs it (LiteLLM spend
212
+ * logs) can then attribute cost per agent and group a session's
213
+ * requests. Default on; set false for a provider that must not see
214
+ * agent or session names.
215
+ */
216
+ sendUserTag: z.boolean().default(true).optional(),
217
+ });
218
+
219
+ /** The one provider variant that carries baseUrl + apiKey. Named so
220
+ * service surfaces (stt, tts, imagegen) can require it in a signature
221
+ * instead of re-narrowing the union at every call site. */
222
+ export type OpenAiCompatibleProvider = z.infer<typeof OpenAiCompatibleProviderSchema>;
223
+
224
+ export const ProviderSchema = z.discriminatedUnion('engine', [
225
+ ClaudeCliProviderSchema,
226
+ CodexCliProviderSchema,
227
+ GrokCliProviderSchema,
228
+ OpenAiCompatibleProviderSchema,
229
+ ]);
230
+ export type Provider = z.infer<typeof ProviderSchema>;
231
+ export type EngineName = Provider['engine'];
232
+
233
+ export const CompactionConfigSchema = z
234
+ .object({
235
+ /** Fraction of contextWindow at which compaction triggers (0..1). Default 0.8. */
236
+ triggerRatio: z.number().positive().max(1).optional(),
237
+ /** Recent user/assistant pairs that stay uncompacted. Default 4. */
238
+ safetyCushionPairs: z.number().int().nonnegative().optional(),
239
+ /** Optional override for the worker model (alias or `provider/modelId`). */
240
+ modelOverride: z.string().min(1).optional(),
241
+ /** Models allowed to summarize, in the order they should be tried. */
242
+ workers: z.array(z.string().min(1)).optional(),
243
+ /**
244
+ * Try the session's own model first — the one that is loaded and
245
+ * answering right now — before `workers` (naxon, 2026-09-26: a
246
+ * session on a model outside the list waited for workers that were
247
+ * not loaded and ended on a weaker one). Only when its engine can
248
+ * summarize and its window fits; `workers` stay the cascade behind
249
+ * it. Default false: a session on a hosted subscription model would
250
+ * otherwise start paying for summaries.
251
+ */
252
+ preferSessionModel: z.boolean().optional(),
253
+ })
254
+ .optional();
255
+ export type CompactionConfigSchema = z.infer<typeof CompactionConfigSchema>;
256
+
257
+ // Memory-Layer config (DECISIONS #25–#27). All optional with sensible defaults.
258
+ // Per-agent overrides may live in agent.yaml later. (Phase 2-Stufe-B)
259
+ export const MemoryEmbeddingConfigSchema = z.object({
260
+ /** Embedding provider. 'local' uses @huggingface/transformers (ONNX); remote providers TBD. */
261
+ provider: z.enum(['local', 'openai', 'gemini', 'mistral', 'ollama']).default('local'),
262
+ /** Model identifier — semantics depend on provider. For 'local': HF Hub repo or alias. */
263
+ model: z.string().min(1).default('all-MiniLM-L6-v2'),
264
+ }).default({ provider: 'local', model: 'all-MiniLM-L6-v2' });
265
+
266
+ export const MemoryChunkingConfigSchema = z.object({
267
+ targetTokens: z.number().int().positive().default(400),
268
+ overlapTokens: z.number().int().nonnegative().default(80),
269
+ }).default({ targetTokens: 400, overlapTokens: 80 });
270
+
271
+ export const MemoryAutoInjectConfigSchema = z.object({
272
+ /** How many last conversation turns feed the embedding query. */
273
+ queryTurns: z.number().int().positive().default(3),
274
+ /** Top-N matches injected per turn. */
275
+ maxResults: z.number().int().positive().default(5),
276
+ /** Discard matches below this hybrid score (0..1). 0.35 lets short
277
+ * single-keyword queries surface wiki/vault hits where vector recall
278
+ * alone wouldn't put them in top-k (BM25-only floor ≈ bm25Weight * 1.0
279
+ * * sourceBoost). Raise to 0.5+ if auto-injection becomes too noisy. */
280
+ minScore: z.number().min(0).max(1).default(0.35),
281
+ /** Hard cap on tokens of the injected memory block (Heuristik 4 chars/token). */
282
+ maxTokens: z.number().int().positive().default(1500),
283
+ /**
284
+ * How much the previous turns steer the vector query, 0..1. The
285
+ * current message is embedded on its own and blended with the
286
+ * embedding of the recent history at this weight — 0.3 = the
287
+ * question decides, the conversation nudges. Before 2026-09-08 the
288
+ * turns were concatenated as one text, and a 46-character question
289
+ * after two long answers about something else recalled that
290
+ * something else (Walter → CerebroCraft). 0 = current message only.
291
+ */
292
+ historyWeight: z.number().min(0).max(1).default(0.3),
293
+ /** History weight when the message has only one or two content words
294
+ * ("und seine frau?") — the conversation must carry more. */
295
+ historyWeightShort: z.number().min(0).max(1).default(0.55),
296
+ /** History weight when the message has NO content word ("das solltest
297
+ * du aber wissen oder?") — the conversation is the whole query. */
298
+ historyWeightEmpty: z.number().min(0).max(1).default(0.8),
299
+ /** Characters kept per history turn for the blend (head of the turn,
300
+ * where the topic usually is). 800 measured best on the labelled
301
+ * cases (400 lost follow-ups whose topic sat past the opening). */
302
+ historyTurnChars: z.number().int().positive().default(800),
303
+ /**
304
+ * BM25 share of the fusion for a message with only one or two content
305
+ * words ("wer ist walter?"): the exact word match IS the question, and
306
+ * the default 0.3 lets a topic-drifted vector outvote it. Vector share
307
+ * is the remainder. `null` = use `memory.hybrid` as for every query.
308
+ */
309
+ shortQueryBm25Weight: z.number().min(0).max(1).nullable().default(0.5),
310
+ }).default({ queryTurns: 3, maxResults: 5, minScore: 0.35, maxTokens: 1500, historyWeight: 0.3, historyWeightShort: 0.55, historyWeightEmpty: 0.8, historyTurnChars: 800, shortQueryBm25Weight: 0.5 });
311
+
312
+ export const MemoryHybridConfigSchema = z.object({
313
+ vectorWeight: z.number().min(0).max(1).default(0.7),
314
+ bm25Weight: z.number().min(0).max(1).default(0.3),
315
+ /**
316
+ * Multiplier on the fused score of a chunk whose slug contains a
317
+ * content word of the query — `personen/walter-siegl` for "wer ist
318
+ * walter?". The page ABOUT something rarely repeats its name in the
319
+ * body, so BM25 ranks the pages that mention it above it; the slug
320
+ * says which page is the canonical one. 1 = off.
321
+ */
322
+ slugMatchBoost: z.number().min(1).max(3).default(1.5),
323
+ }).default({ vectorWeight: 0.7, bm25Weight: 0.3, slugMatchBoost: 1.5 });
324
+
325
+ export const MemoryConfigSchema = z.object({
326
+ embedding: MemoryEmbeddingConfigSchema,
327
+ chunking: MemoryChunkingConfigSchema,
328
+ autoInject: MemoryAutoInjectConfigSchema,
329
+ hybrid: MemoryHybridConfigSchema,
330
+ /**
331
+ * Minutes between full sweeps of the vault/wiki index (0 = off). The
332
+ * file-watcher sees what is written on THIS machine; a file that an
333
+ * editor on another machine saves onto a network share arrives
334
+ * without an event, and used to be indexed only at the next server
335
+ * start (2026-09-25). The sweep skips unchanged files by hash, so it
336
+ * is cheap. Default 10.
337
+ */
338
+ rescanMinutes: z.number().int().min(0).max(24 * 60).default(10),
339
+ }).default({
340
+ embedding: { provider: 'local', model: 'all-MiniLM-L6-v2' },
341
+ chunking: { targetTokens: 400, overlapTokens: 80 },
342
+ autoInject: { queryTurns: 3, maxResults: 5, minScore: 0.35, maxTokens: 1500, historyWeight: 0.3, historyWeightShort: 0.55, historyWeightEmpty: 0.8, historyTurnChars: 800, shortQueryBm25Weight: 0.5 },
343
+ hybrid: { vectorWeight: 0.7, bm25Weight: 0.3, slugMatchBoost: 1.5 },
344
+ rescanMinutes: 10,
345
+ });
346
+ export type MemoryConfig = z.infer<typeof MemoryConfigSchema>;
347
+
348
+ // Global REM tunables (server-wide). Per-agent REM settings (worker
349
+ // model, idle trigger, chunking) stay in agent.yaml `rem:` — this block
350
+ // is for behavior that should not vary per agent.
351
+ //
352
+ // dedup (2026-07-21, buffet's workspace-dedup report): mechanical
353
+ // post-extraction filter against already-persisted knowledge. The
354
+ // extractor prompt ALSO asks the worker model to dedupe, but small
355
+ // worker models (gemma-class) demonstrably ignore that — 26/27 findings
356
+ // in one review round were repeats. This filter is code, not a prompt:
357
+ // - exact slug collision with an existing memory note / loaded wiki
358
+ // page → finding is dropped before review (logged).
359
+ // - hybrid-search similarity (memory+wiki sources) at or above
360
+ // `similarityThreshold` → finding is KEPT but marked
361
+ // `likely_duplicate` so the review can batch-dismiss. Similarity is
362
+ // a judgment call, so no silent drop.
363
+ // Threshold semantics: COSINE similarity of the finding's embedding to
364
+ // the best existing chunk, in [0,1] (memory/retrieval.ts
365
+ // cosineFromVecScore). Not the fused hybrid `score` — that is a rank
366
+ // within one query's candidates (the top hit is always 1.0 before
367
+ // source boosts), which is why the old 0.8 flagged ~70 % of findings
368
+ // against unrelated pages (2026-08-26). Default 0.85, measured on real
369
+ // notes with the bundled embedding model (2026-08-31): verbatim 1.00,
370
+ // paraphrase of the same fact 0.85-0.90, same topic but a different or
371
+ // contradicting fact 0.73-0.84, unrelated 0.3-0.5. A long German note
372
+ // vs a one-line paraphrase can drop to ~0.6 — that finding then simply
373
+ // shows up unmarked, the conservative failure. Tune down if repeats
374
+ // still get through, up if contradicting facts get flagged.
375
+ // The coverage judge (2026-09-25, private/dream-judge/): after the
376
+ // cosine pass a model reads the WHOLE pages of the closest candidates
377
+ // and answers one question — is the finding's substance already stated
378
+ // there, or does it add something? Measured on 100 hand-labelled
379
+ // findings: cosine at 0.85 found 5 duplicates, the question found 93
380
+ // at 91 % precision. Off by default; `model` empty = the REM worker
381
+ // of the agent whose dream is running.
382
+ export const RemJudgeConfigSchema = z.object({
383
+ enabled: z.boolean().default(false),
384
+ /** Alias or `provider/modelId`; absent = the agent's REM worker model. */
385
+ model: z.string().min(1).optional(),
386
+ /** Distinct candidate pages the judge reads per finding. */
387
+ candidates: z.number().int().min(1).max(10).default(4),
388
+ /** Each candidate page is cut to this many characters. */
389
+ maxPageChars: z.number().int().min(500).max(60000).default(6000),
390
+ /** A `covered` verdict below this confidence (0–100) marks nothing. */
391
+ minConfidence: z.number().int().min(0).max(100).default(80),
392
+ /** Findings judged per dream run; the rest stay unjudged (logged once). */
393
+ maxPerRun: z.number().int().min(0).default(60),
394
+ timeoutMs: z.number().int().positive().default(120_000),
395
+ /** Optional thinking level, honoured when the judge model can reason. */
396
+ thinking: ThinkingLevelSchema.optional(),
397
+ });
398
+ export type RemJudgeConfig = z.infer<typeof RemJudgeConfigSchema>;
399
+ const REM_JUDGE_DEFAULTS: RemJudgeConfig = { enabled: false, candidates: 4, maxPageChars: 6000, minConfidence: 80, maxPerRun: 60, timeoutMs: 120_000 };
400
+
401
+ export const RemDedupConfigSchema = z.object({
402
+ enabled: z.boolean().default(true),
403
+ similarityThreshold: z.number().min(0).max(1).default(0.85),
404
+ judge: RemJudgeConfigSchema.default(REM_JUDGE_DEFAULTS),
405
+ }).default({ enabled: true, similarityThreshold: 0.85, judge: REM_JUDGE_DEFAULTS });
406
+
407
+ export type RemDedupConfig = z.infer<typeof RemDedupConfigSchema>;
408
+
409
+ export const RemGlobalConfigSchema = z.object({
410
+ dedup: RemDedupConfigSchema,
411
+ }).default({ dedup: { enabled: true, similarityThreshold: 0.85, judge: REM_JUDGE_DEFAULTS } });
412
+ export type RemGlobalConfig = z.infer<typeof RemGlobalConfigSchema>;
413
+
414
+ // Engine watchdog tunables (Phase A2 — 2026-05-14). Idle-event timeout
415
+ // per engine. If an engine produces no events for the configured
416
+ // duration mid-turn we assume the underlying subprocess died (or the
417
+ // remote HTTP call is wedged), abort, and surface a clean error so the
418
+ // per-session lock releases and the user can try again.
419
+ //
420
+ // Defaults are tuned to engine-realistic latency:
421
+ // - claude-cli / codex-cli: 300s. Subscription-hosted, fast first
422
+ // event; any 5min silence is a dead child, not slow thinking.
423
+ // - openai-compatible: 1200s. Local LLMs (oMLX, ollama, vLLM) on
424
+ // consumer hardware can legitimately take many minutes per turn,
425
+ // especially Wan/Flux-class image pipelines or 30B+ models on
426
+ // CPU/MPS. 20min is generous — raise per-provider if needed.
427
+ //
428
+ // Dream workers (Deep/Lucid) bypass this entirely — they run via
429
+ // src/dream/deep-llm.ts which spawns its own children with its own
430
+ // abort timing, never enters the per-session chat lock.
431
+ export const EngineWatchdogConfigSchema = z.object({
432
+ claudeCliIdleMs: z.number().int().positive().default(300_000),
433
+ codexCliIdleMs: z.number().int().positive().default(300_000),
434
+ grokCliIdleMs: z.number().int().positive().default(300_000),
435
+ openaiCompatibleIdleMs: z.number().int().positive().default(1_200_000),
436
+ }).default({
437
+ claudeCliIdleMs: 300_000,
438
+ codexCliIdleMs: 300_000,
439
+ grokCliIdleMs: 300_000,
440
+ openaiCompatibleIdleMs: 1_200_000,
441
+ });
442
+ export type EngineWatchdogConfig = z.infer<typeof EngineWatchdogConfigSchema>;
443
+
444
+ // SSE broadcast tunables. A healthy writeSSE finishes in microseconds
445
+ // (local TransformStream write). A wedged subscriber — mobile browser
446
+ // backgrounded, TCP receive window stuck at 0, half-dead TLS handshake
447
+ // — can backpressure forever without throwing. Without a budget, ONE
448
+ // stuck subscriber freezes every turn on that (agent, session). Per-
449
+ // sub timeout + parallel-write isolates clients from each other.
450
+ export const SseConfigSchema = z.object({
451
+ /** Max wall-clock per single writeSSE before we evict the subscriber.
452
+ * A healthy write is µs; legitimate slow paths (network jitter, slow
453
+ * mobile link) finish well under 1s. Default 10 000 ms is two orders
454
+ * of magnitude more than a healthy write needs but still self-heals
455
+ * a wedged stream fast. Bug 2026-05-19 driver: iOS Safari background
456
+ * freeze. */
457
+ publishTimeoutMs: z.number().int().positive().default(10_000),
458
+ /** When true (default), broadcast events to all subscribers in
459
+ * parallel — one slow client never blocks the others. When false,
460
+ * subscribers run sequentially in insertion order (legacy behaviour;
461
+ * only flip this if you need strict per-subscriber send ordering for
462
+ * some odd integration). */
463
+ publishParallel: z.boolean().default(true),
464
+ /** Server → client heartbeat interval on /chat/stream and
465
+ * /activity/stream. Clients treat a gap of > ~2 intervals as a lost
466
+ * link (docs/mobile.md). */
467
+ heartbeatMs: z.number().int().positive().default(20_000),
468
+ /** A heartbeat write that has not completed after this long marks
469
+ * the stream dead: it is torn down and its socket destroyed. */
470
+ deadAfterMs: z.number().int().positive().default(60_000),
471
+ /** HTTP/2 PING per client session (TLS listener only). A session
472
+ * that does not ACK within h2PingTimeoutMs is destroyed — the way
473
+ * a silently vanished tab (WLAN drop, sleep) is detected in about
474
+ * a minute instead of never. */
475
+ h2PingIntervalMs: z.number().int().positive().default(30_000),
476
+ h2PingTimeoutMs: z.number().int().positive().default(30_000),
477
+ /** TCP keepalive delay set on every accepted socket. Kernel probe
478
+ * interval/count still apply on top (Linux default 75 s × 9). */
479
+ keepAliveDelayMs: z.number().int().positive().default(30_000),
480
+ }).default({
481
+ publishTimeoutMs: 10_000,
482
+ publishParallel: true,
483
+ heartbeatMs: 20_000,
484
+ deadAfterMs: 60_000,
485
+ h2PingIntervalMs: 30_000,
486
+ h2PingTimeoutMs: 30_000,
487
+ keepAliveDelayMs: 30_000,
488
+ });
489
+ export type SseConfig = z.infer<typeof SseConfigSchema>;
490
+
491
+ // tmux attention watcher — server-side polling of somora-created tmux
492
+ // sessions with a known coding-CLI kind (claude-code / codex). Detects
493
+ // the running→ready transition ("finished or waiting for input") and,
494
+ // when the originating agent missed it, dispatches a wake turn so the
495
+ // agent reads the output and continues. Design:
496
+ // private/tmux-hooks-design.md (Phase 1, watcher-first — no CLI hooks).
497
+ export const TmuxAttentionConfigSchema = z
498
+ .object({
499
+ /** Master switch for the watcher + attention metadata in tmux
500
+ * tool responses / web badge. Off = zero polling, zero traces. */
501
+ enabled: z.boolean().default(true),
502
+ /** Agent-wakeup stage. Off = events only (needs_attention flag +
503
+ * badge), no dispatched turns. */
504
+ wake: z.boolean().default(true),
505
+ /** Watcher poll interval. Also bounds how quickly a missed
506
+ * completion turns into a wake (one extra tick worst-case). */
507
+ pollMs: z.number().int().min(500).default(3_000),
508
+ /** Minimum seconds between two wakes for the same tmux session —
509
+ * flap protection for fast running/ready cycles. */
510
+ cooldownS: z.number().int().min(0).default(60),
511
+ /** Hard daily ceiling per tmux session (UTC day). Past the cap
512
+ * only the needs_attention flag is set, no more turns. */
513
+ dailyCapPerSession: z.number().int().min(1).default(40),
514
+ })
515
+ .default({
516
+ enabled: true,
517
+ wake: true,
518
+ pollMs: 3_000,
519
+ cooldownS: 60,
520
+ dailyCapPerSession: 40,
521
+ });
522
+ export type TmuxAttentionConfig = z.infer<typeof TmuxAttentionConfigSchema>;
523
+
524
+ export const TmuxConfigSchema = z
525
+ .object({
526
+ attention: TmuxAttentionConfigSchema,
527
+ })
528
+ .default({
529
+ attention: {
530
+ enabled: true,
531
+ wake: true,
532
+ pollMs: 3_000,
533
+ cooldownS: 60,
534
+ dailyCapPerSession: 40,
535
+ },
536
+ });
537
+ export type TmuxConfig = z.infer<typeof TmuxConfigSchema>;
538
+
539
+ // Agent-loop tunables for engines that run their own tool-call loop
540
+ // (currently only openai-compatible — Phase 2-Stufe-C). claude-cli and
541
+ // codex-cli have their own internal loops and ignore these values for
542
+ // the per-tool-call race; the long-task fields ALSO inform CLI-engine
543
+ // tools (subagent_result, agent_ask) which run inside MCP children.
544
+ export const AgentLoopConfigSchema = z.object({
545
+ /**
546
+ * Max tool-call rounds per turn. The vast majority of conversations
547
+ * finish in 1-3 rounds; this is a defensive cap that prevents a confused
548
+ * or adversarial model from looping forever. Most agent frameworks
549
+ * default to 10-25; we pick 8 for somora since memory tools are
550
+ * narrow and a higher cap rarely helps.
551
+ */
552
+ maxRounds: z.number().int().positive().max(100).default(8),
553
+ /**
554
+ * Hard ceiling on the TOTAL number of tool calls executed in one turn,
555
+ * across all rounds. `maxRounds` counts rounds (model turns); it does
556
+ * NOT bound how many tool calls a single round contains. Weak/local
557
+ * models — deepseek via OpenRouter, which ignores `parallel_tool_calls`
558
+ * — fan out dozens of tool calls in ONE round (77 and 116 identical
559
+ * calls observed 2026-07-23), never touching the round cap. This budget
560
+ * catches that: once a turn has executed this many tool calls, somora
561
+ * stops and forces a final answer. Openai-compatible engine only.
562
+ * Well-behaved turns finish in a handful; 30 leaves generous headroom.
563
+ */
564
+ maxToolCallsPerTurn: z.number().int().positive().max(500).default(30),
565
+ /**
566
+ * Wall-clock cap for one turn of the openai-compatible loop, in ms.
567
+ * Unset = no time cap (only rounds and calls bound the turn). A
568
+ * builder agent sets this per agent (agent.yaml `agentLoop.maxTurnMs`,
569
+ * default 8 h) so a night build cannot run into the next day unseen.
570
+ * When it fires the model is asked for a final summary, like at the
571
+ * round cap.
572
+ */
573
+ maxTurnMs: z.number().int().positive().optional(),
574
+ /**
575
+ * Per-tool-call timeout in milliseconds for FAST tools that don't
576
+ * declare their own (memory_search, web_fetch, time_now, file_read,
577
+ * obsidian_*). 30s is plenty for everything that hits a local DB,
578
+ * reads a file, or does a single HTTP round-trip. Tools that legitimately
579
+ * take longer (subagent_result with wait_until_done, agent_ask, exec)
580
+ * declare their own timeouts via ToolDefinition.timeoutFromInput +
581
+ * maxTimeoutMs (DECISION #37) and use longTask*TimeoutMs below.
582
+ */
583
+ toolCallTimeoutMs: z.number().int().positive().default(30_000),
584
+ /**
585
+ * DEFAULT timeout for SLOW Agent-to-Agent tools when the caller doesn't
586
+ * specify timeout_ms (subagent_result wait_until_done, agent_ask).
587
+ * Local models (gemma4big via mlx-omx, ollama) routinely need several
588
+ * minutes for a single turn — this default needs to be generous so
589
+ * agents don't have to adapt with retries on every call. 5 min is the
590
+ * "first checkpoint": when this elapses the tool returns
591
+ * state: "pending" (NOT an error), the sub keeps running, and the
592
+ * caller can retry with a higher timeout_ms or check status later
593
+ * (DECISION #37 pending-pattern). Honest "I'm still working" beats
594
+ * a fake error every time.
595
+ */
596
+ longTaskDefaultTimeoutMs: z.number().int().positive().default(300_000),
597
+ /**
598
+ * MAX timeout the caller can pass for slow Agent-to-Agent tools, even
599
+ * with an explicit timeout_ms. Hard ceiling for a single tool-call
600
+ * blocking — the underlying sub-task itself runs unbounded in the
601
+ * background (capped only by its own agentLoop.maxRounds), so this
602
+ * really just bounds how long a single subagent_result or agent_ask
603
+ * call sits open. 30 min covers any realistic local-model workload;
604
+ * raise if you have an exceptionally slow setup (CPU-only inference,
605
+ * huge models). claudeCli.mcpToolTimeoutMs and codexCli.toolTimeoutSec
606
+ * MUST be ≥ this value, otherwise the CLI's MCP layer will cut us off
607
+ * before our own ceiling kicks in.
608
+ */
609
+ longTaskMaxTimeoutMs: z.number().int().positive().default(1_800_000),
610
+ /**
611
+ * Grace before a finished piece of work (an agent_ask answer nobody
612
+ * waited for, a background sub-agent, a rendered video) wakes the
613
+ * agent that asked for it. A requester that fetches the result right
614
+ * away gets no wake. One value for every kind since 2026-09-13.
615
+ */
616
+ wakeGraceMs: z.number().int().min(0).max(60_000).default(3_000),
617
+ /**
618
+ * Max concurrent background exec jobs PER agent. Prevents runaway
619
+ * loops where a confused model fires off dozens of `exec` calls
620
+ * with background:true and floods the host. 8 is the rough sweet
621
+ * spot — tight enough to catch obvious mistakes, loose enough that
622
+ * legitimate parallel-build / parallel-test patterns aren't blocked.
623
+ * Counts both local AND remote background jobs against the same
624
+ * cap (the host's resources are what we're protecting; whether the
625
+ * load lands on the somora server or on spiderman doesn't change
626
+ * the basic "don't go nuts" intent).
627
+ */
628
+ execMaxConcurrentPerAgent: z.number().int().positive().default(8),
629
+ /**
630
+ * Server-wide cap across ALL agents. Multiple agents collectively
631
+ * still shouldn't be allowed to spawn 100 background processes.
632
+ * 32 is generous (4 agents × 8 each), enough headroom for normal
633
+ * multi-agent operation while still preventing a runaway scenario.
634
+ */
635
+ execMaxConcurrentGlobal: z.number().int().positive().default(32),
636
+ /**
637
+ * Inject a short "you have tools — call them, don't narrate" block
638
+ * into the system prompt whenever the agent has at least one tool.
639
+ *
640
+ * Tools reach the model through a separate API field, never through
641
+ * the prompt text. Strong models treat that formal declaration as
642
+ * binding; weaker local models weigh the conversation more heavily
643
+ * and can talk themselves out of tool use (bug 2026-07-22 — see
644
+ * src/engine/tool-trace.ts for the measured case). This block is the
645
+ * cheap belt to that fix's braces. Constant text, so it costs one
646
+ * cache invalidation on rollout and nothing afterwards.
647
+ */
648
+ toolUsageReminder: z.boolean().default(true),
649
+ }).default({
650
+ maxRounds: 8,
651
+ maxToolCallsPerTurn: 30,
652
+ toolUsageReminder: true,
653
+ toolCallTimeoutMs: 30_000,
654
+ longTaskDefaultTimeoutMs: 300_000,
655
+ longTaskMaxTimeoutMs: 1_800_000,
656
+ wakeGraceMs: 3_000,
657
+ execMaxConcurrentPerAgent: 8,
658
+ execMaxConcurrentGlobal: 32,
659
+ });
660
+ export type AgentLoopConfig = z.infer<typeof AgentLoopConfigSchema>;
661
+
662
+ // claude-cli engine tunables. Mostly thin wrappers over claude-agent-sdk
663
+ // env vars — surfaced here so they're visible/editable in config.yaml
664
+ // instead of hidden as undocumented env overrides. Applied at server boot
665
+ // via applyClaudeCliSdkEnv() (config wins unless the env var was already
666
+ // set explicitly — explicit env always wins as the override layer).
667
+ export const ClaudeCliConfigSchema = z
668
+ .object({
669
+ /**
670
+ * Per-MCP-tool-call timeout (ms). Maps to MCP_TOOL_TIMEOUT in the
671
+ * claude-agent-sdk subprocess. The SDK's hidden default is 5 min
672
+ * (300_000) — way too short for slow local models. We default to
673
+ * 30 min to match agentLoop.longTaskMaxTimeoutMs so the CLI's MCP
674
+ * layer never cuts off a long-blocking tool call before our own
675
+ * ceiling does. Raise both together if you need more, lower
676
+ * mcpToolTimeoutMs for fail-fast behavior on a fast setup.
677
+ */
678
+ mcpToolTimeoutMs: z.number().int().positive().default(1_800_000),
679
+ /**
680
+ * Initial MCP server connect timeout (ms). Maps to MCP_TIMEOUT.
681
+ * Affects only server startup handshake, not running calls.
682
+ */
683
+ mcpConnectTimeoutMs: z.number().int().positive().default(60_000),
684
+ /**
685
+ * Shared-login self-healing. When true (default), somora treats
686
+ * `~/.claude/.credentials.json` and the isolated claude-home copy
687
+ * as ONE OAuth session and auto-repairs the symlink whenever the
688
+ * claude CLI's atomic token-refresh write materializes it into a
689
+ * drifting real file (boot-time + on auth-failure during a turn).
690
+ * Set false ONLY if somora deliberately runs on a separate claude
691
+ * account inside CLAUDE_CONFIG_DIR — then somora never touches
692
+ * either credentials file.
693
+ */
694
+ sharedUserCredentials: z.boolean().default(true),
695
+ })
696
+ .default({
697
+ mcpToolTimeoutMs: 1_800_000,
698
+ mcpConnectTimeoutMs: 60_000,
699
+ sharedUserCredentials: true,
700
+ });
701
+ export type ClaudeCliConfig = z.infer<typeof ClaudeCliConfigSchema>;
702
+
703
+ // codex-cli engine tunables. Same posture as claudeCli — surface
704
+ // codex-internal limits in config.yaml so they're visible/editable.
705
+ // Applied via -c TOML overrides on each `codex exec` invocation by
706
+ // the codex-cli engine (src/engine/codex-cli.ts) via process.env.
707
+ export const CodexCliConfigSchema = z
708
+ .object({
709
+ /**
710
+ * Per-MCP-tool-call timeout in seconds. Codex's hidden default is
711
+ * 60s (`tool_timeout_sec`) — way too short for slow local models.
712
+ * Maps to `mcp_servers.somora.tool_timeout_sec` in codex's
713
+ * TOML. Default 1800s (30 min) matches claudeCli.mcpToolTimeoutMs
714
+ * and agentLoop.longTaskMaxTimeoutMs so the CLI's MCP layer never
715
+ * cuts off a long-blocking tool call before our own ceiling does.
716
+ */
717
+ toolTimeoutSec: z.number().int().positive().default(1800),
718
+ /**
719
+ * How codex's `--sandbox read-only` mode forwards env vars to the
720
+ * shell processes spawned by its `exec` tool.
721
+ *
722
+ * `inherit-all` (default) — pass the full somora-server process
723
+ * env into codex's tool shells. Required for skills like `gog`
724
+ * that depend on credentials living in the server's env (loaded
725
+ * via systemd EnvironmentFile or ~/.somora/somora.env).
726
+ * `core-only` — codex's own restrictive default, which keeps only
727
+ * PATH/HOME/USER/LANG/etc. Skills with declared env_vars then
728
+ * silently see them as missing inside the shell — exactly the
729
+ * 2026-05-10 lisa/GOG_KEYRING_PASSWORD bug. Use only if you have
730
+ * a hardening reason and have audited every skill.
731
+ *
732
+ * Maps to codex's `-c shell_environment_policy.inherit=all|core`
733
+ * flag (codex 0.125+).
734
+ */
735
+ shellEnvironmentPolicy: z.enum(['inherit-all', 'core-only']).default('inherit-all'),
736
+ /**
737
+ * somora tools kept in the model's DIRECT tool list on the Codex
738
+ * app-server (schemas in context every turn). Every other tool is a
739
+ * deferred dynamic tool the model reaches via Codex tool search /
740
+ * Code Mode discovery. Default: the everyday core (memory, files,
741
+ * exec, tmux, web, time, A2A, docs).
742
+ */
743
+ directTools: z.array(z.string()).default([...DEFAULT_CODEX_DIRECT_TOOLS]),
744
+ })
745
+ .default({
746
+ toolTimeoutSec: 1800,
747
+ shellEnvironmentPolicy: 'inherit-all',
748
+ directTools: [...DEFAULT_CODEX_DIRECT_TOOLS],
749
+ });
750
+ export type CodexCliConfig = z.infer<typeof CodexCliConfigSchema>;
751
+
752
+ // Workspace — default cwd for the file_* tools. NOT a sandbox: agents
753
+ // can also write outside the workspace (their own persona files, the
754
+ // global config) — protection comes from a path-blacklist in the file
755
+ // tools themselves, not from confinement here. Per-agent override lives
756
+ // in agent.yaml under `workspace.path`. The path is auto-created
757
+ // (mkdir -p) at server start; ~ expands to $HOME.
758
+ export const WorkspaceConfigSchema = z
759
+ .object({
760
+ default: z.string().min(1).default('~/somoraworkspace'),
761
+ })
762
+ .default({ default: '~/somoraworkspace' });
763
+ export type WorkspaceConfig = z.infer<typeof WorkspaceConfigSchema>;
764
+
765
+ // Resources — named SSH targets that file_* and exec tools can act on
766
+ // via a `target` parameter. SSH-only for v1; the discriminated union
767
+ // is set up so we can add other transport types later (Docker host,
768
+ // k8s pod, ...) without breaking existing entries.
769
+ export const SshResourceSchema = z.object({
770
+ type: z.literal('ssh'),
771
+ host: z.string().min(1),
772
+ port: z.number().int().min(1).max(65535).default(22),
773
+ user: z.string().min(1),
774
+ /**
775
+ * Path to the private key file ON THE SOMORA SERVER. ~ expands. The
776
+ * key is loaded once at first connection and held in memory for the
777
+ * pool's lifetime — tools never see it.
778
+ */
779
+ keyPath: z.string().min(1),
780
+ /**
781
+ * Free-form description shown to the agent via resource_list so it
782
+ * knows what each target is for. Multi-line OK.
783
+ */
784
+ description: z.string().optional(),
785
+ /**
786
+ * Default working directory on the remote. Used when file_* tools
787
+ * are called with a relative path against this resource. Falls back
788
+ * to the user's home dir on the remote if unset.
789
+ */
790
+ workspace: z.string().optional(),
791
+ /**
792
+ * Optional SHA256 host-key fingerprint for strict verification.
793
+ * Format: 'sha256:<base64>'. When set, mismatches refuse connection.
794
+ * When unset → TOFU: first connection accepts any key and pins it
795
+ * to ~/.somora/known_hosts; subsequent connections enforce the pin.
796
+ */
797
+ hostKey: z.string().optional(),
798
+ /**
799
+ * Privileged-command allowlist that overrides the global exec-tool
800
+ * blacklist (`sudo`, `reboot`, `shutdown`, etc.) FOR THIS RESOURCE
801
+ * ONLY. The global blacklist is the safe default; this is an opt-in
802
+ * escape valve for dedicated agent-workstations where Somora-agents
803
+ * legitimately maintain the host.
804
+ *
805
+ * Match semantics (intentionally simple): trim+collapse whitespace on
806
+ * both the incoming command and each entry, then entry `E` matches
807
+ * command `C` iff `C === E` OR `C.startsWith(E + ' ')`. No regex, no
808
+ * shell parsing — what you type is what's allowed, plus arguments
809
+ * after a space boundary. Example: `sudo` matches `sudo apt …` and
810
+ * bare `sudo`, but not `pseudo`. `systemctl reboot` matches itself
811
+ * and `systemctl reboot --now`, but not `systemctl rebootthing`.
812
+ *
813
+ * Each match → execute + write one line to
814
+ * `~/.somora/audit/exec-privileged.jsonl`. `local` target ignores
815
+ * this (host-policy is enforced on the resource side).
816
+ */
817
+ allowBlocked: z.array(z.string().min(1)).default([]),
818
+ });
819
+ export type SshResource = z.infer<typeof SshResourceSchema>;
820
+
821
+ export const ResourceSchema = z.discriminatedUnion('type', [SshResourceSchema]);
822
+ export type Resource = z.infer<typeof ResourceSchema>;
823
+
824
+ export const ResourcesConfigSchema = z
825
+ .record(
826
+ z.string().regex(/^[A-Za-z0-9_-]+$/, 'resource name must match [A-Za-z0-9_-]+'),
827
+ ResourceSchema,
828
+ )
829
+ .default({});
830
+ export type ResourcesConfig = z.infer<typeof ResourcesConfigSchema>;
831
+
832
+ // Web tools — provider credentials. Each tool reads its own slice; if a
833
+ // provider block isn't configured the corresponding tool's `available()`
834
+ // probe returns false and the model never sees it.
835
+ export const WebConfigSchema = z
836
+ .object({
837
+ brave: z
838
+ .object({
839
+ apiKey: z.string().min(1),
840
+ })
841
+ .optional(),
842
+ })
843
+ .default({});
844
+ export type WebConfig = z.infer<typeof WebConfigSchema>;
845
+
846
+ // TUI display preferences. Only affect what the Ink CLI renders into the
847
+ // scrollback — never affect actual memory injection or tool execution
848
+ // (those still happen on the server).
849
+ //
850
+ // `show.*` — line visibility (off = the row doesn't appear at all)
851
+ // `verbose.*` — detail level when the row IS shown (off = compact summary,
852
+ // on = full payload / inject text / system prompt)
853
+ //
854
+ // Both are TUI-side display state; the server emits enough data for the
855
+ // "verbose" form on every event so toggling is instant. Live-changeable
856
+ // via `/show <topic> on|off` and `/verbose <topic> on|off`.
857
+ export const TuiConfigSchema = z.object({
858
+ show: z.object({
859
+ memory: z.boolean().default(true),
860
+ tools: z.boolean().default(true),
861
+ }).default({ memory: true, tools: true }),
862
+ verbose: z.object({
863
+ tools: z.boolean().default(false),
864
+ memory: z.boolean().default(false),
865
+ system: z.boolean().default(false),
866
+ /** Model thinking text above each reply (engines that surface it). */
867
+ thinking: z.boolean().default(false),
868
+ }).default({ tools: false, memory: false, system: false, thinking: false }),
869
+ }).default({
870
+ show: { memory: true, tools: true },
871
+ verbose: { tools: false, memory: false, system: false, thinking: false },
872
+ });
873
+ export type TuiConfig = z.infer<typeof TuiConfigSchema>;
874
+
875
+ // Mobile PWA display knobs. Reduced-surface counterpart to TuiConfig:
876
+ // the mobile chat surface is minimal by design (chat-only), and the
877
+ // tool/memory rows that desktop +TUI default-on are default-off here
878
+ // to keep screen real-estate for the conversation. Operators can flip
879
+ // them on per-deployment in config.yaml if they prefer the verbose
880
+ // view on phone too.
881
+ export const MobileConfigSchema = z.object({
882
+ show: z.object({
883
+ /** Show `[tool call · …]` / `[tool result · …]` rows in the
884
+ * mobile chat. Default off; flip to true if you want
885
+ * desktop-parity verbosity. */
886
+ tools: z.boolean().default(false),
887
+ /** Show `[memory · …]` inject rows in the mobile chat. Default
888
+ * off; same rationale as `tools`. */
889
+ memory: z.boolean().default(false),
890
+ }).default({ tools: false, memory: false }),
891
+ }).default({
892
+ show: { tools: false, memory: false },
893
+ });
894
+
895
+ /**
896
+ * Soft budgets for the static prompt text — warnings only, nothing is
897
+ * ever truncated. Surfaced as counters in the web Team and Agent
898
+ * windows and by `somora team check`, so an operator notices when a
899
+ * persona or the team block grows into a biography. Hot: read per
900
+ * request, no restart.
901
+ */
902
+ export const PromptBudgetsSchema = z
903
+ .object({
904
+ /** The rendered "# Your team" block per agent. */
905
+ teamBlockChars: z.number().int().min(500).default(3000),
906
+ /** Each of AGENTS.md / SOUL.md / USER.md. */
907
+ personaFileChars: z.number().int().min(500).default(8000),
908
+ /** The three persona files together. */
909
+ personaTotalChars: z.number().int().min(1000).default(14000),
910
+ })
911
+ .default({ teamBlockChars: 3000, personaFileChars: 8000, personaTotalChars: 14000 });
912
+ export type PromptBudgetsConfig = z.infer<typeof PromptBudgetsSchema>;
913
+ export type MobileConfig = z.infer<typeof MobileConfigSchema>;
914
+
915
+ // Vision/multimodal worker config. Two tools route through this:
916
+ // - file_read polymorph (for the active main model, when it has the
917
+ // right capability — content blocks land directly in main context)
918
+ // - analyze_file (always dispatches to a separate worker model via
919
+ // openai-compatible API, returns the worker's text description)
920
+ //
921
+ // `worker` is the default for both image and PDF dispatch. `pdfWorker`
922
+ // is an optional override for PDF specifically (use case: cheap haiku
923
+ // for image triage but a stronger model for PDF reasoning, à la
924
+ // OpenClaw's `pdfModel ≠ imageModel` distinction). When unset, PDF
925
+ // falls back to `worker`. When `worker` itself is unset, analyze_file
926
+ // returns a clear error at call time — no silent degradation.
927
+ //
928
+ // v1 constraint: workers must be openai-compatible (proxied via
929
+ // openrouter etc. for Claude). Direct Anthropic SDK as worker is
930
+ // future work — same constraint as Dream-Mode. See
931
+ // `private/skills-design.md` and the dream-mode docs for the rationale.
932
+ /**
933
+ * One worker, or an ordered list of them. A list is tried front to
934
+ * back and the first one that answers wins.
935
+ *
936
+ * Why a list at all: a locally hosted worker is the cheap and private
937
+ * choice, but a GPU box runs one profile at a time — switch the profile
938
+ * and that model is simply not loaded any more. With a single value,
939
+ * `analyze_file` is then broken for every agent at once, and quietly:
940
+ * the agent finds out by failing. The last entry is meant to be
941
+ * something externally hosted that is always there.
942
+ *
943
+ * A plain string stays valid and means a one-element list.
944
+ */
945
+ const WorkerRefSchema = z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]);
946
+
947
+ export const VisionConfigSchema = z
948
+ .object({
949
+ /** Worker(s) for image + PDF analysis, `<provider>/<modelId>` each.
950
+ * A worker MUST have `image` capability; PDF use also requires
951
+ * `pdf` (or set `pdfWorker` to a model that has it). Entries that
952
+ * lack the needed capability are skipped, not fatal — the point of
953
+ * a chain is that it survives one entry being unusable. */
954
+ worker: WorkerRefSchema.optional(),
955
+ /** Override for PDF dispatch only. When unset, PDF uses `worker`.
956
+ * Use case: a cheap image-only worker plus a separate PDF-capable
957
+ * one for cost control. */
958
+ pdfWorker: WorkerRefSchema.optional(),
959
+ /** Per-attempt budget. A worker that hasn't answered by then counts
960
+ * as down and the chain moves on. Generous by default because a
961
+ * local vision model describing a large image legitimately takes
962
+ * tens of seconds. */
963
+ timeoutMs: z.number().int().positive().default(60_000),
964
+ /** Budget for the WHOLE chain, not one attempt. Without it a chain
965
+ * of four workers can spend four times `timeoutMs` before the tool
966
+ * gives up — measured 176 s for one screenshot, with the caller
967
+ * and the user waiting (2026-09-08 report). Each attempt gets
968
+ * whatever is left, so the last worker is not started at all when
969
+ * it could not finish in time. */
970
+ totalBudgetMs: z.number().int().positive().default(90_000),
971
+ /** Output cap for a vision answer, overriding the worker model's
972
+ * own `maxTokens`. A chat model's cap (16k and up) lets a
973
+ * reasoning worker think its way past the timeout while writing a
974
+ * caption. Raise it when you ask workers for long transcriptions. */
975
+ maxOutputTokens: z.number().int().positive().default(1_500),
976
+ /** How long a failed worker is skipped before being tried again.
977
+ * Without this, every single call pays the full timeout of a
978
+ * worker that is down for the rest of the afternoon. 0 disables
979
+ * the memory. */
980
+ healthCacheMs: z.number().int().min(0).default(60_000),
981
+ /** Cooldown after a TIMEOUT specifically. A worker that answers too
982
+ * slowly is not the same as one that is gone: it may be loading a
983
+ * model, or the picture may have been unusually large. Shorter by
984
+ * default so a slow answer does not sideline a good worker for a
985
+ * full minute. 0 means no cooldown for timeouts. */
986
+ timeoutCooldownMs: z.number().int().min(0).default(10_000),
987
+ })
988
+ .default({ timeoutMs: 60_000, healthCacheMs: 60_000, totalBudgetMs: 90_000, maxOutputTokens: 1_500, timeoutCooldownMs: 10_000 });
989
+
990
+ /** Normalise either accepted shape into the list the runtime walks. */
991
+ export function workerChain(ref: string | string[] | undefined): string[] {
992
+ if (!ref) return [];
993
+ return Array.isArray(ref) ? ref : [ref];
994
+ }
995
+ export type VisionConfig = z.infer<typeof VisionConfigSchema>;
996
+
997
+ // Speech-to-Text config. Standalone (not in providers.X.models) so the
998
+ // STT model never leaks into chat-model pickers, agent-config validation,
999
+ // or `/v1/models` — STT is a separate service surface, not "another
1000
+ // model to pick". The web mic button POSTs audio to `/stt/transcribe`,
1001
+ // somora forwards multipart to `providers[stt.provider].baseUrl +
1002
+ // /audio/transcriptions` (OpenAI-compatible STT endpoint, supported by
1003
+ // oMLX, faster-whisper-server, OpenAI itself, etc.).
1004
+ export const SttConfigSchema = z
1005
+ .object({
1006
+ /** Master toggle. When false (or block omitted), the /stt/transcribe
1007
+ * endpoint returns 503 and the web mic button auto-hides. */
1008
+ enabled: z.boolean().default(false),
1009
+ /** Name of an existing entry in `providers`. Reuses its baseUrl +
1010
+ * apiKey so connection details aren't duplicated. Provider must be
1011
+ * `openai-compatible` engine. */
1012
+ provider: z.string().min(1),
1013
+ /** Model id passed in the `model` field of the multipart request
1014
+ * (e.g. `mlx-community/whisper-large-v3-turbo`). Whatever string
1015
+ * the upstream STT server expects. */
1016
+ model: z.string().min(1),
1017
+ /** Optional default language hint (ISO 639-1: `de`, `en`, …). Whisper
1018
+ * auto-detects without it, but a hint cuts latency and prevents
1019
+ * language confusion on short utterances. */
1020
+ language: z.string().min(2).max(8).optional(),
1021
+ })
1022
+ .optional();
1023
+ export type SttConfig = z.infer<typeof SttConfigSchema>;
1024
+
1025
+ // Text-to-Speech config. Mirror-image of STT: somora proxies a
1026
+ // client-issued `text → audio` request to an OpenAI-compatible TTS
1027
+ // endpoint (oMLX, fish-audio, etc), caches the result, and serves
1028
+ // it back as audio bytes. Same as STT, the TTS model is NOT listed
1029
+ // in providers.X.models — it's a separate service surface, not "a
1030
+ // chat model to pick".
1031
+ //
1032
+ // Auto-TTS gating: the run-turn pipeline generates an
1033
+ // `assistant_audio` artifact only when ALL of (1) tts.enabled,
1034
+ // (2) the user message arrived via STT (input.modality === 'voice'),
1035
+ // (3) the client requested autoPlayRequested=true with that turn,
1036
+ // and (4) the assistant text passes the speech-sanitizer all hold.
1037
+ // Otherwise the chat behaves text-only.
1038
+ //
1039
+ // `/voice/turn` is independent of the auto-TTS gate: it's a
1040
+ // dedicated audio-in → audio-out endpoint that always generates TTS.
1041
+ export const TtsClientPolicySchema = z.object({
1042
+ /** Default for the per-session "auto-play voice replies" toggle. */
1043
+ autoPlayVoiceReplies: z.boolean().default(false),
1044
+ /** If false, the per-session toggle is hidden in the UI and the
1045
+ * default is forced. Use for kiosk-style installs. */
1046
+ allowUserOverride: z.boolean().default(true),
1047
+ });
1048
+ export type TtsClientPolicy = z.infer<typeof TtsClientPolicySchema>;
1049
+
1050
+ // ─────────────────────────────────────────────────────────────────────
1051
+ // Realtime voice (docs: private/realtime-voice-design.md)
1052
+ //
1053
+ // A standing, interruptible audio connection to a realtime model that
1054
+ // TALKS, while the real somora agent still does the work. Deliberately
1055
+ // separate from `stt`/`tts`: those turn one recording into one answer,
1056
+ // which is the thing this exists to replace.
1057
+ //
1058
+ // The provider decides the protocol — OpenAI's realtime API and
1059
+ // Google's BidiGenerateContent share no wire format (verified
1060
+ // 2026-09-11), and OpenRouter cannot carry either — so this block names
1061
+ // a provider and an adapter handles the rest.
1062
+ export const RealtimeVoiceConfigSchema = z
1063
+ .object({
1064
+ /** Master toggle. Off (or omitted) means: routes answer 503, the
1065
+ * /web tile is not rendered, no agent is callable. */
1066
+ enabled: z.boolean().default(false),
1067
+ /**
1068
+ * Which adapter, and therefore which protocol.
1069
+ *
1070
+ * `openai` and `local` are the SAME adapter: one talks to OpenAI,
1071
+ * the other to a service of your own that speaks the same session
1072
+ * and event language, named by `url` (required for `local`). A
1073
+ * second implementation of a protocol we already speak would drift
1074
+ * from this one within a week. `google` has no adapter yet — its
1075
+ * realtime API speaks something else entirely.
1076
+ */
1077
+ provider: z.enum(['openai', 'google', 'local']).default('openai'),
1078
+ /** Provider model id — never guessed, always configured. */
1079
+ model: z.string().min(1),
1080
+ /** Where the adapter reads its credential. A FILE, not the key
1081
+ * itself: a long-lived realtime key is the one secret that buys
1082
+ * minutes of billed audio, and config.yaml is read by more eyes
1083
+ * than a 600 file. */
1084
+ apiKeyFile: z.string().min(1).optional(),
1085
+ /**
1086
+ * Where the adapter connects. Optional: each adapter knows its own
1087
+ * service, and the OpenAI one defaults to
1088
+ * `wss://api.openai.com/v1/realtime`.
1089
+ *
1090
+ * Set it to point the SAME adapter at a different service that
1091
+ * speaks the same protocol — a local realtime server being the
1092
+ * reason this exists. The model id is appended as a query
1093
+ * parameter, as OpenAI expects it; a service that does not care can
1094
+ * ignore it. `ws://` is accepted so a service on localhost needs no
1095
+ * certificate; anything else must be `wss://`.
1096
+ */
1097
+ url: z
1098
+ .string()
1099
+ .min(1)
1100
+ .refine((u) => /^wss?:\/\//.test(u), {
1101
+ message: 'realtimeVoice.url must start with wss:// or ws://',
1102
+ })
1103
+ .optional(),
1104
+ /** Fallback: name of an existing `providers` entry to borrow the
1105
+ * key from. Only for providers that use the same credential. */
1106
+ provider_ref: z.string().min(1).optional(),
1107
+ // Only websocket is driven (audio browser → somora → provider);
1108
+ // the value is accepted for forward compatibility.
1109
+ transport: z.enum(['webrtc', 'websocket']).default('websocket'),
1110
+ /** Voice used when an agent names none. Provider-specific id. */
1111
+ defaultVoice: z.string().min(1).default('alloy'),
1112
+ /** How hard the voice self is held to asking the real agent before
1113
+ * answering anything of substance. `always` is the honest default
1114
+ * for a system whose whole point is that the AGENT knows things. */
1115
+ consultPolicy: z.enum(['auto', 'substantive', 'always']).default('always'),
1116
+ /**
1117
+ * How long a spoken question waits on the agent. A conversation
1118
+ * cannot wait on a build (live 2026-09-11): the consult waits
1119
+ * `lockPatienceMs` for the session lock, then `answerPatienceMs`
1120
+ * for the answer. Past either the work keeps running and lands in
1121
+ * the session; the voice gets a status it can say out loud. The
1122
+ * two constants moved here 2026-09-13 unchanged.
1123
+ */
1124
+ consult: z
1125
+ .object({
1126
+ /** How long a spoken question waits for its answer before the
1127
+ * call moves on (2026-09-13): the consult is queued like any
1128
+ * turn and waits this long in total — for the session and for
1129
+ * the answer. Past it the voice says it handed the request
1130
+ * over and keeps talking; the answer is read out when it
1131
+ * lands, or fetched when the user asks. */
1132
+ quickAnswerMs: z.number().int().min(1_000).max(120_000).default(8_000),
1133
+ /** Retired 2026-09-13 in favour of quickAnswerMs; read, warned
1134
+ * about, ignored. */
1135
+ lockPatienceMs: z.number().int().optional(),
1136
+ answerPatienceMs: z.number().int().optional(),
1137
+ })
1138
+ .default({ quickAnswerMs: 8_000 }),
1139
+ /** Hard stop for one call. The meter runs while nobody speaks, so
1140
+ * an open tab is a standing bill. */
1141
+ maxCallMinutes: z.number().int().min(1).max(180).default(20),
1142
+ /** Switching agent mid-call (a second tool). Off until the basic
1143
+ * call has proven itself. */
1144
+ allowAgentSwitch: z.boolean().default(false),
1145
+ /**
1146
+ * How easily the model lets itself be interrupted.
1147
+ *
1148
+ * Talking over it was hard in practice (Rene, 2026-09-12): the
1149
+ * provider decides an interruption has happened from its own voice
1150
+ * activity detection, and its defaults are tuned for a caller who
1151
+ * waits politely. Lower `threshold` reacts to quieter speech,
1152
+ * shorter `prefixPaddingMs` reacts sooner, shorter
1153
+ * `silenceDurationMs` ends YOUR turn sooner (that is the pause
1154
+ * before the model answers).
1155
+ */
1156
+ turnDetection: z
1157
+ .object({
1158
+ threshold: z.number().min(0).max(1).default(0.4),
1159
+ prefixPaddingMs: z.number().int().min(0).max(2_000).default(200),
1160
+ silenceDurationMs: z.number().int().min(100).max(5_000).default(420),
1161
+ })
1162
+ .default({ threshold: 0.4, prefixPaddingMs: 200, silenceDurationMs: 420 }),
1163
+ })
1164
+ .optional();
1165
+ export type RealtimeVoiceConfig = z.infer<typeof RealtimeVoiceConfigSchema>;
1166
+
1167
+ export const TtsConfigSchema = z
1168
+ .object({
1169
+ /** Master toggle. When false (or block omitted), /tts/* returns
1170
+ * 503 and play-buttons stay hidden client-side. */
1171
+ enabled: z.boolean().default(false),
1172
+ /** Name of an existing entry in `providers`. Reuses its baseUrl +
1173
+ * apiKey. Provider engine must be `openai-compatible`. */
1174
+ provider: z.string().min(1),
1175
+ /** Model id passed in the OpenAI-compatible /v1/audio/speech call.
1176
+ * Whatever string the upstream expects (e.g. `fish-audio-s2-pro-8bit`). */
1177
+ model: z.string().min(1),
1178
+ /** Optional voice/speaker selector. Forwarded to the upstream as
1179
+ * `voice`. Provider-specific; omit if your model uses one.
1180
+ * Note: many open-source TTS engines (incl. mlx-audio's fish-s2-pro
1181
+ * adapter) ignore this field — see `textPrefix` / `agentVoices`
1182
+ * for an inline-prefix mechanism that works with such engines. */
1183
+ voice: z.string().min(1).optional(),
1184
+ /** Optional default language hint (ISO 639-1). Forwarded as `language`. */
1185
+ language: z.string().min(2).max(8).optional(),
1186
+ /** Optional text-prefix prepended to EVERY synthesize input. Used
1187
+ * to inline speaker / emotion / style tags that the engine reads
1188
+ * as part of the text. Example for Fish Audio S2 Pro on mlx-audio:
1189
+ * textPrefix: "<|speaker:0|>"
1190
+ * Acts as the fallback when an agent doesn't have its own override
1191
+ * in `agentVoices`. */
1192
+ textPrefix: z.string().optional(),
1193
+ /** Optional per-agent text-prefix overrides. Key = agent name (e.g.
1194
+ * "naxon", "hans"); value = the prefix string to prepend to the
1195
+ * synthesize input when somora is generating audio FOR that agent.
1196
+ * Lookup order at synth time:
1197
+ * 1. agentVoices[<agent>] → use it
1198
+ * 2. else textPrefix → use it
1199
+ * 3. else no prefix
1200
+ * The prefix flows into the cache-key, so different speakers get
1201
+ * different cached audio files for the same reply text. */
1202
+ agentVoices: z
1203
+ .record(
1204
+ z.string().regex(/^[A-Za-z0-9_-]+$/, 'agent name must match [A-Za-z0-9_-]+'),
1205
+ z.string(),
1206
+ )
1207
+ .default({}),
1208
+ /** Cache settings for generated audio. */
1209
+ cache: z
1210
+ .object({
1211
+ /** Days a cached audio file lingers after creation. 0 disables
1212
+ * GC entirely (manual cleanup only). */
1213
+ retentionDays: z.number().int().min(0).max(3650).default(7),
1214
+ /** Hard cap on the cache directory size. Older files evicted
1215
+ * first when exceeded. */
1216
+ maxSizeMB: z.number().int().min(1).default(500),
1217
+ })
1218
+ .default({ retentionDays: 7, maxSizeMB: 500 }),
1219
+ /** Optional re-encode pipeline. When enabled, somora can serve
1220
+ * opus/m4a on top of the upstream's native WAV via ffmpeg. */
1221
+ reencode: z
1222
+ .object({
1223
+ enabled: z.boolean().default(true),
1224
+ opusBitrateKbps: z.number().int().min(8).max(256).default(24),
1225
+ })
1226
+ .default({ enabled: true, opusBitrateKbps: 24 }),
1227
+ /** Per-client defaults for the auto-play feature. The web + mobile
1228
+ * PWA clients read this on first session-open to seed their
1229
+ * per-session localStorage toggle. */
1230
+ clients: z
1231
+ .object({
1232
+ web: TtsClientPolicySchema.default({
1233
+ autoPlayVoiceReplies: false,
1234
+ allowUserOverride: true,
1235
+ }),
1236
+ mobile: TtsClientPolicySchema.default({
1237
+ autoPlayVoiceReplies: false,
1238
+ allowUserOverride: true,
1239
+ }),
1240
+ })
1241
+ .default({
1242
+ web: { autoPlayVoiceReplies: false, allowUserOverride: true },
1243
+ mobile: { autoPlayVoiceReplies: false, allowUserOverride: true },
1244
+ }),
1245
+ })
1246
+ .optional();
1247
+ export type TtsConfig = z.infer<typeof TtsConfigSchema>;
1248
+
1249
+ // Image generation. Same standalone shape as stt/tts and for the same
1250
+ // reason: an image model is a separate service surface, not "another
1251
+ // chat model to pick". Listing them in providers.X.models would leak
1252
+ // them into model pickers, persona validation and /v1/models, where
1253
+ // they'd be selectable as a conversation model and fail on the first
1254
+ // turn.
1255
+ //
1256
+ // Wire target is the OpenAI-shaped image endpoint (`POST <baseUrl>/images`
1257
+ // — OpenRouter's /api/v1/images, OpenAI's /v1/images/generations). The
1258
+ // chat.completions + `modalities: ["image"]` route is deliberately NOT
1259
+ // supported: it has no structured spec fields, so aspect ratio and
1260
+ // resolution would degrade to prose inside the prompt.
1261
+ //
1262
+ // Spec validation is capability-driven, not hardcoded — see
1263
+ // src/imagegen/capabilities.ts. Allowed values differ per model (grok
1264
+ // renders 1K/2K only, others do 512/4K), so the truth comes from the
1265
+ // provider's model catalog at runtime, with `allow` below as the
1266
+ // offline override.
1267
+ export const ImageSpecDefaultsSchema = z
1268
+ .object({
1269
+ resolution: z.string().min(1).optional(),
1270
+ aspect_ratio: z.string().min(1).optional(),
1271
+ /** Explicit pixels (`1024x1024`). Some endpoints size images this
1272
+ * way and have no `resolution` tier at all, so it has to be
1273
+ * settable as a default like any other spec. */
1274
+ size: z.string().min(1).optional(),
1275
+ /** Sampling knobs, for backends that expose them. Defaults belong
1276
+ * to the model, so setting one here is for the rare case where an
1277
+ * operator wants a different house style than the model ships. */
1278
+ steps: z.number().int().positive().optional(),
1279
+ cfg: z.number().optional(),
1280
+ guidance: z.number().optional(),
1281
+ quality: z.string().min(1).optional(),
1282
+ output_format: z.string().min(1).optional(),
1283
+ background: z.string().min(1).optional(),
1284
+ })
1285
+ .strict()
1286
+ .default({});
1287
+ export type ImageSpecDefaults = z.infer<typeof ImageSpecDefaultsSchema>;
1288
+
1289
+ export const ImageModelSchema = z.object({
1290
+ /** Short handle used by the tool's `model` arg and the UI picker.
1291
+ * Deliberately NOT the wire id — agents and humans shouldn't have to
1292
+ * type `x-ai/grok-imagine-image-2.0` to pick a model. */
1293
+ name: z
1294
+ .string()
1295
+ .regex(/^[A-Za-z0-9_-]+$/, 'image model name must match [A-Za-z0-9_-]+'),
1296
+ /** Name of an existing entry in `providers`. Reuses its baseUrl +
1297
+ * apiKey. Provider engine must be `openai-compatible`. */
1298
+ provider: z.string().min(1),
1299
+ /** Model id sent in the request's `model` field. */
1300
+ model: z.string().min(1),
1301
+ /** Human-readable label for the UI picker. Falls back to `name`. */
1302
+ label: z.string().min(1).optional(),
1303
+ /** Path appended to the provider's baseUrl. Defaults to `/images`
1304
+ * (OpenRouter). OpenAI direct wants `/images/generations`, and a
1305
+ * local server may sit anywhere — hence configurable rather than
1306
+ * guessed from the hostname. */
1307
+ endpoint: z.string().min(1).default('/images'),
1308
+ /**
1309
+ * Which request dialect this endpoint speaks. Only matters once
1310
+ * reference images are involved — plain generation is the same JSON
1311
+ * POST everywhere:
1312
+ *
1313
+ * openrouter — references ride as base64 in an `input_references`
1314
+ * array on the same JSON body.
1315
+ * openai — references make it a DIFFERENT request: multipart
1316
+ * to the edit endpoint, one `image[]` part per file.
1317
+ * This is what OpenAI itself accepts and what LiteLLM
1318
+ * passes through to a local image backend.
1319
+ *
1320
+ * There is no autodetection. A wrong guess here fails at the worst
1321
+ * possible moment (after the user waited for a render), and the
1322
+ * operator configuring the model knows the answer.
1323
+ */
1324
+ wire: z.enum(['openrouter', 'openai']).default('openrouter'),
1325
+ /** Path for the reference-image (edit) request, appended to baseUrl.
1326
+ * `wire: openai` only. Defaults to the OpenAI/LiteLLM path. */
1327
+ editEndpoint: z.string().min(1).default('/images/edits'),
1328
+ /**
1329
+ * Handle of another image model to try when this one is UNAVAILABLE.
1330
+ * Chains: the fallback may name a fallback of its own.
1331
+ *
1332
+ * Availability only — a rejected spec value or an empty prompt is the
1333
+ * caller's mistake and the next model would reject it too (or worse,
1334
+ * quietly accept and ignore it). Only an unreachable, timing-out or
1335
+ * server-erroring endpoint moves the request along.
1336
+ *
1337
+ * The case this exists for: image models live on a GPU box that runs
1338
+ * one profile at a time, so "the model is configured" and "the model
1339
+ * is loaded right now" are different questions, and the endpoint
1340
+ * answers the second one with a 503.
1341
+ */
1342
+ fallback: z.string().min(1).optional(),
1343
+ /** Path for the model-capability catalog, appended to baseUrl.
1344
+ * Defaults to `/images/models` (OpenRouter). Set to null when the
1345
+ * provider has none — validation then falls back to `allow`, or to
1346
+ * permissive if that's unset too. */
1347
+ capabilitiesEndpoint: z.string().min(1).nullable().default('/images/models'),
1348
+ /** Specs applied when the caller omits them. Validated against the
1349
+ * model's real capabilities like any other spec — a stale default
1350
+ * surfaces as a startup-time warning, not a runtime surprise. */
1351
+ defaults: ImageSpecDefaultsSchema,
1352
+ /** Offline capability override. Set this when the provider has no
1353
+ * discoverable model catalog (a local image server) or when its
1354
+ * catalog is wrong. Takes precedence over discovery. */
1355
+ allow: z
1356
+ .object({
1357
+ // One entry per ENUMERABLE_SPEC_FIELDS (src/imagegen/types.ts).
1358
+ // The two lists have to be kept in step by hand; `background`
1359
+ // was missing here and silently ignored, which is the whole
1360
+ // reason this block is `.strict()` below.
1361
+ resolution: z.array(z.string().min(1)).optional(),
1362
+ aspect_ratio: z.array(z.string().min(1)).optional(),
1363
+ size: z.array(z.string().min(1)).optional(),
1364
+ quality: z.array(z.string().min(1)).optional(),
1365
+ output_format: z.array(z.string().min(1)).optional(),
1366
+ background: z.array(z.string().min(1)).optional(),
1367
+ /**
1368
+ * The complete set of parameter names this model accepts. Same
1369
+ * meaning as a catalog's published list: present ⇒ authoritative,
1370
+ * and a field missing from it is rejected before a request goes
1371
+ * out. Absent ⇒ unknown, and everything is let through.
1372
+ *
1373
+ * This is the only way to get that guarantee out of a provider
1374
+ * with no model catalog. Without it, a field the endpoint doesn't
1375
+ * read is simply ignored on the far side and the caller gets an
1376
+ * image that quietly disregards what was asked for.
1377
+ */
1378
+ supported: z.array(z.string().min(1)).min(1).optional(),
1379
+ maxN: z.number().int().min(1).max(10).optional(),
1380
+ maxReferences: z.number().int().min(0).max(16).optional(),
1381
+ })
1382
+ // Strict on purpose: a stray or misspelled key here would be
1383
+ // dropped without a word, and the operator would be looking at a
1384
+ // restriction that does nothing.
1385
+ .strict()
1386
+ .optional(),
1387
+ });
1388
+ export type ImageModel = z.infer<typeof ImageModelSchema>;
1389
+
1390
+ export const ImageGenConfigSchema = z
1391
+ .object({
1392
+ /** Master toggle. When false (or block omitted), the image tools
1393
+ * stay unavailable, /images/* returns 503 and the desktop tile
1394
+ * auto-hides — same gate shape as wiki/tts. */
1395
+ enabled: z.boolean().default(false),
1396
+ /** Canonical destination for EVERY generated image, regardless of
1397
+ * which agent triggered it. Deliberately absolute rather than
1398
+ * workspace-relative: the gallery and the file-serving route index
1399
+ * one directory, and a per-agent workspace would scatter images
1400
+ * across several. A caller-supplied destination gets a hardlink on
1401
+ * top (see src/imagegen/store.ts), not a second copy. */
1402
+ outputDir: z.string().min(1).default('~/somoraworkspace/images'),
1403
+ /** Bucket files into `<outputDir>/YYYY-MM/`. Off by default —
1404
+ * nesting only starts paying off in the hundreds, and filenames
1405
+ * already sort chronologically. */
1406
+ monthlyFolders: z.boolean().default(false),
1407
+ /** Cost brake. Counts images (not calls) generated within one turn;
1408
+ * the tool refuses past this and tells the agent to ask its human.
1409
+ * Without it, an agent with imageReview: always that keeps
1410
+ * "improving" the result bills real money in a loop. */
1411
+ maxImagesPerTurn: z.number().int().min(1).max(100).default(5),
1412
+ /** Wall-clock cap for one upstream request. Image models are slow —
1413
+ * a 4K render legitimately takes minutes, so this sits far above
1414
+ * the usual HTTP timeouts. */
1415
+ timeoutMs: z.number().int().min(5_000).max(1_800_000).default(300_000),
1416
+ /** Configured image models. First entry is the default when a
1417
+ * caller omits `model`. */
1418
+ models: z.array(ImageModelSchema).min(1),
1419
+ })
1420
+ .optional();
1421
+ export type ImageGenConfig = z.infer<typeof ImageGenConfigSchema>;
1422
+
1423
+ // Video generation. Same standalone shape as imageGen and for the same
1424
+ // reason, plus one that is specific to video: a render takes minutes on
1425
+ // a GPU, so these models must never be reachable as a conversation
1426
+ // model by accident.
1427
+ //
1428
+ // The lifecycle is what separates video from images: create a job, poll
1429
+ // it, then download the result. That is three requests instead of one,
1430
+ // and every provider spells them differently — hence `wire`.
1431
+ export const VideoWireSchema = z.enum(['openai', 'passthrough', 'veo']);
1432
+ export type VideoWire = z.infer<typeof VideoWireSchema>;
1433
+
1434
+ export const VideoModelSchema = z.object({
1435
+ /** Short handle used by the tool's `model` arg and the UI picker. */
1436
+ name: z
1437
+ .string()
1438
+ .regex(/^[A-Za-z0-9_-]+$/, 'video model name must match [A-Za-z0-9_-]+'),
1439
+ /** Name of an existing entry in `providers`. Reuses its baseUrl +
1440
+ * apiKey. Provider engine must be `openai-compatible`. */
1441
+ provider: z.string().min(1),
1442
+ /** Model id sent in the request's `model` field. */
1443
+ model: z.string().min(1),
1444
+ label: z.string().min(1).optional(),
1445
+ /**
1446
+ * Which lifecycle dialect this endpoint speaks. All three do the same
1447
+ * three things; they differ in where the job id lives and what the
1448
+ * status field is called.
1449
+ *
1450
+ * openai — POST /videos, GET /videos/{id},
1451
+ * GET /videos/{id}/content?variant=… (id in the PATH)
1452
+ * passthrough — POST /vid/create, GET /vid/status?id=,
1453
+ * GET /vid/content?id=&variant=… (id in the QUERY)
1454
+ * The shape a proxy can forward without rewriting
1455
+ * paths, which is why a router in front of a local
1456
+ * backend ends up here.
1457
+ * veo — Google Vertex AI: predictLongRunning returns an
1458
+ * OPERATION NAME rather than a job id, polling asks
1459
+ * whether the operation is `done`, and the result
1460
+ * arrives as a GCS URI or inline bytes rather than
1461
+ * from a content endpoint.
1462
+ *
1463
+ * NOTE ON `veo`: implemented against Google's published shape but NOT
1464
+ * yet verified against a live endpoint — somora has had no Vertex
1465
+ * access to test with. Treat it as a prepared seam: the structure is
1466
+ * here so adding Veo is a config entry rather than a refactor, but do
1467
+ * not assume it works until someone has run it once. Every other
1468
+ * dialect in this file was measured against a real endpoint before
1469
+ * being called done.
1470
+ */
1471
+ wire: VideoWireSchema.default('openai'),
1472
+ /** Path that creates a job, appended to the provider's baseUrl. */
1473
+ createEndpoint: z.string().min(1).optional(),
1474
+ /** Path that reports job state. */
1475
+ statusEndpoint: z.string().min(1).optional(),
1476
+ /** Path that yields the finished bytes. */
1477
+ contentEndpoint: z.string().min(1).optional(),
1478
+ /** Model catalog, appended to baseUrl. Null when the provider has
1479
+ * none — OpenAI publishes no video catalog, so `allow` is the truth
1480
+ * there. */
1481
+ capabilitiesEndpoint: z.string().min(1).nullable().default(null),
1482
+ /** Specs applied when the caller omits them. */
1483
+ defaults: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),
1484
+ /** Offline capability override — same meaning as imageGen's. */
1485
+ allow: z
1486
+ .object({
1487
+ supported: z.array(z.string().min(1)).min(1).optional(),
1488
+ /** Content variants this provider serves. `thumbnail` is what
1489
+ * lets a gallery show a frame and an agent judge its own output
1490
+ * through analyze_file. */
1491
+ variants: z.array(z.string().min(1)).min(1).optional(),
1492
+ aspect_ratio: z.array(z.string().min(1)).optional(),
1493
+ size: z.array(z.string().min(1)).optional(),
1494
+ maxSeconds: z.number().positive().optional(),
1495
+ maxReferences: z.number().int().min(0).max(4).optional(),
1496
+ })
1497
+ .strict()
1498
+ .optional(),
1499
+ /** Handle of another video model to try when this one is unavailable.
1500
+ * Availability only, exactly as for images. */
1501
+ fallback: z.string().min(1).optional(),
1502
+ });
1503
+ export type VideoModel = z.infer<typeof VideoModelSchema>;
1504
+
1505
+ export const VideoGenConfigSchema = z
1506
+ .object({
1507
+ enabled: z.boolean().default(false),
1508
+ outputDir: z.string().min(1).default('~/somoraworkspace/videos'),
1509
+ monthlyFolders: z.boolean().default(false),
1510
+ /**
1511
+ * How many renders somora keeps in flight across ALL agents.
1512
+ * Global on purpose: a GPU is a shared resource and a per-agent
1513
+ * budget would let four agents occupy twelve slots. When the cap is
1514
+ * reached the next caller is turned away with a clear message
1515
+ * rather than queued — waiting silently for an unknown number of
1516
+ * minutes is worse than being told to come back.
1517
+ */
1518
+ maxConcurrent: z.number().int().min(1).max(32).default(4),
1519
+ /** How often a running job is polled. */
1520
+ pollIntervalMs: z.number().int().min(1000).default(8000),
1521
+ /** A job that hasn't finished by then is given up on. Renders run
1522
+ * minutes, and a stuck job would otherwise hold a slot forever. */
1523
+ jobTimeoutMs: z.number().int().positive().default(45 * 60_000),
1524
+ /** Per-request budget for create/status/content calls themselves —
1525
+ * not for the render, which is what the job timeout covers. */
1526
+ requestTimeoutMs: z.number().int().positive().default(120_000),
1527
+ models: z.array(VideoModelSchema).min(1),
1528
+ })
1529
+ .optional();
1530
+ export type VideoGenConfig = z.infer<typeof VideoGenConfigSchema>;
1531
+
1532
+ /** Resolve a video-model handle to its config entry + provider. */
1533
+ export function resolveVideoModel(
1534
+ config: Config,
1535
+ name?: string,
1536
+ ): { entry: VideoModel; provider: Provider; providerName: string } | null {
1537
+ const models = config.videoGen?.models;
1538
+ if (!models || models.length === 0) return null;
1539
+ const entry = name ? models.find((m) => m.name === name) : models[0];
1540
+ if (!entry) return null;
1541
+ const provider = config.providers[entry.provider];
1542
+ if (!provider) return null;
1543
+ return { entry, provider, providerName: entry.provider };
1544
+ }
1545
+
1546
+ /** Resolve an image-model handle to its config entry + provider.
1547
+ * Returns null for unknown handles so callers can produce an error
1548
+ * that lists what IS configured. */
1549
+ export function resolveImageModel(
1550
+ config: Config,
1551
+ name?: string,
1552
+ ): { entry: ImageModel; provider: Provider; providerName: string } | null {
1553
+ const models = config.imageGen?.models;
1554
+ if (!models || models.length === 0) return null;
1555
+ const entry = name ? models.find((m) => m.name === name) : models[0];
1556
+ if (!entry) return null;
1557
+ const provider = config.providers[entry.provider];
1558
+ if (!provider) return null;
1559
+ return { entry, provider, providerName: entry.provider };
1560
+ }
1561
+
1562
+ // Projects — pointer-file index over existing storage locations
1563
+ // (Obsidian, local paths, URLs, remote resources). Each project is a
1564
+ // Markdown+frontmatter file under ~/.somora/projects/<slug>.md; a
1565
+ // session can pin one as its current focus, and the pointer-list lands
1566
+ // in the system prompt so the agent knows which paths matter.
1567
+ //
1568
+ // Entities are a CONTROLLED VOCABULARY — projects belong to one entity
1569
+ // (e.g. "privat", "enovom"), and at write time the agent's chosen
1570
+ // entity is validated against this list. Prevents STT mishearings from
1571
+ // inventing new phantom entities ("enofhom" silently becomes a new
1572
+ // category). The list is intentionally USER-curated and edited in
1573
+ // config.yaml — agents cannot extend it via tools.
1574
+ export const ProjectEntitySchema = z.object({
1575
+ slug: z
1576
+ .string()
1577
+ .regex(/^[a-z0-9_-]+$/, 'entity slug must match [a-z0-9_-]+'),
1578
+ label: z.string().min(1),
1579
+ });
1580
+ export type ProjectEntity = z.infer<typeof ProjectEntitySchema>;
1581
+
1582
+ export const ProjectsConfigSchema = z
1583
+ .object({
1584
+ /** Master toggle. When false (or block omitted) the project tools,
1585
+ * slash-commands, HTTP routes and UI surfaces are all dormant.
1586
+ * Existing setups don't change behavior until the operator opts in. */
1587
+ enabled: z.boolean().default(false),
1588
+ /** Curated entity list. Required when enabled. With enabled=true
1589
+ * but entities=[], project_create errors with "no entities
1590
+ * configured" — anti-foot-gun (better than silently letting the
1591
+ * agent pick any string). */
1592
+ entities: z.array(ProjectEntitySchema).default([]),
1593
+ })
1594
+ .optional();
1595
+ export type ProjectsConfig = z.infer<typeof ProjectsConfigSchema>;
1596
+
1597
+ // Sentinel — proactive trigger runtime config. Phase 1 has a single
1598
+ // knob: how long to keep completed/error triggers around before the
1599
+ // scheduler garbage-collects them. Set to 0 to disable GC entirely
1600
+ // (triggers + history are never auto-removed; user/agent has to
1601
+ // delete manually). Default 7 days = balance between clean list and
1602
+ // usable history for debugging.
1603
+ export const SentinelConfigSchema = z
1604
+ .object({
1605
+ /** Days to retain `completed` triggers (one-shot `at` fires that
1606
+ * have already run, OR daily-cap auto-paused via `paused`/`error`
1607
+ * paths that haven't been resumed). Counted from `lastFireAt`.
1608
+ * Defaults to 7. Set to 0 to disable auto-GC. */
1609
+ completedRetentionDays: z.number().int().min(0).max(3650).default(7),
1610
+ })
1611
+ .default({ completedRetentionDays: 7 });
1612
+ export type SentinelConfig = z.infer<typeof SentinelConfigSchema>;
1613
+
1614
+ // Skills budget. Mirrors OpenClaw's defaults — they've shipped 53 real
1615
+ // skills against these limits for months, so we treat them as known-
1616
+ // good rather than re-deriving. Configurable via config.yaml per
1617
+ // `feedback_config_over_env.md`. See `private/skills-design.md`.
1618
+ export const SkillsConfigSchema = z
1619
+ .object({
1620
+ /** Hard cap on number of skills surfaced in the system-prompt
1621
+ * registry. Beyond this, the registry-renderer falls back to
1622
+ * compact format (name+description only). */
1623
+ maxSkillsInPrompt: z.number().int().positive().default(150),
1624
+ /** Char budget for the rendered registry block. Compact-format
1625
+ * fallback kicks in if XML rendering would exceed this. */
1626
+ maxPromptChars: z.number().int().positive().default(18_000),
1627
+ /** Per-file size limit for SKILL.md when activated via the Skill
1628
+ * tool. Skills with larger bodies fail to load with an error. */
1629
+ maxSkillFileBytes: z.number().int().positive().default(256_000),
1630
+ /** Skill-scoped env injection for local exec. When true (default),
1631
+ * env vars declared by ANY skill (`requires.env_vars`) are stripped
1632
+ * from exec children and re-injected only into commands that invoke
1633
+ * one of that skill's `requires.bins`. False restores the legacy
1634
+ * behavior (full process-env inheritance incl. somora.env secrets
1635
+ * in every exec child). See src/skills/env-scope.ts. */
1636
+ envScoping: z.boolean().default(true),
1637
+ })
1638
+ .default({
1639
+ maxSkillsInPrompt: 150,
1640
+ maxPromptChars: 18_000,
1641
+ maxSkillFileBytes: 256_000,
1642
+ // Keep in lockstep with the field defaults above — this literal is
1643
+ // what a config.yaml WITHOUT a `skills:` block gets.
1644
+ envScoping: true,
1645
+ });
1646
+
1647
+ // Obsidian Vault — server-global since 2026.05.08.8 (was per-agent
1648
+ // before). Single shared vault for all agents. Markdown content gets
1649
+ // indexed as a recall source; the wiki layer (Phase 4) lives in a
1650
+ // designated subfolder.
1651
+ export const ObsidianConfigSchema = z
1652
+ .object({
1653
+ /** Absolute path (or `~`-prefixed) to the Obsidian vault. When
1654
+ * unset, no vault is wired up — agents work with own memory only. */
1655
+ vault: z.string().min(1).optional(),
1656
+ })
1657
+ .default({});
1658
+ export type ObsidianConfig = z.infer<typeof ObsidianConfigSchema>;
1659
+
1660
+ // Wiki-System (Phase 4) — long-term shared knowledge in an Obsidian
1661
+ // vault subfolder, written by Deep, audited by Lucid, read by all
1662
+ // agents. See `private/dream-system-v2.md` for the full design.
1663
+ //
1664
+ // `enabled: false` is the default so existing setups don't change
1665
+ // behavior until the operator opts in.
1666
+ // Anti-clobber guard for Deep's MERGE path. The Deep prompt asks the
1667
+ // worker model to return the FULL updated page body; on large pages a
1668
+ // model may silently summarize instead of integrating, and the caller
1669
+ // would write that shrunken body as the new page. Real incident
1670
+ // 2026-07-13 on an external instance: a 22 KB page came back as 2.7 KB
1671
+ // and the pre-existing content was lost (Deep auto-applies, so no human
1672
+ // saw it). The guard compares body sizes before writing and refuses the
1673
+ // merge when the result shrank past `minRatio`.
1674
+ //
1675
+ // `minExistingBytes` exempts small pages: on a 400-byte stub a rewrite
1676
+ // to 150 bytes is normal editing, not a catastrophe, and blocking it
1677
+ // would just stall consolidation.
1678
+ export const WikiMergeShrinkGuardSchema = z
1679
+ .object({
1680
+ enabled: z.boolean().default(true),
1681
+ /** Refuse the merge when newBody < existingBody * minRatio. */
1682
+ minRatio: z.number().positive().max(1).default(0.5),
1683
+ /** Pages smaller than this (bytes of body) are never guarded. */
1684
+ minExistingBytes: z.number().int().nonnegative().default(2000),
1685
+ })
1686
+ .default({ enabled: true, minRatio: 0.5, minExistingBytes: 2000 });
1687
+ export type WikiMergeShrinkGuard = z.infer<typeof WikiMergeShrinkGuardSchema>;
1688
+
1689
+ export const WikiDeepConfigSchema = z
1690
+ .object({
1691
+ enabled: z.boolean().default(true),
1692
+ /** Real-clock cadence for Deep (Memory → Wiki consolidation). */
1693
+ intervalHours: z.number().positive().default(12),
1694
+ /** Worker model for Deep. Format `<provider>/<modelId>`. */
1695
+ model: z.string().min(1).optional(),
1696
+ /** Deep auto-applies (no approval). Reserved as bool in case we
1697
+ * ever need to flip back on. */
1698
+ requireApproval: z.boolean().default(false),
1699
+ /** Optional thinking-level for the Deep LLM one-shot. When set and
1700
+ * the worker model declares the 'reasoning' capability, the call
1701
+ * forwards effort/reasoning_effort per engine. Unset = engine
1702
+ * default (no thinking). */
1703
+ thinking: ThinkingLevelSchema.optional(),
1704
+ /** Anti-clobber guard on the MERGE write path. */
1705
+ mergeShrinkGuard: WikiMergeShrinkGuardSchema,
1706
+ /** How long a cached "skip" stands for an UNCHANGED memory note.
1707
+ * The skip was decided against the wiki as it was that day — "too
1708
+ * thin for a page of its own" stops being true once the page
1709
+ * exists. After this many days the note is looked at again (one
1710
+ * LLM call; skipped again, it rests for another period). 0 = a
1711
+ * skip stands until the note changes. */
1712
+ skipCacheDays: z.number().int().min(0).max(3650).default(30),
1713
+ /** A page this large is not merged into any more: Deep files the
1714
+ * note as a sub-page under it instead (Rene, 2026-09-29: "so große
1715
+ * Seiten sollten nie entstehen" — the migration had folded 97
1716
+ * reports into one 100 KB page). */
1717
+ maxPageChars: z.number().int().min(5_000).default(50_000),
1718
+ })
1719
+ .default({
1720
+ enabled: true,
1721
+ intervalHours: 12,
1722
+ requireApproval: false,
1723
+ mergeShrinkGuard: { enabled: true, minRatio: 0.5, minExistingBytes: 2000 },
1724
+ skipCacheDays: 30,
1725
+ maxPageChars: 50_000,
1726
+ });
1727
+
1728
+ export const WikiLucidConfigSchema = z
1729
+ .object({
1730
+ enabled: z.boolean().default(true),
1731
+ intervalDays: z.number().positive().default(7),
1732
+ /** Worker model for Lucid (wiki cleanup / contradiction detection). */
1733
+ model: z.string().min(1).optional(),
1734
+ /** Lucid findings need user approval before wiki-edits apply.
1735
+ * Approval happens via `dream_list` / `dream_get` / `dream_apply`
1736
+ * / `dream_dismiss` — any agent with the `dream` toolset can
1737
+ * review platform-wide Lucid runs. */
1738
+ requireApproval: z.boolean().default(true),
1739
+ /** Optional thinking-level for the Lucid LLM one-shot. Semantics
1740
+ * identical to wiki.deep.thinking. */
1741
+ thinking: ThinkingLevelSchema.optional(),
1742
+ /** Per-turn cap on `wiki_*` tool invocations from the Lucid loop
1743
+ * holder. Prevents the model from batch-editing many pages in
1744
+ * one turn without per-page user confirmation. The cap resets
1745
+ * on every user turn. Raise if you regularly OK multi-page
1746
+ * plans and find the default of 3 cuts off legitimate work;
1747
+ * lower if you want stricter check-in-with-user enforcement. */
1748
+ maxCallsPerTurn: z.number().int().positive().default(3),
1749
+ /** How much page text one Lucid call carries at most (characters;
1750
+ * a page larger than this travels alone). One call per folder used
1751
+ * to be the rule; after a migration onto the template the big
1752
+ * folders are cut into parts of this size. */
1753
+ batchChars: z.number().int().min(10_000).default(100_000),
1754
+ /** Pages over this many characters are reported as `oversized_page`
1755
+ * (only in a wiki on the template). */
1756
+ oversizedChars: z.number().int().min(5_000).default(50_000),
1757
+ /** How many findings a run keeps for review at most. Every call may
1758
+ * answer with up to 8; with the wiki cut into ninety calls that is
1759
+ * more than a person walks through. Kept by weight: contradictions,
1760
+ * dead refs, duplicates, misfiled and oversized pages, wanted pages
1761
+ * first — link suggestions fill what is left. */
1762
+ maxFindings: z.number().int().min(1).default(12),
1763
+ /** Link suggestions are set by Lucid itself (first plain mention →
1764
+ * [[link]]) instead of waiting for review; at most this many per run. */
1765
+ autoLinks: z.boolean().default(true),
1766
+ autoLinksPerRun: z.number().int().min(0).default(30),
1767
+ /** A finding a person dismissed is not filed again for this many days. */
1768
+ seenDays: z.number().int().min(0).default(90),
1769
+ })
1770
+ .default({
1771
+ enabled: true,
1772
+ intervalDays: 7,
1773
+ requireApproval: true,
1774
+ maxCallsPerTurn: 3,
1775
+ batchChars: 100_000,
1776
+ oversizedChars: 50_000,
1777
+ maxFindings: 12,
1778
+ autoLinks: true,
1779
+ autoLinksPerRun: 30,
1780
+ seenDays: 90,
1781
+ });
1782
+
1783
+ export const WikiSearchConfigSchema = z
1784
+ .object({
1785
+ /** Score multipliers applied to the fused hybrid score per source.
1786
+ * Higher = ranked first. Wiki at 1.4 is intentional: BM25-only matches
1787
+ * on short keyword queries (e.g. "garten") only reach ~0.3 hybrid
1788
+ * before boost, so wiki-curated pages need a lift to surface above
1789
+ * noisier memory chunks that vector-recall happens to pick up. */
1790
+ boostWiki: z.number().positive().default(1.4),
1791
+ boostMemory: z.number().positive().default(0.85),
1792
+ boostVault: z.number().positive().default(0.65),
1793
+ /** Char budget for the wiki-overview block. It is snapshotted once
1794
+ * per session into the system prompt (not re-injected per turn), so
1795
+ * this is paid once inside the cached prefix — 4000 keeps page names
1796
+ * visible for wikis up to roughly 120 pages before the overview
1797
+ * degrades to section names + counts. Raise it to keep page names on
1798
+ * a larger wiki; the cost is a bigger constant prefix. */
1799
+ overviewMaxChars: z.number().int().positive().default(4000),
1800
+ /** Cap on how many `## sections` survive in the last-resort overview
1801
+ * (section names + page counts) when even the bare page list exceeds
1802
+ * overviewMaxChars. The largest sections win. */
1803
+ overviewTopNSlugs: z.number().int().positive().default(30),
1804
+ })
1805
+ .default({
1806
+ boostWiki: 1.4,
1807
+ boostMemory: 0.85,
1808
+ boostVault: 0.65,
1809
+ overviewMaxChars: 4000,
1810
+ overviewTopNSlugs: 30,
1811
+ });
1812
+
1813
+ export const WikiConfigSchema = z
1814
+ .object({
1815
+ enabled: z.boolean().default(false),
1816
+ /** Path relative to each agent's vault root where the somora wiki
1817
+ * lives. Dream-B writes here; everything else in the vault is
1818
+ * read-only for somora. */
1819
+ vaultSubfolder: z.string().min(1).default('somora'),
1820
+ /** Language of the wiki scaffolding: section headings, page types,
1821
+ * default subfolders, index/log wording and the language Deep
1822
+ * writes page prose in. `de` is the historical default; existing
1823
+ * installations keep it. See src/wiki/language.ts. */
1824
+ language: z.enum(['de', 'en']).default('de'),
1825
+ /** Subdirs Deep uses by default. Unset → the language's set
1826
+ * (de: personen/projekte/wissen, en: people/projects/knowledge).
1827
+ * New subdirs may be created on demand when topics don't fit. */
1828
+ defaultSubdirs: z.array(z.string().min(1)).optional(),
1829
+ deep: WikiDeepConfigSchema,
1830
+ lucid: WikiLucidConfigSchema,
1831
+ search: WikiSearchConfigSchema,
1832
+ })
1833
+ .default({
1834
+ enabled: false,
1835
+ vaultSubfolder: 'somora',
1836
+ language: 'de',
1837
+ deep: {
1838
+ enabled: true,
1839
+ intervalHours: 12,
1840
+ requireApproval: false,
1841
+ mergeShrinkGuard: { enabled: true, minRatio: 0.5, minExistingBytes: 2000 },
1842
+ skipCacheDays: 30,
1843
+ maxPageChars: 50_000,
1844
+ },
1845
+ lucid: {
1846
+ enabled: true,
1847
+ intervalDays: 7,
1848
+ requireApproval: true,
1849
+ maxCallsPerTurn: 3,
1850
+ batchChars: 100_000,
1851
+ oversizedChars: 50_000,
1852
+ maxFindings: 12,
1853
+ autoLinks: true,
1854
+ autoLinksPerRun: 30,
1855
+ seenDays: 90,
1856
+ },
1857
+ search: {
1858
+ // Keep in lockstep with WikiSearchConfigSchema's defaults above —
1859
+ // this literal is what a config.yaml WITHOUT a `wiki:` block gets.
1860
+ // (1.0 here was a typo that silently weakened wiki ranking for
1861
+ // exactly those installs; found in the 2026-07-22 investigation.)
1862
+ boostWiki: 1.4,
1863
+ boostMemory: 0.85,
1864
+ boostVault: 0.65,
1865
+ overviewMaxChars: 4000,
1866
+ overviewTopNSlugs: 30,
1867
+ },
1868
+ });
1869
+ export type WikiConfig = z.infer<typeof WikiConfigSchema>;
1870
+
1871
+ // TLS — switches the server from plain HTTP/1.1 to HTTP/2-over-TLS.
1872
+ // HTTP/2 multiplexes all streams (SSE, fetch, future WebSocket) over a
1873
+ // single TCP connection, dodging the 6-per-origin browser limit that
1874
+ // otherwise caps how many chat windows + tmux attaches a user can open.
1875
+ //
1876
+ // somora's only supported deployment for HTTPS is **Tailscale**: run
1877
+ // `tailscale cert <your-tailnet-fqdn>` to get Let's-Encrypt-signed
1878
+ // certs for free, then point cert/key at the resulting files. Tailscale
1879
+ // certs are publicly trusted (Node + browsers accept them out of the
1880
+ // box) and renew via the same one-shot command. Setups without
1881
+ // Tailscale would need to plug in their own CA — secure-context-only
1882
+ // browser APIs (mic, screenshare, clipboard, push) require HTTPS too,
1883
+ // so this is a hard prerequisite for those features.
1884
+ export const TlsConfigSchema = z
1885
+ .object({
1886
+ /** Path to TLS certificate file (PEM). When set together with `key`,
1887
+ * the server listens on HTTP/2-over-TLS instead of plain HTTP. `~`
1888
+ * expands to $HOME. */
1889
+ cert: z.string().min(1),
1890
+ /** Path to TLS private key file (PEM). `~` expands to $HOME. */
1891
+ key: z.string().min(1),
1892
+ /** External hostname clients should use to reach the server — must
1893
+ * match the cert's CN/SAN, otherwise strict TLS verification will
1894
+ * reject the connection. Used by the MCP-child fallback caller in
1895
+ * src/tools/agents/spawn.ts (which switches from plain-HTTP
1896
+ * loopback to HTTPS once TLS is on) and surfaced in client docs.
1897
+ * Example: `<your-host>.<your-tailnet>.ts.net`. */
1898
+ publicHost: z.string().min(1),
1899
+ /** `tailscale`: the server asks Tailscale for a fresh certificate
1900
+ * before the current one runs out (checked twice a day) and loads
1901
+ * it without a restart. Needs `tailscale cert` to work for the
1902
+ * user somora runs as (`sudo tailscale set --operator=$USER`).
1903
+ * Absent: the files are only watched — whoever renews them, the
1904
+ * server picks the new pair up on its next check. */
1905
+ renew: z.enum(['tailscale']).optional(),
1906
+ })
1907
+ .optional();
1908
+ export type TlsConfig = z.infer<typeof TlsConfigSchema>;
1909
+
1910
+ // Attachments — caps + per-turn count for user-uploaded files (Y.B).
1911
+ // Defaults pick the LOWEST-COMMON-DENOMINATOR across all engines:
1912
+ // image: 5 MB (Anthropic ceiling)
1913
+ // pdf: 32 MB (Anthropic ceiling)
1914
+ // text: 1 MB (file_read fallback ceiling)
1915
+ // Operators with a fleet that can handle bigger files raise these
1916
+ // in config; nobody who runs against Anthropic ever has to lower
1917
+ // them. maxPerTurn is a UX-sanity cap well under any engine's
1918
+ // hard limit (Anthropic 100, OpenAI ~50, codex/omlx undocumented).
1919
+ /** Language servers for builder agents (docs/lsp.md): after file_write /
1920
+ * file_patch the server's errors ride on the tool result. */
1921
+ export const LspServerConfigSchema = z
1922
+ .object({
1923
+ enabled: z.boolean().default(true),
1924
+ /** Executable to run instead of the one found under ~/.somora/lsp or PATH. */
1925
+ command: z.string().min(1).optional(),
1926
+ })
1927
+ .strict();
1928
+ export const LspConfigSchema = z
1929
+ .object({
1930
+ enabled: z.boolean().default(true),
1931
+ /** How long a write waits for the server's verdict (ms). The first
1932
+ * verdict of a project waits longer (the server loads the project). */
1933
+ waitMs: z.number().int().min(200).max(60_000).default(3000),
1934
+ servers: z.record(z.string(), LspServerConfigSchema).default({}),
1935
+ })
1936
+ .default({ enabled: true, waitMs: 3000, servers: {} });
1937
+
1938
+ export const AttachmentsConfigSchema = z
1939
+ .object({
1940
+ maxImageBytes: z.number().int().positive().default(5 * 1024 * 1024),
1941
+ maxPdfBytes: z.number().int().positive().default(32 * 1024 * 1024),
1942
+ maxTextBytes: z.number().int().positive().default(1 * 1024 * 1024),
1943
+ maxPerTurn: z.number().int().positive().default(10),
1944
+ })
1945
+ .default({
1946
+ maxImageBytes: 5 * 1024 * 1024,
1947
+ maxPdfBytes: 32 * 1024 * 1024,
1948
+ maxTextBytes: 1 * 1024 * 1024,
1949
+ maxPerTurn: 10,
1950
+ });
1951
+ export type AttachmentsConfig = z.infer<typeof AttachmentsConfigSchema>;
1952
+
1953
+ // External MCP servers (design: private/mcp-hub-design.md). The main
1954
+ // server is the single MCP client ("hub"); discovered tools are bridged
1955
+ // into the ToolRegistry and proxied to claude-cli/codex-cli via the MCP
1956
+ // child. Phase 1: remote HTTP servers, tools-only.
1957
+ //
1958
+ // Server-name charset deliberately EXCLUDES underscore: the
1959
+ // `mcp__<server>__<tool>` convention parses/strips on `__`, and both
1960
+ // somora's shortToolName regex and the reverse-parse in other clients
1961
+ // break when the server segment itself contains `_`. Hyphens only.
1962
+ // Auth for MCP servers whose credential is an OAuth login that expires
1963
+ // and must be refreshed (design: private/mcp-hub-design.md §4.8). The
1964
+ // credential is NOT in config.yaml — it lives in a JSON file written by
1965
+ // an interactive login (e.g. Claude Code's `/design-login`), keyed by a
1966
+ // top-level property. The hub reads the access token from there and
1967
+ // refreshes it against `tokenEndpoint` when it nears expiry, writing the
1968
+ // rotated token back. This is the generic mechanism; `preset` below
1969
+ // fills it in for known services.
1970
+ export const McpOAuthRefreshSchema = z.object({
1971
+ type: z.literal('oauth-refresh'),
1972
+ /** JSON file holding the credential. Default: somora's claude-home
1973
+ * `.credentials.json` (where `/design-login` writes). `~` expands. */
1974
+ credentialFile: z.string().optional(),
1975
+ /**
1976
+ * Top-level key in that file, e.g. `designOauth`. An ordered LIST is
1977
+ * also accepted, and the first key actually present in the file wins.
1978
+ *
1979
+ * That exists because a provider can move the goalposts: Claude
1980
+ * Design authenticated off the ordinary login until Anthropic split
1981
+ * out a `user:design:*` scope, after which only the separate
1982
+ * `/design-login` credential works. A list survives the change in
1983
+ * either direction without an operator editing config — and without
1984
+ * somora pinning a constant that upstream then invalidates.
1985
+ */
1986
+ credentialKey: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
1987
+ /** OAuth token endpoint for the refresh_token grant. */
1988
+ tokenEndpoint: z.string().url(),
1989
+ /** Whether the hub may refresh the token ITSELF — `true` for every
1990
+ * key, `false` for none, or a LIST of the keys it owns. Set false /
1991
+ * leave a key out when the credential is owned by another process
1992
+ * that rotates it (the Claude CLI's own `claudeAiOauth` login): two
1993
+ * refreshers racing on one rotating refresh-token chain invalidate
1994
+ * each other. Read-only mode just re-reads the file on every connect
1995
+ * and relies on the owner (plus somora's credential sync) to keep it
1996
+ * fresh.
1997
+ *
1998
+ * The list form is what the claude-design preset uses: `designOauth`
1999
+ * is somora's to refresh (nothing else keeps it alive — it expired
2000
+ * daily and needed a manual `/design-login`, 2026-08-31 report),
2001
+ * `claudeAiOauth` stays the CLI's. */
2002
+ refresh: z.union([z.boolean(), z.array(z.string().min(1))]).default(true),
2003
+ });
2004
+ export type McpOAuthRefresh = z.infer<typeof McpOAuthRefreshSchema>;
2005
+
2006
+ export const McpServerConfigSchema = z.object({
2007
+ /** Known-service preset — fills url/auth/headers so the operator only
2008
+ * writes `preset: claude-design`. Explicit fields still override. */
2009
+ preset: z.enum(['claude-design']).optional(),
2010
+ /** Phase 1 supports remote HTTP only (streamable-http with automatic
2011
+ * SSE-legacy fallback). `stdio` is Phase 2. */
2012
+ transport: z.literal('http').default('http'),
2013
+ // Optional when a preset supplies it; validated as URL post-expansion.
2014
+ url: z.string().url().optional(),
2015
+ /** Refreshable-OAuth auth (see McpOAuthRefreshSchema). Omit for
2016
+ * static-header / no-auth servers. */
2017
+ auth: McpOAuthRefreshSchema.optional(),
2018
+ /** Static request headers. Values support `${VAR}` / `${VAR:-default}`
2019
+ * env expansion at connect time — `Authorization: "Bearer ${TOKEN}"`
2020
+ * is the idiom for API-key auth. Missing vars fail the connect (state
2021
+ * `failed`), never the config load. */
2022
+ headers: z.record(z.string(), z.string()).default({}),
2023
+ enabled: z.boolean().default(true),
2024
+ /** Which upstream tools to import. Empty include = all. Exclude wins. */
2025
+ tools: z
2026
+ .object({
2027
+ include: z.array(z.string()).default([]),
2028
+ exclude: z.array(z.string()).default([]),
2029
+ })
2030
+ .default({ include: [], exclude: [] }),
2031
+ /** Per tools/call timeout. */
2032
+ timeoutMs: z.number().int().positive().default(60_000),
2033
+ connectTimeoutMs: z.number().int().positive().default(15_000),
2034
+ /** Registry-side cap on the stringified result (DEFAULT_MAX_RESULT_SIZE_CHARS). */
2035
+ maxResultChars: z.number().int().positive().optional(),
2036
+ /** Servers are called serially by default — many MCP servers mishandle
2037
+ * concurrent requests. Opt in per server only when it's known-safe. */
2038
+ supportsParallelToolCalls: z.boolean().default(false),
2039
+ });
2040
+ export type McpServerConfig = z.infer<typeof McpServerConfigSchema>;
2041
+
2042
+ export const McpConfigSchema = z
2043
+ .object({
2044
+ servers: z
2045
+ .record(
2046
+ z
2047
+ .string()
2048
+ // Proxy children register as `somora-<name>`; somora's own
2049
+ // server is `somora`, so no external name can collide with it.
2050
+ .regex(
2051
+ /^[a-z0-9][a-z0-9-]{0,29}$/,
2052
+ 'MCP server name must match [a-z0-9][a-z0-9-]{0,29} (no underscores)',
2053
+ ),
2054
+ McpServerConfigSchema,
2055
+ )
2056
+ .default({}),
2057
+ })
2058
+ .default({ servers: {} });
2059
+ export type McpConfig = z.infer<typeof McpConfigSchema>;
2060
+
2061
+ /**
2062
+ * Thinking content — the model's reasoning text shown in the clients
2063
+ * (web bubble block, TUI `/verbose thinking`). `capture: false` drops
2064
+ * it at the server: no SSE event, no JSONL row, nothing for any client
2065
+ * to show. `maxChars` caps what is persisted per turn (a Qwen turn at
2066
+ * xhigh can think for tens of thousands of tokens). See docs/thinking.md.
2067
+ */
2068
+ export const ThinkingContentSchema = z
2069
+ .object({
2070
+ capture: z.boolean().default(true),
2071
+ maxChars: z.number().int().positive().default(65_536),
2072
+ })
2073
+ .default({ capture: true, maxChars: 65_536 });
2074
+
2075
+ // Shared browser — a managed Chromium per agent profile that agents drive
2076
+ // through the `browser` tool and the user can watch and take over in the
2077
+ // web client. Design: private/browser-design.md. Off by default: it
2078
+ // needs a Chromium on the host.
2079
+ export const BrowserConfigSchema = z
2080
+ .object({
2081
+ enabled: z.boolean().default(false),
2082
+ /** Chromium/Chrome binary. Unset = auto-detect (chromium, chromium-browser,
2083
+ * google-chrome, Chrome.app …); the error says what was tried. */
2084
+ executablePath: z.string().min(1).optional(),
2085
+ /**
2086
+ * Run Chromium with a window instead of headless. Headless Chromium
2087
+ * announces itself ("HeadlessChrome" user agent, navigator.webdriver);
2088
+ * headed does not. On a host without a display somora starts an Xvfb
2089
+ * per browser (system package, see docs/setup.md); without Xvfb the
2090
+ * browser refuses to start — no silent headless fallback.
2091
+ */
2092
+ headed: z.boolean().default(false),
2093
+ /** Extra Chromium launch flags, appended verbatim (e.g. a proxy or
2094
+ * window size). Process-wide; take effect on the next browser start. */
2095
+ extraArgs: z.array(z.string().min(1)).default([]),
2096
+ /** Open tabs per browser (= per profile). The ninth `open` is refused. */
2097
+ maxTabsPerAgent: z.number().int().min(1).max(32).default(8),
2098
+ /** A browser with no tool call and no viewer for this long is stopped;
2099
+ * its profile (cookies, logins) stays on disk. */
2100
+ idleStopMinutes: z.number().int().min(1).default(30),
2101
+ viewport: z
2102
+ .object({ width: z.number().int().min(320).default(1280), height: z.number().int().min(240).default(800) })
2103
+ .default({ width: 1280, height: 800 }),
2104
+ /** Screencast to the web client (stage 2). */
2105
+ stream: z
2106
+ .object({ quality: z.number().int().min(10).max(100).default(60), maxFps: z.number().int().min(1).max(30).default(15) })
2107
+ .default({ quality: 60, maxFps: 15 }),
2108
+ /**
2109
+ * Where agents may navigate. Public hosts are allowed unless denied.
2110
+ * Private networks (RFC1918, loopback, link-local, ULA) are BLOCKED
2111
+ * unless the host or CIDR is listed in `allowPrivate` — a page an
2112
+ * agent reads could otherwise steer it to an internal service.
2113
+ * Hostnames are resolved before the check; `file:`/`chrome:` never.
2114
+ */
2115
+ allowPrivate: z.array(z.string().min(1)).default([]),
2116
+ /** Hostnames (exact or `*.suffix`) never navigated to. */
2117
+ deny: z.array(z.string().min(1)).default([]),
2118
+ /**
2119
+ * Named profiles shared by several agents. Without an entry every
2120
+ * agent has its own profile (`~/.somora/browser/profiles/<agent>`);
2121
+ * a shared profile means shared cookies AND shared tabs.
2122
+ */
2123
+ profiles: z.record(z.string().regex(/^[a-z0-9][a-z0-9_-]*$/), z.object({ agents: z.array(z.string().min(1)).min(1) })).default({}),
2124
+ })
2125
+ .default({
2126
+ enabled: false,
2127
+ headed: false,
2128
+ extraArgs: [],
2129
+ maxTabsPerAgent: 8,
2130
+ idleStopMinutes: 30,
2131
+ viewport: { width: 1280, height: 800 },
2132
+ stream: { quality: 60, maxFps: 15 },
2133
+ allowPrivate: [],
2134
+ deny: [],
2135
+ profiles: {},
2136
+ });
2137
+ export type BrowserConfig = z.infer<typeof BrowserConfigSchema>;
2138
+
2139
+ export const ConfigSchema = z.object({
2140
+ thinkingContent: ThinkingContentSchema,
2141
+ server: z
2142
+ .object({
2143
+ // Bind address. Default loopback (private, anti-footgun). Set
2144
+ // `0.0.0.0` to accept LAN/Tailscale clients — an explicit,
2145
+ // auditable opt-in that lives in config.yaml so it survives
2146
+ // `somora update` (unlike a SOMORA_HOST env var in the systemd
2147
+ // unit, which the update rebake drops). Env `SOMORA_HOST` still
2148
+ // overrides this at runtime if set.
2149
+ host: z.string().min(1).default('127.0.0.1'),
2150
+ port: z.number().int().positive().default(18737),
2151
+ tls: TlsConfigSchema,
2152
+ })
2153
+ .default({ host: '127.0.0.1', port: 18737 }),
2154
+ providers: z.record(z.string().regex(/^[A-Za-z0-9_-]+$/), ProviderSchema),
2155
+ compaction: CompactionConfigSchema,
2156
+ memory: MemoryConfigSchema,
2157
+ rem: RemGlobalConfigSchema,
2158
+ /**
2159
+ * Model outages are remembered for every cascade (chat fallback, REM
2160
+ * workers, compaction workers): a model that was unreachable is not
2161
+ * tried again for this many minutes; a success clears the note early
2162
+ * (naxon/Rene, 2026-09-27 — a swapped GPU profile keeps models away
2163
+ * for hours, and every turn paid the dead hops again).
2164
+ */
2165
+ fallback: z
2166
+ .object({ retryUnavailableMinutes: z.number().int().min(1).max(24 * 60).default(60) })
2167
+ .default({ retryUnavailableMinutes: 60 }),
2168
+ agentLoop: AgentLoopConfigSchema,
2169
+ promptBudgets: PromptBudgetsSchema,
2170
+ engineWatchdog: EngineWatchdogConfigSchema,
2171
+ sse: SseConfigSchema,
2172
+ tmux: TmuxConfigSchema,
2173
+ claudeCli: ClaudeCliConfigSchema,
2174
+ codexCli: CodexCliConfigSchema,
2175
+ tui: TuiConfigSchema,
2176
+ mobile: MobileConfigSchema,
2177
+ web: WebConfigSchema,
2178
+ workspace: WorkspaceConfigSchema,
2179
+ resources: ResourcesConfigSchema,
2180
+ skills: SkillsConfigSchema,
2181
+ vision: VisionConfigSchema,
2182
+ stt: SttConfigSchema,
2183
+ tts: TtsConfigSchema,
2184
+ realtimeVoice: RealtimeVoiceConfigSchema,
2185
+ imageGen: ImageGenConfigSchema,
2186
+ videoGen: VideoGenConfigSchema,
2187
+ browser: BrowserConfigSchema,
2188
+ projects: ProjectsConfigSchema,
2189
+ sentinel: SentinelConfigSchema,
2190
+ obsidian: ObsidianConfigSchema,
2191
+ wiki: WikiConfigSchema,
2192
+ attachments: AttachmentsConfigSchema,
2193
+ lsp: LspConfigSchema,
2194
+ mcp: McpConfigSchema,
2195
+ });
2196
+ export type Config = z.infer<typeof ConfigSchema>;
2197
+
2198
+ // A resolved (provider, model) pair — what the engine adapter receives at turn time.
2199
+ export interface ResolvedModel {
2200
+ providerName: string;
2201
+ provider: Provider;
2202
+ modelId: string;
2203
+ model: Model;
2204
+ }
2205
+
2206
+ export function resolveModelRef(config: Config, ref: string): ResolvedModel | null {
2207
+ const slash = ref.indexOf('/');
2208
+ if (slash < 0) return null;
2209
+ const providerName = ref.slice(0, slash);
2210
+ const modelId = ref.slice(slash + 1);
2211
+ const provider = config.providers[providerName];
2212
+ if (!provider) return null;
2213
+ const model = provider.models.find((m) => m.id === modelId);
2214
+ if (!model) return null;
2215
+ return { providerName, provider, modelId, model };
2216
+ }
2217
+
2218
+ /**
2219
+ * Resolve a string ref to a model. Tries (in order): alias → provider/id → bare id.
2220
+ * Aliases are global and take precedence; bare ids are backwards-compat for older
2221
+ * AGENTS.md files written before the provider/id format existed.
2222
+ */
2223
+ export function resolveAnyRef(config: Config, ref: string): ResolvedModel | null {
2224
+ // 1. alias lookup (global unique)
2225
+ for (const [providerName, provider] of Object.entries(config.providers)) {
2226
+ for (const model of provider.models) {
2227
+ if (model.alias === ref) {
2228
+ return { providerName, provider, modelId: model.id, model };
2229
+ }
2230
+ }
2231
+ }
2232
+ // 2. provider/modelId
2233
+ if (ref.includes('/')) return resolveModelRef(config, ref);
2234
+ // 3. bare modelId (backwards-compat)
2235
+ for (const [providerName, provider] of Object.entries(config.providers)) {
2236
+ const model = provider.models.find((m) => m.id === ref);
2237
+ if (model) return { providerName, provider, modelId: ref, model };
2238
+ }
2239
+ return null;
2240
+ }
2241
+
2242
+ /**
2243
+ * Human-readable list of every model ref the config accepts — for error
2244
+ * messages when a ref doesn't resolve, so the caller (usually an agent
2245
+ * that guessed a name) can self-correct without reading config.yaml.
2246
+ * Format per model: `alias → provider/modelId` or bare `provider/modelId`.
2247
+ */
2248
+ export function describeModelRefs(config: Config): string {
2249
+ const out: string[] = [];
2250
+ for (const [providerName, provider] of Object.entries(config.providers)) {
2251
+ for (const model of provider.models) {
2252
+ const ref = `${providerName}/${model.id}`;
2253
+ out.push(model.alias ? `${model.alias} → ${ref}` : ref);
2254
+ }
2255
+ }
2256
+ return out.join(', ');
2257
+ }
2258
+
2259
+ /**
2260
+ * Enumerate every (provider, model) pair in the config as a ResolvedModel.
2261
+ * Used by compaction to pick a worker model with appropriate context
2262
+ * window (DECISION #21a) — independent of which model the current
2263
+ * turn is on.
2264
+ */
2265
+ export function listAllModels(config: Config): ResolvedModel[] {
2266
+ const list: ResolvedModel[] = [];
2267
+ for (const [providerName, provider] of Object.entries(config.providers)) {
2268
+ for (const model of provider.models) {
2269
+ list.push({ providerName, provider, modelId: model.id, model });
2270
+ }
2271
+ }
2272
+ return list;
2273
+ }
2274
+
2275
+ /**
2276
+ * Walks the config and asserts that no alias is shared by two models.
2277
+ * Throws with a descriptive error if duplicates are found.
2278
+ */
2279
+ export function assertUniqueAliases(config: Config): void {
2280
+ const seen = new Map<string, string>();
2281
+ for (const [providerName, provider] of Object.entries(config.providers)) {
2282
+ for (const model of provider.models) {
2283
+ if (!model.alias) continue;
2284
+ const previous = seen.get(model.alias);
2285
+ const here = `${providerName}/${model.id}`;
2286
+ if (previous) {
2287
+ throw new Error(`alias '${model.alias}' is used by both '${previous}' and '${here}' — aliases must be globally unique`);
2288
+ }
2289
+ seen.set(model.alias, here);
2290
+ }
2291
+ }
2292
+ }