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,782 @@
1
+ // REM-phase extraction worker. LLM-driven analysis of session JSONL
2
+ // delta against existing memory + relevant wiki pages + referenced
3
+ // vault content, produces structured Findings ready for user review
4
+ // via the dream tools.
5
+ //
6
+ // Worker model is configured per-agent in agent.yaml under `rem.model`.
7
+ // For v1 the worker MUST be an openai-compatible provider (uses the
8
+ // chat.completions API directly). claude-cli / codex-cli as worker is
9
+ // future work — would require routing through their respective adapters
10
+ // with a synthetic JSON-output prompt.
11
+ //
12
+ // Wiki-awareness (v2.5): the LLM sees the wiki index plus top-N
13
+ // embedding-matched wiki pages so it can dedupe against canonical
14
+ // long-term knowledge. Wiki = source of truth. Memory = volatile inbox.
15
+
16
+ import OpenAI from 'openai';
17
+ import { createPatientOpenAIClient } from '../server/openai-client.ts';
18
+ import { userTagParam } from '../engine/user-tag.ts';
19
+ import { readFile } from 'node:fs/promises';
20
+ import matter from 'gray-matter';
21
+ import type { Config, ResolvedModel, ThinkingLevel } from '../config/types.ts';
22
+ import { resolveAnyRef } from '../config/types.ts';
23
+ import { logger } from '../server/logger.ts';
24
+ import { firstCompleteJson } from './json-salvage.ts';
25
+ import type { NormalizedEvent } from '../types/events.ts';
26
+ import type { Finding, FindingAction } from './types.ts';
27
+ import { openAiReasoningState, withReasoningRetry } from '../engine/reasoning-retry.ts';
28
+ import { samplingBody } from '../engine/sampling.ts';
29
+ import { isAvailabilityError } from '../engine/availability.ts';
30
+ import { markModelAvailable, markModelUnavailable, modelRef, modelUnavailable } from '../engine/model-availability.ts';
31
+ import { normalizeSlug } from '../memory/slug.ts';
32
+
33
+ export interface ExtractContext {
34
+ agent: string;
35
+ /** Slice of session JSONL to analyze. */
36
+ events: NormalizedEvent[];
37
+ /** Memory inbox — un-consolidated notes. As of v2.2 there are no
38
+ * stub pointers here; every entry is full content (or empty if the
39
+ * agent has no current memory). Wiki is canonical for stable
40
+ * knowledge — dedupe against `relevantWikiPages` not against
41
+ * `existingMemory`. */
42
+ existingMemory: Array<{ slug: string; markdown: string }>;
43
+ /** Vault notes referenced during the session (filtered subset). */
44
+ referencedVault: Array<{ slug: string; markdown: string }>;
45
+ /** Wiki index.md content (topology header). Always-on snapshot of
46
+ * what subfolders + slugs exist in the shared wiki. Empty
47
+ * placeholder string when wiki is disabled or empty. */
48
+ wikiIndex?: string;
49
+ /** Top-N wiki pages relevant to this session (embedding-matched
50
+ * against user-text). Full bodies. The dedup target — if a fact is
51
+ * already in one of these, don't surface it as a finding. */
52
+ relevantWikiPages?: Array<{ slug: string; markdown: string }>;
53
+ /** The resolved dream worker model. */
54
+ workerModel: ResolvedModel;
55
+ /** Optional backup workers (`rem.fallback`), in order. The next one
56
+ * takes over for the rest of the run when the current worker is
57
+ * unreachable — connection refused, 5xx, timeout — never on a 4xx
58
+ * rejection. The chunk that hit the outage is retried on the
59
+ * backup; nothing of it was persisted, so the retry cannot double
60
+ * findings. When the chain is exhausted the chunk fails as before. */
61
+ fallbackModels?: ResolvedModel[];
62
+ /** Per-chunk LLM-call timeout. */
63
+ chunkTimeoutMs: number;
64
+ /** Roughly tokens per chunk; events are packed up to this size. */
65
+ chunkTokens: number;
66
+ /** Optional thinking-level for the REM extraction LLM. Per-agent via
67
+ * `rem.thinking` in AGENTS.md. Helper handles `model.capabilities`
68
+ * guarding — unset / non-reasoning models skip the param. */
69
+ thinking?: ThinkingLevel;
70
+ /** Optional cancellation signal — set by AutoDreamWorker on user activity. */
71
+ signal?: AbortSignal;
72
+ /** Skip the first N chunks (for resume after pause/crash). */
73
+ startChunk?: number;
74
+ /** Per-chunk progress callback so the driver can persist `chunks_done`. */
75
+ onChunkComplete?: (info: {
76
+ chunkIndex: number;
77
+ totalChunks: number;
78
+ chunkFindings: Finding[];
79
+ /** `provider/modelId` that produced this chunk. */
80
+ workerModel: string;
81
+ }) => Promise<void>;
82
+ /** Fired once, when the run moved from `workerModel` to
83
+ * `fallbackModel`, so the driver can persist the switch before the
84
+ * retried chunk runs. */
85
+ onWorkerSwitch?: (info: WorkerSwitch) => Promise<void>;
86
+ }
87
+
88
+ /** The moment a REM run switched to its backup worker. */
89
+ export interface WorkerSwitch {
90
+ /** `provider/modelId` that became unreachable. */
91
+ from: string;
92
+ /** `provider/modelId` that finished the run. */
93
+ to: string;
94
+ /** The primary's failure, trimmed. */
95
+ reason: string;
96
+ /** 1-based chunk that hit the outage and was retried on the backup. */
97
+ atChunk: number;
98
+ }
99
+
100
+ export interface ExtractResult {
101
+ findings: Finding[];
102
+ chunksProcessed: number;
103
+ totalChunks: number;
104
+ /** True if the run completed all chunks; false if cancelled mid-way. */
105
+ completed: boolean;
106
+ /** Chunks whose LLM call errored (backend reject, timeout, transport)
107
+ * or whose answer stayed unreadable after one retry.
108
+ * The runner MUST NOT treat a run with failedChunks > 0 as a clean
109
+ * empty result — that would silently lose the session range (bug
110
+ * report 2026-07-24: 19 runs masked as "no findings" in 3 days). */
111
+ failedChunks: number;
112
+ /** Set when the backup worker took over mid-run. */
113
+ workerSwitch?: WorkerSwitch;
114
+ }
115
+
116
+ const SYSTEM_PROMPT = `You are REM, the session→memory extraction worker for an AI agent in the somora system.
117
+
118
+ Layered knowledge model:
119
+ - WIKI = long-term, consolidated, shared across all agents. Source of truth
120
+ for stable facts. You cannot edit it directly — Deep (a different worker)
121
+ promotes facts there from agent memory.
122
+ - MEMORY = short-term, per-agent inbox. Holds atomic facts that are not yet
123
+ in the wiki. Deep moves them to the wiki on its next run, then deletes
124
+ them from memory.
125
+ - VAULT = user-maintained Obsidian content outside the wiki subfolder.
126
+ Read-only for agents.
127
+
128
+ You are given:
129
+ 1. A transcript chunk of recent conversation between the user and the agent.
130
+ 2. The agent's current memory inbox (markdown bodies keyed by slug).
131
+ 3. The wiki index (topology of subfolders + slugs).
132
+ 4. Top-N wiki pages most relevant to the session content (full bodies).
133
+ 5. Vault notes referenced during the session.
134
+
135
+ Your job: identify FACTS in the user's messages that should land in the
136
+ agent's memory inbox. Return ONLY a JSON array of finding objects. No
137
+ commentary, no markdown fences.
138
+
139
+ Each finding has these fields:
140
+ - action: one of "memory_write" | "memory_edit" | "memory_delete" | "vault_hint"
141
+ - slug: short kebab-case identifier (lowercase, [a-z0-9_-]).
142
+ - proposed_content: full new markdown body (for memory_write / memory_edit)
143
+ - current_excerpt: short quoted snippet of the existing memory content that
144
+ is being changed/removed (for memory_edit / memory_delete)
145
+ - reason: 1-2 sentences explaining the finding, quoting the user's statement
146
+
147
+ DEDUP RULES (critical — wiki is canonical):
148
+ - If the WIKI already covers the fact accurately → DO NOT surface. Dedupe
149
+ against the wiki pages provided, not against memory. Memory is volatile
150
+ inbox; just because something is missing from memory does NOT mean it's
151
+ unknown to the system.
152
+ - If a USER-STATEMENT CONTRADICTS the wiki → DO surface as memory_write
153
+ with a fresh slug. Deep will see it next run, decide MERGE into the
154
+ existing wiki page (updating the contradicted fact).
155
+ - If a fact is in the wiki AND the user just confirms or repeats it → SKIP.
156
+ - If a fact is in agent memory already (un-consolidated) → SKIP, unless
157
+ this is a contradiction or correction.
158
+ - The vault is user-managed and may already cover the fact → SKIP if so.
159
+
160
+ WHAT TO SURFACE:
161
+ - New stable facts the wiki doesn't have yet (a project, a device, a contact,
162
+ a place, a person, a preference).
163
+ - Contradictions: wiki/memory says X, user said not-X.
164
+ - Concrete corrections to specific data (Luca turned 9, moved house, etc.).
165
+
166
+ WHAT NOT TO SURFACE:
167
+ - Transient state ("working on X today", "feeling tired", "right now I'm…").
168
+ - Jokes, speculation, hypotheticals.
169
+ - Statements made by the AGENT — only USER statements are authoritative.
170
+ - SYSTEM(...) lines: automatic triggers and wakes. Never a source of facts.
171
+
172
+ OTHER-AGENT(name) LINES — another agent wrote this, not the user:
173
+ - Never report it as something the user said, decided or wants.
174
+ - A stable fact in it (a decision passed on, a new setup, a contact) MAY be
175
+ surfaced — often it is the only way this agent learns it. Then name the
176
+ source in BOTH fields: start proposed_content with "Laut <name>: " (or
177
+ "According to <name>: " in an English conversation) and say in reason that
178
+ it came from agent <name>, not from the user. The person reviews it.
179
+ - Instructions, task briefs and status chatter between agents are not facts.
180
+ - If a USER line says the same, the USER line is the source — no "Laut".
181
+ - Tool-result content the agent quoted back (memory_search, somora_docs_read,
182
+ file_read output) — those are not user assertions.
183
+ - "Consolidated overviews" ("everything about X", thematic summaries) — memory is
184
+ atomic, consolidation is Deep's job.
185
+ - For vault_hint: only when an existing vault note is clearly outdated given
186
+ user statements; do not propose creating new vault notes.
187
+
188
+ Output format example:
189
+ [
190
+ {
191
+ "action": "memory_write",
192
+ "slug": "neuer-wagen",
193
+ "proposed_content": "User confirmed a new family car arrived in 2026-05.",
194
+ "reason": "User said on 2026-05-09: 'der neue Familienwagen ist eingetroffen'. Wiki personen/familie-klein mentions verschiedene Fahrzeuge, but not this specific model — this is a new fact."
195
+ },
196
+ {
197
+ "action": "memory_write",
198
+ "slug": "luca-alter",
199
+ "proposed_content": "Luca ist jetzt 9 (Wiki-Page personen/luca sagt 8).",
200
+ "reason": "User said on 2026-05-08 that Luca turned 9 last week. Wiki personen/luca says 8 — contradicts; Deep will merge this into the page next run."
201
+ }
202
+ ]
203
+
204
+ If there are no findings, return: []`;
205
+
206
+ const VALID_ACTIONS: ReadonlySet<FindingAction> = new Set([
207
+ 'memory_write',
208
+ 'memory_edit',
209
+ 'memory_delete',
210
+ 'vault_hint',
211
+ ]);
212
+
213
+ /**
214
+ * Build the OpenAI client for the worker model. v1 requires baseUrl+apiKey
215
+ * (i.e. openai-compatible providers). claude-cli/codex-cli workers would
216
+ * need different routing — explicit error keeps the failure visible.
217
+ */
218
+ function buildClient(model: ResolvedModel): OpenAI {
219
+ if (model.provider.engine !== 'openai-compatible') {
220
+ throw new Error(
221
+ `dream worker model '${model.providerName}/${model.modelId}' is on engine '${model.provider.engine}'; ` +
222
+ `only openai-compatible engines are supported as dream workers in v1.`,
223
+ );
224
+ }
225
+ return createPatientOpenAIClient({
226
+ baseURL: model.provider.baseUrl,
227
+ apiKey: model.provider.apiKey,
228
+ });
229
+ }
230
+
231
+ /**
232
+ * Resolve a `dream.model` ref (alias or provider/id) against the loaded
233
+ * Config. Throws if the ref doesn't resolve — fail-loud is intentional.
234
+ */
235
+ export function resolveDreamModel(config: Config, ref: string): ResolvedModel {
236
+ const resolved = resolveAnyRef(config, ref);
237
+ if (!resolved) {
238
+ throw new Error(`dream.model '${ref}' is not a configured model — fix agent.yaml or config.yaml`);
239
+ }
240
+ return resolved;
241
+ }
242
+
243
+ /**
244
+ * Token-count estimator. Same 4-chars-per-token heuristic the rest of the
245
+ * codebase uses. Good enough for chunk-budget decisions.
246
+ */
247
+ function estimateTokens(text: string): number {
248
+ return Math.ceil(text.length / 4);
249
+ }
250
+
251
+ interface EventChunk {
252
+ events: NormalizedEvent[];
253
+ /** ISO range bounds for diagnostics + finding-attribution. */
254
+ fromTs: number;
255
+ throughTs: number;
256
+ }
257
+
258
+ /**
259
+ * Pack events into chunks of ~chunkTokens each. Chunk boundaries fall
260
+ * between turn pairs (we never split a single event across chunks).
261
+ */
262
+ function chunkEvents(events: NormalizedEvent[], chunkTokens: number): EventChunk[] {
263
+ const out: EventChunk[] = [];
264
+ let current: NormalizedEvent[] = [];
265
+ let acc = 0;
266
+ for (const ev of events) {
267
+ const text = (ev as { text?: unknown }).text;
268
+ const evTokens = typeof text === 'string' ? estimateTokens(text) : 50; // rough cost for non-text events
269
+ if (acc + evTokens > chunkTokens && current.length > 0) {
270
+ out.push({
271
+ events: current,
272
+ fromTs: current[0]!.ts,
273
+ throughTs: current[current.length - 1]!.ts,
274
+ });
275
+ current = [];
276
+ acc = 0;
277
+ }
278
+ current.push(ev);
279
+ acc += evTokens;
280
+ }
281
+ if (current.length > 0) {
282
+ out.push({
283
+ events: current,
284
+ fromTs: current[0]!.ts,
285
+ throughTs: current[current.length - 1]!.ts,
286
+ });
287
+ }
288
+ return out;
289
+ }
290
+
291
+ /**
292
+ * Who wrote a `user_message`. Not every one is the person: another
293
+ * agent's agent_ask, a sentinel trigger's prompt, a tmux or job wake
294
+ * all arrive as user_message. They used to be labelled USER, and the
295
+ * prompt makes USER lines authoritative — so an orchestrator's
296
+ * instruction or a trigger text could come back as "the user said …".
297
+ * A voice consult IS the person, relayed by the voice self.
298
+ * Exported for tests.
299
+ */
300
+ export function speakerLabel(ev: { from_agent?: string; from_system?: string }): string {
301
+ if (ev.from_agent) return `OTHER-AGENT(${ev.from_agent})`;
302
+ if (ev.from_system === 'voice') return 'USER (voice call, relayed)';
303
+ if (ev.from_system) return `SYSTEM(${ev.from_system})`;
304
+ return 'USER';
305
+ }
306
+
307
+ function formatTranscript(events: NormalizedEvent[]): string {
308
+ const lines: string[] = [];
309
+ for (const ev of events) {
310
+ const ts = new Date(ev.ts).toISOString();
311
+ if (ev.kind === 'user_message') {
312
+ lines.push(`[${ts}] ${speakerLabel(ev)}: ${ev.text}`);
313
+ } else if (ev.kind === 'assistant_message') {
314
+ lines.push(`[${ts}] AGENT: ${ev.text}`);
315
+ } else if (ev.kind === 'tool_call') {
316
+ const args = JSON.stringify(ev.input).slice(0, 200);
317
+ lines.push(`[${ts}] AGENT-tool-call: ${ev.tool}(${args})`);
318
+ }
319
+ // Skip deltas, turn boundaries, errors — not informative for extraction.
320
+ }
321
+ return lines.join('\n');
322
+ }
323
+
324
+ function formatMemory(notes: Array<{ slug: string; markdown: string }>): string {
325
+ if (notes.length === 0) return '(empty — agent has no current memory notes)';
326
+ return notes
327
+ .map((n) => {
328
+ // Strip frontmatter for the extractor; only body matters semantically.
329
+ const parsed = matter(n.markdown);
330
+ return `### ${n.slug}\n${parsed.content.trim()}`;
331
+ })
332
+ .join('\n\n');
333
+ }
334
+
335
+ function formatVault(notes: Array<{ slug: string; markdown: string }>): string {
336
+ if (notes.length === 0) return '(no vault notes were referenced in this transcript window)';
337
+ return notes
338
+ .map((n) => {
339
+ const parsed = matter(n.markdown);
340
+ return `### ${n.slug}\n${parsed.content.trim().slice(0, 1500)}`; // cap per-vault-note length
341
+ })
342
+ .join('\n\n');
343
+ }
344
+
345
+ function formatWikiPages(notes: Array<{ slug: string; markdown: string }>): string {
346
+ if (notes.length === 0) {
347
+ return '(no wiki pages matched this session by recall — wiki may be empty or topic outside its scope)';
348
+ }
349
+ return notes
350
+ .map((n) => {
351
+ const parsed = matter(n.markdown);
352
+ return `### wiki/${n.slug}\n${parsed.content.trim().slice(0, 2000)}`;
353
+ })
354
+ .join('\n\n');
355
+ }
356
+
357
+ function buildUserMessage(args: {
358
+ agentName: string;
359
+ chunk: EventChunk;
360
+ existingMemory: Array<{ slug: string; markdown: string }>;
361
+ referencedVault: Array<{ slug: string; markdown: string }>;
362
+ wikiIndex: string;
363
+ relevantWikiPages: Array<{ slug: string; markdown: string }>;
364
+ }): string {
365
+ // Order matters for prefix-cache hit-rate across chunks of the same
366
+ // REM extraction:
367
+ // - existingMemory + wiki + referencedVault are computed ONCE per
368
+ // run (in runDream) and are byte-identical across every chunk
369
+ // - chunk.events is the only piece that varies per chunk
370
+ // → stable blocks BEFORE the variable transcript so the prefix tokens
371
+ // up to the transcript-content match across chunks. Backends with
372
+ // prefix-cache (mlx-omx, OpenAI, Anthropic-via-openai-shim) cache
373
+ // the memory + wiki + vault prefix on chunk 1 and reuse it on
374
+ // chunks 2..N.
375
+ return [
376
+ `Agent name: ${args.agentName}`,
377
+ '',
378
+ '<existing_memory>',
379
+ formatMemory(args.existingMemory),
380
+ '</existing_memory>',
381
+ '',
382
+ '<wiki_index>',
383
+ args.wikiIndex.trim() || '(empty — no index.md or wiki disabled)',
384
+ '</wiki_index>',
385
+ '',
386
+ '<wiki_relevant_pages>',
387
+ formatWikiPages(args.relevantWikiPages),
388
+ '</wiki_relevant_pages>',
389
+ '',
390
+ '<vault_referenced>',
391
+ formatVault(args.referencedVault),
392
+ '</vault_referenced>',
393
+ '',
394
+ '<transcript>',
395
+ formatTranscript(args.chunk.events),
396
+ '</transcript>',
397
+ ].join('\n');
398
+ }
399
+
400
+ /** The worker answered, but not with a findings array we can read:
401
+ * empty content (thinking ate the token budget), output cut off mid-
402
+ * string, unescaped quotes inside a value. Thrown so the chunk lands
403
+ * in `failedChunks` — an unreadable answer is NOT "no findings". */
404
+ export class UnreadableFindingsError extends Error {
405
+ constructor(message: string) {
406
+ super(message);
407
+ this.name = 'UnreadableFindingsError';
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Validate + coerce a raw LLM output into a sanitized Finding[].
413
+ * Findings with bad/missing fields are dropped (with a warn log) — we
414
+ * never throw on a single bad finding because that would lose all good
415
+ * findings in the same chunk.
416
+ *
417
+ * An answer that is not a readable array at all THROWS
418
+ * (UnreadableFindingsError). It used to return [] — which the caller
419
+ * counted as a clean chunk, the runner archived as "no findings", and
420
+ * the worker stamped as dreamed: 20 such answers in the live logs up to
421
+ * 2026-09-21, 16 of them carrying real findings that were lost for good.
422
+ */
423
+ export function parseFindings(raw: string): Omit<Finding, 'id' | 'status' | 'resolved_at'>[] {
424
+ // Strip common fence patterns the model might emit despite the prompt.
425
+ let text = raw.trim();
426
+ if (text.startsWith('```')) {
427
+ const fenceEnd = text.lastIndexOf('```');
428
+ if (fenceEnd > 0) {
429
+ text = text.slice(text.indexOf('\n') + 1, fenceEnd).trim();
430
+ }
431
+ }
432
+ // A stray reasoning tail (`…</think>[]`): what follows is the answer.
433
+ const thinkEnd = text.lastIndexOf('</think>');
434
+ if (thinkEnd >= 0) text = text.slice(thinkEnd + '</think>'.length).trim();
435
+ let parsed: unknown;
436
+ try {
437
+ parsed = JSON.parse(text);
438
+ } catch (err) {
439
+ // Prose after (or before) a complete array is harmless — read the
440
+ // array. Anything else is unreadable.
441
+ const candidate = firstCompleteJson(text, '[');
442
+ let recovered: unknown;
443
+ if (candidate !== null) {
444
+ try {
445
+ recovered = JSON.parse(candidate);
446
+ } catch {
447
+ recovered = undefined;
448
+ }
449
+ }
450
+ if (!Array.isArray(recovered)) {
451
+ logger.warn({ msg: 'dream.extract_parse_failed', err: (err as Error).message, sample: text.slice(0, 200) });
452
+ throw new UnreadableFindingsError(
453
+ text.length === 0
454
+ ? 'worker returned empty content (no findings array)'
455
+ : `worker output is not a readable findings array: ${(err as Error).message}`,
456
+ );
457
+ }
458
+ logger.info({ msg: 'dream.extract_array_recovered', droppedChars: text.length - candidate!.length });
459
+ parsed = recovered;
460
+ }
461
+ if (!Array.isArray(parsed)) {
462
+ logger.warn({ msg: 'dream.extract_not_array', got: typeof parsed });
463
+ throw new UnreadableFindingsError(`worker output is ${typeof parsed}, not a findings array`);
464
+ }
465
+ const out: Omit<Finding, 'id' | 'status' | 'resolved_at'>[] = [];
466
+ for (const item of parsed) {
467
+ if (!item || typeof item !== 'object') continue;
468
+ const obj = item as Record<string, unknown>;
469
+ const action = obj.action;
470
+ if (typeof action !== 'string' || !VALID_ACTIONS.has(action as FindingAction)) continue;
471
+ const rawSlug = obj.slug;
472
+ if (typeof rawSlug !== 'string' || rawSlug.length === 0) continue;
473
+ // The worker model writes slugs the way the conversation spelled
474
+ // them (umlauts, CamelCase) and memory_write's validator rejects
475
+ // those at apply time. Normalise here so the finding is applicable.
476
+ const slug = normalizeSlug(rawSlug);
477
+ if (!slug) continue;
478
+ if (slug !== rawSlug) {
479
+ logger.info({ msg: 'dream.extract_slug_normalized', from: rawSlug, to: slug });
480
+ }
481
+ const reason = obj.reason;
482
+ if (typeof reason !== 'string' || reason.length === 0) continue;
483
+ out.push({
484
+ action: action as FindingAction,
485
+ slug,
486
+ reason,
487
+ ...(typeof obj.current_excerpt === 'string' ? { current_excerpt: obj.current_excerpt } : {}),
488
+ ...(typeof obj.proposed_content === 'string' ? { proposed_content: obj.proposed_content } : {}),
489
+ ...(Array.isArray(obj.frontmatter_tags)
490
+ ? { frontmatter_tags: obj.frontmatter_tags.filter((t): t is string => typeof t === 'string') }
491
+ : {}),
492
+ });
493
+ }
494
+ return out;
495
+ }
496
+
497
+ /**
498
+ * Dedupe findings across chunks: if two findings target the same slug
499
+ * with the same action, keep the one with the longest reason (proxy for
500
+ * "more context"). Then assign sequential ids and default `pending` status.
501
+ */
502
+ function dedupeAndAssignIds(
503
+ raw: Omit<Finding, 'id' | 'status' | 'resolved_at'>[],
504
+ ): Finding[] {
505
+ const seen = new Map<string, (typeof raw)[number]>();
506
+ for (const f of raw) {
507
+ const key = `${f.action}::${f.slug}`;
508
+ const existing = seen.get(key);
509
+ if (!existing || (f.reason.length > existing.reason.length)) {
510
+ seen.set(key, f);
511
+ }
512
+ }
513
+ return [...seen.values()].map((f, i) => ({
514
+ ...f,
515
+ id: i + 1,
516
+ status: 'pending' as const,
517
+ }));
518
+ }
519
+
520
+ /**
521
+ * Run extraction across the full event range with chunking + cancellation.
522
+ * Returns partial results on cancel — `completed: false` then.
523
+ */
524
+ export async function extractFromSession(ctx: ExtractContext): Promise<ExtractResult> {
525
+ const chunks = chunkEvents(ctx.events, ctx.chunkTokens);
526
+ const totalChunks = chunks.length;
527
+ if (totalChunks === 0) {
528
+ return { findings: [], chunksProcessed: 0, totalChunks: 0, completed: true, failedChunks: 0 };
529
+ }
530
+
531
+ const systemPrompt = SYSTEM_PROMPT;
532
+
533
+ // The worker in use. Starts as the configured model; after an
534
+ // availability failure it is the backup for the rest of the run
535
+ // (no ping-pong: the primary that just went away is not asked
536
+ // again on the next chunk).
537
+ let model = ctx.workerModel;
538
+ let client = buildClient(model);
539
+ let reasoning = openAiReasoningState(ctx.thinking, model.model);
540
+ let workerSwitch: WorkerSwitch | undefined;
541
+ // Position in the fallback chain: the next backup to try.
542
+ let fallbackIdx = 0;
543
+ const accumulated: Omit<Finding, 'id' | 'status' | 'resolved_at'>[] = [];
544
+ const startAt = ctx.startChunk ?? 0;
545
+ let failedChunks = 0;
546
+ // Chunks already re-asked after an unreadable answer (one retry each).
547
+ const unreadableRetried = new Set<number>();
548
+
549
+ for (let i = startAt; i < totalChunks; i++) {
550
+ if (ctx.signal?.aborted) {
551
+ logger.info({
552
+ msg: 'dream.extract_cancelled',
553
+ agent: ctx.agent,
554
+ chunkIndex: i,
555
+ totalChunks,
556
+ });
557
+ return {
558
+ findings: dedupeAndAssignIds(accumulated),
559
+ chunksProcessed: i,
560
+ totalChunks,
561
+ completed: false,
562
+ failedChunks,
563
+ ...(workerSwitch ? { workerSwitch } : {}),
564
+ };
565
+ }
566
+ const chunk = chunks[i]!;
567
+ try {
568
+ const userMsg = buildUserMessage({
569
+ agentName: ctx.agent,
570
+ chunk,
571
+ existingMemory: ctx.existingMemory,
572
+ referencedVault: ctx.referencedVault,
573
+ wikiIndex: ctx.wikiIndex ?? '',
574
+ relevantWikiPages: ctx.relevantWikiPages ?? [],
575
+ });
576
+ const reqTokens = estimateTokens(systemPrompt) + estimateTokens(userMsg);
577
+ const reqStart = Date.now();
578
+ logger.info({
579
+ msg: 'dream.llm_request',
580
+ agent: ctx.agent,
581
+ chunkIndex: i + 1,
582
+ totalChunks,
583
+ workerModel: `${model.providerName}/${model.modelId}`,
584
+ baseUrl: model.provider.engine === 'openai-compatible'
585
+ ? (model.provider as { baseUrl?: string }).baseUrl
586
+ : undefined,
587
+ eventsInChunk: chunk.events.length,
588
+ estimatedTokensIn: reqTokens,
589
+ });
590
+ const completion = await Promise.race([
591
+ // Same reasoning mapping + one retry on rejection as chat turns
592
+ // (src/engine/reasoning-retry.ts); the adjusted value sticks for
593
+ // the remaining chunks of this run. `max_tokens` from the model's
594
+ // `maxTokens` bounds a runaway thinking phase on reasoning workers.
595
+ withReasoningRetry(
596
+ reasoning,
597
+ (reasoningBody) =>
598
+ client.chat.completions.create(
599
+ {
600
+ model: model.modelId,
601
+ messages: [
602
+ { role: 'system', content: systemPrompt },
603
+ { role: 'user', content: userMsg },
604
+ ],
605
+ stream: false,
606
+ ...(model.model.maxTokens ? { max_tokens: model.model.maxTokens } : {}),
607
+ ...samplingBody(model.model.sampling),
608
+ ...userTagParam(model, ctx.agent, 'rem'),
609
+ ...reasoningBody,
610
+ },
611
+ // Pass the abort signal through to the HTTP layer so shutdown /
612
+ // user-activity aborts cancel the in-flight request cleanly
613
+ // instead of dying later with an opaque transport error
614
+ // ("terminated") when the process tears down its sockets.
615
+ ctx.signal ? { signal: ctx.signal } : undefined,
616
+ ),
617
+ {
618
+ engine: 'openai-compatible',
619
+ phase: 'rem',
620
+ agent: ctx.agent,
621
+ provider: model.providerName,
622
+ model: model.modelId,
623
+ },
624
+ ),
625
+ new Promise<never>((_, reject) =>
626
+ setTimeout(
627
+ () => reject(new Error(`chunk ${i + 1}/${totalChunks} timed out after ${ctx.chunkTimeoutMs}ms`)),
628
+ ctx.chunkTimeoutMs,
629
+ ),
630
+ ),
631
+ ]);
632
+ // Defensive: backends can answer 200 with an error body that has no
633
+ // `choices` (omlx prefill-memory-guard rejections, 2026-07-24). A
634
+ // bare `completion.choices[0]` access would throw the useless
635
+ // "Cannot read properties of undefined (reading '0')" — surface the
636
+ // actual backend payload instead.
637
+ const choice = completion.choices?.[0];
638
+ if (!choice?.message) {
639
+ const bodyPreview = JSON.stringify(completion)?.slice(0, 500) ?? '(unserializable)';
640
+ throw new Error(`backend response has no choices — raw body: ${bodyPreview}`);
641
+ }
642
+ const text = choice.message.content ?? '';
643
+ let chunkFindings: ReturnType<typeof parseFindings>;
644
+ try {
645
+ chunkFindings = parseFindings(text);
646
+ } catch (parseErr) {
647
+ // Unreadable output is a dice roll of sampling (an unescaped
648
+ // quote, a runaway thinking phase), so ask once more before
649
+ // giving the chunk up. A second miss falls through to the
650
+ // failed-chunk path below — never to "no findings".
651
+ if (parseErr instanceof UnreadableFindingsError && !unreadableRetried.has(i)) {
652
+ unreadableRetried.add(i);
653
+ logger.warn({
654
+ msg: 'dream.chunk_unreadable_retry',
655
+ agent: ctx.agent,
656
+ chunkIndex: i + 1,
657
+ totalChunks,
658
+ workerModel: `${model.providerName}/${model.modelId}`,
659
+ err: parseErr.message,
660
+ responseChars: text.length,
661
+ finishReason: choice.finish_reason,
662
+ });
663
+ i -= 1;
664
+ continue;
665
+ }
666
+ throw parseErr;
667
+ }
668
+ accumulated.push(...chunkFindings);
669
+ markModelAvailable(modelRef(model));
670
+ logger.info({
671
+ msg: 'dream.chunk_done',
672
+ agent: ctx.agent,
673
+ chunkIndex: i + 1,
674
+ totalChunks,
675
+ rawFindings: chunkFindings.length,
676
+ responseChars: text.length,
677
+ responsePreview: text.slice(0, 300).replace(/\s+/g, ' ').trim(),
678
+ durationMs: Date.now() - reqStart,
679
+ usage: completion.usage,
680
+ });
681
+ if (ctx.onChunkComplete) {
682
+ await ctx.onChunkComplete({
683
+ chunkIndex: i + 1,
684
+ totalChunks,
685
+ chunkFindings: dedupeAndAssignIds(chunkFindings),
686
+ workerModel: `${model.providerName}/${model.modelId}`,
687
+ });
688
+ }
689
+ } catch (err) {
690
+ // An abort (shutdown or user activity) surfaces here as an SDK
691
+ // abort error once the signal is wired into the request. That is a
692
+ // cancellation, not a chunk failure — return the paused-shape
693
+ // result so the runner parks the dream for resume.
694
+ if (ctx.signal?.aborted) {
695
+ logger.info({
696
+ msg: 'dream.extract_cancelled',
697
+ agent: ctx.agent,
698
+ chunkIndex: i,
699
+ totalChunks,
700
+ during: 'in-flight chunk request',
701
+ });
702
+ return {
703
+ findings: dedupeAndAssignIds(accumulated),
704
+ chunksProcessed: i,
705
+ totalChunks,
706
+ completed: false,
707
+ failedChunks,
708
+ };
709
+ }
710
+ // Backup worker: only for an outage of the primary, only once
711
+ // per run, and only if the chunk produced nothing (it didn't —
712
+ // findings are pushed after a successful parse). A 4xx is a
713
+ // config error and must stay visible as a failed chunk.
714
+ if (!(err instanceof UnreadableFindingsError) && isAvailabilityError(err)) {
715
+ markModelUnavailable(modelRef(model), (err as Error).message);
716
+ }
717
+ // Next backup in the chain that is not itself marked unavailable
718
+ // (a marked one is skipped unless nothing after it is free).
719
+ let nextBackup = ctx.fallbackModels?.[fallbackIdx];
720
+ while (nextBackup && modelUnavailable(modelRef(nextBackup)) && ctx.fallbackModels!.slice(fallbackIdx + 1).some((m) => !modelUnavailable(modelRef(m)))) {
721
+ logger.info({ msg: 'dream.worker_fallback_skip_unavailable', agent: ctx.agent, model: modelRef(nextBackup) });
722
+ fallbackIdx += 1;
723
+ nextBackup = ctx.fallbackModels?.[fallbackIdx];
724
+ }
725
+ if (
726
+ nextBackup &&
727
+ !(err instanceof UnreadableFindingsError) &&
728
+ isAvailabilityError(err)
729
+ ) {
730
+ fallbackIdx += 1;
731
+ const from = `${model.providerName}/${model.modelId}`;
732
+ const to = `${nextBackup.providerName}/${nextBackup.modelId}`;
733
+ workerSwitch = { from, to, reason: (err as Error).message.slice(0, 300), atChunk: i + 1 };
734
+ logger.warn({
735
+ msg: 'dream.worker_fallback',
736
+ agent: ctx.agent,
737
+ chunkIndex: i + 1,
738
+ totalChunks,
739
+ from,
740
+ to,
741
+ reason: workerSwitch.reason,
742
+ });
743
+ if (nextBackup.model.contextWindow < ctx.chunkTokens * 1.2) {
744
+ logger.warn({
745
+ msg: 'dream.worker_fallback_small_window',
746
+ agent: ctx.agent,
747
+ to,
748
+ contextWindow: nextBackup.model.contextWindow,
749
+ chunkTokens: ctx.chunkTokens,
750
+ hint: 'rem.chunkTokens is close to the backup worker\'s window — chunks may overflow on the backup',
751
+ });
752
+ }
753
+ model = nextBackup;
754
+ client = buildClient(model);
755
+ reasoning = openAiReasoningState(ctx.thinking, model.model);
756
+ if (ctx.onWorkerSwitch) await ctx.onWorkerSwitch(workerSwitch);
757
+ i -= 1; // retry this chunk on the backup
758
+ continue;
759
+ }
760
+ failedChunks++;
761
+ logger.warn({
762
+ msg: 'dream.chunk_failed',
763
+ agent: ctx.agent,
764
+ chunkIndex: i + 1,
765
+ totalChunks,
766
+ workerModel: `${model.providerName}/${model.modelId}`,
767
+ err: (err as Error).message,
768
+ });
769
+ // continue to next chunk — single-chunk failure shouldn't sink the
770
+ // whole dream; the runner decides what a non-zero failedChunks means
771
+ }
772
+ }
773
+
774
+ return {
775
+ findings: dedupeAndAssignIds(accumulated),
776
+ chunksProcessed: totalChunks,
777
+ totalChunks,
778
+ completed: true,
779
+ failedChunks,
780
+ ...(workerSwitch ? { workerSwitch } : {}),
781
+ };
782
+ }