@openchamber/web 2.0.4 → 2.1.0

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 (264) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-C_zL-eri.js → CodeMirrorCommentWidgets-qlshRzAf.js} +1 -1
  2. package/dist/assets/{DiffView-BeN2_YYF.js → DiffView-BI_YgdKl.js} +3 -3
  3. package/dist/assets/FilesView-B_NJFLBH.js +17 -0
  4. package/dist/assets/{GitView-DLDazOo1.js → GitView-BWKg6TNS.js} +4 -4
  5. package/dist/assets/{GuestAttachDialog-C0xe_Lyy.js → GuestAttachDialog-DO4x4vIR.js} +1 -1
  6. package/dist/assets/{GuestSurfacePane-BdaurnDr.js → GuestSurfacePane-4PY11vEP.js} +1 -1
  7. package/dist/assets/JsonTreeView-u4yx65zn.js +1 -0
  8. package/dist/assets/{LinearIssuesView-BryoAHow.js → LinearIssuesView-C4gGBhU8.js} +1 -1
  9. package/dist/assets/{MarkdownImageGallery-DfuEoaGq.js → MarkdownImageGallery-fqVRCTdC.js} +1 -1
  10. package/dist/assets/MarkdownRendererImpl-Cfb5fTnq.js +39 -0
  11. package/dist/assets/OnboardingScreen-CiTV2_OT.js +1 -0
  12. package/dist/assets/PatchDiff-BrjhzXDM.js +1 -0
  13. package/dist/assets/{PierreDiffViewer-BC950e3F.js → PierreDiffViewer-CVx2e1cx.js} +5 -5
  14. package/dist/assets/{PlanView-B7Xgihqk.js → PlanView-DP9DOnI-.js} +4 -4
  15. package/dist/assets/{PluginPane-2C71F8uF.js → PluginPane-rZvoMQSi.js} +3 -3
  16. package/dist/assets/SettingsView-Dp9jubRs.js +30 -0
  17. package/dist/assets/SettingsWindow-Dst0yiV7.js +1 -0
  18. package/dist/assets/{SubmoduleDiffSummary-BSA9gnIO.js → SubmoduleDiffSummary-CixkM4fI.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-DprkVKcj.js → ToolOutputDialog-f0cS2DIf.js} +6 -6
  20. package/dist/assets/ToolPartDiffPreview-CFFIAFFY.js +8 -0
  21. package/dist/assets/{VirtualizedFileDiff-Kp8hKJdT.js → VirtualizedFileDiff-B-U_aQwV.js} +4 -4
  22. package/dist/assets/{WalkthroughView-DGnTzqIU.js → WalkthroughView-C1uB3Pl3.js} +2 -2
  23. package/dist/assets/{appThemeRegistry-BdEHBA4s.js → appThemeRegistry-DU-UKEHq.js} +1 -1
  24. package/dist/assets/{commitAndPush-LwtVa2Oc.js → commitAndPush-CtWGqrtW.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-6V1xNpO9.js → computeVirtualFileMetrics-BmhViPMt.js} +1 -1
  26. package/dist/assets/de-D4hpTCNY.js +10 -0
  27. package/dist/assets/es-Bw9m3H62.js +16 -0
  28. package/dist/assets/fileTreeStatus-CvPnAWSi.js +1 -0
  29. package/dist/assets/fr-Bhll42P0.js +14 -0
  30. package/dist/assets/index-Btd2mmYT.js +42 -0
  31. package/dist/assets/index-C-7hQnEc.css +1 -0
  32. package/dist/assets/{index-CmNPYddV.js → index-DwtCnbiK.js} +1 -1
  33. package/dist/assets/{isDiffPlainText-1bXcWCrw.js → isDiffPlainText-CPDhzF1K.js} +1 -1
  34. package/dist/assets/{isFilePlainText-CBAppvy1.js → isFilePlainText-n8k0lMTZ.js} +1 -1
  35. package/dist/assets/ja-CsHoT43d.js +16 -0
  36. package/dist/assets/ko-BBNdtFa4.js +16 -0
  37. package/dist/assets/{main-CzjTMTfW.js → main-D6rlXjug.js} +2 -2
  38. package/dist/assets/main-kYkr_urz.js +1000 -0
  39. package/dist/assets/markdownCore-CHm8ycaW.js +7 -0
  40. package/dist/assets/{miniChat-CP68IL8Q.js → miniChat-2JY8K3Qw.js} +2 -2
  41. package/dist/assets/mobile-CviaXnnU.js +2 -0
  42. package/dist/assets/nl-DszyktfH.js +16 -0
  43. package/dist/assets/openSessionFromRoute-BIlcJIf3.js +1 -0
  44. package/dist/assets/{web-components-ngpHPEDU.js → parseDiffFromFile-DeZzEah8.js} +5 -5
  45. package/dist/assets/{patchFileDiff-pqRSHLHI.js → patchFileDiff-BnEHIdM2.js} +2 -2
  46. package/dist/assets/pl-Bk9_mUXc.js +16 -0
  47. package/dist/assets/pt-BR-BIXmm3Gw.js +16 -0
  48. package/dist/assets/{renderElectronMiniChatApp-DKIilR7N.js → renderElectronMiniChatApp-DvUphkjj.js} +2 -2
  49. package/dist/assets/renderMobileApp-Cdc49X8Y.js +25 -0
  50. package/dist/assets/runtimeEndpointReset-Cu6RUve4.js +56 -0
  51. package/dist/assets/shikiHighlight-CcVzlYit.js +1 -0
  52. package/dist/assets/space-apply-CgJ5JYPK.js +1 -0
  53. package/dist/assets/space-close-C1tL-_0t.js +1 -0
  54. package/dist/assets/{textMateThemeFromAppTheme-BSUFChBY.js → textMateThemeFromAppTheme-CAOCeVjl.js} +1 -1
  55. package/dist/assets/tr-C_13w7CX.js +7 -0
  56. package/dist/assets/uk-BZTsG-q_.js +16 -0
  57. package/dist/assets/{useAppFontEffects-Dsl_sLrj.js → useAppFontEffects-CeMgbeVa.js} +185 -177
  58. package/dist/assets/{useInlineCommentController-d5vntsQ_.js → useInlineCommentController-U97JJifS.js} +2 -2
  59. package/dist/assets/useRootScrollLock-DMBY2aTT.js +2 -0
  60. package/dist/assets/{vendor-base-ui-DnNniUWp.js → vendor-base-ui-DWgyZK2k.js} +1 -1
  61. package/dist/assets/vendor-codemirror-autocomplete-DetzHhtC.js +1 -0
  62. package/dist/assets/{vendor-codemirror-commands-B7H_j0iU.js → vendor-codemirror-commands-ConqfjLn.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-angular-DEPs2M5t.js → vendor-codemirror-lang-angular-Dbpx8qe-.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-cpp-DhkseaMo.js → vendor-codemirror-lang-cpp-TRtQWrpl.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-css-O0cZX78y.js → vendor-codemirror-lang-css-DY4CGDG2.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-go-fMdQYcON.js → vendor-codemirror-lang-go-CLKXh6B8.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-html-CfgK872x.js → vendor-codemirror-lang-html-CQnNjmg9.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-java-CQj4S3zl.js → vendor-codemirror-lang-java-CokZKqls.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-javascript-Cc2ZYbgX.js → vendor-codemirror-lang-javascript-Kgp6fZRE.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-jinja-BmZZv8g-.js → vendor-codemirror-lang-jinja-DZchyrN1.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-json-CMBS2tG9.js → vendor-codemirror-lang-json-CkdBRvqj.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-less-C6Eo8hVS.js → vendor-codemirror-lang-less-_k-GKz0A.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-liquid-DSTR47-H.js → vendor-codemirror-lang-liquid-DuHUMKoh.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-markdown-BPGOH9ye.js → vendor-codemirror-lang-markdown-CdG1RXm1.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-php-DD9udfPH.js → vendor-codemirror-lang-php-Ca15KQSA.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-python-HahnQaAS.js → vendor-codemirror-lang-python-B4MRHRva.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-rust-nLTovbjv.js → vendor-codemirror-lang-rust-8fLJdxQA.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-sass-pL2Yc72v.js → vendor-codemirror-lang-sass-CASr_yQ1.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-sql-BVBnan19.js → vendor-codemirror-lang-sql-Dc4ER-re.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-vue-BqGzJVm1.js → vendor-codemirror-lang-vue-fu2BqdK2.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-wast-B0_m5DqU.js → vendor-codemirror-lang-wast-BkCOgSpV.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-xml-Dj3voadT.js → vendor-codemirror-lang-xml-7e-kPepH.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-yaml-yu-9Z5u7.js → vendor-codemirror-lang-yaml-Cq3p_9DI.js} +1 -1
  84. package/dist/assets/vendor-codemirror-language-CZcLdzDM.js +3 -0
  85. package/dist/assets/{vendor-codemirror-language-data-B1EetJur.js → vendor-codemirror-language-data-B8HKnqZy.js} +2 -2
  86. package/dist/assets/vendor-codemirror-search-BZNojiZO.js +2 -0
  87. package/dist/assets/{vendor-codemirror-state-C9awkmn-.js → vendor-codemirror-state--21VQleR.js} +1 -1
  88. package/dist/assets/vendor-codemirror-view-8PpN-8l4.js +4 -0
  89. package/dist/assets/vendor-opencode-client-Byb4ZSqI.js +12 -0
  90. package/dist/assets/vendor-remend-DcBOpbSu.js +24 -0
  91. package/dist/assets/{vendor-replit-codemirror-vim-B2DJlAhT.js → vendor-replit-codemirror-vim-EX7OnecQ.js} +1 -1
  92. package/dist/assets/zh-CN-C62wm2Tg.js +16 -0
  93. package/dist/assets/zh-TW-BgGTiQA6.js +16 -0
  94. package/dist/index.html +4 -4
  95. package/dist/mini-chat.html +4 -4
  96. package/dist/mobile.html +4 -4
  97. package/package.json +4 -4
  98. package/server/index.js +58 -1
  99. package/server/lib/browser-control/DOCUMENTATION.md +8 -1
  100. package/server/lib/dev-tunnel/DOCUMENTATION.md +6 -0
  101. package/server/lib/dev-tunnel/runtime.js +94 -38
  102. package/server/lib/dev-tunnel/tunnel.test.js +16 -2
  103. package/server/lib/dictation/DOCUMENTATION.md +23 -10
  104. package/server/lib/dictation/audio.js +28 -0
  105. package/server/lib/dictation/local/sherpa-recognizer.js +33 -7
  106. package/server/lib/dictation/local/sherpa-recognizer.test.js +94 -0
  107. package/server/lib/dictation/local/worker-client.js +28 -10
  108. package/server/lib/dictation/local/worker-process.js +25 -1
  109. package/server/lib/dictation/stream-manager.js +160 -53
  110. package/server/lib/dictation/stream-manager.test.js +108 -7
  111. package/server/lib/enterprise-mode.d.ts +2 -0
  112. package/server/lib/enterprise-mode.js +84 -9
  113. package/server/lib/enterprise-mode.test.js +115 -0
  114. package/server/lib/fs/DOCUMENTATION.md +3 -2
  115. package/server/lib/fs/routes.js +28 -1
  116. package/server/lib/fs/routes.test.js +31 -5
  117. package/server/lib/git/DOCUMENTATION.md +1 -1
  118. package/server/lib/git/service.js +61 -2
  119. package/server/lib/git/service.test.js +141 -0
  120. package/server/lib/github/DOCUMENTATION.md +18 -0
  121. package/server/lib/github/checks-summary.js +76 -0
  122. package/server/lib/github/pr-summaries.js +282 -0
  123. package/server/lib/github/pr-summaries.test.js +209 -0
  124. package/server/lib/github/routes.js +42 -77
  125. package/server/lib/github/routes.test.js +77 -0
  126. package/server/lib/inherited-env.js +51 -0
  127. package/server/lib/inherited-env.test.js +59 -0
  128. package/server/lib/message-search/DOCUMENTATION.md +83 -0
  129. package/server/lib/message-search/indexer.js +336 -0
  130. package/server/lib/message-search/indexer.test.js +341 -0
  131. package/server/lib/message-search/routes.js +92 -0
  132. package/server/lib/message-search/runtime.js +234 -0
  133. package/server/lib/message-search/runtime.test.js +108 -0
  134. package/server/lib/message-search/sqlite.js +74 -0
  135. package/server/lib/message-search/store.js +289 -0
  136. package/server/lib/openchamber-control/DOCUMENTATION.md +6 -1
  137. package/server/lib/openchamber-control/actions.js +1 -1
  138. package/server/lib/openchamber-control/service.js +21 -2
  139. package/server/lib/openchamber-control/service.test.js +50 -0
  140. package/server/lib/openchamber-sessions/routes.js +15 -0
  141. package/server/lib/openchamber-sessions/routes.test.js +31 -0
  142. package/server/lib/opencode/DOCUMENTATION.md +43 -38
  143. package/server/lib/opencode/auth.d.ts +24 -0
  144. package/server/lib/opencode/auth.js +130 -66
  145. package/server/lib/opencode/auth.test.js +114 -70
  146. package/server/lib/opencode/compatibility.js +4 -3
  147. package/server/lib/opencode/compatibility.test.js +10 -10
  148. package/server/lib/opencode/feature-routes-runtime.js +3 -0
  149. package/server/lib/opencode/lifecycle.js +21 -12
  150. package/server/lib/opencode/lifecycle.test.js +38 -5
  151. package/server/lib/opencode/provider-source-route.test.js +55 -2
  152. package/server/lib/opencode/routes.js +17 -4
  153. package/server/lib/opencode/settings-helpers.js +6 -0
  154. package/server/lib/opencode/settings-helpers.test.js +1 -1
  155. package/server/lib/opencode/settings-registry.json +16 -0
  156. package/server/lib/opencode/settings-runtime.js +9 -0
  157. package/server/lib/opencode/shutdown-runtime.js +2 -0
  158. package/server/lib/opencode/v1-migration-topup.js +13 -3
  159. package/server/lib/opencode/v2-install.test.js +13 -13
  160. package/server/lib/quota/DOCUMENTATION.md +11 -5
  161. package/server/lib/quota/providers/claude/auth.js +19 -6
  162. package/server/lib/quota/providers/claude/auth.test.js +22 -9
  163. package/server/lib/quota/providers/claude/index.js +3 -3
  164. package/server/lib/quota/providers/claude/index.test.js +3 -2
  165. package/server/lib/quota/providers/cline-pass.js +4 -4
  166. package/server/lib/quota/providers/codex.js +3 -4
  167. package/server/lib/quota/providers/codex.test.js +1 -1
  168. package/server/lib/quota/providers/copilot.js +4 -5
  169. package/server/lib/quota/providers/copilot.test.js +1 -1
  170. package/server/lib/quota/providers/deepseek.js +3 -4
  171. package/server/lib/quota/providers/deepseek.test.js +1 -1
  172. package/server/lib/quota/providers/google/auth.js +1 -3
  173. package/server/lib/quota/providers/google/index.js +3 -2
  174. package/server/lib/quota/providers/hyper.js +4 -4
  175. package/server/lib/quota/providers/index.js +9 -2
  176. package/server/lib/quota/providers/index.test.js +5 -3
  177. package/server/lib/quota/providers/kimi.js +16 -11
  178. package/server/lib/quota/providers/kimi.test.js +81 -38
  179. package/server/lib/quota/providers/minimax-shared.js +3 -4
  180. package/server/lib/quota/providers/nanogpt.js +3 -4
  181. package/server/lib/quota/providers/neuralwatt.js +3 -4
  182. package/server/lib/quota/providers/neuralwatt.test.js +1 -1
  183. package/server/lib/quota/providers/openai.js +2 -8
  184. package/server/lib/quota/providers/opencode-go.js +5 -5
  185. package/server/lib/quota/providers/opencode-go.test.js +1 -1
  186. package/server/lib/quota/providers/openrouter.js +30 -6
  187. package/server/lib/quota/providers/openrouter.test.js +122 -1
  188. package/server/lib/quota/providers/wafer.js +3 -4
  189. package/server/lib/quota/providers/xai.js +12 -12
  190. package/server/lib/quota/providers/zai.js +3 -4
  191. package/server/lib/quota/providers/zai.test.js +1 -1
  192. package/server/lib/quota/providers/zhipuai-coding-plan.js +5 -6
  193. package/server/lib/quota/providers/zhipuai-coding-plan.test.js +1 -1
  194. package/server/lib/quota/routes.js +1 -1
  195. package/server/lib/routing/DOCUMENTATION.md +4 -0
  196. package/server/lib/routing/runtime.js +45 -4
  197. package/server/lib/routing/runtime.test.js +35 -6
  198. package/server/lib/scheduled-tasks/DOCUMENTATION.md +27 -0
  199. package/server/lib/scheduled-tasks/chats-scope.js +50 -0
  200. package/server/lib/scheduled-tasks/runtime.js +57 -23
  201. package/server/lib/scheduled-tasks/runtime.test.js +103 -1
  202. package/server/lib/scheduled-tasks/service.js +37 -29
  203. package/server/lib/scheduled-tasks/service.test.js +39 -0
  204. package/server/lib/spaces/DOCUMENTATION.md +54 -9
  205. package/server/lib/spaces/host.js +24 -3
  206. package/server/lib/spaces/journey.js +111 -11
  207. package/server/lib/spaces/journey.test.js +189 -8
  208. package/server/lib/spaces/places/docker-disk.js +151 -0
  209. package/server/lib/spaces/places/docker-disk.test.js +167 -0
  210. package/server/lib/spaces/places/docker-tools.js +11 -1
  211. package/server/lib/spaces/places/docker.js +4 -2
  212. package/server/lib/spaces/places/fake-docker.js +36 -2
  213. package/server/lib/spaces/routes.js +21 -4
  214. package/server/lib/spaces/routes.test.js +6 -2
  215. package/server/lib/spaces/space-archive.js +275 -0
  216. package/server/lib/spaces/space-archive.test.js +194 -0
  217. package/server/lib/spaces/space-opencode.js +139 -6
  218. package/server/lib/spaces/space-opencode.test.js +82 -1
  219. package/server/lib/spaces/space-records.js +3 -0
  220. package/server/lib/spaces/space-setup.js +10 -5
  221. package/server/lib/spaces/space-setup.test.js +8 -2
  222. package/server/lib/terminal/DOCUMENTATION.md +1 -0
  223. package/server/lib/terminal/runtime.js +6 -1
  224. package/server/lib/terminal/runtime.test.js +19 -0
  225. package/server/lib/tts/routes.js +2 -2
  226. package/server/lib/tts/service.js +8 -8
  227. package/dist/assets/FilesView-CN34wm_N.js +0 -17
  228. package/dist/assets/JsonTreeView-B1Xq-k2t.js +0 -1
  229. package/dist/assets/MarkdownRendererImpl-B_ZcWOvX.js +0 -12
  230. package/dist/assets/OnboardingScreen-C22bGmnP.js +0 -1
  231. package/dist/assets/PatchDiff-0xd6UeFB.js +0 -1
  232. package/dist/assets/SettingsView-m_zoFiaT.js +0 -30
  233. package/dist/assets/SettingsWindow-CofS020b.js +0 -1
  234. package/dist/assets/ToolPartDiffPreview-Dq0go_fX.js +0 -8
  235. package/dist/assets/de-DlgBHUAI.js +0 -10
  236. package/dist/assets/es-BC8G41U8.js +0 -16
  237. package/dist/assets/fr-I0z3vVjy.js +0 -14
  238. package/dist/assets/index-CgR5rJq_.js +0 -41
  239. package/dist/assets/index-adyy_sEk.css +0 -1
  240. package/dist/assets/ja-BIElEsY8.js +0 -16
  241. package/dist/assets/ko-DRnnHetA.js +0 -16
  242. package/dist/assets/main-DVX34beR.js +0 -886
  243. package/dist/assets/markdownCore-Cxbkn5NR.js +0 -7
  244. package/dist/assets/mobile-BrlBrNfZ.js +0 -2
  245. package/dist/assets/nl-DzUV-kwp.js +0 -16
  246. package/dist/assets/pl-Bb-cb7k7.js +0 -16
  247. package/dist/assets/pt-BR-CyIWrTcE.js +0 -16
  248. package/dist/assets/renderMobileApp-B0z6-x58.js +0 -25
  249. package/dist/assets/runtimeEndpointReset-uu1DBwLL.js +0 -52
  250. package/dist/assets/scheduledTasksApi-BuzWT445.js +0 -1
  251. package/dist/assets/shikiHighlight-BWGrY5YU.js +0 -1
  252. package/dist/assets/tr-DXEDSoYO.js +0 -7
  253. package/dist/assets/uk-C8hN--q_.js +0 -16
  254. package/dist/assets/useRootScrollLock-2rd5Y6gR.js +0 -2
  255. package/dist/assets/vendor-codemirror-autocomplete-DzPz9Wgq.js +0 -1
  256. package/dist/assets/vendor-codemirror-language-BgPj_McA.js +0 -3
  257. package/dist/assets/vendor-codemirror-search-BmS-GmcX.js +0 -2
  258. package/dist/assets/vendor-codemirror-view-CiLROUVV.js +0 -4
  259. package/dist/assets/vendor-opencode-client-DSZl7jSi.js +0 -12
  260. package/dist/assets/vendor-remend-BWYYytN3.js +0 -22
  261. package/dist/assets/zh-CN-CtzXdjMZ.js +0 -16
  262. package/dist/assets/zh-TW-Ds0CADSz.js +0 -16
  263. package/server/lib/opencode/credential-db.js +0 -144
  264. package/server/lib/opencode/credential-db.test.js +0 -104
