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,373 @@
1
+ # Prompt-Cache Strategy
2
+
3
+ > How somora keeps prefix-cache hit rates high across the three engine
4
+ > adapters and the dream worker. Why it matters, how it works, where
5
+ > the bodies are buried.
6
+
7
+ ## The problem
8
+
9
+ Every modern LLM provider implements some form of **prefix cache**:
10
+ the inference engine remembers the KV-cache state for the longest
11
+ exact-token prefix it has seen recently and reuses it on the next
12
+ request. For long-running conversations that share a stable prefix
13
+ (system prompt, tools list, accumulated history), the cache turns
14
+ re-encoding cost from O(N) to O(new tokens only).
15
+
16
+ The win is huge:
17
+
18
+ - **Anthropic** charges 10% of fresh-input price for cached tokens.
19
+ A 20k-token system+history that hits cache costs ~$0.30 instead
20
+ of ~$3.00 per turn on Opus.
21
+ - **Local models (mlx-omx, ollama)** save the full pre-encode pass
22
+ on cached tokens. On a local 30B-class model at 30-50 tok/s, a
23
+ 20k-token cached prefix means **6-10 seconds less time-to-first-token**.
24
+ - **OpenAI** discounts cached input by 50% on supported models.
25
+
26
+ **The trap:** cache works on **byte-identical prefix matching**. Any
27
+ per-turn change in the prompt — even a single character — invalidates
28
+ the cache from that point onward. Get the prompt structure wrong and
29
+ every turn re-encodes the whole prior conversation.
30
+
31
+ Memory recall is the most common per-turn variable. Dump it in the
32
+ wrong place and cache dies.
33
+
34
+ ## The three-engine landscape
35
+
36
+ somora has three engine adapters with very different cache mechanics:
37
+
38
+ | Engine | Backend | Cache scope |
39
+ |---|---|---|
40
+ | `claude-cli` | Anthropic via SDK, stateful resumed session | SDK manages internal session state; we send only the new user message; Anthropic cache_control on system+tools holds across turns |
41
+ | `codex-cli` | OpenAI via the bundled Codex app-server, stateful via `thread/resume <thread_id>` | Codex remembers history internally; we send only new content; Codex's API call to OpenAI gets full prefix cache |
42
+ | `openai-compatible` | Anything (mlx-omx, ollama, OpenAI, vLLM, ...), stateless | We reconstruct the full conversation from JSONL on every call; the request must be byte-identical to prior calls for the prefix to match |
43
+
44
+ The first two are stateful — the underlying CLI/SDK preserves session
45
+ state, and we just hand it the next user message. Cache works
46
+ naturally because the API call's prefix is whatever the backend
47
+ already saw.
48
+
49
+ `openai-compatible` is the hard case. There's no session resumption.
50
+ We rebuild the entire conversation array from JSONL and send it.
51
+ Byte-identity across turns is on us.
52
+
53
+ ## What belongs in the prefix vs. the per-turn block
54
+
55
+ Before asking *where* a block goes, ask whether it changes with the
56
+ question:
57
+
58
+ | | Example | Goes to |
59
+ |---|---|---|
60
+ | Changes per turn | memory hits for this query | `<memory-context>`, per turn |
61
+ | Stable for the session | wiki topology overview, skills registry, persona | system prompt |
62
+
63
+ Getting this wrong is expensive in a way that hides well. Take the
64
+ wiki overview: it is byte-identical on every turn. Carried in the
65
+ per-turn memory block it is a duplicate per turn on
66
+ `claude-cli`/`codex-cli`, and on `openai-compatible` — where
67
+ `buildMessages` replays every past turn — it is re-sent once per turn
68
+ *of history*: 900 chars × 27 turns = 24 KB on every single request,
69
+ for something that has not changed since turn 1.
70
+
71
+ The system-prompt version is measurably free after the first turn.
72
+ `claude-cli`, fresh session:
73
+
74
+ ```
75
+ turn 1 tokens_in 9081 cached 878
76
+ turn 2 tokens_in 9696 cached 9079 ← 94% of the prefix
77
+ ```
78
+
79
+ The corollary: a block in the prefix must not move. The wiki overview
80
+ is snapshotted into `session.meta.json` on the first turn and reused
81
+ verbatim afterwards, even after Deep rewrites `index.md`. Freshness
82
+ there is worth less than the cache — and recall (`memory_search`,
83
+ auto-injection) is live regardless.
84
+
85
+ ## Where memory recall goes per engine
86
+
87
+ The runtime injects a `<memory-context>...</memory-context>` block per
88
+ turn that contains the top-N memory hits for the current query. Each
89
+ engine handles it differently:
90
+
91
+ ### claude-cli (stateful)
92
+
93
+ ```ts
94
+ // src/engine/claude-cli.ts
95
+ const memoryBlock = ephemeralContext ? `${ephemeralContext}\n\n` : '';
96
+ const effectiveUserMessage = replayPrefix + memoryBlock + userMessage;
97
+
98
+ // systemPromptForTurn = systemPrompt unchanged
99
+ SDK.query({ systemPrompt, userMessage: effectiveUserMessage });
100
+ ```
101
+
102
+ `ephemeralContext` already carries the turn's frame (an A2A header,
103
+ a sentinel evidence block) ahead of the recall block, composed by the
104
+ server (`src/server/turn-framing.ts`); the adapter adds nothing.
105
+ Memory lives at the **start of the new user-message text**. The SDK
106
+ sends only the new turn to Anthropic; the persistent system prompt
107
+ stays stable across turns; Anthropic's `cache_control` ephemeral
108
+ breakpoint on the system block holds. Hits 95-98% cache after the
109
+ first turn.
110
+
111
+ ### codex-cli (stateful)
112
+
113
+ ```ts
114
+ // src/engine/codex-cli.ts — one app-server process per turn
115
+ thread/start | thread/resume { developerInstructions: systemPrompt + tool guidance, dynamicTools, config }
116
+ turn/start { input: [ text: ephemeral + replayPrefix + userMessage, localImage… ], effort }
117
+ ```
118
+
119
+ The system prompt travels as Codex *developer instructions* on every
120
+ thread start/resume (stable across turns), the tool schemas as dynamic
121
+ tools, and only the new turn as user input. Memory lands at the start of
122
+ the user text. Codex keeps the thread and sends it to its OpenAI backend
123
+ with the right cache shape. Hits ~70–85% cache (128k of 153k input
124
+ cached on a six-tool turn).
125
+
126
+ ### openai-compatible (stateless)
127
+
128
+ This is where it gets interesting. We persist the memory block on
129
+ the `user_message` JSONL event — together with the turn's frame (an
130
+ A2A header, a sentinel evidence block, the instructions beside a
131
+ wake-up; see `user_message` in [api.md](api.md)), which goes in the
132
+ same field ahead of the recall block:
133
+
134
+ ```jsonc
135
+ {"kind":"user_message","ts":..."text":"the user typed this","ephemeral":"<memory-context>...</memory-context>"}
136
+ ```
137
+
138
+ When `buildMessages` rebuilds the conversation for the next API call,
139
+ it reads the `ephemeral` field off each historic user_message and
140
+ prepends it to the message content:
141
+
142
+ ```ts
143
+ // src/engine/openai-compatible.ts:buildMessages()
144
+ if (ev.kind === 'user_message') {
145
+ // A row with `origin` carries its A2A header inside `ephemeral`;
146
+ // an older row never stored it, so it is added here as before.
147
+ const headed = ev.origin ? ev.text : withFromAgentHeader(ev.text, ev.from_agent, ev.from_session);
148
+ const composed = ev.ephemeral ? `${ev.ephemeral}\n\n${headed}` : headed;
149
+ // → user message content is byte-identical to what was sent at turn N
150
+ }
151
+ ```
152
+
153
+ Result: the entire prior conversation reconstructs to the same byte
154
+ sequence the backend already cached. Cache match holds across the
155
+ full history; only the new user message is fresh.
156
+
157
+ The trade-off is JSONL size: each user_message stores the recall
158
+ block alongside the user-typed text (~500-2000 chars per turn).
159
+ Acceptable cost for the cache win.
160
+
161
+ #### Tool history
162
+
163
+ Turns that used tools are replayed in the **native** OpenAI shape: an
164
+ assistant message carrying `tool_calls`, followed by one `role:'tool'`
165
+ message per result.
166
+
167
+ ```jsonc
168
+ {"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function",
169
+ "function":{"name":"file_write","arguments":"{\"path\":\"tetris.js\"}"}}]}
170
+ {"role":"tool","tool_call_id":"c1","content":"{\"ok\":true}"}
171
+ {"role":"assistant","content":"Fertig, läuft auf Port 3020."}
172
+ ```
173
+
174
+ Flattening those turns to prose is not a neutral simplification. Measured
175
+ against a real session history, N=20 per cell: with tool turns
176
+ flattened, deepseek-chat produced **0/20** tool calls and deepseek-r1
177
+ **1/20**; replaying the native shape lifted them to **14/20** and
178
+ **10/20**. A model has no memory beyond what the rebuild hands it, so a
179
+ transcript in which the assistant never calls tools is a demonstration
180
+ that here, one does not call tools.
181
+
182
+ Two rules keep providers from rejecting the request:
183
+
184
+ - every `tool_calls` entry is immediately followed by its matching
185
+ `role:'tool'` message, in order;
186
+ - calls with no recorded result are **dropped** — a crashed turn leaves
187
+ exactly that, and an unmatched call is a hard 400 on most backends.
188
+
189
+ Tool results are capped at `MAX_REPLAYED_TOOL_RESULT_CHARS` (800) each.
190
+ Unbounded results are what bloated the context in the first place; the
191
+ model can re-read anything it needs by calling the tool again.
192
+
193
+ This is cache-safe: the reconstruction is deterministic over immutable
194
+ JSONL events, so repeated rebuilds of the same history are byte-identical
195
+ and the prefix match holds.
196
+
197
+ ### Why a late system message does not work
198
+
199
+ The obvious alternative — inject memory as a SECOND `role:'system'`
200
+ message right before the latest user message, keeping the persistent
201
+ system prompt stable — works for stateful engines but **does not work
202
+ for stateless openai-compatible**. An instrumented two-turn dump shows
203
+ why:
204
+
205
+ - Turn 1 sent: `[sys persona] [sys eph_v1] [user_eins]`
206
+ - Turn 2 sent: `[sys persona] [user_eins] [asst_eins] [sys eph_v2] [user_zwei]`
207
+ - Position 1 mismatch (turn 1: sys eph_v1, turn 2: user_eins) → cache stops at position 0
208
+
209
+ The dynamic memory block "wanders" through the message array as
210
+ history grows. Whatever position it sits at now becomes a different
211
+ message at that position next turn.
212
+
213
+ **Lesson:** for stateless prompt-cache, variable content must sit at
214
+ the **very end** of the prompt sequence, with no per-turn-changing
215
+ content earlier in the byte stream.
216
+
217
+ JSONL persistence is what makes this hold: by persisting the memory
218
+ block on each user_message, the "variable" content for prior turns
219
+ becomes effectively stable (frozen at original send-time) on every
220
+ subsequent reconstruction.
221
+
222
+ ## Dream-worker cache
223
+
224
+ The REM extractor (`src/dream/rem-extract.ts`) runs the same problem
225
+ in miniature: per-chunk LLM calls send a stable system prompt + a
226
+ user message containing transcript + memory + vault. Memory and
227
+ vault are computed **once per dream run** and reused across all
228
+ chunks. Transcript varies per chunk.
229
+
230
+ The user message is therefore built stable-first:
231
+
232
+ ```
233
+ Agent name: <your-agent>
234
+ <existing_memory>... stable ...</existing_memory> ← cached chunks 2..N
235
+ <vault_referenced>... stable ...</vault_referenced> ← cached chunks 2..N
236
+ <transcript>... per-chunk ...</transcript> ← variable, end of prompt
237
+ ```
238
+
239
+ Transcript-first would be the same anti-pattern as above: variable
240
+ content shifts the stable blocks to different byte positions across
241
+ chunks, and memory + vault (~4-15k tokens combined) are re-encoded
242
+ every chunk instead of cached.
243
+
244
+ For long sessions that chunk into 5+ pieces on local models, this
245
+ saves multiple seconds per chunk.
246
+
247
+ ## Configuration
248
+
249
+ Per-provider on `openai-compatible` providers in `config.yaml`:
250
+
251
+ ```yaml
252
+ providers:
253
+ local:
254
+ engine: openai-compatible
255
+ baseUrl: ...
256
+ apiKey: ...
257
+ memoryInjectMode: inline-user # default — JSONL-persistence + reconstruct
258
+ models: [...]
259
+
260
+ some-quirky-backend:
261
+ engine: openai-compatible
262
+ baseUrl: ...
263
+ apiKey: ...
264
+ memoryInjectMode: system # fallback — concat-onto-system
265
+ models: [...]
266
+ ```
267
+
268
+ Two values:
269
+
270
+ - `inline-user` (default) — memory persisted on each user_message,
271
+ reconstructed byte-identical on every call. Cache-friendly. Works
272
+ for any backend that accepts standard OpenAI Chat Completions
273
+ message arrays.
274
+ - `system` — concat-onto-system-prompt. Cache-destructive.
275
+ Only set this if a backend mishandles embedded memory blocks
276
+ inside user-message content (rare).
277
+
278
+ `claude-cli` and `codex-cli` have no `memoryInjectMode` knob — their
279
+ backend is deterministic, the right placement is hardcoded.
280
+
281
+ ## Verifying cache strategy changes
282
+
283
+ `cached_tokens` reporting in API responses is **unreliable** across
284
+ backends:
285
+
286
+ - mlx-omx returns `cached_tokens: null` even when the cache is
287
+ actively being used (verified via byte-identical direct curl).
288
+ Their dashboard shows hits but the API field stays null.
289
+ - OpenAI nests it as `prompt_tokens_details.cached_tokens`.
290
+ - Anthropic returns `cache_read_input_tokens` separately.
291
+ - Some backends don't report it at all.
292
+
293
+ **Don't trust cache hit numbers alone.** When changing anything
294
+ that affects prompt construction (memory placement, system prompt,
295
+ tool list, history reconstruction), instrument the engine adapter
296
+ to dump the message array per turn and compare position-by-position
297
+ across two consecutive turns. Every position before the new content
298
+ should match exactly:
299
+
300
+ ```ts
301
+ // temp instrumentation, remove after verification
302
+ logger.info({
303
+ msg: 'engine.X.messages_dump',
304
+ messages: messages.map((m, i) => ({
305
+ idx: i,
306
+ role: m.role,
307
+ contentLen: typeof m.content === 'string' ? m.content.length : -1,
308
+ contentHead:
309
+ typeof m.content === 'string' ? m.content.slice(0, 80) : '[non-str]',
310
+ })),
311
+ });
312
+ ```
313
+
314
+ Run two turns on the same session. Pull both dumps from the server
315
+ log. Check that role + length + content-head match at positions
316
+ 0..N-2; only the last position should differ in turn 2 (the new
317
+ user message). If anything earlier diverges, the cache is being
318
+ invalidated at that point and the fix isn't right yet.
319
+
320
+ ## Lessons learned
321
+
322
+ 1. **Cache wins are real and worth fighting for** — not just a
323
+ nice-to-have. On Anthropic the cost difference is 10× per cached
324
+ token. On local models the latency difference is the user's
325
+ subjective "this feels fast vs. slow."
326
+
327
+ 2. **Variable content always at the end.** Any per-turn-changing
328
+ block — memory, dynamic context, tool-call updates — must sit at
329
+ the very end of the prompt sequence. If it's earlier, every turn
330
+ invalidates everything after it.
331
+
332
+ 3. **Stateless backends are a different beast** than stateful ones
333
+ (`claude-cli`/`codex-cli`). For stateless, byte-identity across
334
+ reconstructions matters. The cleanest way to guarantee that is
335
+ to **persist what you sent** (in JSONL or equivalent storage)
336
+ and rebuild from that record, not from the source variables.
337
+
338
+ 4. **Don't trust cache-hit numbers from the API alone.** Always
339
+ verify the prompt structure with a position-dump comparison.
340
+ Backends report cache state inconsistently or not at all.
341
+
342
+ 5. **Reference repos don't always have the answer.** OpenClaw and
343
+ Hermes both punt on stateless-openai-compatible cache (Hermes
344
+ relies on Anthropic's cache_control; OpenClaw's bundles are
345
+ minified). Sometimes the right pattern is the one you build
346
+ yourself.
347
+
348
+ 6. **Verify with a two-turn position dump.** A late-system layout
349
+ looks plausible and even passes when judged by `cached_tokens`
350
+ from a single response; only a 2-turn position-dump comparison
351
+ shows the wandering block.
352
+
353
+ 7. **Not every backend has a cache to protect.** Same session, same
354
+ day, three consecutive turns: `claude-cli` reported 94% of the
355
+ prefix cached, while `deepseek-chat` via OpenRouter reported
356
+ `cached_tokens: 0` on every turn. Before trading anything away to
357
+ keep a prefix stable, check that the provider on that path is
358
+ actually caching it.
359
+
360
+ ## Code pointers
361
+
362
+ | Concern | File |
363
+ |---|---|
364
+ | `user_message.ephemeral` event field | `src/types/events.ts` |
365
+ | Persist ephemeral in JSONL | `src/server/run-turn.ts` (`appendEvent`) |
366
+ | Reconstruct from history | `src/engine/openai-compatible.ts` (`buildMessages`) |
367
+ | Memory placement claude-cli | `src/engine/claude-cli.ts` (effectiveUserMessage) |
368
+ | Memory placement codex-cli | `src/engine/codex-cli.ts` (promptPayload) |
369
+ | Turn frame ahead of the recall block | `src/server/turn-framing.ts` (`composeTurnPrefix`) |
370
+ | REM worker stable-prefix | `src/dream/rem-extract.ts` (`buildUserMessage`) |
371
+ | Wiki-overview snapshot | `src/server/prompt-assembly.ts` (`buildWikiOverviewBlock`) |
372
+ | Wiki-overview shortener | `src/memory/manager.ts` (`renderWikiOverview`) |
373
+ | `memoryInjectMode` schema | `src/config/types.ts` (`OpenAiCompatibleProviderSchema`) |
@@ -0,0 +1,253 @@
1
+ # Compaction — how somora keeps a session inside the context window
2
+
3
+ A session grows with every turn. Somewhere before it stops fitting into
4
+ the model's context window, the older part of the conversation is
5
+ folded into a summary and only the recent exchanges travel to the model
6
+ verbatim. This page describes when that happens, who does it, which
7
+ model does the summarising, and — the part people trip over — what the
8
+ per-model `contextWindow` value actually controls on each engine.
9
+
10
+ Related: [setup.md → Tunables](setup.md#tunables) (the knobs),
11
+ [models.md](models.md) (recommended `contextWindow` per model),
12
+ [thinking.md](thinking.md), [cache-strategy.md](cache-strategy.md).
13
+
14
+ ## Two kinds of compaction
15
+
16
+ | | who compacts | when | what you see |
17
+ |---|---|---|---|
18
+ | `openai-compatible` | **somora** | before a turn, when the prompt reaches `triggerRatio × inputBudget` (default 0.8; the budget is the window minus the answer, and the number is the one the provider measured last) | a `context compacted` row when the reactive path ran; otherwise nothing — the summary is invisible, the recent pairs are verbatim |
19
+ | `claude-cli`, `codex-cli`, `grok-cli` | **the CLI itself**, inside its own session/thread | at the CLI's own threshold (codex: its server-delivered session cap) | nothing from somora; the engine's own compaction is opaque to it. The `▣` percentage still tells the truth: codex reports its own `modelContextWindow` per thread, and the prompt size it reports is the prompt, cached part included, so somora does not add `cachedInputTokens` on top (that would count the cached part twice and drive the badge past 100 % on long threads). Anthropic counts the other way round, `input_tokens` EXCLUDES the cached part, so claude-cli sums. |
20
+
21
+ somora's history file (`sessions/<id>.jsonl`) is never shortened by
22
+ either. Compaction only changes what is *sent*; the JSONL stays the
23
+ full record, and REM reads it independently.
24
+
25
+ ## The openai-compatible path in detail
26
+
27
+ 1. **Measure.** The number that decides is the one the provider
28
+ reported for this session's last request (`usage.prompt_tokens`,
29
+ kept on the session as `contextTokens`). Only when there is none —
30
+ a new session, a model switch, a provider that omits usage — does
31
+ somora fall back to a character estimate: system prompt, latest
32
+ summary, every user/assistant message after it, and the tool traffic
33
+ (arguments in full, results capped the way the replay caps them), at
34
+ **4 characters per token**.
35
+
36
+ That estimate is corrected by what the last request actually cost
37
+ (`tokenRatio`, measured ÷ estimated). Prose runs near 4 characters
38
+ per token; code, JSON and markup near 2.5. Tool traffic is counted
39
+ on purpose: a session made of tool calls can carry twenty times more
40
+ tokens than its visible chat text, and an estimate that only counts
41
+ chat never triggers on such a session.
42
+ 2. **Trigger.** `tokens >= triggerRatio × inputBudget`, where the input
43
+ budget is `contextWindow − maxTokens` of the **model that will answer
44
+ this turn**. The output reservation comes out of the same window, so
45
+ measuring against the full window would let a session walk into a
46
+ provider 400 while every check says it fits. Switching a long
47
+ session from a 1M-window model to a
48
+ 131k one triggers a compaction on the next turn; the measured number
49
+ is dropped on a model switch because tokenizers differ.
50
+ 3. **Range.** Everything after the previous summary up to, but not
51
+ including, the last `safetyCushionPairs` exchanges (default 4) is
52
+ summarised. Unanswered user messages are never folded in. The
53
+ previous summary is passed to the worker as *prior summary*, so the
54
+ result is a rolling summary, not a chain of summaries.
55
+ 4. **Worker.** See below — a separate model call, one-shot, no tools.
56
+ When the cushion covers the whole session there is nothing to
57
+ summarise; somora then retries once keeping only the last exchange,
58
+ because an aggressive summary beats a turn that cannot run. After a
59
+ compaction the next real reading is checked against the trigger, and
60
+ a compaction that did not clear it is logged rather than assumed to
61
+ have worked.
62
+ 5. **Persist.** The summary is stored with the timestamp it covers
63
+ (`throughTs`) in the session's meta; later turns replay
64
+ `[summary] + pairs after throughTs`. CLI engines use the same
65
+ record when they rebuild a session (a Codex thread that no longer
66
+ exists, an MCP server rename on claude-cli) — the replay is bounded
67
+ to the most recent 40 exchanges either way.
68
+
69
+ **Reactive path.** The estimate can be wrong (tool payloads, images, a
70
+ backend with a smaller real limit than configured). When a backend
71
+ rejects the prompt as too long — `400 "Prompt too long"`, `"maximum
72
+ context length"`, oMLX's prefill guard — the engine forces a compaction
73
+ down to the last exchange, retries the turn once, and leaves a
74
+ `context compacted` engine row. A second refusal surfaces as a
75
+ plain-language error (switch model, or `/reset`) instead of the raw
76
+ 400. This path only runs before anything has streamed and before any
77
+ tool has run: retrying later would execute those tools a second time.
78
+ Mid-turn the same refusal ends the turn with an explanation, because the
79
+ work already done cannot be replayed.
80
+
81
+ **Either way the refusal is read.** It is the one moment a backend states
82
+ its own limits — the window it enforces and how many input tokens it
83
+ counted — and somora takes both: the count corrects this session's
84
+ estimate, and a reported window smaller than the configured one is logged
85
+ with the value to put in `config.yaml`.
86
+
87
+ ## Inside a running turn
88
+
89
+ Steps 1 to 5 size the conversation *before* the turn. A turn with tools
90
+ grows while it runs — every result, every image, and the tool schemas
91
+ that travel with each request. Sized once, a turn estimated at a few
92
+ tens of thousands of tokens can reach the backend at ten times that,
93
+ die on a raw 400, and lose its work.
94
+
95
+ So before **every** request of a turn, somora measures what it is about
96
+ to send: all messages, images counted as images rather than as their
97
+ base64 length, plus the tool schemas. It compares that against the
98
+ window minus the model's output reserve minus a 5% margin. If it does
99
+ not fit:
100
+
101
+ 1. **The oldest tool results are shortened** to a one-line notice that
102
+ says the call already ran and must not be repeated. Nothing is
103
+ dropped: an assistant message with `tool_calls` and no matching
104
+ reply is rejected by every OpenAI-compatible backend, and the
105
+ model's own record of what it did is what stops it repeating work.
106
+ 2. If that is not enough, more recent results follow, **except the
107
+ newest**, which is what the model is reasoning about right now.
108
+ 3. As a last resort the newest result is **cut**, keeping its beginning
109
+ and labelling the cut.
110
+ 4. Only when there is nothing left to shorten does the turn stop, with
111
+ an explanation naming the numbers instead of a raw backend error.
112
+ The tool results already produced stay in the session, so nothing
113
+ has to be redone.
114
+
115
+ A trimmed turn leaves a `context trimmed` engine row, so it is visible
116
+ that the model saw less than the full results.
117
+
118
+ A **builder** turn ([builder.md](builder.md#long-turns)) goes one step
119
+ further before trimming: when the turn's own traffic passes the trigger
120
+ mid-way, the rounds so far are summarised into a work-state block (what
121
+ was done, what the files look like now, what is left) and the last six
122
+ rounds stay verbatim, then the turn continues on the smaller context.
123
+ Chat agents keep the trimming above; nothing changes for them.
124
+
125
+ ### What a summary keeps
126
+
127
+ The summary a compaction writes follows a fixed template — the goal,
128
+ what was done, decisions and their reasons, the work state, the
129
+ relevant files, open points, and the tone of the conversation — and
130
+ the pairs after it stay verbatim. Tool calls are not flattened into
131
+ prose: each summarised pair carries its **tool trail** (the tool, the
132
+ essential argument such as a path or a command, and whether it
133
+ succeeded), so a model that continues after the compaction knows which
134
+ file it already wrote and which command already ran, instead of
135
+ repeating them.
136
+
137
+ **Reading the numbers.** The chat header shows two different things.
138
+ `▣` is occupancy: the prompt size of the turn's **last** request against
139
+ the window. `Σ↑` is spend, and the Σ is the point — it sums every
140
+ request the turn made. Example: 21 tool rounds on a 524k window read
141
+ `▣ 62%` (about 323k tokens in the last request) and `Σ↑ 6.0M` (sent in
142
+ total, because the context travels with every request). Both are
143
+ correct; only the first one says how full it is.
144
+
145
+ ## Which model summarises
146
+
147
+ `compaction.workers` is an **ordered list** of the models allowed to
148
+ summarise, and that order is the cascade — the first entry is asked
149
+ first, and a model that is not on the list is never a worker:
150
+
151
+ ```yaml
152
+ compaction:
153
+ workers: [<small-local-alias>, <hosted-alias>]
154
+ ```
155
+
156
+ Listed entries are honoured as written, including their window: naming
157
+ a model means you meant it. An entry that matches no configured alias
158
+ or `provider/modelId` is skipped with a `compaction.workers_unresolved`
159
+ warning.
160
+
161
+ Workers that are currently marked unreachable (see `fallback.retryUnavailableMinutes` in [setup.md](setup.md#tunables) — the note the chat fallback and REM share) are left out of the cascade, unless that would leave nothing to try.
162
+
163
+ `compaction.preferSessionModel: true` puts the session's own model —
164
+ the one answering right now, session override included — in front of
165
+ the list, provided its engine can summarise and its window fits the
166
+ summary with headroom; the list stays the cascade behind it. Off by
167
+ default: a session on a hosted subscription model would otherwise start
168
+ paying for its own summaries. Use it when sessions run on models that
169
+ are loaded and answering while the listed workers may not be (a GPU
170
+ profile that swaps models).
171
+
172
+ Without the list, somora picks automatically **from every configured
173
+ model on every engine that has a one-shot path** (claude-cli,
174
+ codex-cli, openai-compatible), in this order:
175
+
176
+ > every model whose `contextWindow >= estimatedTokens × 1.3`,
177
+ > **smallest window first**
178
+
179
+ `compaction.modelOverride` still works and simply goes to the front of
180
+ whatever cascade is in play.
181
+
182
+ **A refusal costs one attempt, not the compaction.** At most
183
+ **three** workers are asked per compaction; each failure is logged as
184
+ `compaction.worker_failed` with the reason and the next candidate, and
185
+ only when all of them refuse does the compaction fail. This matters
186
+ because a worker can fail for reasons that have nothing to do with the
187
+ summary: a memory guard on a busy host, a route being reloaded, a rate
188
+ limit. somora cannot see which machine sits behind which route, so it
189
+ does not guess — it asks the next model.
190
+
191
+ Three consequences worth knowing:
192
+
193
+ - The worker may be a **subscription-backed CLI model**. If the
194
+ smallest fitting window belongs to a Claude or Codex model, the
195
+ summary is produced through that CLI and counts against that
196
+ subscription. Nothing in the UI says so. Set `workers` if you
197
+ want the summariser kept to local models.
198
+ - A `contextWindow` that is **too high** for what the engine can
199
+ really take makes that model eligible for histories it cannot
200
+ hold; the summarise call then fails or is compacted again by the
201
+ CLI. Too **low** just removes it from the candidate list.
202
+ - The history handed to the worker is the *range* above, not the
203
+ whole session, so a 32k local model is a perfectly good worker for a
204
+ session that has been compacting all along.
205
+
206
+ ## What `contextWindow` really controls — per engine
207
+
208
+ The same per-model field does three different jobs:
209
+
210
+ | meaning | openai-compatible | claude-cli / codex-cli / grok-cli |
211
+ |---|---|---|
212
+ | **Compaction trigger** (`triggerRatio ×`) | yes — this is the wall somora compacts against | **no** — the CLI compacts on its own threshold |
213
+ | **Worker selection** (smallest fitting window, engine-agnostic) | yes | yes |
214
+ | **Usage display** (`X / contextWindow` in TUI header and `agent` SSE end event) | yes | yes |
215
+
216
+ So on a CLI engine the value never prevents an overflow — it decides
217
+ whether that model is picked as a summariser for *other* sessions and
218
+ whether the percentage in the header tells the truth. Which is exactly
219
+ why it must be the **effective session limit of the CLI**, not the
220
+ native API window of the model:
221
+
222
+ - **codex-cli**: Codex runs a session against a window it delivers
223
+ itself and reports per thread as `modelContextWindow` — **258,400**
224
+ for the GPT-5.6 and GPT-6 models, although the model's API window
225
+ is 1.05M. somora uses that reported number for the header
226
+ as soon as the first turn reports it, so the configured value matters
227
+ before the first turn and for the compaction-worker choice: configure
228
+ `contextWindow: 258400`. A value of 400000 or 1000000 — the obvious
229
+ thing to copy from the model card — makes the header claim "68 %
230
+ free" while codex is already compacting internally, and lets the
231
+ model be picked as a summariser for histories it will refuse.
232
+ - **claude-cli**: Claude Code sessions run against the model's real
233
+ window (1M for the Claude 5 family, 200k for Haiku 4.5), so the
234
+ native value is correct here.
235
+ - **openai-compatible**: use the **server's** limit, not the model
236
+ card's — vLLM `--max-model-len`, SGLang `--context-length`, oMLX's
237
+ configured length. With 1000000 configured against a 700k backend
238
+ somora only compacts at 800k and the backend answers 400 first.
239
+
240
+ [models.md](models.md) lists the recommended values per model.
241
+
242
+ ## Knobs
243
+
244
+ ```yaml
245
+ compaction:
246
+ triggerRatio: 0.8 # fraction of the input budget (openai-compatible only)
247
+ safetyCushionPairs: 4 # most-recent exchanges never summarised
248
+ # workers: [<small-local-alias>, <hosted-alias>] # who may summarise, in the order they are tried
249
+ # modelOverride: <alias> # pin the summariser (any engine with a one-shot path)
250
+ ```
251
+
252
+ Environment overrides `SOMORA_COMPACTION_*` are listed in
253
+ [setup.md → Environment overrides](setup.md#environment-overrides).