@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
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { SpaceError } from '../errors.js';
5
5
  import { GATEKEEPER_PROGRAM_PATH, IMAGE_CAT, IMAGE_CURL, IMAGE_SH, SPACE_HOME, SPACE_TOKEN_PATH, TOOLS_MOUNT_PATH } from '../layout.js';
6
+ import { SPACE_BASE_IMAGE } from './docker.js';
6
7
 
7
8
  const ok = (stdout = '') => ({ code: 0, stdout, stderr: '' });
8
9
  const failed = (stderr, stdout = '') => ({ code: 1, stdout, stderr });
@@ -16,6 +17,9 @@ const NOT_FOUND_TEXT = {
16
17
 
17
18
  const ISOLATED_GATEWAY_OPTION = 'com.docker.network.bridge.gateway_mode_ipv4';
18
19
 
20
+ // Every container the place makes comes from its one image; a seeded stranger's may name another.
21
+ const FAKE_BASE_IMAGE = SPACE_BASE_IMAGE;
22
+
19
23
  const readPairs = (args, flag) => {
20
24
  const pairs = {};
21
25
  args.forEach((arg, index) => {
@@ -59,6 +63,7 @@ export function hardenedContainerEntry({
59
63
  memoryBytes = 4294967296,
60
64
  tmpfs = '/tmp:rw,exec,nosuid,size=256m',
61
65
  aliases = [],
66
+ image = FAKE_BASE_IMAGE,
62
67
  }) {
63
68
  const mountList = mounts ?? [
64
69
  ...volumes.map((volume) => ({ volume, destination: `/mnt/${volume}` })),
@@ -69,7 +74,7 @@ export function hardenedContainerEntry({
69
74
  Id: newContainerId(),
70
75
  Name: `/${name}`,
71
76
  State: { Running: running, Status: running ? 'running' : 'created' },
72
- Config: { User: '1000:1000', Labels: labels, Env: env },
77
+ Config: { User: '1000:1000', Labels: labels, Env: env, Image: image },
73
78
  HostConfig: {
74
79
  ReadonlyRootfs: true,
75
80
  Privileged: false,
@@ -154,6 +159,9 @@ const readMounts = (args) => args
154
159
  * `gatekeeperReady: false` does the same for every gatekeeper's control channel.
155
160
  * `start` is where the clock of `now()` begins. `wait(ms)` moves that clock, so nothing here sleeps.
156
161
  * `beforeFill()` runs before a tools fill ends, so a test can hold it open.
162
+ * For the disk: `volumeSizes` maps a volume name to its size as `docker system df` prints it,
163
+ * `imageBytes` is the size of the space image, `engineName` what `docker info` calls the machine,
164
+ * and `colima(args)` answers a call of the colima CLI, any file whose name ends in `colima`.
157
165
  */
158
166
  export function createFakeDocker({
159
167
  failAt = () => false,
@@ -161,6 +169,10 @@ export function createFakeDocker({
161
169
  interruptionCode = 'command_timeout',
162
170
  resources = [],
163
171
  imagePresent = true,
172
+ imageBytes = 1_632_000_000,
173
+ volumeSizes = {},
174
+ engineName = 'docker-desktop',
175
+ colima = () => ok(),
164
176
  alterContainer = (entry) => entry,
165
177
  serverReady = true,
166
178
  gatekeeperReady = true,
@@ -168,6 +180,7 @@ export function createFakeDocker({
168
180
  start = new Date('2026-09-20T08:00:00.000Z'),
169
181
  } = {}) {
170
182
  let clock = start.getTime();
183
+ let image = imagePresent;
171
184
  const calls = [];
172
185
  const late = [];
173
186
  const state = new Map(resources.map((resource) => [`${resource.kind}:${resource.name}`, resource]));
@@ -190,6 +203,7 @@ export function createFakeDocker({
190
203
  const labels = (resource.kind === 'container' ? resource.entry.Config?.Labels : resource.entry.Labels) ?? {};
191
204
  return args.every((arg, index) => {
192
205
  if (args[index - 1] !== '--filter') return true;
206
+ if (arg.startsWith('ancestor=')) return resource.entry.Config?.Image === arg.slice('ancestor='.length);
193
207
  const pair = arg.slice('label='.length);
194
208
  return labels[pair.slice(0, pair.indexOf('='))] === pair.slice(pair.indexOf('=') + 1);
195
209
  });
@@ -283,7 +297,25 @@ export function createFakeDocker({
283
297
  if (first === 'create') return fails ? (addContainer(args, { running: false }), failed('Error response from daemon: simulated failure')) : addContainer(args, { running: false });
284
298
  if (fails) return failed('Error response from daemon: simulated failure');
285
299
  if (first === 'inspect') return inspect('container', args.slice(3));
286
- if (first === 'image' && second === 'inspect') return imagePresent ? ok('[{}]') : failed(NOT_FOUND_TEXT.image(args[2]), '[]');
300
+ // The size here is the compressed download, as the containerd image store reports it; the place must not use it.
301
+ if (first === 'image' && second === 'inspect') return image ? ok(JSON.stringify([{ Id: 'sha256:0123', Size: Math.round(imageBytes / 4) }])) : failed(NOT_FOUND_TEXT.image(args[2]), '[]');
302
+ if (first === 'image' && second === 'rm') {
303
+ if (!image || args[args.length - 1] !== FAKE_BASE_IMAGE) return failed(NOT_FOUND_TEXT.image(args[args.length - 1]));
304
+ // Like the real engine: without --force an image that any container was made from stays.
305
+ const user = ofKind('container').find((resource) => resource.entry.Config?.Image === FAKE_BASE_IMAGE);
306
+ if (user && !args.includes('--force')) return failed(`Error response from daemon: conflict: unable to delete 0123 (must be forced) - image is being used by stopped container ${user.entry.Id}`);
307
+ image = false;
308
+ return ok(`Deleted: sha256:0123`);
309
+ }
310
+ if (first === 'system' && second === 'df') {
311
+ const mountedBy = (name) => ofKind('container').filter((resource) => resource.entry.Mounts.some((mount) => mount.Name === name)).length;
312
+ return ok(JSON.stringify({
313
+ // Like the containerd image store: the id is the digest, and the size is what the image alone takes unpacked.
314
+ Images: image ? [{ ID: 'sha256:0123', Size: `${imageBytes / 1e9}GB`, UniqueSize: `${imageBytes / 1e9}GB` }] : [],
315
+ Volumes: ofKind('volume').map((resource) => ({ Name: resource.name, Size: volumeSizes[resource.name] ?? '0B', Links: String(mountedBy(resource.name)) })),
316
+ }));
317
+ }
318
+ if (first === 'info') return ok(`${JSON.stringify(engineName)}\n`);
287
319
  if (first === 'pull') return ok();
288
320
  if (first === 'ps') return ok(ofKind('container').filter((resource) => matchesFilters(resource, args)).map((resource) => resource.name).join('\n'));
289
321
  if (first === 'rm') {
@@ -349,6 +381,7 @@ export function createFakeDocker({
349
381
 
350
382
  const runCommand = async (file, args, options) => {
351
383
  calls.push({ file, args, options });
384
+ if (String(file).endsWith('colima')) return colima(args);
352
385
  if (timeoutAt(args)) {
353
386
  late.push(args);
354
387
  throw new SpaceError(interruptionCode, `docker ${args[0]} was stopped before it finished`);
@@ -372,6 +405,7 @@ export function createFakeDocker({
372
405
  now: () => new Date(clock),
373
406
  calls,
374
407
  names: () => Array.from(state.keys()),
408
+ imagePresent: () => image,
375
409
  token: (container) => tokens.get(homeOf(container)),
376
410
  };
377
411
  }
@@ -5,8 +5,10 @@
5
5
  //
6
6
  // Every route but the switch exists only while the switch is on: `getJourney()` answers null
7
7
  // while it is off, and then the journey routes say so with 404 and `isolated_spaces_off`, the same
8
- // answer a route that does not exist would give. The switch itself is the one thing reachable
9
- // while the feature is off, because turning it on is what makes the feature exist (decision 19).
8
+ // answer a route that does not exist would give. The switch itself is reachable while the feature
9
+ // is off, because turning it on is what makes the feature exist (decision 19), and so is the list
10
+ // of chat archives: those chats stay on the Archive page with the switch on or off, and reading
11
+ // that list is a file of the host's, which runs nothing of the feature.
10
12
  // `/api/openchamber/spaces` is on the JSON-body allowlist of `core-routes.js`.
11
13
 
12
14
  import { z } from 'zod';
@@ -59,6 +61,7 @@ const STATUS_BY_CODE = new Map([
59
61
  ['gatekeeper_missing', 409],
60
62
  ['invalid_setup_commands', 400],
61
63
  ['space_setup_running', 409],
64
+ ['chats_not_saved', 409],
62
65
  ]);
63
66
 
64
67
  /** One JSON answer per failure, with a stable code. Details travel as data; a stack never does. */
@@ -133,7 +136,7 @@ export function createSwitchController({ getHost, setHost, buildHost, startHost,
133
136
  * `readSwitch()` and `setSwitch(enabled)` the switch: `setSwitch(false)` stops the spaces and takes
134
137
  * the feature down, `setSwitch(true)` brings it up, and each resolves what the client shows.
135
138
  */
136
- export function registerSpaceRoutes(app, { getJourney, getPlaces = () => [], readSwitch, setSwitch }) {
139
+ export function registerSpaceRoutes(app, { getJourney, getPlaces = () => [], readSwitch, setSwitch, getArchive = () => null }) {
137
140
  const withJourney = (handler) => async (req, res) => {
138
141
  const journey = getJourney();
139
142
  if (!journey) {
@@ -176,6 +179,11 @@ export function registerSpaceRoutes(app, { getJourney, getPlaces = () => [], rea
176
179
  }
177
180
  });
178
181
 
182
+ // The archives of deleted spaces, for the Archive page: which directory holds which space's chats.
183
+ app.get(`${SPACES_ROUTE}/archives`, (_req, res) => {
184
+ res.json({ archives: getArchive()?.listArchives() ?? [] });
185
+ });
186
+
179
187
  // The idle stop setting (decision 11): kept in the settings and told to every running space.
180
188
  app.get(`${SPACES_ROUTE}/idle-stop`, withJourney(async (journey, _req, res) => {
181
189
  res.json(await journey.readIdleStopSetting());
@@ -190,6 +198,14 @@ export function registerSpaceRoutes(app, { getJourney, getPlaces = () => [], rea
190
198
  res.json({ places });
191
199
  }));
192
200
 
201
+ // The disk a place's spaces take, and the clean-up of what OpenChamber can make again.
202
+ app.get(`${SPACES_ROUTE}/places/:placeId/disk`, withJourney(async (journey, req, res) => {
203
+ res.json(await journey.readDisk(String(req.params.placeId ?? '')));
204
+ }));
205
+ app.post(`${SPACES_ROUTE}/places/:placeId/clean-up`, withJourney(async (journey, req, res) => {
206
+ res.json(await journey.cleanUpDisk(String(req.params.placeId ?? '')));
207
+ }));
208
+
193
209
  app.get(SPACES_ROUTE, withJourney(async (journey, _req, res) => {
194
210
  res.json({ spaces: await journey.listSpaces({ access: true }) });
195
211
  }));
@@ -217,7 +233,8 @@ export function registerSpaceRoutes(app, { getJourney, getPlaces = () => [], rea
217
233
  }));
218
234
 
219
235
  app.delete(`${SPACES_ROUTE}/:id`, withJourney(async (journey, req, res) => {
220
- res.json(await journey.removeSpace(spaceIdOf(req)));
236
+ // `?unsavedChats=delete` is the user's "Delete anyway" after chats could not be saved.
237
+ res.json(await journey.removeSpace(spaceIdOf(req), { allowUnsaved: req.query?.unsavedChats === 'delete' }));
221
238
  }));
222
239
 
223
240
  // A grant for a running space; the key in the body goes to the gatekeeper and nowhere else.
@@ -66,6 +66,8 @@ const journeyOf = (overrides = {}) => {
66
66
  changeIdleStop: record('changeIdleStop', { enabled: false, hours: 8 }),
67
67
  runSetup: record('runSetup', { id: ID, state: 'running', setup: { state: 'running', index: 0, total: 1, command: 'npm ci' } }),
68
68
  readSetup: record('readSetup', { setup: null, output: null }),
69
+ readDisk: record('readDisk', { imageBytes: null, toolsBytes: 0, spacesBytes: 0, freeBytes: 0, freesImage: false }),
70
+ cleanUpDisk: record('cleanUpDisk', { freedBytes: 0, kept: [], disk: null }),
69
71
  ...overrides,
70
72
  };
71
73
  };
@@ -73,7 +75,7 @@ const journeyOf = (overrides = {}) => {
73
75
  describe('space routes', () => {
74
76
  it('answers every journey route with 404 and isolated_spaces_off while the feature is off, and the switch still works', async () => {
75
77
  const { call, calls } = await serve({ journey: null, switchState: { enabled: false } });
76
- for (const [method, path] of [['GET', ''], ['POST', ''], ['GET', '/places'], ['POST', `/${ID}/start`], ['POST', `/${ID}/stop`], ['POST', `/${ID}/restart`], ['POST', `/${ID}/restart-opencode`], ['POST', `/${ID}/grants`], ['DELETE', `/${ID}`], ['GET', `/${ID}/journal`], ['GET', `/${ID}/apply`], ['POST', `/${ID}/apply`], ['GET', '/idle-stop'], ['PUT', '/idle-stop'], ['POST', `/${ID}/setup`], ['GET', `/${ID}/setup`]]) {
78
+ for (const [method, path] of [['GET', ''], ['POST', ''], ['GET', '/places'], ['POST', `/${ID}/start`], ['POST', `/${ID}/stop`], ['POST', `/${ID}/restart`], ['POST', `/${ID}/restart-opencode`], ['POST', `/${ID}/grants`], ['DELETE', `/${ID}`], ['GET', `/${ID}/journal`], ['GET', `/${ID}/apply`], ['POST', `/${ID}/apply`], ['GET', '/idle-stop'], ['PUT', '/idle-stop'], ['POST', `/${ID}/setup`], ['GET', `/${ID}/setup`], ['GET', '/places/docker/disk'], ['POST', '/places/docker/clean-up']]) {
77
79
  expect(await call(method, `${SPACES_ROUTE}${path}`, method === 'GET' || method === 'DELETE' ? undefined : {}), `${method} ${path}`).toEqual({ status: 404, body: { code: 'isolated_spaces_off', message: 'Isolated spaces are turned off.', details: null } });
78
80
  }
79
81
  expect(await call('GET', `${SPACES_ROUTE}/switch`)).toEqual({ status: 200, body: { enabled: false, spaces: [] } });
@@ -103,6 +105,8 @@ describe('space routes', () => {
103
105
  const { call } = await serve({ journey, places });
104
106
  expect(await call('GET', `${SPACES_ROUTE}/places`)).toEqual({ status: 200, body: { places: [{ id: 'docker', available: true, version: '29.2.1', hostIsolation: true }] } });
105
107
  expect(await call('GET', SPACES_ROUTE)).toEqual({ status: 200, body: { spaces: [{ id: ID, name: 'One', state: 'running' }] } });
108
+ expect(await call('GET', `${SPACES_ROUTE}/places/docker/disk`)).toEqual({ status: 200, body: { imageBytes: null, toolsBytes: 0, spacesBytes: 0, freeBytes: 0, freesImage: false } });
109
+ expect(await call('POST', `${SPACES_ROUTE}/places/docker/clean-up`)).toEqual({ status: 200, body: { freedBytes: 0, kept: [], disk: null } });
106
110
  const request = { projectDirectory: '/home/me/project', name: 'One', start: 'clean', network: { mode: 'open' } };
107
111
  expect(await call('POST', SPACES_ROUTE, request)).toEqual({ status: 202, body: { id: ID, state: 'preparing' } });
108
112
  expect(await call('POST', `${SPACES_ROUTE}/${ID}/start`)).toEqual({ status: 200, body: { id: ID, state: 'running' } });
@@ -118,7 +122,7 @@ describe('space routes', () => {
118
122
  expect(await call('GET', `${SPACES_ROUTE}/${ID}/setup`)).toEqual({ status: 200, body: { setup: null, output: null } });
119
123
  expect(await call('DELETE', `${SPACES_ROUTE}/${ID}`)).toEqual({ status: 200, body: { id: ID, removed: true } });
120
124
  expect(journey.calls).toEqual([
121
- ['listSpaces', { access: true }], ['createSpace', request], ['startSpace', ID], ['stopSpace', ID], ['restartSpace', ID], ['restartOpenCode', ID], ['grantAccess', ID, { kind: 'domain', upstream: 'https://registry.example.com/' }], ['openDomain', ID, { domain: 'registry.npmjs.org' }], ['readJournal', ID], ['previewApply', ID], ['applySpace', ID, { as: 'branch', branch: 'b' }], ['runSetup', ID, { commands: ['npm ci'] }], ['readSetup', ID], ['removeSpace', ID],
125
+ ['listSpaces', { access: true }], ['readDisk', 'docker'], ['cleanUpDisk', 'docker'], ['createSpace', request], ['startSpace', ID], ['stopSpace', ID], ['restartSpace', ID], ['restartOpenCode', ID], ['grantAccess', ID, { kind: 'domain', upstream: 'https://registry.example.com/' }], ['openDomain', ID, { domain: 'registry.npmjs.org' }], ['readJournal', ID], ['previewApply', ID], ['applySpace', ID, { as: 'branch', branch: 'b' }], ['runSetup', ID, { commands: ['npm ci'] }], ['readSetup', ID], ['removeSpace', ID, { allowUnsaved: false }],
122
126
  ]);
123
127
  });
124
128
 
@@ -0,0 +1,275 @@
1
+ // The chat archive of a deleted space (DESIGN.md, decision 9 and journey step 7), built in 5e-2.
2
+ //
3
+ // Before a space goes, its chats are taken out and imported into the host's OpenCode at a
4
+ // directory of the archive's own, stamped archived, so they show on the Archive page and nowhere
5
+ // else. An imported chat is a live session of the host's OpenCode: anything sent to it would run
6
+ // on the host, measured. So the archive is read-only here, on the server, and not only on the
7
+ // screen: `guard` refuses every request that would run or change an archived chat, and lets it be
8
+ // read and deleted.
9
+ //
10
+ // The host keeps one small file per archive, `<data dir>/spaces/archive/<space id>.json`: the
11
+ // space's name, its project and the ids of its chats. The guard and the Archive page read those.
12
+ // Nothing here runs a container or a `docker` command, so the archive and its guard are there
13
+ // whether the feature's switch is on or off: an archived chat stays read-only either way.
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ import { z } from 'zod';
19
+
20
+ import { SpaceError } from './errors.js';
21
+ import { archivedChatOf, chatIdSchema } from './space-opencode.js';
22
+
23
+ // The maintainer's call of 2026-09-30: at most this many chats of one space go to the archive.
24
+ export const ARCHIVE_MAX_CHATS = 1000;
25
+ // All the chats of one space are taken out within this, however slowly the space answers; the
26
+ // rest counts as not saved, so a space cannot hold its own delete.
27
+ const SAVE_TIMEOUT_MS = 30 * 60_000;
28
+ // A title from a space is shown as text; this much of it is enough to name the chat.
29
+ const TITLE_SHOWN_CHARACTERS = 200;
30
+
31
+ const spaceIdSchema = z.string().regex(/^[a-f0-9]{12}$/);
32
+
33
+ const archiveEntrySchema = z.object({
34
+ version: z.literal(1),
35
+ spaceId: spaceIdSchema,
36
+ name: z.string().max(200),
37
+ projectDirectory: z.string().nullable(),
38
+ archivedAt: z.number().int().nonnegative(),
39
+ chats: z.array(chatIdSchema),
40
+ });
41
+
42
+ // A request that would run or change a chat, by the session id in its path. Reads pass, and so
43
+ // does `DELETE /api/session/<id>`, which is how the user deletes an archived chat.
44
+ const CHAT_ROUTES = [
45
+ /^\/api\/session\/([^/]+)(\/.*)?$/i,
46
+ /^\/api\/experimental\/session\/([^/]+)\/.+$/i,
47
+ /^\/api\/openchamber\/sessions\/([^/]+)\/.+$/i,
48
+ /^\/api\/message-queue\/sessions\/([^/]+)(\/.*)?$/i,
49
+ /^\/api\/goals\/objective\/([^/]+)$/i,
50
+ /^\/api\/permission-auto-accept\/sessions\/([^/]+)$/i,
51
+ ];
52
+ const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
53
+ const SESSION_DELETE = /^\/api\/session\/[^/]+$/i;
54
+
55
+ const listedTitleSchema = z.string().trim().min(1);
56
+ /** A listed chat's title, from the space, cut to what names it; null when it has none. */
57
+ const titleShown = (title) => {
58
+ const parsed = listedTitleSchema.safeParse(title);
59
+ return parsed.success ? parsed.data.slice(0, TITLE_SHOWN_CHARACTERS) : null;
60
+ };
61
+
62
+ /**
63
+ * `hostOpenCode.importChat(chat)` imports one chat into the host's OpenCode and
64
+ * `hostOpenCode.removeChat(id)` deletes one again, for a save that is taken back.
65
+ */
66
+ export function createSpaceArchive({ dataDir, hostOpenCode, logger = console, now = () => Date.now() }) {
67
+ const root = path.join(dataDir, 'spaces', 'archive');
68
+ const directoryOf = (spaceId) => path.join(root, spaceId);
69
+ const entryFileOf = (spaceId) => path.join(root, `${spaceId}.json`);
70
+
71
+ /** Every archive the data directory holds; a file that cannot be read is skipped and logged. */
72
+ const readEntries = () => {
73
+ let names = [];
74
+ try {
75
+ names = fs.readdirSync(root);
76
+ } catch (error) {
77
+ if (error?.code !== 'ENOENT') logger.warn?.(`[spaces] the chat archive could not be read: ${error?.code ?? error?.message ?? error}`);
78
+ return new Map();
79
+ }
80
+ const entries = new Map();
81
+ for (const name of names) {
82
+ if (!name.endsWith('.json')) continue;
83
+ try {
84
+ const entry = archiveEntrySchema.parse(JSON.parse(fs.readFileSync(path.join(root, name), 'utf8')));
85
+ entries.set(entry.spaceId, entry);
86
+ } catch (error) {
87
+ logger.warn?.(`[spaces] an archive entry could not be read: ${name}: ${error?.code ?? 'malformed'}`);
88
+ }
89
+ }
90
+ return entries;
91
+ };
92
+
93
+ const entries = readEntries();
94
+ let locked = new Set();
95
+ const relock = () => { locked = new Set([...entries.values()].flatMap((entry) => entry.chats)); };
96
+ relock();
97
+
98
+ /** Keeps an archive's entry, or drops it when it holds no chat, and the guard follows at once. */
99
+ const writeEntry = (entry) => {
100
+ const file = entryFileOf(entry.spaceId);
101
+ if (entry.chats.length === 0) {
102
+ fs.rmSync(file, { force: true });
103
+ entries.delete(entry.spaceId);
104
+ } else {
105
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
106
+ const temporary = `${file}.${process.pid}.tmp`;
107
+ fs.writeFileSync(temporary, `${JSON.stringify(entry, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
108
+ fs.renameSync(temporary, file);
109
+ entries.set(entry.spaceId, entry);
110
+ }
111
+ relock();
112
+ };
113
+
114
+ /** The archives, for the Archive page: which directory holds which space's chats. */
115
+ const listArchives = () => [...entries.values()].map((entry) => ({
116
+ spaceId: entry.spaceId,
117
+ name: entry.name,
118
+ projectDirectory: entry.projectDirectory,
119
+ directory: directoryOf(entry.spaceId),
120
+ archivedAt: entry.archivedAt,
121
+ }));
122
+
123
+ const isArchivedChat = (id) => locked.has(id);
124
+
125
+ /**
126
+ * Express middleware, before every route that acts on a session: an archived chat is read-only.
127
+ * The id is compared decoded, as the route behind it decodes it, so `ses%5F...` is the same chat.
128
+ */
129
+ const guard = (req, res, next) => {
130
+ if (locked.size === 0 || READ_METHODS.has(req.method)) return next();
131
+ if (req.method === 'DELETE' && SESSION_DELETE.test(req.path)) return next();
132
+ for (const pattern of CHAT_ROUTES) {
133
+ const match = pattern.exec(req.path);
134
+ if (!match) continue;
135
+ let id = match[1];
136
+ try {
137
+ id = decodeURIComponent(id);
138
+ } catch {
139
+ // Not a valid encoding: the route behind refuses it as well, and it names no chat here.
140
+ }
141
+ if (locked.has(id)) {
142
+ res.status(409).json({ code: 'archived_chat_read_only', message: 'This chat belongs to a deleted space and is read-only.' });
143
+ return undefined;
144
+ }
145
+ }
146
+ return next();
147
+ };
148
+
149
+ /**
150
+ * Takes the chats of a space out and imports them into the host's OpenCode, parents first.
151
+ * `source.listChats()` answers `{ chats: [{ id, title }], complete }` and `source.exportChat(id)`
152
+ * one chat as OpenCode exports it. Without `allowUnsaved` it is all or nothing: a chat that
153
+ * cannot be taken out or imported leaves nothing new in the archive and fails with
154
+ * `chats_not_saved`, whose details name the chats that were too large. With it, what can be
155
+ * saved is saved and the rest is reported. Answers `{ saved, tooLarge, failed, listed }`.
156
+ *
157
+ * A space can be saved again, when a delete saved its chats and then could not remove it: the
158
+ * chats saved before stay in the archive and stay read-only, and one the host already holds
159
+ * there counts as saved.
160
+ */
161
+ const saveChats = async ({ spaceId, name, projectDirectory, source, allowUnsaved }) => {
162
+ const deadline = now() + SAVE_TIMEOUT_MS;
163
+ const earlier = entries.get(spaceId)?.chats ?? [];
164
+ const tooLarge = [];
165
+ let failed = 0;
166
+ let listed;
167
+ try {
168
+ listed = await source.listChats();
169
+ } catch (error) {
170
+ logger.warn?.(`[spaces] the chats of space ${spaceId} could not be listed: ${error?.code ?? error?.message ?? error}`);
171
+ listed = null;
172
+ }
173
+ const refuse = () => new SpaceError('chats_not_saved', `The chats of "${name}" could not be saved.`, { name, tooLarge, failed, listed: listed !== null });
174
+ if (listed === null) {
175
+ if (!allowUnsaved) throw refuse();
176
+ return { saved: 0, tooLarge, failed, listed: false };
177
+ }
178
+ const wanted = listed.chats.filter((chat) => chatIdSchema.safeParse(chat.id).success);
179
+ failed += listed.chats.length - wanted.length + Math.max(0, wanted.length - ARCHIVE_MAX_CHATS);
180
+ if (!listed.complete) failed += 1;
181
+ // Known from the list alone: nothing is taken out for a save that cannot be whole.
182
+ if (!allowUnsaved && failed > 0) throw refuse();
183
+ const chosen = wanted.slice(0, ARCHIVE_MAX_CHATS);
184
+
185
+ // Each chat is taken out and written to disk before any goes in, so a refusal leaves the
186
+ // host's OpenCode untouched and memory holds one chat at a time.
187
+ const incoming = path.join(root, `.incoming-${spaceId}`);
188
+ fs.rmSync(incoming, { recursive: true, force: true });
189
+ fs.mkdirSync(incoming, { recursive: true, mode: 0o700 });
190
+ try {
191
+ const taken = new Map();
192
+ for (const chat of chosen) {
193
+ if (now() > deadline) {
194
+ failed += 1;
195
+ continue;
196
+ }
197
+ try {
198
+ const exported = await source.exportChat(chat.id);
199
+ fs.writeFileSync(path.join(incoming, `${chat.id}.json`), JSON.stringify(exported), { mode: 0o600 });
200
+ taken.set(chat.id, exported.info.parentID ?? null);
201
+ } catch (error) {
202
+ if (error?.code === 'chat_too_large') tooLarge.push(titleShown(chat.title) ?? chat.id);
203
+ else failed += 1;
204
+ logger.warn?.(`[spaces] chat ${chat.id} of space ${spaceId} was not taken out: ${error?.code ?? error?.message ?? error}`);
205
+ }
206
+ }
207
+ if (!allowUnsaved && (tooLarge.length > 0 || failed > 0)) throw refuse();
208
+
209
+ // Parents before children, as the import requires. A parent that is not in this archive
210
+ // leaves the chat a root one.
211
+ const order = [];
212
+ const placed = new Set();
213
+ const place = (id) => {
214
+ if (placed.has(id)) return;
215
+ placed.add(id);
216
+ const parent = taken.get(id);
217
+ if (parent && taken.has(parent)) place(parent);
218
+ order.push(id);
219
+ };
220
+ for (const id of taken.keys()) place(id);
221
+
222
+ const directory = directoryOf(spaceId);
223
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
224
+ const archivedAt = now();
225
+ const entry = { version: 1, spaceId, name, projectDirectory, archivedAt, chats: earlier };
226
+ const withChats = (chats) => ({ ...entry, chats: Array.from(new Set([...earlier, ...chats])) });
227
+ // Locked before the first one exists on the host, so no request slips in between.
228
+ writeEntry(withChats(order));
229
+ const added = [];
230
+ const saved = [];
231
+ const notImported = new Set();
232
+ for (const id of order) {
233
+ const parent = taken.get(id);
234
+ if (parent && notImported.has(parent)) {
235
+ notImported.add(id);
236
+ failed += 1;
237
+ continue;
238
+ }
239
+ try {
240
+ const exported = JSON.parse(fs.readFileSync(path.join(incoming, `${id}.json`), 'utf8'));
241
+ await hostOpenCode.importChat(archivedChatOf(exported, { directory, archivedAt, keepParent: Boolean(parent && taken.has(parent)) }));
242
+ added.push(id);
243
+ saved.push(id);
244
+ } catch (error) {
245
+ // Saved by an earlier delete of this space: the host holds it here already.
246
+ if (error?.status === 409 && earlier.includes(id)) {
247
+ saved.push(id);
248
+ continue;
249
+ }
250
+ notImported.add(id);
251
+ failed += 1;
252
+ logger.warn?.(`[spaces] chat ${id} of space ${spaceId} was not imported: ${error?.status ?? error?.code ?? error?.message ?? error}`);
253
+ if (!allowUnsaved) break;
254
+ }
255
+ }
256
+ if (!allowUnsaved && notImported.size > 0) {
257
+ // What this save added is taken back, children first, so the space and its chats stay as
258
+ // they were; what an earlier save put there stays.
259
+ for (const id of added.reverse()) {
260
+ await hostOpenCode.removeChat(id).catch((error) => {
261
+ logger.warn?.(`[spaces] imported chat ${id} could not be taken back: ${error?.status ?? error?.code ?? error?.message ?? error}`);
262
+ });
263
+ }
264
+ writeEntry(withChats([]));
265
+ throw refuse();
266
+ }
267
+ writeEntry(withChats(saved));
268
+ return { saved: saved.length, tooLarge, failed, listed: true };
269
+ } finally {
270
+ fs.rmSync(incoming, { recursive: true, force: true });
271
+ }
272
+ };
273
+
274
+ return { guard, listArchives, isArchivedChat, saveChats, directoryOf };
275
+ }