@@ -0,0 +1,289 @@
1
+ /**
2
+ * The message search index: one SQLite file in the OpenChamber data dir.
3
+ *
4
+ * `messages` holds the searchable text of settled user messages and agent
5
+ * replies; `messages_fts` is an external-content FTS5 index over it, kept by
6
+ * triggers. The trigram tokenizer matches any three or more characters inside
7
+ * a word, in any script, so "світ" finds "світу" and CJK text needs no word
8
+ * segmentation. `sessions` remembers where each session's reading stopped.
9
+ *
10
+ * The file is derived data. A schema change drops and rebuilds it.
11
+ */
12
+
13
+ const MESSAGE_SEARCH_SCHEMA_VERSION = '2';
14
+
15
+ // Private-use characters around each match in a snippet. They cannot occur in
16
+ // ordinary text and are not markup, so a snippet is never rendered as HTML.
17
+ export const MATCH_START = '';
18
+ export const MATCH_END = '';
19
+
20
+ const MIN_TERM_LENGTH = 3;
21
+
22
+ const SCHEMA = `
23
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
24
+ CREATE TABLE IF NOT EXISTS sessions (
25
+ id TEXT PRIMARY KEY,
26
+ directory TEXT NOT NULL,
27
+ title TEXT NOT NULL DEFAULT '',
28
+ created_at INTEGER NOT NULL DEFAULT 0,
29
+ revert_id TEXT,
30
+ user_cursor TEXT,
31
+ assistant_cursor TEXT,
32
+ synced_updated_at INTEGER
33
+ );
34
+ CREATE TABLE IF NOT EXISTS messages (
35
+ seq INTEGER PRIMARY KEY,
36
+ id TEXT NOT NULL UNIQUE,
37
+ message_id TEXT NOT NULL,
38
+ session_id TEXT NOT NULL,
39
+ role TEXT NOT NULL,
40
+ created_at INTEGER NOT NULL,
41
+ text TEXT NOT NULL
42
+ );
43
+ CREATE INDEX IF NOT EXISTS messages_by_session ON messages (session_id, created_at);
44
+ CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
45
+ text, content='messages', content_rowid='seq', tokenize='trigram'
46
+ );
47
+ CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
48
+ INSERT INTO messages_fts (rowid, text) VALUES (new.seq, new.text);
49
+ END;
50
+ CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
51
+ INSERT INTO messages_fts (messages_fts, rowid, text) VALUES ('delete', old.seq, old.text);
52
+ END;
53
+ CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE OF text ON messages BEGIN
54
+ INSERT INTO messages_fts (messages_fts, rowid, text) VALUES ('delete', old.seq, old.text);
55
+ INSERT INTO messages_fts (rowid, text) VALUES (new.seq, new.text);
56
+ END;
57
+ `;
58
+
59
+ const DROP = `
60
+ DROP TRIGGER IF EXISTS messages_ai;
61
+ DROP TRIGGER IF EXISTS messages_ad;
62
+ DROP TRIGGER IF EXISTS messages_au;
63
+ DROP TABLE IF EXISTS messages_fts;
64
+ DROP TABLE IF EXISTS messages;
65
+ DROP TABLE IF EXISTS sessions;
66
+ DROP TABLE IF EXISTS meta;
67
+ `;
68
+
69
+ const characterLength = (value) => Array.from(value).length;
70
+
71
+ /**
72
+ * A query as FTS5 understands it: every word must occur, each matched
73
+ * literally. Words shorter than the trigram window cannot be looked up and are
74
+ * left out; a query made only of them has no answer rather than every answer.
75
+ */
76
+ export const toSearchTerms = (query) => String(query ?? '')
77
+ .trim()
78
+ .split(/\s+/)
79
+ .filter((term) => characterLength(term) >= MIN_TERM_LENGTH);
80
+
81
+ export const toMatchExpression = (query) => {
82
+ const terms = toSearchTerms(query);
83
+ if (terms.length === 0) return null;
84
+ return terms.map((term) => `"${term.replaceAll('"', '""')}"`).join(' AND ');
85
+ };
86
+
87
+ const SNIPPET_RADIUS = 90;
88
+
89
+ /**
90
+ * The part of a message around a match, every match in it marked.
91
+ * FTS5's own snippet() counts trigrams, not words, and cuts a hit to a few
92
+ * characters, so the window is taken here, on the text of the hits only.
93
+ * Matching is case-insensitive the same way the trigram index is; where
94
+ * lowercasing changes a string's length (rare scripts), offsets would drift,
95
+ * so that text is returned unmarked.
96
+ */
97
+ export const buildSnippet = (text, terms, radius = SNIPPET_RADIUS) => {
98
+ const lower = text.toLowerCase();
99
+ if (lower.length !== text.length) return text.slice(0, radius * 2);
100
+ const ranges = [];
101
+ for (const term of terms) {
102
+ const needle = term.toLowerCase();
103
+ for (let at = lower.indexOf(needle); at >= 0; at = lower.indexOf(needle, at + needle.length)) {
104
+ ranges.push([at, at + needle.length]);
105
+ }
106
+ }
107
+ if (ranges.length === 0) return text.slice(0, radius * 2);
108
+ ranges.sort((left, right) => left[0] - right[0]);
109
+ const merged = [];
110
+ for (const range of ranges) {
111
+ const previous = merged[merged.length - 1];
112
+ if (previous && range[0] <= previous[1]) previous[1] = Math.max(previous[1], range[1]);
113
+ else merged.push([...range]);
114
+ }
115
+ // Centre on the longest word: in "git rebase" the rare one says more than
116
+ // the short one that also matches inside "github".
117
+ const longest = terms.reduce((best, term) => (term.length > best.length ? term : best), '').toLowerCase();
118
+ const anchorAt = lower.indexOf(longest);
119
+ const anchor = merged.find(([from, to]) => from <= anchorAt && anchorAt < to) ?? merged[0];
120
+ let start = Math.max(0, anchor[0] - radius);
121
+ let end = Math.min(text.length, anchor[1] + radius);
122
+ // Whole words at the edges read better than a cut one.
123
+ if (start > 0) {
124
+ const space = text.lastIndexOf(' ', anchor[0]);
125
+ if (space > start) start = space + 1;
126
+ }
127
+ if (end < text.length) {
128
+ const space = text.indexOf(' ', end);
129
+ if (space >= 0 && space - end < 20) end = space;
130
+ }
131
+ let out = start > 0 ? '…' : '';
132
+ let cursor = start;
133
+ for (const [from, to] of merged) {
134
+ if (to <= start || from >= end) continue;
135
+ out += text.slice(cursor, Math.max(cursor, from)) + MATCH_START + text.slice(Math.max(from, cursor), Math.min(to, end)) + MATCH_END;
136
+ cursor = Math.min(to, end);
137
+ }
138
+ out += text.slice(cursor, end) + (end < text.length ? '…' : '');
139
+ return out.replace(/\s+/g, ' ');
140
+ };
141
+
142
+ export const openMessageSearchStore = (connection) => {
143
+ const version = (() => {
144
+ try {
145
+ return connection.get('SELECT value FROM meta WHERE key = ?', ['schema'])?.value ?? null;
146
+ } catch {
147
+ return null;
148
+ }
149
+ })();
150
+ if (version !== MESSAGE_SEARCH_SCHEMA_VERSION) connection.exec(DROP);
151
+ connection.exec('PRAGMA journal_mode = WAL');
152
+ connection.exec(SCHEMA);
153
+ connection.run('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)', ['schema', MESSAGE_SEARCH_SCHEMA_VERSION]);
154
+
155
+ const readSession = (sessionId) => connection.get(
156
+ 'SELECT id, directory, title, revert_id, user_cursor, assistant_cursor, synced_updated_at FROM sessions WHERE id = ?',
157
+ [sessionId],
158
+ );
159
+
160
+ return {
161
+ readSession,
162
+
163
+ upsertSession: ({ id, directory, title, createdAt }) => {
164
+ connection.run(
165
+ `INSERT INTO sessions (id, directory, title, created_at) VALUES (?, ?, ?, ?)
166
+ ON CONFLICT (id) DO UPDATE SET directory = excluded.directory, title = excluded.title`,
167
+ [id, directory, title ?? '', createdAt ?? 0],
168
+ );
169
+ },
170
+
171
+ renameSession: (sessionId, title) => {
172
+ connection.run('UPDATE sessions SET title = ? WHERE id = ?', [title, sessionId]);
173
+ },
174
+
175
+ moveSession: (sessionId, directory) => {
176
+ connection.run('UPDATE sessions SET directory = ? WHERE id = ?', [directory, sessionId]);
177
+ },
178
+
179
+ /** Forgets what was read, for a session whose history changed under the cursors. */
180
+ resetSession: (sessionId, revertId) => {
181
+ connection.transaction(() => {
182
+ connection.run('DELETE FROM messages WHERE session_id = ?', [sessionId]);
183
+ connection.run(
184
+ 'UPDATE sessions SET revert_id = ?, user_cursor = NULL, assistant_cursor = NULL, synced_updated_at = NULL WHERE id = ?',
185
+ [revertId, sessionId],
186
+ );
187
+ });
188
+ },
189
+
190
+ deleteSession: (sessionId) => {
191
+ connection.transaction(() => {
192
+ connection.run('DELETE FROM messages WHERE session_id = ?', [sessionId]);
193
+ connection.run('DELETE FROM sessions WHERE id = ?', [sessionId]);
194
+ });
195
+ },
196
+
197
+ /** Messages are immutable once settled; a re-read replaces nothing it does not change. */
198
+ putMessages: (rows) => {
199
+ if (rows.length === 0) return;
200
+ connection.transaction(() => {
201
+ for (const row of rows) {
202
+ connection.run(
203
+ `INSERT INTO messages (id, message_id, session_id, role, created_at, text) VALUES (?, ?, ?, ?, ?, ?)
204
+ ON CONFLICT (id) DO UPDATE SET text = excluded.text WHERE text <> excluded.text`,
205
+ [row.id, row.messageId ?? row.id, row.sessionId, row.role, row.createdAt, row.text],
206
+ );
207
+ }
208
+ });
209
+ },
210
+
211
+ setCursor: (sessionId, role, cursor) => {
212
+ const column = role === 'user' ? 'user_cursor' : 'assistant_cursor';
213
+ connection.run(`UPDATE sessions SET ${column} = ? WHERE id = ?`, [cursor, sessionId]);
214
+ },
215
+
216
+ markSynced: (sessionId, updatedAt) => {
217
+ connection.run('UPDATE sessions SET synced_updated_at = ? WHERE id = ?', [updatedAt, sessionId]);
218
+ },
219
+
220
+ readMeta: (key) => connection.get('SELECT value FROM meta WHERE key = ?', [key])?.value ?? null,
221
+
222
+ writeMeta: (key, value) => {
223
+ connection.run('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)', [key, value]);
224
+ },
225
+
226
+ /** Drops every row of one kind, e.g. reasoning once it is no longer indexed. */
227
+ deleteRole: (role) => {
228
+ connection.run('DELETE FROM messages WHERE role = ?', [role]);
229
+ },
230
+
231
+ /**
232
+ * Makes the next walk read every session's agent records again from the
233
+ * start (user messages keep their cursor): what is indexed from them changed.
234
+ */
235
+ rereadAssistantRecords: () => {
236
+ connection.run('UPDATE sessions SET assistant_cursor = NULL, synced_updated_at = NULL');
237
+ },
238
+
239
+ sessionIds: () => connection.all('SELECT id FROM sessions').map((row) => row.id),
240
+
241
+ counts: () => ({
242
+ sessions: connection.get('SELECT count(*) AS n FROM sessions')?.n ?? 0,
243
+ messages: connection.get('SELECT count(*) AS n FROM messages')?.n ?? 0,
244
+ }),
245
+
246
+ /**
247
+ * Newest matches first. `before` pages by creation time (with the message
248
+ * id breaking ties), so a page boundary never repeats or skips a hit.
249
+ */
250
+ search: ({ match, sessionId = null, directories = [], role = null, includeReasoning = true, before = null, limit, order = 'desc' }) => {
251
+ const where = ['messages_fts MATCH ?'];
252
+ const params = [match];
253
+ if (sessionId) {
254
+ where.push('m.session_id = ?');
255
+ params.push(sessionId);
256
+ }
257
+ if (directories.length > 0) {
258
+ where.push(`s.directory IN (${directories.map(() => '?').join(', ')})`);
259
+ params.push(...directories);
260
+ }
261
+ if (role) {
262
+ where.push('m.role = ?');
263
+ params.push(role);
264
+ }
265
+ if (!includeReasoning) where.push("m.role <> 'reasoning'");
266
+ if (before) {
267
+ where.push(order === 'desc'
268
+ ? '(m.created_at < ? OR (m.created_at = ? AND m.id < ?))'
269
+ : '(m.created_at > ? OR (m.created_at = ? AND m.id > ?))');
270
+ params.push(before.createdAt, before.createdAt, before.id);
271
+ }
272
+ const direction = order === 'desc' ? 'DESC' : 'ASC';
273
+ params.push(limit);
274
+ return connection.all(
275
+ `SELECT m.id AS rowId, m.message_id AS id, m.session_id AS sessionId, m.role AS role, m.created_at AS createdAt,
276
+ s.title AS sessionTitle, s.directory AS directory, m.text AS text
277
+ FROM messages_fts
278
+ JOIN messages m ON m.seq = messages_fts.rowid
279
+ JOIN sessions s ON s.id = m.session_id
280
+ WHERE ${where.join(' AND ')}
281
+ ORDER BY m.created_at ${direction}, m.id ${direction}
282
+ LIMIT ?`,
283
+ params,
284
+ );
285
+ },
286
+
287
+ close: () => connection.close(),
288
+ };
289
+ };
@@ -54,7 +54,12 @@ other.
54
54
  callers can correct an invalid request without an upfront usage manual.
