@openchamber/web 2.0.2 → 2.0.4

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 (257) hide show
  1. package/bin/lib/DOCUMENTATION.md +1 -1
  2. package/bin/lib/commands-connect-url.js +6 -5
  3. package/bin/lib/commands-tunnel.js +24 -5
  4. package/dist/assets/{CodeMirrorCommentWidgets-CmKmyb9T.js → CodeMirrorCommentWidgets-C_zL-eri.js} +1 -1
  5. package/dist/assets/{DiffView-8-PFpZ2p.js → DiffView-BeN2_YYF.js} +3 -3
  6. package/dist/assets/FilesView-CN34wm_N.js +17 -0
  7. package/dist/assets/{GitView-DNUSu00w.js → GitView-DLDazOo1.js} +4 -4
  8. package/dist/assets/{GuestAttachDialog-Cv6QzjHC.js → GuestAttachDialog-C0xe_Lyy.js} +1 -1
  9. package/dist/assets/{GuestSurfacePane-Bt3jB_Ye.js → GuestSurfacePane-BdaurnDr.js} +1 -1
  10. package/dist/assets/{JsonTreeView-BlyHTRhM.js → JsonTreeView-B1Xq-k2t.js} +1 -1
  11. package/dist/assets/LinearIssuesView-BryoAHow.js +1 -0
  12. package/dist/assets/{MarkdownImageGallery-2UXJF-5B.js → MarkdownImageGallery-DfuEoaGq.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-B_ZcWOvX.js +12 -0
  14. package/dist/assets/OnboardingScreen-C22bGmnP.js +1 -0
  15. package/dist/assets/{PatchDiff-ByvnbG5T.js → PatchDiff-0xd6UeFB.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BXieg0mH.js → PierreDiffViewer-BC950e3F.js} +3 -3
  17. package/dist/assets/PlanView-B7Xgihqk.js +5 -0
  18. package/dist/assets/PluginPane-2C71F8uF.js +3 -0
  19. package/dist/assets/SettingsView-m_zoFiaT.js +30 -0
  20. package/dist/assets/{SettingsWindow-BIz224xs.js → SettingsWindow-CofS020b.js} +1 -1
  21. package/dist/assets/{SubmoduleDiffSummary-CXKmlps9.js → SubmoduleDiffSummary-BSA9gnIO.js} +1 -1
  22. package/dist/assets/{ToolOutputDialog-BsgAK8xu.js → ToolOutputDialog-DprkVKcj.js} +7 -7
  23. package/dist/assets/{ToolPartDiffPreview-vdPObXOf.js → ToolPartDiffPreview-Dq0go_fX.js} +2 -2
  24. package/dist/assets/{VirtualizedFileDiff-BkFNKWS5.js → VirtualizedFileDiff-Kp8hKJdT.js} +1 -1
  25. package/dist/assets/WalkthroughView-DGnTzqIU.js +4 -0
  26. package/dist/assets/{appThemeRegistry-aHUNHoqP.js → appThemeRegistry-BdEHBA4s.js} +1 -1
  27. package/dist/assets/{commitAndPush-Bon9r94r.js → commitAndPush-LwtVa2Oc.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-DKqr_1AQ.js → computeVirtualFileMetrics-6V1xNpO9.js} +2 -2
  29. package/dist/assets/de-DlgBHUAI.js +10 -0
  30. package/dist/assets/es-BC8G41U8.js +16 -0
  31. package/dist/assets/fr-I0z3vVjy.js +14 -0
  32. package/dist/assets/index-CgR5rJq_.js +41 -0
  33. package/dist/assets/{index-DpFttslC.js → index-CmNPYddV.js} +1 -1
  34. package/dist/assets/index-adyy_sEk.css +1 -0
  35. package/dist/assets/{isDiffPlainText-kzAgpIgi.js → isDiffPlainText-1bXcWCrw.js} +1 -1
  36. package/dist/assets/{isFilePlainText-Uj6y-jzz.js → isFilePlainText-CBAppvy1.js} +1 -1
  37. package/dist/assets/ja-BIElEsY8.js +16 -0
  38. package/dist/assets/ko-DRnnHetA.js +16 -0
  39. package/dist/assets/{main-CbfMxn-I.js → main-CzjTMTfW.js} +2 -2
  40. package/dist/assets/main-DVX34beR.js +886 -0
  41. package/dist/assets/markdownCore-Cxbkn5NR.js +7 -0
  42. package/dist/assets/{miniChat-CiAKBC10.js → miniChat-CP68IL8Q.js} +2 -2
  43. package/dist/assets/{mobile-CsT4sJwC.js → mobile-BrlBrNfZ.js} +2 -2
  44. package/dist/assets/nl-DzUV-kwp.js +16 -0
  45. package/dist/assets/{patchFileDiff-DeaE08W0.js → patchFileDiff-pqRSHLHI.js} +2 -2
  46. package/dist/assets/pl-Bb-cb7k7.js +16 -0
  47. package/dist/assets/pt-BR-CyIWrTcE.js +16 -0
  48. package/dist/assets/renderElectronMiniChatApp-DKIilR7N.js +2 -0
  49. package/dist/assets/renderMobileApp-B0z6-x58.js +25 -0
  50. package/dist/assets/runtimeEndpointReset-uu1DBwLL.js +52 -0
  51. package/dist/assets/{scheduledTasksApi-BZCNJ588.js → scheduledTasksApi-BuzWT445.js} +1 -1
  52. package/dist/assets/{shikiHighlight-BSUEa3yF.js → shikiHighlight-BWGrY5YU.js} +1 -1
  53. package/dist/assets/{textMateThemeFromAppTheme-CsATFZIV.js → textMateThemeFromAppTheme-BSUFChBY.js} +1 -1
  54. package/dist/assets/tr-DXEDSoYO.js +7 -0
  55. package/dist/assets/uk-C8hN--q_.js +16 -0
  56. package/dist/assets/useAppFontEffects-Dsl_sLrj.js +7366 -0
  57. package/dist/assets/useInlineCommentController-d5vntsQ_.js +2 -0
  58. package/dist/assets/{useRootScrollLock-Cp1eFoM2.js → useRootScrollLock-2rd5Y6gR.js} +2 -2
  59. package/dist/assets/{vendor-base-ui-CsXYnR5c.js → vendor-base-ui-DnNniUWp.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-language-data-BwwommM0.js → vendor-codemirror-language-data-B1EetJur.js} +2 -2
  61. package/dist/assets/vendor-opencode-client-DSZl7jSi.js +12 -0
  62. package/dist/assets/{vendor-tanstack-react-virtual-ClYN8CzB.js → vendor-tanstack-react-virtual--0sBrLRh.js} +1 -1
  63. package/dist/assets/{vendor-tanstack-virtual-core-BewVQryB.js → vendor-tanstack-virtual-core-BoA4iGMw.js} +1 -1
  64. package/dist/assets/{vendor-zod-BSoePkpP.js → vendor-zod-CxRSdNoV.js} +4 -4
  65. package/dist/assets/{web-components-D3Yjr4Zx.js → web-components-ngpHPEDU.js} +1 -1
  66. package/dist/assets/zh-CN-CtzXdjMZ.js +16 -0
  67. package/dist/assets/zh-TW-Ds0CADSz.js +16 -0
  68. package/dist/index.html +5 -5
  69. package/dist/mini-chat.html +5 -5
  70. package/dist/mobile.html +5 -5
  71. package/package.json +5 -5
  72. package/server/index.js +82 -4
  73. package/server/lib/agent-tool/DOCUMENTATION.md +8 -1
  74. package/server/lib/agent-tool/runtime.js +13 -4
  75. package/server/lib/agent-tool/runtime.test.js +15 -0
  76. package/server/lib/context-obligatory/DOCUMENTATION.md +10 -7
  77. package/server/lib/context-obligatory/runtime.js +2 -1
  78. package/server/lib/context-obligatory/runtime.test.js +76 -30
  79. package/server/lib/dictation/DOCUMENTATION.md +4 -1
  80. package/server/lib/dictation/openai-compatible-session.js +7 -0
  81. package/server/lib/enterprise-mode.d.ts +30 -0
  82. package/server/lib/enterprise-mode.js +253 -0
  83. package/server/lib/enterprise-mode.test.js +247 -0
  84. package/server/lib/event-stream/translate-v2.js +6 -0
  85. package/server/lib/event-stream/translate-v2.test.js +6 -0
  86. package/server/lib/git/DOCUMENTATION.md +2 -1
  87. package/server/lib/git/routes.js +44 -1
  88. package/server/lib/git/routes.test.js +98 -1
  89. package/server/lib/git/service.js +146 -11
  90. package/server/lib/git/service.test.js +195 -0
  91. package/server/lib/github/routes.js +9 -19
  92. package/server/lib/github/routes.test.js +112 -0
  93. package/server/lib/guests/DOCUMENTATION.md +4 -2
  94. package/server/lib/guests/background.test.js +1 -1
  95. package/server/lib/guests/catalog.js +56 -2
  96. package/server/lib/guests/catalog.test.js +24 -1
  97. package/server/lib/guests/clone-network.test.js +52 -0
  98. package/server/lib/guests/clone.js +30 -4
  99. package/server/lib/guests/enterprise.js +68 -0
  100. package/server/lib/guests/enterprise.test.js +106 -0
  101. package/server/lib/guests/grant-scope.js +8 -2
  102. package/server/lib/guests/grant-scope.test.js +9 -0
  103. package/server/lib/guests/html-styles.js +16 -2
  104. package/server/lib/guests/html-styles.test.js +53 -4
  105. package/server/lib/guests/install.js +10 -0
  106. package/server/lib/guests/persist.js +1 -0
  107. package/server/lib/guests/routes.js +40 -5
  108. package/server/lib/guests/updates.js +9 -2
  109. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  110. package/server/lib/notifications/runtime.js +22 -8
  111. package/server/lib/notifications/trigger-runtime.test.js +45 -0
  112. package/server/lib/openchamber-sessions/session-metadata-store.js +27 -0
  113. package/server/lib/openchamber-sessions/session-metadata-store.test.js +18 -0
  114. package/server/lib/opencode/DOCUMENTATION.md +13 -9
  115. package/server/lib/opencode/auth-state-runtime.js +2 -2
  116. package/server/lib/opencode/config-paths.test.js +1 -0
  117. package/server/lib/opencode/env-runtime.js +26 -3
  118. package/server/lib/opencode/env-runtime.test.js +57 -0
  119. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  120. package/server/lib/opencode/hmr-state-runtime.js +4 -3
  121. package/server/lib/opencode/lifecycle.js +10 -5
  122. package/server/lib/opencode/lifecycle.test.js +6 -2
  123. package/server/lib/opencode/managed-config-file.js +2 -1
  124. package/server/lib/opencode/managed-config-file.test.js +18 -0
  125. package/server/lib/opencode/npm-registry-config.d.ts +1 -0
  126. package/server/lib/opencode/npm-registry-config.js +123 -0
  127. package/server/lib/opencode/npm-registry-config.test.js +167 -0
  128. package/server/lib/opencode/npm-registry.js +5 -6
  129. package/server/lib/opencode/npm-registry.test.js +30 -0
  130. package/server/lib/opencode/openchamber-routes.js +8 -0
  131. package/server/lib/opencode/project-icon-routes.js +2 -2
  132. package/server/lib/opencode/project-icon-routes.test.js +44 -0
  133. package/server/lib/opencode/provider-source-route.test.js +32 -0
  134. package/server/lib/opencode/routes.js +17 -2
  135. package/server/lib/opencode/settings-helpers.js +26 -3
  136. package/server/lib/opencode/settings-helpers.test.js +12 -5
  137. package/server/lib/opencode/settings-registry.json +35 -1
  138. package/server/lib/opencode/settings-runtime.js +1 -0
  139. package/server/lib/opencode/shutdown-runtime.js +2 -0
  140. package/server/lib/opencode/static-routes-runtime.js +9 -1
  141. package/server/lib/opencode/static-routes-runtime.test.js +58 -1
  142. package/server/lib/package-manager.js +4 -1
  143. package/server/lib/package-manager.test.js +24 -0
  144. package/server/lib/permission-auto-accept/DOCUMENTATION.md +23 -15
  145. package/server/lib/permission-auto-accept/modes.js +26 -0
  146. package/server/lib/permission-auto-accept/runtime.js +146 -40
  147. package/server/lib/permission-auto-accept/runtime.test.js +93 -9
  148. package/server/lib/quota/DOCUMENTATION.md +6 -0
  149. package/server/lib/quota/providers/zhipuai-coding-plan.js +74 -30
  150. package/server/lib/quota/providers/zhipuai-coding-plan.test.js +124 -0
  151. package/server/lib/relay/DOCUMENTATION.md +1 -1
  152. package/server/lib/relay/service.js +32 -12
  153. package/server/lib/relay/service.test.js +30 -0
  154. package/server/lib/routing/DOCUMENTATION.md +150 -41
  155. package/server/lib/routing/classifier.js +156 -0
  156. package/server/lib/routing/defaults.js +27 -0
  157. package/server/lib/routing/jev.js +5 -17
  158. package/server/lib/routing/routes.http.test.js +9 -0
  159. package/server/lib/routing/routes.js +27 -1
  160. package/server/lib/routing/runtime.js +199 -33
  161. package/server/lib/routing/runtime.test.js +299 -15
  162. package/server/lib/routing/store.js +57 -0
  163. package/server/lib/routing/store.test.js +37 -0
  164. package/server/lib/session-assist/DOCUMENTATION.md +17 -7
  165. package/server/lib/session-assist/context.js +42 -2
  166. package/server/lib/session-assist/context.test.js +38 -1
  167. package/server/lib/session-assist/runtime.js +57 -13
  168. package/server/lib/session-assist/runtime.test.js +45 -0
  169. package/server/lib/session-goal/DOCUMENTATION.md +47 -22
  170. package/server/lib/session-goal/audit.js +112 -0
  171. package/server/lib/session-goal/audit.test.js +58 -0
  172. package/server/lib/session-goal/runtime.js +113 -134
  173. package/server/lib/session-goal/runtime.test.js +146 -13
  174. package/server/lib/session-lineage.js +52 -0
  175. package/server/lib/session-lineage.test.js +45 -0
  176. package/server/lib/session-work/DOCUMENTATION.md +108 -0
  177. package/server/lib/session-work/questions.js +126 -0
  178. package/server/lib/session-work/runtime.js +278 -0
  179. package/server/lib/session-work/runtime.test.js +255 -0
  180. package/server/lib/session-work/state.js +48 -0
  181. package/server/lib/session-work/state.test.js +34 -0
  182. package/server/lib/small-model/DOCUMENTATION.md +14 -7
  183. package/server/lib/small-model/client.js +7 -4
  184. package/server/lib/small-model/index.js +11 -21
  185. package/server/lib/small-model/index.test.js +13 -26
  186. package/server/lib/spaces/DOCUMENTATION.md +79 -25
  187. package/server/lib/spaces/gatekeeper-channel.js +63 -11
  188. package/server/lib/spaces/gatekeeper-channel.test.js +34 -4
  189. package/server/lib/spaces/gatekeeper-program.cjs +64 -13
  190. package/server/lib/spaces/gatekeeper-program.test.js +115 -3
  191. package/server/lib/spaces/host.js +58 -13
  192. package/server/lib/spaces/host.test.js +34 -1
  193. package/server/lib/spaces/idle-stop.js +98 -0
  194. package/server/lib/spaces/idle-stop.test.js +130 -0
  195. package/server/lib/spaces/journey.js +427 -17
  196. package/server/lib/spaces/journey.test.js +592 -5
  197. package/server/lib/spaces/layout.js +27 -6
  198. package/server/lib/spaces/manager.test.js +1 -1
  199. package/server/lib/spaces/places/contract-suite.js +4 -2
  200. package/server/lib/spaces/places/docker-live-support.js +27 -4
  201. package/server/lib/spaces/places/docker.js +32 -5
  202. package/server/lib/spaces/places/docker.test.js +38 -8
  203. package/server/lib/spaces/places/escape-suite.js +32 -0
  204. package/server/lib/spaces/places/fake-docker.js +3 -1
  205. package/server/lib/spaces/places/grants.docker.live.test.js +197 -0
  206. package/server/lib/spaces/places/memory-place.js +3 -3
  207. package/server/lib/spaces/places/sessions.docker.live.test.js +4 -2
  208. package/server/lib/spaces/routes.js +49 -1
  209. package/server/lib/spaces/routes.test.js +31 -3
  210. package/server/lib/spaces/space-opencode.js +52 -0
  211. package/server/lib/spaces/space-opencode.test.js +41 -0
  212. package/server/lib/spaces/space-records.js +90 -2
  213. package/server/lib/spaces/space-records.test.js +58 -1
  214. package/server/lib/spaces/space-server.js +13 -1
  215. package/server/lib/spaces/space-server.test.js +13 -0
  216. package/server/lib/spaces/space-setup.js +173 -0
  217. package/server/lib/spaces/space-setup.test.js +174 -0
  218. package/server/lib/tts/DOCUMENTATION.md +3 -0
  219. package/server/lib/tts/base-url.js +8 -0
  220. package/server/lib/tts/routes.js +13 -1
  221. package/server/lib/tts/routes.test.js +26 -0
  222. package/server/lib/tunnels/DOCUMENTATION.md +2 -0
  223. package/server/lib/tunnels/routes.js +14 -0
  224. package/server/lib/tunnels/routes.test.js +26 -0
  225. package/server/lib/walkthrough/index.js +11 -7
  226. package/server/lib/walkthrough/jobs.test.js +8 -0
  227. package/server/lib/walkthrough/languages.js +1 -0
  228. package/server/lib/walkthrough/routes.js +7 -1
  229. package/dist/assets/FilesView-0Ie20mEk.js +0 -17
  230. package/dist/assets/LinearIssuesView-CSl2MUfA.js +0 -1
  231. package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +0 -12
  232. package/dist/assets/OnboardingScreen-CIdXJpfc.js +0 -1
  233. package/dist/assets/PlanView-DEIi3Q7M.js +0 -5
  234. package/dist/assets/PluginPane-BEPUWVho.js +0 -3
  235. package/dist/assets/SettingsView-CiNh-RbW.js +0 -30
  236. package/dist/assets/WalkthroughView-6oE-MuDL.js +0 -4
  237. package/dist/assets/de-CgAJ51z7.js +0 -10
  238. package/dist/assets/es-zGi_ravM.js +0 -16
  239. package/dist/assets/fr-CPfogrWx.js +0 -14
  240. package/dist/assets/index-CHfphYL3.js +0 -41
  241. package/dist/assets/index-DvMJ3w6V.css +0 -1
  242. package/dist/assets/ja-DMk6wd-U.js +0 -16
  243. package/dist/assets/ko-BFpzJ8jc.js +0 -16
  244. package/dist/assets/main-anyZFMIs.js +0 -896
  245. package/dist/assets/markdownCore-CmM47cAE.js +0 -7
  246. package/dist/assets/pl-VdRPcZrB.js +0 -16
  247. package/dist/assets/pt-BR-BRys_lOW.js +0 -16
  248. package/dist/assets/renderElectronMiniChatApp-C5677jy0.js +0 -2
  249. package/dist/assets/renderMobileApp-D4dBBAqQ.js +0 -25
  250. package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +0 -27
  251. package/dist/assets/tr-CA9ckNnm.js +0 -7
  252. package/dist/assets/uk-byjR-y8D.js +0 -16
  253. package/dist/assets/useAppFontEffects-BWQZ5DeI.js +0 -7341
  254. package/dist/assets/useInlineCommentController-DlFyVfBu.js +0 -2
  255. package/dist/assets/vendor-opencode-client-DYdsLbCM.js +0 -12
  256. package/dist/assets/zh-CN-DRabgxdG.js +0 -16
  257. package/dist/assets/zh-TW-rbY5c9UK.js +0 -16
@@ -9,13 +9,35 @@
9
9
  // the sidebar can say what is happening now (DESIGN.md, journey step 2). A creation that fails
10
10
  // after the containers exist removes them again, and its failure stays listed until the user
11
11
  // dismisses it, so an error is never silent.
12
+ //
13
+ // Grants, since 5b: a model key the gatekeeper's window adds to the provider's requests, or an
14
+ // opened domain the window forwards to with no credential. The host keeps the grant without its
15
+ // value (decision 5) and says it again to the gatekeeper after every start; a value it cannot
16
+ // find again leaves the space "needs access" until the user grants once more.
17
+ //
18
+ // Repair, since 5d-2 (DESIGN.md, journey step 8 and decision 10): restart OpenCode inside, and
19
+ // restart the container with a fresh token for the server inside. A space whose gatekeeper is gone
20
+ // is listed as such, because no restart brings it back.
21
+ //
22
+ // Idle stop, since 5d-3 (decision 11): the server inside stops itself after the user's idle hours.
23
+ // The host tells it the setting at every start and whenever the user changes it, lists a space
24
+ // that stopped that way as such, and stops the gatekeeper it finds running beside a stopped space,
25
+ // which is what an idle stop leaves while OpenChamber is closed.
26
+ //
27
+ // Setup commands, since 5d-4 (DESIGN.md, "Code in and out"): the project's worktree setup commands
28
+ // run inside the space once its code arrived, in the background, and again when the user asks.
29
+
30
+ import crypto from 'node:crypto';
12
31
 
13
32
  import { z } from 'zod';
14
33
 
15
34
  import { SpaceError } from './errors.js';
16
- import { createSpaceId, hashProjectDirectory } from './labels.js';
17
- import { spaceProjectPath } from './layout.js';
18
- import { networkSchema } from './space-records.js';
35
+ import { DEFAULT_IDLE_STOP, idleStopSchema } from './idle-stop.js';
36
+ import { ROLE_GATEKEEPER, createSpaceId, hashProjectDirectory, spaceResourceName } from './labels.js';
37
+ import { spaceProjectPath, spaceWindowUrl } from './layout.js';
38
+ import { domainSchema, grantSchema, networkSchema, secretSourceSchema } from './space-records.js';
39
+ import { createSpaceToken } from './space-server.js';
40
+ import { createSpaceSetup, setupCommandsSchema } from './space-setup.js';
19
41
 
20
42
  // The four choices of the create dialog, parsed at the boundary. Each field refuses with a code
21
43
  // of its own, so the dialog can point at the field.
@@ -24,13 +46,50 @@ const createRequestSchema = z.object({
24
46
  name: z.string().trim().min(1),
25
47
  start: z.enum(['clean', 'uncommitted']).default('uncommitted'),
26
48
  network: networkSchema.default({ mode: 'allowlist', domains: [] }),
49
+ // The project's worktree setup commands as the client resolved them, the shared ones only when
50
+ // the user trusted them; they run once the code arrived (5d-4).
51
+ setupCommands: setupCommandsSchema.default([]),
27
52
  });
28
53
  const CREATE_REFUSALS = {
29
54
  projectDirectory: ['project_not_registered', 'A space is made for a project this OpenChamber knows. Add the project first, then create the space.'],
30
55
  name: ['invalid_space_name', 'A space needs a name.'],
31
56
  start: ['invalid_snapshot_mode', 'A space starts from a clean commit or with the uncommitted changes.'],
32
57
  network: ['invalid_network', 'The network of a space is allowlist or open, with a list of domain names for the allowlist.'],
58
+ setupCommands: ['invalid_setup_commands', 'The setup commands are a list of at most 100 commands of at most 4000 characters each.'],
33
59
  };
60
+ const setupRequestSchema = z.object({ commands: setupCommandsSchema }).strict();
61
+ // The grant dialog's request, parsed at the boundary. A model grant names the provider as the
62
+ // host's catalog does, the provider's API as the upstream, and where the key comes from: typed
63
+ // once, or an environment variable of the host's by name. The value of a typed key is used now
64
+ // and remembered nowhere. An opened domain has no key.
65
+ const MAX_SECRET_LENGTH = 8192;
66
+ const grantRequestSchema = z.discriminatedUnion('kind', [
67
+ z.object({
68
+ kind: z.literal('model'),
69
+ provider: grantSchema.options[0].shape.provider,
70
+ upstream: grantSchema.options[0].shape.upstream,
71
+ secret: z.discriminatedUnion('kind', [
72
+ z.object({ kind: z.literal('typed'), value: z.string().min(1).max(MAX_SECRET_LENGTH) }).strict(),
73
+ secretSourceSchema.options[0],
74
+ ]),
75
+ }).strict(),
76
+ z.object({ kind: z.literal('domain'), upstream: grantSchema.options[1].shape.upstream }).strict(),
77
+ ]);
78
+ // The header the window sets for a provider: what its API reads a key from. Only providers
79
+ // named here are taken: one that reads its key another way or signs its requests, Azure,
80
+ // Bedrock or Vertex, would take the grant and fail every turn with a 401 upstream.
81
+ const HEADER_BY_PROVIDER = new Map([
82
+ ['anthropic', 'x-api-key'],
83
+ ['google', 'x-goog-api-key'],
84
+ ...['openai', 'openrouter', 'groq', 'mistral', 'deepseek', 'xai'].map((provider) => [provider, 'authorization']),
85
+ ]);
86
+
87
+ // A domain the user opens for a running space, from the grant dialog or from a blocked attempt
88
+ // in the journal: the allowlist's own rule for a name, read in any case.
89
+ const openDomainRequestSchema = z.object({
90
+ domain: z.string().trim().toLowerCase().pipe(domainSchema),
91
+ }).strict();
92
+
34
93
  const applyRequestSchema = z.discriminatedUnion('as', [
35
94
  z.object({ as: z.literal('branch'), branch: z.string(), removeAfterwards: z.boolean().default(false) }),
36
95
  z.object({ as: z.literal('changes'), removeAfterwards: z.boolean().default(false) }),
@@ -45,7 +104,13 @@ const failureOf = (error) => ({
45
104
  /**
46
105
  * `listProjectDirectories` answers the host's registered projects; a space is made for one of them
47
106
  * and its label carries the project's hash. `announce(spaceId, payload)` enters an event into the
48
- * host's hub, `onSpacesChanged()` tells the host to read its list again at once.
107
+ * host's hub, `onSpacesChanged()` tells the host to read its list again at once. `spaceOpenCode`
108
+ * writes OpenCode's files inside a space, and `readHostSecret(name)` is how a key named by an
109
+ * environment variable of the host's is found again: its value or undefined, never stored.
110
+ * `serverInside.writeToken(spaceId, token)` replaces the token the server inside reads when it
111
+ * starts, and `restartOpenCodeInside(spaceId)` asks the server inside to restart its OpenCode.
112
+ * `readIdleStop()` and `saveIdleStop(setting)` read and keep the user's idle stop setting, and
113
+ * `serverInside.writeIdleStop(spaceId, setting)` tells it to the server inside.
49
114
  */
50
115
  export function createSpaceJourney({
51
116
  manager,
@@ -54,7 +119,13 @@ export function createSpaceJourney({
54
119
  codeIn,
55
120
  codeOut,
56
121
  records,
122
+ spaceOpenCode,
123
+ serverInside,
124
+ restartOpenCodeInside,
57
125
  listProjectDirectories,
126
+ readHostSecret = () => undefined,
127
+ readIdleStop = async () => ({ ...DEFAULT_IDLE_STOP }),
128
+ saveIdleStop = async () => {},
58
129
  announce = () => {},
59
130
  onSpacesChanged = () => {},
60
131
  logger = console,
@@ -68,6 +139,20 @@ export function createSpaceJourney({
68
139
  // Set while the switch is being turned off: no creation may slip in between the stop of the
69
140
  // spaces and the moment the feature is gone.
70
141
  let closing = false;
142
+ // Every write of the idle stop setting, a change's and a start's, one after the other, so a
143
+ // space never ends up with an older one.
144
+ let idleStopTurn = Promise.resolve();
145
+ // Stops of a gatekeeper left beside a stopped space, under way, by space id; a start waits for one.
146
+ const strayStops = new Map();
147
+ // The project's setup commands inside a space, since 5d-4; each step is announced so the
148
+ // clients read the list again.
149
+ const setup = createSpaceSetup({
150
+ exec: place.exec,
151
+ records,
152
+ announce: (spaceId) => announce(spaceId, { type: 'openchamber:space-setup', properties: { spaceId, timestamp: now().getTime() } }),
153
+ logger,
154
+ now,
155
+ });
71
156
 
72
157
  const exclusive = async (spaceId, work) => {
73
158
  if (busy.has(spaceId)) throw new SpaceError('space_busy', 'Another action on this space is still running. Wait for it to finish.');
@@ -129,6 +214,28 @@ export function createSpaceJourney({
129
214
  return outcome;
130
215
  };
131
216
 
217
+ /**
218
+ * Tells the server inside the idle stop setting. It saves memory and guards nothing, so a write
219
+ * that fails is logged and the space runs with what it had: the setting of its last start, or
220
+ * none, which stops nothing.
221
+ */
222
+ const writeIdleStop = async (spaceId, setting) => {
223
+ try {
224
+ await serverInside.writeIdleStop(spaceId, setting);
225
+ } catch (error) {
226
+ logger.warn?.(`[spaces] space ${spaceId} keeps its idle stop setting: ${error?.code ?? error?.message ?? error}`);
227
+ }
228
+ };
229
+
230
+ /** The setting as kept now, told to a space that was made or started, in turn with the changes. */
231
+ const deliverIdleStop = (spaceId) => {
232
+ const delivery = idleStopTurn.then(async () => writeIdleStop(spaceId, await readIdleStop()));
233
+ idleStopTurn = delivery.catch(() => {});
234
+ return delivery.catch((error) => {
235
+ logger.warn?.(`[spaces] space ${spaceId} keeps its idle stop setting: ${error?.code ?? error?.message ?? error}`);
236
+ });
237
+ };
238
+
132
239
  const sendHistoryInBackground = ({ repository, spaceId, spacePath, base }) => {
133
240
  codeIn.sendHistory({ repository, spaceId, spacePath, base })
134
241
  .then((result) => { records.update(spaceId, { history: result.status }); })
@@ -138,7 +245,7 @@ export function createSpaceJourney({
138
245
  });
139
246
  };
140
247
 
141
- const prepare = async (entry, { projectDirectory, name, start, network }) => {
248
+ const prepare = async (entry, { projectDirectory, name, start, network, setupCommands }) => {
142
249
  let created = false;
143
250
  try {
144
251
  progress(entry, 'checking_place');
@@ -157,9 +264,12 @@ export function createSpaceJourney({
157
264
  const arrived = await codeIn.bringCodeIn({ repository: projectDirectory, spaceId: entry.id, mode: start });
158
265
  records.update(entry.id, { spacePath: arrived.spacePath, base: arrived.base });
159
266
  entry.identityCopied = arrived.identityCopied;
267
+ await deliverIdleStop(entry.id);
160
268
  pending.delete(entry.id);
161
269
  progress(entry, 'ready');
162
270
  onSpacesChanged();
271
+ // In the background, while the agent can already start (DESIGN.md, journey step 2).
272
+ if (setupCommands.length > 0) setup.start(entry.id, { projectPath: arrived.spacePath, commands: setupCommands });
163
273
  sendHistoryInBackground({ repository: projectDirectory, spaceId: entry.id, spacePath: arrived.spacePath, base: arrived.base });
164
274
  } catch (error) {
165
275
  const failure = failureOf(error);
@@ -185,7 +295,7 @@ export function createSpaceJourney({
185
295
  const [code, message] = CREATE_REFUSALS[parsed.error.issues[0]?.path?.[0]] ?? CREATE_REFUSALS.network;
186
296
  throw new SpaceError(code, message);
187
297
  }
188
- const { name, start, network } = parsed.data;
298
+ const { name, start, network, setupCommands } = parsed.data;
189
299
  const projectDirectory = await requireRegisteredProject(parsed.data.projectDirectory);
190
300
  const id = createSpaceId();
191
301
  const entry = {
@@ -199,12 +309,103 @@ export function createSpaceJourney({
199
309
  step: 'checking_place',
200
310
  failure: null,
201
311
  network,
312
+ setupTotal: setupCommands.length,
202
313
  };
203
314
  pending.set(entry.id, entry);
204
- void prepare(entry, { projectDirectory, name, start, network });
315
+ void prepare(entry, { projectDirectory, name, start, network, setupCommands });
205
316
  return describePending(entry);
206
317
  };
207
318
 
319
+ /** A grant as the list and the grant route show it: everything the record holds, which holds no value. */
320
+ const describeGrant = (grant) => ({ ...grant, url: spaceWindowUrl(grant.id) });
321
+
322
+ /**
323
+ * Says one grant of the record to the gatekeeper. Resolves whether it could: a typed key is
324
+ * not remembered and needs the user again, and so does an environment variable that is not set
325
+ * now; a gatekeeper that refuses or does not answer counts the same way and is logged, because
326
+ * the space runs either way and the list must say that its access is missing.
327
+ */
328
+ const deliverGrant = async (spaceId, grant) => {
329
+ let secret = null;
330
+ if (grant.kind === 'model') {
331
+ if (grant.source.kind === 'typed') return false;
332
+ secret = readHostSecret(grant.source.name);
333
+ if (typeof secret !== 'string' || secret === '') return false;
334
+ }
335
+ try {
336
+ await gatekeeper.addGrant(spaceId, { id: grant.id, upstream: grant.upstream, header: grant.kind === 'model' ? grant.header : null, secret });
337
+ return true;
338
+ } catch (error) {
339
+ logger.warn?.(`[spaces] the grant ${grant.id} of space ${spaceId} could not be said again: ${error?.code ?? error?.message ?? error}`);
340
+ return false;
341
+ }
342
+ };
343
+
344
+ /**
345
+ * OpenCode's configuration inside, written again from the record at a start: it survives a
346
+ * stop in the home volume, but a write that failed at the grant is repaired only here. It
347
+ * cooperates and enforces nothing, so a failure is logged and the start goes on.
348
+ */
349
+ const rewriteProviderConfig = async (spaceId, grants) => {
350
+ if (!grants.some((grant) => grant.kind === 'model')) return;
351
+ try {
352
+ await spaceOpenCode.writeProviderConfig(spaceId, grants);
353
+ } catch (error) {
354
+ logger.warn?.(`[spaces] the provider configuration of space ${spaceId} was not written again: ${error?.code ?? error?.message ?? error}`);
355
+ }
356
+ };
357
+
358
+ /** Every grant of the record said again after a start. Resolves the ids that went and the ids that need the user. */
359
+ const restoreGrants = async (spaceId, grants) => {
360
+ const restored = [];
361
+ const needsAccess = [];
362
+ for (const grant of grants) {
363
+ (await deliverGrant(spaceId, grant) ? restored : needsAccess).push(grant.id);
364
+ }
365
+ return { restored, needsAccess };
366
+ };
367
+
368
+ /**
369
+ * Which grants of the record a running gatekeeper holds now, read from the gatekeeper itself:
370
+ * after a machine restart it holds none, and the space "needs access" (DESIGN.md, Gatekeeper).
371
+ * A gatekeeper that cannot be asked leaves the answer unknown, never "granted".
372
+ */
373
+ const readAccess = async (space, grants) => {
374
+ // A start that is still saying the grants again, or a grant on its way, would read as
375
+ // "needs access" for a moment; while an action holds the space the answer is not given.
376
+ if (space.state !== 'running' || grants.length === 0 || busy.has(space.id)) return { access: null, needsAccess: [] };
377
+ try {
378
+ const held = new Set((await gatekeeper.readPolicy(space.id)).grants);
379
+ const needsAccess = grants.filter((grant) => !held.has(grant.id)).map((grant) => grant.id);
380
+ return { access: needsAccess.length === 0 ? 'granted' : 'needs_access', needsAccess };
381
+ } catch (error) {
382
+ logger.warn?.(`[spaces] the gatekeeper of space ${space.id} did not say what it holds: ${error?.code ?? error?.message ?? error}`);
383
+ return { access: 'unknown', needsAccess: [] };
384
+ }
385
+ };
386
+
387
+ /**
388
+ * What is broken in a damaged space, for the group's status line: `gatekeeper_gone` when its
389
+ * gatekeeper container no longer exists, which no start makes again (STAGES.md, "Things stage 2
390
+ * leaves"), and `repairable` for the rest, a gatekeeper that stopped while the space runs among
391
+ * them, which the next start brings back. The place's list names the gatekeeper as missing in
392
+ * both cases; its verification tells them apart, and is asked only for a space that is damaged
393
+ * that way. A verification that cannot answer leaves it `repairable`, so the user is offered
394
+ * the restart rather than told the space is lost on a guess.
395
+ */
396
+ const readDamage = async (space) => {
397
+ if (!space.damaged) return null;
398
+ if (!space.missing.includes(spaceResourceName(space.id, ROLE_GATEKEEPER))) return 'repairable';
399
+ try {
400
+ const violations = await place.verify(space.id);
401
+ return violations.some((violation) => violation.check === 'gatekeeper_missing') ? 'gatekeeper_gone' : 'repairable';
402
+ } catch (error) {
403
+ if (error instanceof SpaceError && error.code === 'gatekeeper_missing') return 'gatekeeper_gone';
404
+ logger.warn?.(`[spaces] space ${space.id} could not be verified: ${error?.code ?? error?.message ?? error}`);
405
+ return 'repairable';
406
+ }
407
+ };
408
+
208
409
  const describePending = (entry) => ({
209
410
  id: entry.id,
210
411
  name: entry.name,
@@ -213,11 +414,18 @@ export function createSpaceJourney({
213
414
  directory: entry.directory,
214
415
  created: entry.created,
215
416
  state: entry.state,
417
+ stoppedIdle: false,
216
418
  step: entry.step,
217
419
  failure: entry.failure,
218
420
  network: entry.network,
219
421
  history: 'pending',
422
+ // The client waits for the setup only when the host said it will run one; a host before 5d-4 never says so.
423
+ setup: entry.setupTotal > 0 ? { state: 'queued', total: entry.setupTotal } : null,
424
+ grants: [],
425
+ access: null,
426
+ needsAccess: [],
220
427
  damaged: false,
428
+ damage: null,
221
429
  missing: [],
222
430
  orphans: [],
223
431
  });
@@ -225,13 +433,16 @@ export function createSpaceJourney({
225
433
  /**
226
434
  * Every space of this host: the place's list with what the host remembers about each, the
227
435
  * creations under way in their place, and the failed ones after it. A record the host cannot read leaves `network` null,
228
- * which the UI must show as "unknown" and never as "open".
436
+ * which the UI must show as "unknown" and never as "open". With `access` each running space
437
+ * with grants is asked what its gatekeeper holds, one request per such space, so the list can
438
+ * say "needs access"; without it `access` stays null.
229
439
  */
230
- const listSpaces = async () => {
440
+ const listSpaces = async ({ access = false } = {}) => {
231
441
  const [spaces, projects] = await Promise.all([manager.listSpaces({ placeId: place.id }), registeredProjects()]);
232
- const listed = spaces.map((space) => {
442
+ const listed = await Promise.all(spaces.map(async (space) => {
233
443
  const projectDirectory = projects.get(space.project) ?? null;
234
444
  const { record } = records.read(space.id);
445
+ const grants = record?.grants ?? [];
235
446
  return {
236
447
  id: space.id,
237
448
  name: space.name,
@@ -240,15 +451,23 @@ export function createSpaceJourney({
240
451
  directory: projectDirectory === null ? null : spaceProjectPath(space.id, projectDirectory),
241
452
  created: space.created,
242
453
  state: space.state,
454
+ stoppedIdle: space.stoppedIdle === true,
243
455
  step: null,
244
456
  failure: null,
245
457
  network: record?.network ?? null,
246
458
  history: record?.history ?? 'unknown',
459
+ setup: setup.describe(space.id, record),
460
+ grants: grants.map(describeGrant),
461
+ ...(access ? await readAccess(space, grants) : { access: null, needsAccess: [] }),
247
462
  damaged: space.damaged,
463
+ damage: await readDamage(space),
248
464
  missing: space.missing,
249
465
  orphans: space.orphans,
250
466
  };
251
- });
467
+ }));
468
+ for (const space of spaces) {
469
+ if (space.state === 'exited' && space.gatekeeperRunning === true && !pending.has(space.id)) stopStrayGatekeeper(space.id);
470
+ }
252
471
  // A creation under way wins over the place's view of it: the containers run before the code is there.
253
472
  const waiting = new Map(Array.from(pending.values(), (entry) => [entry.id, describePending(entry)]));
254
473
  const merged = listed.map((space) => waiting.get(space.id) ?? space);
@@ -256,6 +475,24 @@ export function createSpaceJourney({
256
475
  return [...merged, ...Array.from(waiting.values()).filter((entry) => !known.has(entry.id))];
257
476
  };
258
477
 
478
+ /**
479
+ * Stops the gatekeeper found running beside a stopped space: a space that stopped itself for the
480
+ * idle stop leaves it running, because it cannot reach it (the maintainer's call of 2026-09-28).
481
+ * It serves nobody then, and a key typed into it goes with it, as with a stop by hand. The place's
482
+ * stop of a stopped space stops only what still runs. A space that another action holds is left
483
+ * for the next look, since a start is what brings a gatekeeper up before its space; a start that
484
+ * comes while this runs waits for it, rather than being refused as busy.
485
+ */
486
+ const stopStrayGatekeeper = (spaceId) => {
487
+ if (busy.has(spaceId) || strayStops.has(spaceId)) return;
488
+ const stopping = manager.stopSpace({ placeId: place.id, spaceId })
489
+ .catch((error) => {
490
+ logger.warn?.(`[spaces] the gatekeeper beside stopped space ${spaceId} still runs: ${error?.code ?? error?.message ?? error}`);
491
+ })
492
+ .finally(() => { strayStops.delete(spaceId); });
493
+ strayStops.set(spaceId, stopping);
494
+ };
495
+
259
496
  const requireListed = async (spaceId) => {
260
497
  const space = (await listSpaces()).find((entry) => entry.id === spaceId);
261
498
  if (!space) throw new SpaceError('space_not_found', `There is no space ${spaceId}`);
@@ -267,26 +504,162 @@ export function createSpaceJourney({
267
504
  * chose is said again from the record; without a readable record the space stays closed, and
268
505
  * the answer says so with `networkRestored` false.
269
506
  */
270
- const startSpace = (spaceId) => exclusive(spaceId, async () => {
507
+ const startUnlocked = async (spaceId) => {
271
508
  // As for a creation: no start may slip in while the switch is stopping the spaces one by one.
272
509
  if (closing) throw new SpaceError('isolated_spaces_off', 'Isolated spaces are being turned off.');
273
510
  requireNotPending(spaceId);
511
+ await strayStops.get(spaceId);
274
512
  await manager.startSpace({ placeId: place.id, spaceId });
275
513
  const { record } = records.read(spaceId);
276
514
  let networkRestored = false;
515
+ let grants = { restored: [], needsAccess: [] };
277
516
  if (record) {
278
517
  await gatekeeper.setNetwork(spaceId, record.network);
279
518
  networkRestored = true;
519
+ grants = await restoreGrants(spaceId, record.grants);
520
+ await rewriteProviderConfig(spaceId, record.grants);
280
521
  // A history that never arrived, or that failed, is sent again: a stop right after the
281
522
  // creation is the usual way it fails, and the space would otherwise stay shallow for good.
282
523
  if ((record.history === 'pending' || record.history === 'failed') && record.repository && record.spacePath && record.base) {
283
524
  sendHistoryInBackground({ repository: record.repository, spaceId, spacePath: record.spacePath, base: record.base });
284
525
  }
285
526
  }
527
+ await deliverIdleStop(spaceId);
528
+ onSpacesChanged();
529
+ return { ...(await requireListed(spaceId)), networkRestored, grantsRestored: grants.restored, needsAccess: grants.needsAccess };
530
+ };
531
+ const startSpace = (spaceId) => exclusive(spaceId, () => startUnlocked(spaceId));
532
+
533
+ /**
534
+ * Restarts the container of a running space, the second of the repair actions, and gives the
535
+ * server inside a fresh token on the way (DESIGN.md, "Dispatcher, sessions, events"): the new
536
+ * token is written while the space runs, and the server reads it when it starts again. The
537
+ * token is not a secret from the agent, so one that cannot be written is logged and the restart
538
+ * goes on; the dispatcher reads the token again when the server inside refuses the old one.
539
+ * A stop, then a start with the network and the grants said again, exactly as the two apart.
540
+ */
541
+ const restartSpace = (spaceId) => exclusive(spaceId, async () => {
542
+ if (closing) throw new SpaceError('isolated_spaces_off', 'Isolated spaces are being turned off.');
543
+ requireNotPending(spaceId);
544
+ const space = await requireListed(spaceId);
545
+ if (space.state !== 'running') throw new SpaceError('space_not_running', 'This space is stopped. Start it instead.');
546
+ try {
547
+ await serverInside.writeToken(spaceId, createSpaceToken());
548
+ } catch (error) {
549
+ logger.warn?.(`[spaces] the server inside space ${spaceId} keeps its token: ${error?.code ?? error?.message ?? error}`);
550
+ }
551
+ await manager.stopSpace({ placeId: place.id, spaceId });
552
+ return startUnlocked(spaceId);
553
+ });
554
+
555
+ /**
556
+ * Restarts OpenCode inside a running space, the softest of the repair actions: the server inside
557
+ * restarts the OpenCode it manages and answers once it is ready again. The container, its
558
+ * gatekeeper and the grants stay as they are.
559
+ */
560
+ const restartOpenCode = (spaceId) => exclusive(spaceId, async () => {
561
+ requireNotPending(spaceId);
562
+ const space = await requireListed(spaceId);
563
+ if (space.state !== 'running') throw new SpaceError('space_not_running', 'OpenCode runs inside a running space. Start the space.');
564
+ await restartOpenCodeInside(spaceId);
286
565
  onSpacesChanged();
287
- return { ...(await requireListed(spaceId)), networkRestored };
566
+ return requireListed(spaceId);
567
+ });
568
+
569
+ /**
570
+ * Gives a running space a grant: the key goes to the gatekeeper, the grant without its value
571
+ * goes to the record, and for a model grant OpenCode inside is told to send that provider's
572
+ * calls through the window. A second grant for the same provider replaces the first, which is
573
+ * how a key is changed; a grant is never taken back (decision 4). The value of a typed key is
574
+ * in this request and in the gatekeeper's memory, and nowhere else afterwards.
575
+ */
576
+ const grantAccess = (spaceId, request) => exclusive(spaceId, async () => {
577
+ requireNotPending(spaceId);
578
+ const parsed = grantRequestSchema.safeParse(request ?? {});
579
+ if (!parsed.success) throw new SpaceError('invalid_grant_request', 'A grant is a model key for a provider, typed or named by a host environment variable, or an opened domain.');
580
+ const space = await requireListed(spaceId);
581
+ if (space.state !== 'running') throw new SpaceError('space_not_running', 'A grant goes to the gatekeeper of a running space. Start the space, then grant.');
582
+ const current = records.read(spaceId);
583
+ if (current.status !== 'ok') throw new SpaceError('space_record_unreadable', 'The host\'s record of this space cannot be read, so a grant could not be remembered. Remove the space and create it again.');
584
+
585
+ const asked = parsed.data;
586
+ if (asked.kind === 'model' && !HEADER_BY_PROVIDER.has(asked.provider)) {
587
+ throw new SpaceError('provider_not_supported', `A key for ${asked.provider} cannot be given through the network filter yet: it reads its key in a way the network filter does not know.`);
588
+ }
589
+ let grant;
590
+ let secret = null;
591
+ if (asked.kind === 'model') {
592
+ const source = asked.secret.kind === 'typed' ? { kind: 'typed' } : { kind: 'env', name: asked.secret.name };
593
+ secret = asked.secret.kind === 'typed' ? asked.secret.value : readHostSecret(asked.secret.name);
594
+ if (typeof secret !== 'string' || secret === '') {
595
+ throw new SpaceError('secret_source_missing', `The environment variable ${asked.secret.name} is not set for OpenChamber, so there is no key to give.`);
596
+ }
597
+ grant = { kind: 'model', id: asked.provider, provider: asked.provider, upstream: asked.upstream, header: HEADER_BY_PROVIDER.get(asked.provider), source };
598
+ } else {
599
+ grant = { kind: 'domain', id: `open-${crypto.randomBytes(6).toString('hex')}`, upstream: asked.upstream };
600
+ }
601
+ await gatekeeper.addGrant(spaceId, { id: grant.id, upstream: grant.upstream, header: grant.kind === 'model' ? grant.header : null, secret });
602
+ const grants = [...current.record.grants.filter((entry) => entry.id !== grant.id), grant];
603
+ if (records.update(spaceId, { grants }).status !== 'ok') {
604
+ throw new SpaceError('space_record_unreadable', 'The grant reached the network filter and could not be remembered, so it is gone at the next start. Remove the space and create it again.');
605
+ }
606
+ // A failure here answers the grant with it; the key is in the gatekeeper and the record, and
607
+ // the next start writes the configuration again.
608
+ if (grant.kind === 'model') await spaceOpenCode.writeProviderConfig(spaceId, grants);
609
+ return { grant: describeGrant(grant) };
610
+ });
611
+
612
+ /**
613
+ * Adds a domain to a running space's allowlist, live: the gatekeeper is told first, then the
614
+ * record, so the next start says it again. A record that cannot be written after the gatekeeper
615
+ * took the domain leaves it open until the next start, which closes it: the safe direction.
616
+ * The name may come from the journal, which the agent wrote; what makes it a decision is the
617
+ * user reading it and pressing "Open", and the name rule refuses anything that is not a name.
618
+ */
619
+ const openDomain = (spaceId, request) => exclusive(spaceId, async () => {
620
+ requireNotPending(spaceId);
621
+ const parsed = openDomainRequestSchema.safeParse(request ?? {});
622
+ if (!parsed.success) throw new SpaceError('invalid_domain', 'A domain is a name such as registry.npmjs.org: letters, digits and hyphens, with a dot.');
623
+ const { domain } = parsed.data;
624
+ const space = await requireListed(spaceId);
625
+ if (space.state !== 'running') throw new SpaceError('space_not_running', 'A domain is opened by the gatekeeper of a running space. Start the space, then open it.');
626
+ const current = records.read(spaceId);
627
+ if (current.status !== 'ok') throw new SpaceError('space_record_unreadable', 'The host\'s record of this space cannot be read, so an opened domain could not be remembered. Remove the space and create it again.');
628
+ const { network } = current.record;
629
+ if (network.mode === 'open') throw new SpaceError('network_is_open', 'The network of this space is open, so there is no list to add a domain to.');
630
+ if (network.domains.includes(domain)) return { network };
631
+ const next = networkSchema.safeParse({ mode: network.mode, domains: [...network.domains, domain] });
632
+ if (!next.success) throw new SpaceError('too_many_domains', 'This space already has as many opened domains as a list holds.');
633
+ await gatekeeper.setNetwork(spaceId, next.data);
634
+ if (records.update(spaceId, { network: next.data }).status !== 'ok') {
635
+ throw new SpaceError('space_record_unreadable', 'The domain is open now and could not be remembered, so it closes at the next start. Remove the space and create it again.');
636
+ }
637
+ return { network: next.data };
638
+ });
639
+
640
+ /**
641
+ * Runs the project's setup commands again in a running space, from the "⋯" menu or after a run
642
+ * that failed or was interrupted. The client resolves them as for a new space, trust included.
643
+ * Answers the listed entry once the run began; the run goes on in the background.
644
+ */
645
+ const runSetup = (spaceId, request) => exclusive(spaceId, async () => {
646
+ requireNotPending(spaceId);
647
+ const parsed = setupRequestSchema.safeParse(request ?? {});
648
+ if (!parsed.success) throw new SpaceError(...CREATE_REFUSALS.setupCommands);
649
+ const space = await requireListed(spaceId);
650
+ if (space.state !== 'running') throw new SpaceError('space_not_running', 'The setup commands run inside a running space. Start the space.');
651
+ const { record } = records.read(spaceId);
652
+ if (!record?.spacePath) throw new SpaceError('space_record_unreadable', 'The host\'s record of this space cannot be read, so it does not know where the project is inside. Remove the space and create it again.');
653
+ setup.start(spaceId, { projectPath: record.spacePath, commands: parsed.data.commands });
654
+ return requireListed(spaceId);
288
655
  });
289
656
 
657
+ /** The setup as the list carries it, with the end of the failed command's output. */
658
+ const readSetup = async (spaceId) => {
659
+ const space = await requireListed(spaceId);
660
+ return { setup: space.setup, output: setup.outputOf(records.read(spaceId).record) };
661
+ };
662
+
290
663
  const stopSpace = (spaceId) => exclusive(spaceId, async () => {
291
664
  requireNotPending(spaceId);
292
665
  await manager.stopSpace({ placeId: place.id, spaceId });
@@ -320,17 +693,30 @@ export function createSpaceJourney({
320
693
 
321
694
  /**
322
695
  * Stops every running space, for the switch being turned off. Each space is tried on its own:
323
- * one that could not be stopped is reported as still running, never counted as stopped.
696
+ * one that could not be stopped is reported as still running, never counted as stopped. When
697
+ * the place cannot even list them, Docker being down among the reasons, the turn-off still goes
698
+ * through and says so in `unknown`: the switch must stay reachable, and what runs cannot be
699
+ * stopped from here either way (decision 18).
324
700
  */
325
701
  const stopAllSpaces = async () => {
326
702
  const preparing = Array.from(pending.values()).filter((entry) => entry.state === 'preparing');
327
703
  if (preparing.length > 0) throw new SpaceError('space_preparing', `${preparing.length === 1 ? 'A space is' : `${preparing.length} spaces are`} still being made. Wait for that to finish first.`, { spaces: preparing.map((entry) => entry.id) });
328
704
  closing = true;
329
- const spaces = await manager.listSpaces({ placeId: place.id });
705
+ let spaces;
706
+ try {
707
+ spaces = await manager.listSpaces({ placeId: place.id });
708
+ } catch (error) {
709
+ logger.warn?.(`[spaces] turning off without knowing which spaces run: ${error?.code ?? error?.message ?? error}`);
710
+ return { stopped: [], stillRunning: [], unknown: failureOf(error) };
711
+ }
330
712
  const stopped = [];
331
713
  const stillRunning = [];
332
714
  for (const space of spaces) {
333
- if (space.state !== 'running') continue;
715
+ if (space.state !== 'running') {
716
+ // A gatekeeper left by an idle stop goes too, and the space is not counted: it was stopped.
717
+ if (space.gatekeeperRunning === true && !busy.has(space.id)) await manager.stopSpace({ placeId: place.id, spaceId: space.id }).catch(() => {});
718
+ continue;
719
+ }
334
720
  try {
335
721
  await manager.stopSpace({ placeId: place.id, spaceId: space.id });
336
722
  stopped.push({ id: space.id, name: space.name });
@@ -341,6 +727,30 @@ export function createSpaceJourney({
341
727
  return { stopped, stillRunning };
342
728
  };
343
729
 
730
+ /** The user's idle stop setting, as the settings screen shows it. */
731
+ const readIdleStopSetting = () => readIdleStop();
732
+
733
+ /**
734
+ * Keeps a new idle stop setting and tells every running space, one change after the other. A
735
+ * space that cannot be told keeps its old setting until its next start, which says the new one;
736
+ * a stopped space hears it at its start. Answers the setting as kept.
737
+ */
738
+ const changeIdleStop = (request) => {
739
+ const parsed = idleStopSchema.safeParse(request ?? {});
740
+ if (!parsed.success) return Promise.reject(new SpaceError('invalid_idle_stop', 'The idle stop is on or off, with a whole number of hours from 1 to 168.'));
741
+ const setting = parsed.data;
742
+ const change = idleStopTurn.then(async () => {
743
+ await saveIdleStop(setting);
744
+ const spaces = await manager.listSpaces({ placeId: place.id });
745
+ for (const space of spaces) {
746
+ if (space.state === 'running' && !pending.has(space.id)) await writeIdleStop(space.id, setting);
747
+ }
748
+ return setting;
749
+ });
750
+ idleStopTurn = change.catch(() => {});
751
+ return change;
752
+ };
753
+
344
754
  /** For a turn-off that did not go through after the spaces were stopped: creations are taken again. */
345
755
  const reopen = () => { closing = false; };
346
756
 
@@ -389,5 +799,5 @@ export function createSpaceJourney({
389
799
  return { brought, applied, removal };
390
800
  });
391
801
 
392
- return { createSpace, listSpaces, startSpace, stopSpace, removeSpace, stopAllSpaces, reopen, readJournal, previewApply, applySpace };
802
+ return { createSpace, listSpaces, startSpace, stopSpace, restartSpace, restartOpenCode, removeSpace, stopAllSpaces, reopen, grantAccess, openDomain, readJournal, previewApply, applySpace, readIdleStopSetting, changeIdleStop, runSetup, readSetup };
393
803
  }