55
55
  - Explicit `projectId` or `directory` scope takes precedence over the managed
56
56
  tool's current-session directory fallback; the fallback never creates a
57
- conflicting second scope.
57
+ conflicting second scope. Session reads (`session.list`, `session.status`,
58
+ `session.messages`) resolve `projectId` through the session service's
59
+ `resolveDirectory`, the lookup create/send/fork use: an unknown project is a
60
+ 404 and a missing project folder a 400, never a read of the current or every
61
+ directory. Every `session.*` action refuses `projectId` and `directory`
62
+ together with a 400, so neither silently wins.
58
63
  - One failed directory status lookup produces `unknown` for only that
59
64
  directory and does not erase other session results.
60
65
  - Destructive session/worktree deletion and project-path registration are not
@@ -10,7 +10,7 @@
10
10
  export const OPENCHAMBER_CONTROL_ACTION_DEFINITIONS = Object.freeze([
11
11
  { action: 'projects.list', title: 'List configured projects', description: 'List configured projects; no parameters' },
12
12
  { action: 'models.list', title: 'Show model preferences', description: 'Show default, favorite, and recent model preferences; no parameters' },
13
- { action: 'session.list', title: 'List sessions', description: 'List sessions; optional directory, limit (default 10), all, or withStatus' },
13
+ { action: 'session.list', title: 'List sessions', description: 'List sessions; optional projectId or directory, limit (default 10), all, or withStatus' },
14
14
  { action: 'session.create', title: 'Create a session', description: 'Create a session in the current directory by default; prompt is optional' },
15
15
  { action: 'session.send', title: 'Send a prompt', description: 'Send a new prompt to sessionId; scope with projectId or directory' },
16
16
  { action: 'session.fork', title: 'Fork a session', description: 'Fork sessionId; messageId selects the boundary; prompt is optional' },
@@ -211,6 +211,24 @@ export const createOpenChamberControlService = (dependencies) => {
211
211
  }));
212
212
  };
213
213
 
214
+ // projectId and directory are two names for one scope. Accepting both let
215
+ // one silently win over the other, so every session action refuses the pair.
216
+ const assertSingleScope = (input) => {
217
+ if (asNonEmptyString(input.projectId) && asNonEmptyString(input.directory)) {
218
+ throw new OpenChamberControlError('Provide only one of projectId or directory', 400);
219
+ }
220
+ };
221
+
222
+ // An explicit projectId scopes a session read to that project's directory,
223
+ // resolved the same way create/send/fork resolve it. An unknown project is
224
+ // an error, never a silent read of the caller's directory or of every project.
225
+ const resolveReadDirectory = async (input, contextDirectory) => {
226
+ assertSingleScope(input);
227
+ const projectID = asNonEmptyString(input.projectId);
228
+ if (!projectID) return asNonEmptyString(input.directory) || asNonEmptyString(contextDirectory);
229
+ return sessionService.resolveDirectory({ projectId: projectID });
230
+ };
231
+
214
232
  const models = async () => {
215
233
  const settings = await readSettingsFromDiskMigrated();
216
234
  return {
@@ -299,6 +317,7 @@ export const createOpenChamberControlService = (dependencies) => {
299
317
  const executeSessionAction = async (action, input, contextDirectory, signal) => {
300
318
  if (input.timeout !== undefined && input.wait !== true) throw new OpenChamberControlError('timeout requires wait', 400);
301
319
  if (input.lastAssistant === true && input.wait !== true) throw new OpenChamberControlError('lastAssistant requires wait', 400);
320
+ assertSingleScope(input);
302
321
  const sessionID = asNonEmptyString(input.sessionId);
303
322
  let directory = asNonEmptyString(input.directory) || (!input.projectId ? asNonEmptyString(contextDirectory) : null);
304
323
  if (sessionID && action !== 'session.create' && !asNonEmptyString(input.directory) && !input.projectId) {
@@ -585,8 +604,9 @@ export const createOpenChamberControlService = (dependencies) => {
585
604
  return executeSessionAction(action, input, contextDirectory, options.signal);
586
605
  }
587
606
  if (action.startsWith('session.')) {
588
- const directory = asNonEmptyString(input.directory) || asNonEmptyString(contextDirectory);
589
607
  const sessionID = asNonEmptyString(input.sessionId);
608
+ if (action !== 'session.list' && !sessionID) throw new OpenChamberControlError('sessionId is required', 400);
609
+ const directory = await resolveReadDirectory(input, contextDirectory);
590
610
  const client = await getClient(directory);
591
611
  if (action === 'session.list') {
592
612
  const limit = positiveInteger(input.limit, 10, 'limit');
@@ -609,7 +629,6 @@ export const createOpenChamberControlService = (dependencies) => {
609
629
  }
610
630
  return { sessions, limit, directory, archived: input.all === true ? 'included' : 'excluded' };
611
631
  }
612
- if (!sessionID) throw new OpenChamberControlError('sessionId is required', 400);
613
632
  if (!directory) throw new OpenChamberControlError('directory is required', 400);
614
633
  if (action === 'session.status') {
615
634
  return { sessionId: sessionID, directory, sessionStatus: await sessionStatus(client, sessionID) };
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import fs from 'node:fs/promises';
6
6
 
7
7
  import { createOpenChamberControlService } from './service.js';
8
+ import { OpenChamberControlError } from './error.js';
8
9
 
9
10
  const createService = (overrides = {}) => {
10
11
  const client = {
@@ -18,6 +19,10 @@ const createService = (overrides = {}) => {
18
19
  };
19
20
  const sessionService = {
20
21
  create: vi.fn(async () => ({ sessionId: 'ses_1', directory: '/repo', promptDispatched: false })),
22
+ resolveDirectory: vi.fn(async ({ projectId }) => {
23
+ if (projectId === 'project-1') return '/repo';
24
+ throw new OpenChamberControlError('Project not found', 404);
25
+ }),
21
26
  send: vi.fn(),
22
27
  fork: vi.fn(),
23
28
  };
@@ -228,6 +233,51 @@ describe('OpenChamber control service', () => {
228
233
  });
229
234
  });
230
235
 
236
+ it('scopes session reads to an explicit project instead of the tool context directory', async () => {
237
+ const { service, client, sessionService } = createService();
238
+ client.session.list.mockResolvedValue({ data: [{ id: 'ses_repo', location: { directory: '/repo' }, time: {} }] });
239
+
240
+ await expect(service.execute('session.list', { projectId: ' project-1 ' }, '/current-session')).resolves.toEqual(
241
+ expect.objectContaining({ directory: '/repo', sessions: [{ id: 'ses_repo', location: { directory: '/repo' }, time: {} }] }),
242
+ );
243
+ expect(sessionService.resolveDirectory).toHaveBeenCalledWith({ projectId: 'project-1' });
244
+ expect(client.session.list).toHaveBeenCalledWith({ directory: '/repo' });
245
+
246
+ await expect(service.execute('session.status', { projectId: 'project-1', sessionId: 'ses_repo' }, '/current-session'))
247
+ .resolves.toEqual({ sessionId: 'ses_repo', directory: '/repo', sessionStatus: { type: 'idle' } });
248
+ });
249
+
250
+ it('rejects an unknown project instead of reading another directory', async () => {
251
+ const { service, client } = createService();
252
+ await expect(service.execute('session.list', { projectId: 'missing' }, '/current-session'))
253
+ .rejects.toMatchObject({ statusCode: 404, message: 'Project not found' });
254
+ await expect(service.execute('session.list', { projectId: 'missing' }))
255
+ .rejects.toMatchObject({ statusCode: 404 });
256
+ await expect(service.execute('session.messages', { projectId: 'missing', sessionId: 'ses_1' }, '/current-session'))
257
+ .rejects.toMatchObject({ statusCode: 404 });
258
+ expect(client.session.list).not.toHaveBeenCalled();
259
+ expect(client.message.list).not.toHaveBeenCalled();
260
+ });
261
+
262
+ it('asks for sessionId before looking up the project', async () => {
263
+ const { service, sessionService } = createService();
264
+ await expect(service.execute('session.status', { projectId: 'missing' }, '/current-session'))
265
+ .rejects.toMatchObject({ statusCode: 400, message: 'sessionId is required' });
266
+ expect(sessionService.resolveDirectory).not.toHaveBeenCalled();
267
+ });
268
+
269
+ it('rejects any session action scoped by both projectId and directory', async () => {
270
+ const { service, client, sessionService } = createService();
271
+ for (const action of ['session.list', 'session.status', 'session.create', 'session.send', 'session.fork']) {
272
+ await expect(service.execute(action, { projectId: 'project-1', directory: '/other', sessionId: 'ses_1', prompt: 'hi' }))
273
+ .rejects.toMatchObject({ statusCode: 400, message: 'Provide only one of projectId or directory' });
274
+ }
275
+ expect(client.session.list).not.toHaveBeenCalled();
276
+ expect(sessionService.create).not.toHaveBeenCalled();
277
+ expect(sessionService.send).not.toHaveBeenCalled();
278
+ expect(sessionService.fork).not.toHaveBeenCalled();
279
+ });
280
+
231
281
  it('names limit in positive-integer validation errors', async () => {
232
282
  const { service, client } = createService();
233
283
  await expect(service.execute('session.list', { limit: 0 })).rejects.toThrow('limit must be a positive integer');
@@ -979,8 +979,23 @@ export const createOpenChamberSessionService = (dependencies) => {
979
979
  }
980
980
  };
981
981
 
982
+ // The control service's session reads resolve projectId through the same
983
+ // lookup as create/send/fork, so an unknown project or a missing project
984
+ // folder fails the same way everywhere.
985
+ const resolveDirectory = async (payload) => {
986
+ const resolved = await resolveRequestedDirectory({
987
+ payload,
988
+ readSettingsFromDiskMigrated,
989
+ sanitizeProjects,
990
+ validateDirectoryPath,
991
+ });
992
+ if (!resolved.ok) throw new OpenChamberControlError(resolved.error, resolved.status || 400);
993
+ return resolved.directory;
994
+ };
995
+
982
996
  return {
983
997
  create,
998
+ resolveDirectory,
984
999
  archive,
985
1000
  unarchive,
986
1001
  archiveStore,
@@ -1068,3 +1068,34 @@ describe('openchamber session routes', () => {
1068
1068
  expect(sessionPromptMock).not.toHaveBeenCalled();
1069
1069
  });
1070
1070
  });
1071
+
1072
+ describe('openchamber session service directory resolution', () => {
1073
+ const createService = async (overrides = {}) => {
1074
+ const { createOpenChamberSessionService } = await import('./routes.js');
1075
+ return createOpenChamberSessionService({
1076
+ archiveStore: createMemoryArchiveStore(),
1077
+ sessionMetadataStore: createMemorySessionMetadataStore(),
1078
+ readSettingsFromDiskMigrated: async () => ({ projects: [{ id: 'proj_1', path: '/repo/app' }] }),
1079
+ sanitizeProjects: (projects) => projects,
1080
+ validateDirectoryPath: async (directory) => ({ ok: true, directory }),
1081
+ buildOpenCodeUrl: (route) => `http://opencode.test${route}`,
1082
+ getOpenCodeAuthHeaders: () => ({}),
1083
+ ...overrides,
1084
+ });
1085
+ };
1086
+
1087
+ it('resolves a registered project to its directory', async () => {
1088
+ const service = await createService();
1089
+ await expect(service.resolveDirectory({ projectId: 'proj_1' })).resolves.toBe('/repo/app');
1090
+ });
1091
+
1092
+ it('fails for an unknown project, a missing project folder, or unreadable settings', async () => {
1093
+ await expect((await createService()).resolveDirectory({ projectId: 'missing' }))
1094
+ .rejects.toMatchObject({ statusCode: 404, message: 'Project not found' });
1095
+ const goneFolder = await createService({ validateDirectoryPath: async () => ({ ok: false, error: 'Directory not found' }) });
1096
+ await expect(goneFolder.resolveDirectory({ projectId: 'proj_1' }))
1097
+ .rejects.toMatchObject({ statusCode: 400, message: 'Directory not found' });
1098
+ const unreadable = await createService({ readSettingsFromDiskMigrated: async () => { throw new Error('settings unreadable'); } });
1099
+ await expect(unreadable.resolveDirectory({ projectId: 'proj_1' })).rejects.toThrow('settings unreadable');
1100
+ });
1101
+ });
@@ -96,40 +96,45 @@ and OpenChamber resolves the directory itself.
96
96
  - `packages/web/server/lib/ui-auth/ui-passkeys.js`: UI passkey storage and WebAuthn registration/authentication helpers (outside OpenCode module).
97
97
 
98
98
  ## Public exports (auth.js)
99
- `auth.js` is read-only. OpenCode 2.x imports `auth.json` once into its own
100
- database and never writes the file again; credentials live behind
101
- `/api/integration` and `/api/credential`, and no HTTP route hands a key back.
102
- OpenChamber needs the raw credential for provider quota lookups, voice keys and
103
- the GitHub and Linear helpers, so `readAuthFile()` answers from the database
104
- OpenCode actually uses (`credential-db.js`, below). A successful database read
105
- is authoritative, `{}` included: OpenCode never clears `auth.json` after the
106
- import and a credential removed in OpenCode vanishes only from the database,
107
- so the file is never merged over a readable database. The legacy file is the
108
- fallback only when the database cannot be read (no sqlite runtime, no file,
109
- unknown schema); a corrupt file then throws, but never blocks a healthy
110
- database. A write here would be invisible to the running OpenCode, so every
111
- write path is gone.
112
-
113
- - `readAuthFile()`: The credentials OpenCode uses, keyed by provider id, in the
114
- legacy `auth.json` entry shape (`{ type: 'api', key }` /
99
+ `auth.js` is read-only. OpenCode 2.x owns every credential and, since 2.0.20,
100
+ hands them back over `GET /api/credential`, secrets included. OpenChamber needs
101
+ the raw credential for provider quota lookups, voice keys and routing, so
102
+ `readOpenCodeCredentials()` asks the running OpenCode, through the connection
103
+ `server/index.js` wires with `configureOpenCodeCredentials()`. Concurrent
104
+ callers share one request; nothing is cached between calls. A failed read
105
+ throws, so an unreachable OpenCode never reads as "no keys".
106
+
107
+ Clients never get that list. `GET /api/credential` (any spelling OpenCode
108
+ routes the same way, matched by `isCredentialListRequest` in
109
+ `../enterprise-mode.js`) answers 403 `credential_list_refused` before the
110
+ generic proxy, in and out of enterprise mode: anyone signed in to the UI,
111
+ over a tunnel or a paired phone too, would otherwise read every key. Renaming,
112
+ switching and removing an account still reach OpenCode.
113
+
114
+ Keys OpenCode takes from environment variables (`ZAI_API_KEY`, ...) are never
115
+ stored and `/api/credential` does not list them; `GET /api/integration` names
116
+ the variable behind each such connection, but not its value. For a managed
117
+ OpenCode the lifecycle keeps the exact environment it launched the process
118
+ with (`getManagedOpenCodeProcessEnv()`), and the reader takes the value from
119
+ there, only for variables OpenCode itself reports. A stored credential wins
120
+ over a variable, as in OpenCode. An external OpenCode runs with its own
121
+ environment, so its variable keys stay unknown and are left out.
122
+ `getProviderAuth()` answers stored credentials only: it asks whether a login
123
+ exists in OpenCode's store.
124
+
125
+ - `configureOpenCodeCredentials(source | null)`: wires the reader to a `{ list }` credential source; reads throw until it is wired.
126
+ - `openCodeCredentialSource({ buildOpenCodeUrl, getOpenCodeAuthHeaders, getLaunchEnvironment? })`: the running OpenCode as that source, URL and headers read per call; `getLaunchEnvironment` returns the managed launch environment or null.
127
+ - `readOpenCodeCredentials()`: each integration's active credential, keyed by
128
+ integration id (the provider id for providers), in the legacy `auth.json`
129
+ entry shape (`{ type: 'api', key }` /
115
130
  `{ type: 'oauth', access, refresh, expires, accountId?, enterpriseUrl? }`).
116
- - `getProviderAuth(providerId)`: Returns auth for a specific provider or null.
117
- - `listProviderAuths()`: Returns list of provider IDs with configured auth.
118
- - `AUTH_FILE`: Legacy auth file path constant.
119
- - `OPENCODE_DATA_DIR`: OpenCode data directory path constant.
120
-
121
- ### credential-db.js
122
-
123
- Reads `<data>/opencode.db` (or `OPENCODE_DB`), table `credential`, where
124
- OpenCode 2.x stores every credential as plain JSON. This is OpenCode's private
125
- schema, verified against v2.0.x `packages/core/src/credential/sql.ts`; the
126
- reader opens the file read-only, picks the `active` row per integration (else
127
- the newest), projects `{ type: 'key' }` / `{ type: 'oauth' }` values into the
128
- legacy entry shape, and answers `null` for anything it cannot do (no sqlite
129
- runtime, no file, a changed schema), so the caller can tell "no credentials"
130
- from "could not look" and fall back to the file. `node:sqlite` on Node 22.13+,
131
- `bun:sqlite` on Bun; no dependency is added. `packages/vscode/src/opencodeAuth.ts`
132
- is the extension-host mirror.
131
+ - `getProviderAuth(providerId)`: that map's entry for one provider, or null.
132
+ - `projectCredentialEntries(entries)`: the wire-to-legacy projection.
133
+ - `projectEnvironmentKeys(integrations, environment)`: variable values for the env connections OpenCode reports, by integration id.
134
+
135
+ The VS Code extension host uses this same module through
136
+ `packages/vscode/src/opencodeAuth.ts`, which only builds the source from its
137
+ OpenCode manager (`getManagedLaunchEnvironment()` there).
133
138
 
134
139
  ### v1-migration-topup.js
135
140
 
@@ -145,8 +150,8 @@ It runs from `lifecycle.js` immediately before the MANAGED OpenCode is spawned:
145
150
  never for an external, user-started OpenCode, and never while a managed one is
146
151
  running, because the write would race OpenCode's own loop. Failure is never
147
152
  fatal to startup. It opens `<data>/opencode.db` (or `OPENCODE_DB`) read-write
148
- with the same loader strategy as `credential-db.js` — `node:sqlite` on Node,
149
- `bun:sqlite` on Bun, skip silently on neither. It returns
153
+ through `node:sqlite` on Node or `bun:sqlite` on Bun, and skips silently on
154
+ neither. It returns
150
155
  `{ status: 'skipped' | 'scheduled' | 'unsafe' | 'unavailable', missing, revisited, reason? }`
151
156
  and logs one line; there is no HTTP route and no UI.
152
157
 
@@ -190,7 +195,7 @@ Hard rules, verified against v2.0.8 (the completion stamp against v2.0.16)
190
195
  ## Public exports (providers.js)
191
196
  - `getProviderSources(providerId, workingDirectory)`: Resolves which OpenCode config layers define a provider.
192
197
  - `listProviderConfigs(workingDirectory)`: Every provider a config layer defines, projected into the canonical v2 `ProviderEntity` shape, with `legacy` marking entries still stored under the v1 `provider` key.
193
- - `upsertProviderConfig(providerId, config, workingDirectory, scope?, options?)`: Validates and writes a custom provider block into the user/project/custom config layer. The payload may use the v2 spelling (`package`, `settings.baseURL`, `headers`) or the v1 spelling (`npm`, `options.baseURL`); what lands on disk is always a v2 `providers` entry with `package: "aisdk:<npm>"` and `settings.baseURL`. The adapter may be OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages. Existing provider, option, and retained-model fields not managed by the form are preserved; omitted models, headers, and env credentials remain explicit removals. A model's `variants` (reasoning levels) are replaced when the payload carries the array, cleared when it carries an empty one, and kept when the key is absent. Updating an entry still stored under the legacy `provider` key rewrites it under `providers` in the same file, dropping the fields v2 accepts but ignores; unrelated legacy siblings are untouched. Does not store API keys. Requires `config.env` or `options.hasStoredAuth`. OpenCode 2 keeps credentials in its own store, so `PUT /api/provider` sets `hasStoredAuth` from the request's `hasCredential` (the form is about to store a key, or the edited provider keeps its credential) as well as a legacy `auth.json` entry. The key itself goes through `integration.connect.key` after this write, because OpenCode registers a custom provider's key method only once the provider is in config. Edit flows must pass the provider's effective existing layer (`custom` > `project` > `user`) so updates do not create a global user override.
198
+ - `upsertProviderConfig(providerId, config, workingDirectory, scope?, options?)`: Validates and writes a custom provider block into the user/project/custom config layer. The payload may use the v2 spelling (`package`, `settings.baseURL`, `headers`) or the v1 spelling (`npm`, `options.baseURL`); what lands on disk is always a v2 `providers` entry with `package: "aisdk:<npm>"` and `settings.baseURL`. The adapter may be OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages. Existing provider, option, and retained-model fields not managed by the form are preserved; omitted models, headers, and env credentials remain explicit removals. A model's `variants` (reasoning levels) are replaced when the payload carries the array, cleared when it carries an empty one, and kept when the key is absent. Updating an entry still stored under the legacy `provider` key rewrites it under `providers` in the same file, dropping the fields v2 accepts but ignores; unrelated legacy siblings are untouched. Does not store API keys. Requires `config.env` or `options.hasStoredAuth`. OpenCode 2 keeps credentials in its own store, so `PUT /api/provider` sets `hasStoredAuth` from the request's `hasCredential` (the form is about to store a key, or the edited provider keeps its credential) as well as a credential OpenCode already stores for the provider. The key itself goes through `integration.connect.key` after this write, because OpenCode registers a custom provider's key method only once the provider is in config. Edit flows must pass the provider's effective existing layer (`custom` > `project` > `user`) so updates do not create a global user override.
194
199
  - `validateCustomProviderConfig(providerId, config, options?)`: Structural validation for custom provider payloads (id format, adapter allowlist `@ai-sdk/openai-compatible`/`@ai-sdk/openai`/`@ai-sdk/anthropic`, http(s) base URL, models, credentials via `env` or `hasStoredAuth`). Accepts both spellings and returns the normalized v2 value.
195
200
  - `removeProviderConfig(providerId, workingDirectory, scope?)`: Removes a provider block from the selected config layer.
196
201
 
@@ -223,7 +228,7 @@ Hard rules, verified against v2.0.8 (the completion stamp against v2.0.16)
223
228
  - `GET /api/provider/:providerId/source`
224
229
  - `PUT /api/provider` (create/update custom OpenAI-compatible provider config in OpenCode user/project/custom layers via `scope`; secrets stay in auth via the OpenCode auth API)
225
230
  - `DELETE /api/provider/:providerId/auth`
226
- - Enterprise mode (`../enterprise-mode.js`): `PUT /api/provider` and the OpenCode writes that would otherwise pass the generic proxy — every `POST` under `/api/integration/:id/connect` (key, OAuth start and complete, command) and `POST /api/experimental/integration/wellknown`, matched by `isProviderConnectRequest` — answer 403 `enterprise_mode`. The VS Code extension host refuses the same requests with the same matcher. Removing, activating or renaming an existing credential still reaches OpenCode. This closes the way in through the app; OpenCode's `provider.use` policy is the real lock.
231
+ - Enterprise mode (`../enterprise-mode.js`): `PUT /api/provider` and the OpenCode writes that would otherwise pass the generic proxy — every `POST` under `/api/integration/:id/connect` (key, OAuth start and complete, command), `POST /api/credential` (stores a key, OpenCode 2.0.20) and `POST /api/experimental/integration/wellknown`, matched by `isProviderConnectRequest` — answer 403 `enterprise_mode`. The matcher mirrors how OpenCode 2.0.18 to 2.0.20 route a path (any letter case, doubled slashes, `\` for `/`, percent escapes, anything after `;`), refuses a dot segment or a bad escape, and needs rechecking when OpenCode changes its router. Signing in to a remote MCP server (`POST /api/integration/mcp_<16 hex>/connect/oauth` and its `/:attempt/complete`) passes: it reaches a tool server from the OpenCode config, not a model provider. The VS Code extension host refuses the same requests with the same matcher. Removing, activating or renaming an existing credential still reaches OpenCode. This closes the way in through the app; OpenCode's `provider.use` policy is the real lock.
227
232
  - Owns lazy auth library loading for provider auth checks/removal.
228
233
  - Keeps route behavior independent from composition root; `index.js` now supplies dependencies only.
229
234
 
@@ -899,7 +904,7 @@ The VS Code extension owns its separate Git and proxy implementation.
899
904
  - Translates each v2 wire event through `lib/event-stream/translate-v2.js` before handing it to notification/session side effects, so those consumers keep speaking the server's own event vocabulary.
900
905
 
901
906
  ## Storage and configuration
902
- - Provider auth: `~/.local/share/opencode/opencode.db` table `credential` (read-only), with `auth.json` as the legacy fallback; OpenCode 2.x owns credentials.
907
+ - Provider auth: read from the running OpenCode over `GET /api/credential` (2.0.20+); OpenCode 2.x owns credentials.
903
908
  - Session archive state: `sessions-archive.json` under the OpenChamber data dir.
904
909
  - Session metadata (goal progress, the assist recap, the obligatory-context cursor, pinned notes) lives on the OpenCode session record, written with `PATCH /api/session/{id}` (OpenCode 2.0.15+, the minimum `compatibility.js` enforces). OpenCode replaces the whole object, so `sessionMetadataStore.setSessionMetadata` reads the record, applies the JSON Merge Patch and writes the result, one write per session at a time; a record that cannot be read stops the write. Every reader and writer (routes, goal loop, session assist, session knowledge, obligatory context, notifications) goes through `sessionMetadataStore.get` / `setSessionMetadata`. Older OpenChamber versions kept this state in `sessions-metadata.json` under the data dir. Its entries are the newest metadata their sessions have: the proxy lays them over OpenCode's records, a session's next write pushes its entry, and a sweep after OpenCode starts pushes the rest (a session OpenCode no longer knows is dropped, any other failure waits for the next write or start). The emptied file is renamed to `sessions-metadata.json.migrated`. Archive mutations still run one transaction at a time in the archive store.
905
910
  - User config: `<config dir>/opencode.json(c)` where the config dir is `OPENCODE_CONFIG_DIR`, else `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`. The v1 `config.json` is not read.
@@ -0,0 +1,24 @@
1
+ import type { CredentialEntry, IntegrationInfo, JsonValue } from '@opencode/client';
2
+
3
+ export type LegacyAuthEntry =
4
+ | { type: 'api'; key: string; metadata?: { [key: string]: JsonValue } }
5
+ | { type: 'oauth'; access: string; refresh: string; expires: number; accountId?: string; enterpriseUrl?: string };
6
+ export type LegacyAuthFile = Record<string, LegacyAuthEntry>;
7
+
8
+ /** Where credentials come from: the running OpenCode in production, a fixture in tests. */
9
+ export type CredentialSource = {
10
+ list: () => Promise<CredentialEntry[]>;
11
+ /** Variable keys by integration id; absent when the environment is unknown. */
12
+ listEnvironmentKeys?: () => Promise<Record<string, string>>;
13
+ };
14
+
15
+ export function configureOpenCodeCredentials(next: CredentialSource | null): void;
16
+ export function openCodeCredentialSource(connection: {
17
+ buildOpenCodeUrl: (path: string, prefix?: string) => string;
18
+ getOpenCodeAuthHeaders: () => Record<string, string>;
19
+ getLaunchEnvironment?: () => Record<string, string | undefined> | null;
20
+ }): CredentialSource;
21
+ export function projectEnvironmentKeys(integrations: IntegrationInfo[], environment: Record<string, string | undefined>): Record<string, string>;
22
+ export function projectCredentialEntries(entries: CredentialEntry[]): LegacyAuthFile;
23
+ export function readOpenCodeCredentials(): Promise<LegacyAuthFile>;
24
+ export function getProviderAuth(providerId: string): Promise<LegacyAuthEntry | null>;