@openchamber/web 2.0.1 → 2.0.2

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 (159) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-zm3C1FvM.js → CodeMirrorCommentWidgets-CmKmyb9T.js} +1 -1
  2. package/dist/assets/{DiffView-DNExNi1z.js → DiffView-8-PFpZ2p.js} +1 -1
  3. package/dist/assets/{FilesView-DUCLmHBi.js → FilesView-0Ie20mEk.js} +9 -9
  4. package/dist/assets/{GitView-Bz9z6gZA.js → GitView-DNUSu00w.js} +1 -1
  5. package/dist/assets/{GuestAttachDialog-UGp4KDlK.js → GuestAttachDialog-Cv6QzjHC.js} +1 -1
  6. package/dist/assets/{GuestSurfacePane-B3pdB_2u.js → GuestSurfacePane-Bt3jB_Ye.js} +1 -1
  7. package/dist/assets/{JsonTreeView-7lVecnZl.js → JsonTreeView-BlyHTRhM.js} +1 -1
  8. package/dist/assets/{LinearIssuesView-CTGRS9Vq.js → LinearIssuesView-CSl2MUfA.js} +1 -1
  9. package/dist/assets/MarkdownImageGallery-2UXJF-5B.js +1 -0
  10. package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +12 -0
  11. package/dist/assets/{OnboardingScreen-CBx6cXPP.js → OnboardingScreen-CIdXJpfc.js} +1 -1
  12. package/dist/assets/{PatchDiff-D7VVpR_l.js → PatchDiff-ByvnbG5T.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-Gbfks1pk.js → PierreDiffViewer-BXieg0mH.js} +1 -1
  14. package/dist/assets/{PlanView-CPSK0x97.js → PlanView-DEIi3Q7M.js} +3 -3
  15. package/dist/assets/PluginPane-BEPUWVho.js +3 -0
  16. package/dist/assets/{SettingsView-Dql7z6Ww.js → SettingsView-CiNh-RbW.js} +16 -16
  17. package/dist/assets/{SettingsWindow-D6oi-UmV.js → SettingsWindow-BIz224xs.js} +1 -1
  18. package/dist/assets/{SubmoduleDiffSummary-BXA0FAWj.js → SubmoduleDiffSummary-CXKmlps9.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-BQJsSbDm.js → ToolOutputDialog-BsgAK8xu.js} +6 -6
  20. package/dist/assets/{ToolPartDiffPreview-FY9w0TVT.js → ToolPartDiffPreview-vdPObXOf.js} +1 -1
  21. package/dist/assets/{VirtualizedFileDiff-B9YhAya5.js → VirtualizedFileDiff-BkFNKWS5.js} +1 -1
  22. package/dist/assets/{WalkthroughView-CmFgOUFN.js → WalkthroughView-6oE-MuDL.js} +2 -2
  23. package/dist/assets/{appThemeRegistry-BebxalUt.js → appThemeRegistry-aHUNHoqP.js} +1 -1
  24. package/dist/assets/{commitAndPush-Wfxng_IK.js → commitAndPush-Bon9r94r.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-BCOqgixN.js → computeVirtualFileMetrics-DKqr_1AQ.js} +1 -1
  26. package/dist/assets/de-CgAJ51z7.js +10 -0
  27. package/dist/assets/es-zGi_ravM.js +16 -0
  28. package/dist/assets/fr-CPfogrWx.js +14 -0
  29. package/dist/assets/index-CHfphYL3.js +41 -0
  30. package/dist/assets/{index-3TiDNtfN.js → index-DpFttslC.js} +1 -1
  31. package/dist/assets/index-DvMJ3w6V.css +1 -0
  32. package/dist/assets/{isDiffPlainText-DnDYQmWK.js → isDiffPlainText-kzAgpIgi.js} +1 -1
  33. package/dist/assets/{isFilePlainText-BA_AHX7d.js → isFilePlainText-Uj6y-jzz.js} +1 -1
  34. package/dist/assets/ja-DMk6wd-U.js +16 -0
  35. package/dist/assets/ko-BFpzJ8jc.js +16 -0
  36. package/dist/assets/{main-DtUmJp9B.js → main-CbfMxn-I.js} +2 -2
  37. package/dist/assets/main-anyZFMIs.js +896 -0
  38. package/dist/assets/{markdownCore-BSnlUXBf.js → markdownCore-CmM47cAE.js} +5 -5
  39. package/dist/assets/{miniChat-BYfLUnDK.js → miniChat-CiAKBC10.js} +2 -2
  40. package/dist/assets/{mobile-DH3hI6gd.js → mobile-CsT4sJwC.js} +2 -2
  41. package/dist/assets/{patchFileDiff--L7lt_GZ.js → patchFileDiff-DeaE08W0.js} +1 -1
  42. package/dist/assets/{pl-BkI_xHqz.js → pl-VdRPcZrB.js} +5 -5
  43. package/dist/assets/pt-BR-BRys_lOW.js +16 -0
  44. package/dist/assets/{renderElectronMiniChatApp-C7kpNW_-.js → renderElectronMiniChatApp-C5677jy0.js} +2 -2
  45. package/dist/assets/{renderMobileApp-i0nq7Dwy.js → renderMobileApp-D4dBBAqQ.js} +7 -7
  46. package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +27 -0
  47. package/dist/assets/{scheduledTasksApi-Cy7uZCaI.js → scheduledTasksApi-BZCNJ588.js} +1 -1
  48. package/dist/assets/{shikiHighlight-D4vxipfr.js → shikiHighlight-BSUEa3yF.js} +1 -1
  49. package/dist/assets/{textMateThemeFromAppTheme-BYAHtJwQ.js → textMateThemeFromAppTheme-CsATFZIV.js} +1 -1
  50. package/dist/assets/tr-CA9ckNnm.js +7 -0
  51. package/dist/assets/uk-byjR-y8D.js +16 -0
  52. package/dist/assets/{useAppFontEffects-DHZ9-L30.js → useAppFontEffects-BWQZ5DeI.js} +153 -150
  53. package/dist/assets/{useInlineCommentController-CvpOMK-R.js → useInlineCommentController-DlFyVfBu.js} +1 -1
  54. package/dist/assets/{useRootScrollLock-DzNFi-fn.js → useRootScrollLock-Cp1eFoM2.js} +2 -2
  55. package/dist/assets/{vendor-codemirror-language-data-j3fhlwUM.js → vendor-codemirror-language-data-BwwommM0.js} +2 -2
  56. package/dist/assets/{web-components-BvHNFSEG.js → web-components-D3Yjr4Zx.js} +1 -1
  57. package/dist/assets/zh-CN-DRabgxdG.js +16 -0
  58. package/dist/assets/zh-TW-rbY5c9UK.js +16 -0
  59. package/dist/index.html +3 -3
  60. package/dist/mini-chat.html +3 -3
  61. package/dist/mobile.html +3 -3
  62. package/package.json +2 -2
  63. package/server/index.js +64 -0
  64. package/server/lib/event-stream/global-hub.js +23 -1
  65. package/server/lib/event-stream/global-hub.test.js +35 -0
  66. package/server/lib/event-stream/global-ws-bridge.js +3 -1
  67. package/server/lib/event-stream/upstream-reader.js +3 -2
  68. package/server/lib/opencode/DOCUMENTATION.md +6 -2
  69. package/server/lib/opencode/bootstrap-runtime.js +2 -1
  70. package/server/lib/opencode/config-entity-v2.test.js +27 -0
  71. package/server/lib/opencode/config-paths.test.js +12 -0
  72. package/server/lib/opencode/core-routes.js +17 -4
  73. package/server/lib/opencode/core-routes.test.js +26 -0
  74. package/server/lib/opencode/mcp.js +7 -2
  75. package/server/lib/opencode/project-directory-runtime.js +8 -0
  76. package/server/lib/opencode/project-directory-runtime.test.js +13 -0
  77. package/server/lib/opencode/proxy.js +38 -2
  78. package/server/lib/opencode/routes.js +18 -0
  79. package/server/lib/opencode/server-utils-runtime.js +5 -0
  80. package/server/lib/opencode/settings-helpers.js +3 -0
  81. package/server/lib/opencode/settings-helpers.test.js +1 -1
  82. package/server/lib/opencode/settings-registry.json +3 -0
  83. package/server/lib/opencode/shared.js +17 -2
  84. package/server/lib/opencode/shutdown-runtime.js +3 -0
  85. package/server/lib/opencode/watcher.js +3 -1
  86. package/server/lib/realtime-proxy.js +5 -1
  87. package/server/lib/realtime-proxy.test.js +29 -0
  88. package/server/lib/relay/tunnel-host.js +4 -1
  89. package/server/lib/relay/tunnel-host.test.js +11 -0
  90. package/server/lib/small-model/DOCUMENTATION.md +11 -10
  91. package/server/lib/small-model/index.js +27 -32
  92. package/server/lib/small-model/index.test.js +28 -16
  93. package/server/lib/spaces/DOCUMENTATION.md +381 -20
  94. package/server/lib/spaces/code-in-bait.js +145 -6
  95. package/server/lib/spaces/code-in.js +10 -150
  96. package/server/lib/spaces/code-in.test.js +7 -83
  97. package/server/lib/spaces/code-out.js +1819 -0
  98. package/server/lib/spaces/code-out.test.js +3945 -0
  99. package/server/lib/spaces/code-transfer.js +173 -0
  100. package/server/lib/spaces/command-stream.test.js +181 -0
  101. package/server/lib/spaces/dispatcher.js +670 -0
  102. package/server/lib/spaces/dispatcher.test.js +582 -0
  103. package/server/lib/spaces/gatekeeper-channel.js +2 -0
  104. package/server/lib/spaces/gatekeeper-channel.test.js +9 -3
  105. package/server/lib/spaces/gatekeeper-program.cjs +4 -1
  106. package/server/lib/spaces/gatekeeper-program.test.js +3 -0
  107. package/server/lib/spaces/hardening.js +20 -4
  108. package/server/lib/spaces/hardening.test.js +18 -3
  109. package/server/lib/spaces/host-git.js +7 -4
  110. package/server/lib/spaces/host-git.test.js +6 -2
  111. package/server/lib/spaces/host.js +304 -0
  112. package/server/lib/spaces/host.test.js +273 -0
  113. package/server/lib/spaces/journey.js +393 -0
  114. package/server/lib/spaces/journey.test.js +384 -0
  115. package/server/lib/spaces/layout.js +26 -2
  116. package/server/lib/spaces/manager.js +4 -3
  117. package/server/lib/spaces/manager.test.js +6 -0
  118. package/server/lib/spaces/places/code-out.docker.live.test.js +412 -0
  119. package/server/lib/spaces/places/contract-suite.js +36 -0
  120. package/server/lib/spaces/places/dispatcher.docker.live.test.js +296 -0
  121. package/server/lib/spaces/places/docker.js +15 -3
  122. package/server/lib/spaces/places/docker.test.js +33 -2
  123. package/server/lib/spaces/places/escape-suite.js +86 -14
  124. package/server/lib/spaces/places/memory-place.js +24 -1
  125. package/server/lib/spaces/places/registry.js +1 -1
  126. package/server/lib/spaces/places/server.docker.live.test.js +69 -33
  127. package/server/lib/spaces/places/sessions.docker.live.test.js +220 -0
  128. package/server/lib/spaces/routes.js +207 -0
  129. package/server/lib/spaces/routes.test.js +211 -0
  130. package/server/lib/spaces/run-command.js +261 -8
  131. package/server/lib/spaces/run-command.test.js +193 -3
  132. package/server/lib/spaces/space-events.js +153 -0
  133. package/server/lib/spaces/space-events.test.js +160 -0
  134. package/server/lib/spaces/space-records.js +98 -0
  135. package/server/lib/spaces/space-records.test.js +73 -0
  136. package/server/lib/spaces/space-sessions.js +210 -0
  137. package/server/lib/spaces/space-sessions.test.js +161 -0
  138. package/server/lib/spaces/websocket.js +329 -0
  139. package/server/lib/spaces/websocket.test.js +345 -0
  140. package/server/lib/ui-auth/ui-auth.js +8 -2
  141. package/server/lib/ui-auth/ui-auth.test.js +29 -0
  142. package/server/opencode-proxy.test.js +113 -0
  143. package/dist/assets/MarkdownImageGallery-DQk5adUs.js +0 -1
  144. package/dist/assets/MarkdownRendererImpl-DPF8fZpX.js +0 -12
  145. package/dist/assets/PluginPane-BIGsUx69.js +0 -3
  146. package/dist/assets/de-CMA45TC-.js +0 -10
  147. package/dist/assets/es-DPL4fBtl.js +0 -16
  148. package/dist/assets/fr-OHBKBseP.js +0 -14
  149. package/dist/assets/index-BLUZa5u0.js +0 -41
  150. package/dist/assets/index-Cm2rrq69.css +0 -1
  151. package/dist/assets/ja-DvX4WSRf.js +0 -16
  152. package/dist/assets/ko-BUcLd8YZ.js +0 -16
  153. package/dist/assets/main-B_jri4i-.js +0 -896
  154. package/dist/assets/pt-BR-7wFtQlV9.js +0 -16
  155. package/dist/assets/runtimeEndpointReset-CfEYbcCc.js +0 -27
  156. package/dist/assets/tr-TsD-AqEH.js +0 -7
  157. package/dist/assets/uk-B-qspCmD.js +0 -16
  158. package/dist/assets/zh-CN-DYuPJV5i.js +0 -16
  159. package/dist/assets/zh-TW-BX_2D_lV.js +0 -16
@@ -0,0 +1,296 @@
1
+ // The dispatcher in front of a real space on a real Docker daemon. Runs only with
2
+ // OPENCHAMBER_TEST_DOCKER=1. Two parts: the dispatcher over the Docker place, mounted in an
3
+ // Express app the way `server/index.js` mounts it; and the real server started headless, once
4
+ // with the switch off and once with it on, in front of a stand-in Docker daemon that records
5
+ // whether anything ever spoke to it.
6
+
7
+ import { spawn } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import http from 'node:http';
10
+ import net from 'node:net';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+
15
+ import express from 'express';
16
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
17
+
18
+ import { createSpacesHost } from '../host.js';
19
+ import { createSpaceId, hashProjectDirectory } from '../labels.js';
20
+ import { LIVE_DOCKER_ENABLED, createLiveDockerPlace } from './docker-live-support.js';
21
+
22
+ const CREATE_TIMEOUT_MS = 25 * 60_000;
23
+ const SERVER_ENTRY = fileURLToPath(new URL('../../../index.js', import.meta.url));
24
+
25
+ const temporary = (prefix) => fs.mkdtempSync(path.join(os.tmpdir(), prefix));
26
+
27
+ const listen = (app) => new Promise((resolve) => {
28
+ const server = http.createServer(app);
29
+ server.listen(0, '127.0.0.1', () => resolve(server));
30
+ });
31
+
32
+ describe.skipIf(!LIVE_DOCKER_ENABLED)('dispatcher over a real space: docker (live)', () => {
33
+ const spec = {
34
+ id: createSpaceId(),
35
+ name: 'Dispatcher live',
36
+ project: hashProjectDirectory('/dispatcher/live/project'),
37
+ created: new Date().toISOString(),
38
+ memoryBytes: 2 * 1024 * 1024 * 1024,
39
+ };
40
+ const repo = `/spaces/${spec.id}/repo`;
41
+ let place;
42
+ let dispose = async () => {};
43
+ let dataDir;
44
+ let host;
45
+ let server;
46
+ let hostRouteRuns = 0;
47
+ const url = (suffix) => `http://127.0.0.1:${server.address().port}${suffix}`;
48
+ const shell = async (script) => {
49
+ const result = await place.exec(spec.id, ['sh', '-c', script]);
50
+ expect(result.code, `${script}: ${result.stderr}`).toBe(0);
51
+ return result.stdout;
52
+ };
53
+
54
+ beforeAll(async () => {
55
+ ({ place, dispose } = createLiveDockerPlace());
56
+ await place.create(spec);
57
+ await shell(`mkdir -p ${repo} && cd ${repo} && git init -q . && git -c user.email=space@example.invalid -c user.name=Space commit -q --allow-empty -m init`);
58
+ dataDir = temporary('openchamber-dispatcher-live-');
59
+ host = createSpacesHost({ dataDir, place, logger: { warn: () => {} } });
60
+ const app = express();
61
+ // The host's auth gate stands in front of the dispatcher in the real server; here the request
62
+ // is taken as authenticated, and one host route records whether it ever ran.
63
+ app.use(host.middleware);
64
+ app.all('/api/git/status', (req, res) => {
65
+ hostRouteRuns += 1;
66
+ res.json({ ranOnHost: true, directory: req.query.directory ?? null });
67
+ });
68
+ app.use((_req, res) => res.status(404).json({ error: 'not found on host' }));
69
+ server = await listen(app);
70
+ }, CREATE_TIMEOUT_MS);
71
+
72
+ afterAll(async () => {
73
+ host?.close();
74
+ await new Promise((resolve) => { if (server) server.close(() => resolve()); else resolve(); });
75
+ await dispose();
76
+ if (dataDir) fs.rmSync(dataDir, { recursive: true, force: true });
77
+ });
78
+
79
+ it('forwards a prefixed request to the server inside and returns its answer', async () => {
80
+ const response = await fetch(url(`/api/spaces/${spec.id}/session?directory=${encodeURIComponent(repo)}`));
81
+ expect(response.status).toBe(200);
82
+ expect(response.headers.get('x-content-type-options')).toBe('nosniff');
83
+ expect(response.headers.get('set-cookie')).toBeNull();
84
+ const list = await response.json();
85
+ expect(Array.isArray(list.data ?? list)).toBe(true);
86
+ });
87
+
88
+ it('creates a session inside through a streamed POST body, and lists it back', async () => {
89
+ const created = await fetch(url(`/api/spaces/${spec.id}/session`), {
90
+ method: 'POST',
91
+ headers: { 'content-type': 'application/json' },
92
+ body: JSON.stringify({ location: { directory: repo } }),
93
+ });
94
+ expect(created.status, await created.clone().text()).toBe(200);
95
+ const session = (await created.json()).data;
96
+ expect(session.location.directory).toBe(repo);
97
+
98
+ const listed = await fetch(url(`/api/spaces/${spec.id}/session?directory=${encodeURIComponent(repo)}`));
99
+ const ids = ((await listed.json()).data ?? []).map((entry) => entry.id);
100
+ expect(ids).toContain(session.id);
101
+ });
102
+
103
+ it('streams the event stream of the server inside', async () => {
104
+ const controller = new AbortController();
105
+ const response = await fetch(url(`/api/spaces/${spec.id}/event`), { signal: controller.signal, headers: { accept: 'text/event-stream' } });
106
+ expect(response.status).toBe(200);
107
+ expect(response.headers.get('content-type')).toContain('text/event-stream');
108
+ const reader = response.body.getReader();
109
+ const { value, done } = await reader.read();
110
+ expect(done).toBe(false);
111
+ expect(new TextDecoder().decode(value).length).toBeGreaterThan(0);
112
+ controller.abort();
113
+ }, 60_000);
114
+
115
+ it('refuses a prefixed request that names a directory outside the space, and a host-only route', async () => {
116
+ const outside = await fetch(url(`/api/spaces/${spec.id}/session?directory=${encodeURIComponent('/home/me/project')}`));
117
+ expect(outside.status).toBe(400);
118
+ expect(await outside.json()).toMatchObject({ code: 'directory_outside_space' });
119
+ const hostOnly = await fetch(url(`/api/spaces/${spec.id}/config/settings`));
120
+ expect(hostOnly.status).toBe(403);
121
+ expect(await hostOnly.json()).toMatchObject({ code: 'host_only_route' });
122
+ });
123
+
124
+ // The escape check of TESTING.md: a request without the space prefix, but with a space
125
+ // directory, does not run on the host.
126
+ it('refuses an unprefixed request with the space\'s directory before any host route runs', async () => {
127
+ const response = await fetch(url(`/api/git/status?directory=${encodeURIComponent(repo)}`));
128
+ expect(response.status).toBe(400);
129
+ expect(await response.json()).toMatchObject({ code: 'space_directory_needs_prefix' });
130
+ expect(hostRouteRuns).toBe(0);
131
+ const ordinary = await fetch(url('/api/git/status?directory=/tmp'));
132
+ expect(ordinary.status).toBe(200);
133
+ expect(hostRouteRuns).toBe(1);
134
+ });
135
+
136
+ // Processes inside are read from /proc, because the image has no pgrep. The match is anchored
137
+ // to the bridge's own command line, so the shell that runs this count is not counted.
138
+ const bridgesInside = async () => Number((await shell('n=0; for p in /proc/[0-9]*; do if tr "\\0" " " < "$p/cmdline" 2>/dev/null | grep -q "^/usr/local/bin/node -e "; then n=$((n+1)); fi; done; echo $n')).trim());
139
+
140
+ it('ends the bridge inside when the host closes its connections', async () => {
141
+ expect((await fetch(url(`/api/spaces/${spec.id}/session?directory=${encodeURIComponent(repo)}`))).status).toBe(200);
142
+ expect(await bridgesInside()).toBeGreaterThan(0);
143
+ host.close();
144
+ let left = await bridgesInside();
145
+ for (let attempt = 0; attempt < 40 && left > 0; attempt += 1) {
146
+ await new Promise((resolve) => { setTimeout(resolve, 250); });
147
+ left = await bridgesInside();
148
+ }
149
+ expect(left).toBe(0);
150
+ // The next request opens a new one.
151
+ expect((await fetch(url(`/api/spaces/${spec.id}/session?directory=${encodeURIComponent(repo)}`))).status).toBe(200);
152
+ }, 60_000);
153
+
154
+ it('answers 503 with a stable code for a stopped space, and serves it again after a start', async () => {
155
+ await place.stop(spec.id);
156
+ const stopped = await fetch(url(`/api/spaces/${spec.id}/session?directory=${encodeURIComponent(repo)}`));
157
+ expect(stopped.status).toBe(503);
158
+ expect(await stopped.json()).toMatchObject({ code: 'space_not_running' });
159
+
160
+ await place.start(spec.id);
161
+ const again = await fetch(url(`/api/spaces/${spec.id}/session?directory=${encodeURIComponent(repo)}`));
162
+ expect(again.status).toBe(200);
163
+ }, 5 * 60_000);
164
+ });
165
+
166
+ /**
167
+ * The real server, started headless, with a stand-in for the Docker daemon on `DOCKER_HOST`
168
+ * that records every connection. The docker CLI on this machine is the real one: whether the
169
+ * feature ever called it is exactly what the daemon's connection count says.
170
+ */
171
+ const startFakeDaemon = async (folder) => {
172
+ const socketPath = path.join(folder, 'docker.sock');
173
+ let connections = 0;
174
+ const open = new Set();
175
+ const daemon = net.createServer((socket) => {
176
+ connections += 1;
177
+ open.add(socket);
178
+ socket.on('close', () => open.delete(socket));
179
+ socket.on('error', () => {});
180
+ socket.end('HTTP/1.1 500 Internal Server Error\r\ncontent-length: 0\r\n\r\n');
181
+ });
182
+ await new Promise((resolve) => daemon.listen(socketPath, resolve));
183
+ return {
184
+ host: `unix://${socketPath}`,
185
+ connections: () => connections,
186
+ // A docker CLI may hold a connection open; `close` alone would wait for it for ever.
187
+ stop: () => new Promise((resolve) => {
188
+ for (const socket of open) socket.destroy();
189
+ daemon.close(() => resolve());
190
+ }),
191
+ };
192
+ };
193
+
194
+ const freePort = () => new Promise((resolve) => {
195
+ const probe = net.createServer();
196
+ probe.listen(0, '127.0.0.1', () => {
197
+ const { port } = probe.address();
198
+ probe.close(() => resolve(port));
199
+ });
200
+ });
201
+
202
+ const startServer = async ({ dataDir, dockerHost, port }) => {
203
+ const child = spawn(process.execPath, [SERVER_ENTRY, '--port', String(port), '--api-only'], {
204
+ env: { ...process.env, OPENCHAMBER_DATA_DIR: dataDir, DOCKER_HOST: dockerHost, OPENCHAMBER_RELAY_HOST: 'off' },
205
+ stdio: ['ignore', 'pipe', 'pipe'],
206
+ });
207
+ let output = '';
208
+ child.stdout.on('data', (chunk) => { output += chunk; });
209
+ child.stderr.on('data', (chunk) => { output += chunk; });
210
+ const base = `http://127.0.0.1:${port}`;
211
+ const deadline = Date.now() + 60_000;
212
+ let healthy = false;
213
+ while (!healthy && Date.now() < deadline) {
214
+ if (child.exitCode !== null) throw new Error(`the server left early:\n${output.slice(-2000)}`);
215
+ try {
216
+ healthy = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(5_000) })).status === 200;
217
+ } catch {
218
+ // Not up yet.
219
+ }
220
+ if (!healthy) await new Promise((resolve) => { setTimeout(resolve, 250); });
221
+ }
222
+ if (!healthy) throw new Error(`the server did not become healthy:\n${output.slice(-2000)}`);
223
+ return {
224
+ base,
225
+ /** One request with a bound, so a hang names itself and the server's output instead of a timeout. */
226
+ get: async (suffix) => {
227
+ try {
228
+ return await fetch(`${base}${suffix}`, { signal: AbortSignal.timeout(30_000) });
229
+ } catch (error) {
230
+ throw new Error(`${suffix}: ${error.message}\n${output.slice(-2000)}`);
231
+ }
232
+ },
233
+ output: () => output,
234
+ stop: () => new Promise((resolve) => {
235
+ child.once('exit', resolve);
236
+ child.kill('SIGTERM');
237
+ setTimeout(() => child.kill('SIGKILL'), 10_000).unref();
238
+ }),
239
+ };
240
+ };
241
+
242
+ describe.skipIf(!LIVE_DOCKER_ENABLED)('the switch, on the real server (live)', () => {
243
+ const folders = [];
244
+ afterAll(() => {
245
+ for (const folder of folders) fs.rmSync(folder, { recursive: true, force: true });
246
+ });
247
+
248
+ const startWith = async (enabled) => {
249
+ const folder = temporary('openchamber-switch-live-');
250
+ folders.push(folder);
251
+ const dataDir = path.join(folder, 'data');
252
+ fs.mkdirSync(dataDir, { recursive: true });
253
+ // The server copies `projects`, `themes` and `speech-models` from the default data directory
254
+ // into a fresh one at start; the last of those can be gigabytes. Present and empty, they stay.
255
+ for (const entry of ['projects', 'themes', 'speech-models']) fs.mkdirSync(path.join(dataDir, entry));
256
+ fs.writeFileSync(path.join(dataDir, 'settings.json'), JSON.stringify({ isolatedSpacesEnabled: enabled }));
257
+ const daemon = await startFakeDaemon(folder);
258
+ const server = await startServer({ dataDir, dockerHost: daemon.host, port: await freePort() });
259
+ return { dataDir, daemon, server, stop: async () => { await server.stop(); await daemon.stop(); } };
260
+ };
261
+
262
+ it('registers no route of the feature and never speaks to Docker while the switch is off', async () => {
263
+ const run = await startWith(false);
264
+ try {
265
+ const prefixed = await run.server.get('/api/spaces/aaaaaaaaaaaa/session');
266
+ // Whatever the host answers, it is not the feature: no space code, and the request went on
267
+ // to the host's own routes.
268
+ const body = await prefixed.text();
269
+ expect(body).not.toMatch(/space_not_found|space_unreachable|host_only_route/);
270
+ const unguarded = await run.server.get('/api/git/status?directory=/spaces/aaaaaaaaaaaa/repo');
271
+ expect(unguarded.status).not.toBe(400);
272
+ expect(run.daemon.connections()).toBe(0);
273
+ expect(fs.existsSync(path.join(run.dataDir, 'spaces'))).toBe(false);
274
+ } finally {
275
+ await run.stop();
276
+ }
277
+ }, 120_000);
278
+
279
+ it('registers the routes and asks Docker for its spaces while the switch is on', async () => {
280
+ const run = await startWith(true);
281
+ try {
282
+ const prefixed = await run.server.get('/api/spaces/aaaaaaaaaaaa/session');
283
+ expect(prefixed.status).toBe(502);
284
+ expect(await prefixed.json()).toMatchObject({ code: 'space_unreachable' });
285
+ expect(run.daemon.connections()).toBeGreaterThan(0);
286
+ const guarded = await run.server.get('/api/git/status?directory=/spaces/aaaaaaaaaaaa/repo');
287
+ expect(guarded.status).toBe(400);
288
+ expect(await guarded.json()).toMatchObject({ code: 'space_directory_needs_prefix' });
289
+ const hostOnly = await run.server.get('/api/spaces/aaaaaaaaaaaa/config/settings');
290
+ expect(hostOnly.status).toBe(403);
291
+ expect(fs.existsSync(path.join(run.dataDir, 'spaces', 'owner'))).toBe(true);
292
+ } finally {
293
+ await run.stop();
294
+ }
295
+ }, 120_000);
296
+ });
@@ -25,7 +25,8 @@ import {
25
25
  requireSpaceId,
26
26
  spaceResourceName,
27
27
  } from '../labels.js';
28
- import { SPACE_USER, TOOLS_MOUNT_PATH } from '../layout.js';
28
+ import { SPACE_CONNECT_COMMAND, SPACE_USER, TOOLS_MOUNT_PATH } from '../layout.js';
29
+ import { openCommandStream as openCommandStreamProcess } from '../run-command.js';
29
30
  import { createSpaceServerChannel, createSpaceToken } from '../space-server.js';
30
31
  import { CHANGE_TIMEOUT_MS, ROLLBACK_SETTLE_MS, createDockerEngine, entryLabels, entryName, isInterrupted, pause } from './docker-engine.js';
31
32
  import { createDockerTools } from './docker-tools.js';
@@ -57,7 +58,7 @@ function execRole(target) {
57
58
  throw new SpaceError('invalid_exec_target', `A command runs in the space or in its gatekeeper, not in '${target}'`);
58
59
  }
59
60
 
60
- export function createDockerPlace({ runCommand, dockerPath, owner, toolsSource, wait = pause, now = () => new Date() }) {
61
+ export function createDockerPlace({ runCommand, openCommandStream = openCommandStreamProcess, dockerPath, owner, toolsSource, wait = pause, now = () => new Date() }) {
61
62
  requireOwner(owner);
62
63
 
63
64
  const engine = createDockerEngine({ runCommand, dockerPath });
@@ -425,6 +426,17 @@ export function createDockerPlace({ runCommand, dockerPath, owner, toolsSource,
425
426
  return [dockerPath, 'exec', '--interactive', '--user', SPACE_USER, spaceResourceName(spaceId, ROLE_SPACE)];
426
427
  };
427
428
 
429
+ /**
430
+ * A channel to the server inside the space: the bridge of `layout.js` over the argv of
431
+ * `execArgv`, so the same ownership and running checks come first, and the same process
432
+ * shape as a push carries the bytes. The space's network never sees it. The stream is a
433
+ * `CommandStream` of `run-command.js`, and the dispatcher's agent uses it as a socket.
434
+ */
435
+ const connect = async (spaceId) => {
436
+ const [file, ...args] = await execArgv(spaceId);
437
+ return openCommandStream(file, [...args, ...SPACE_CONNECT_COMMAND]);
438
+ };
439
+
428
440
  /**
429
441
  * The space stops first and its gatekeeper after it, so a space is never running while its
430
442
  * way out is not under the host's control. A stop of the gatekeeper that fails leaves the
@@ -583,5 +595,5 @@ export function createDockerPlace({ runCommand, dockerPath, owner, toolsSource,
583
595
  return starting.get(spaceId);
584
596
  };
585
597
 
586
- return { id: DOCKER_PLACE_ID, check, create, list, exec, execArgv, stop, start, remove, verify };
598
+ return { id: DOCKER_PLACE_ID, check, create, list, exec, execArgv, connect, stop, start, remove, verify };
587
599
  }
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
3
3
  import { SpaceError } from '../errors.js';
4
4
  import { GATEKEEPER_PROGRAM } from '../gatekeeper-channel.js';
5
5
  import { buildSpaceLabels, buildToolsLabels, hashProjectDirectory } from '../labels.js';
6
- import { SPACE_ENVIRONMENT, SPACE_SERVER_COMMAND } from '../layout.js';
6
+ import { SPACE_CONNECT_COMMAND, SPACE_ENVIRONMENT, SPACE_SERVER_COMMAND } from '../layout.js';
7
7
  import { createRegistryToolsSource, toolsContentKey } from '../tools.js';
8
8
  import { SPACE_BASE_IMAGE, createDockerPlace } from './docker.js';
9
9
  import { bridgeNetworkEntry, createFakeDocker, hardenedContainerEntry, internalNetworkEntry } from './fake-docker.js';
@@ -27,7 +27,7 @@ const NOW = new Date('2026-09-20T08:00:00.000Z');
27
27
  /** A place on a plain runner, for the tests that wrap or replace the fake. */
28
28
  const placeOn = (runCommand, options = {}) => createDockerPlace({ runCommand, dockerPath: 'docker', owner: OWNER, toolsSource: SOURCE, now: () => NOW, ...options });
29
29
 
30
- const makePlace = (fake, owner = OWNER, toolsSource = SOURCE) => placeOn(fake.runCommand, { dockerPath: '/usr/bin/docker', owner, toolsSource, wait: fake.wait, now: fake.now });
30
+ const makePlace = (fake, owner = OWNER, toolsSource = SOURCE, options = {}) => placeOn(fake.runCommand, { dockerPath: '/usr/bin/docker', owner, toolsSource, wait: fake.wait, now: fake.now, ...options });
31
31
 
32
32
  const labelsFor = (role, { id = ID, owner = OWNER } = {}) => buildSpaceLabels({ ...SPEC, id, role, owner });
33
33
 
@@ -833,6 +833,37 @@ describe('docker place: exec, stop, start, verify', () => {
833
833
  await expect(makePlace(createFakeDocker({ resources: aside })).execArgv(ID)).rejects.toMatchObject({ code: 'space_move_unfinished' });
834
834
  });
835
835
 
836
+ // Added in stage 4a. `connect` runs the bridge of layout.js over the argv of `execArgv`, through
837
+ // the injected stream opener, so the same checks come first and no process starts in a unit test.
838
+ it('connects through the bridge inside the space container, over the exec argv, and changes nothing', async () => {
839
+ const fake = createFakeDocker({ resources: spaceResources() });
840
+ const opened = [];
841
+ const stream = { destroyed: false };
842
+ const place = makePlace(fake, OWNER, SOURCE, { openCommandStream: (file, args) => { opened.push([file, ...args]); return stream; } });
843
+
844
+ expect(await place.connect(ID)).toBe(stream);
845
+ expect(opened).toEqual([['/usr/bin/docker', 'exec', '--interactive', '--user', '1000:1000', CONTAINER, ...SPACE_CONNECT_COMMAND]]);
846
+ expect(SPACE_CONNECT_COMMAND.slice(0, 2)).toEqual(['/usr/local/bin/node', '-e']);
847
+ expect(SPACE_CONNECT_COMMAND.slice(-2)).toEqual(['127.0.0.1', '27600']);
848
+ expect(SPACE_CONNECT_COMMAND.join(' ')).not.toMatch(/\n/);
849
+ expect(changes(fake)).toEqual([]);
850
+ });
851
+
852
+ it('connects to no stopped space, no stranger\'s container, no space of another installation, none that is missing or mid-move', async () => {
853
+ const opened = [];
854
+ const connectWith = (fake) => makePlace(fake, OWNER, SOURCE, { openCommandStream: (...args) => { opened.push(args); return {}; } }).connect(ID);
855
+ await expect(connectWith(createFakeDocker({ resources: spaceResources({ running: false }) }))).rejects.toMatchObject({ code: 'space_not_running' });
856
+ const stranger = hardenedContainerEntry({ name: CONTAINER, labels: {}, network: NETWORK, volumes: [] });
857
+ await expect(connectWith(createFakeDocker({ resources: [{ kind: 'container', name: CONTAINER, entry: stranger }] }))).rejects.toMatchObject({ code: 'space_not_ours' });
858
+ await expect(connectWith(createFakeDocker({ resources: spaceResources({ owner: 'install-b' }) }))).rejects.toMatchObject({ code: 'space_not_ours' });
859
+ await expect(connectWith(createFakeDocker())).rejects.toMatchObject({ code: 'space_not_found' });
860
+ const aside = spaceResources({ running: false }).map((resource) => (resource.name === CONTAINER
861
+ ? { ...resource, name: `${CONTAINER}-old`, entry: { ...resource.entry, Name: `/${CONTAINER}-old` } }
862
+ : resource));
863
+ await expect(connectWith(createFakeDocker({ resources: aside }))).rejects.toMatchObject({ code: 'space_move_unfinished' });
864
+ expect(opened).toEqual([]);
865
+ });
866
+
836
867
  it('stops the space, starts the same container again, and waits for its server', async () => {
837
868
  const fake = createFakeDocker({ resources: [toolsResource(), ...spaceResources()] });
838
869
  const place = makePlace(fake);
@@ -190,17 +190,51 @@ Promise.all(Array.from({ length: 80 }, attempt)).then((outcomes) => {
190
190
  const LONG_LIVED_CREDENTIAL = '"refresh"[[:space:]]*:[[:space:]]*"|BEGIN [A-Z ]*PRIVATE KEY|gh[pousr]_[A-Za-z0-9]{16}|sk-[A-Za-z0-9_-]{20}|xox[baprs]-';
191
191
 
192
192
  /** Everything the space holds that could be a long-lived credential, as text for the host to read.
193
- * HOME, the work directory and /tmp, which is writable and 256 MiB. */
193
+ * HOME, the work directory and /tmp, which is writable and 256 MiB. `-a` reads binary files as
194
+ * text: OpenCode 2 keeps its logins in the SQLite database `opencode.db` under HOME, and `-I`
195
+ * skipped that file. `-o` prints the matched shape and its file, never the binary around it. */
194
196
  const credentialSearch = (spaceId) => `
195
197
  PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
196
198
  echo "auth-record: $([ -e "$HOME/.local/share/opencode/auth.json" ] && echo present || echo absent)";
197
199
  echo "--- files";
198
- grep -rIsE '${LONG_LIVED_CREDENTIAL}' "$HOME" /tmp /spaces/${spaceId} 2>/dev/null | head -20;
200
+ grep -raosE '${LONG_LIVED_CREDENTIAL}' "$HOME" /tmp /spaces/${spaceId} 2>/dev/null | head -20;
199
201
  echo "--- environments";
200
202
  for process in /proc/[0-9]*/environ; do tr '\\0' '\\n' < "$process" 2>/dev/null; done | grep -E '${LONG_LIVED_CREDENTIAL}' | head -20;
201
203
  echo "--- end";
202
204
  `;
203
205
 
206
+ // OpenCode 2's own login store: rows in the `credential` table of `opencode.db`. The control
207
+ // writes two the way OpenCode stores them: an OpenAI browser login, and a key for a provider of the
208
+ // user's own that OpenCode's catalog does not know, which no integration route lists and no key
209
+ // pattern matches. No route can create an OAuth record without a real login, so the rows are
210
+ // written with Node's built-in SQLite into the database the running OpenCode uses. The timeout
211
+ // waits for OpenCode's own lock instead of failing on it.
212
+ const DECOY_CREDENTIAL_ID = 'cred_decoy000000000000000000';
213
+ const DECOY_CUSTOM_CREDENTIAL_ID = 'cred_decoy000000000000000001';
214
+ const openDatabase = (databasePath, options = '{ timeout: 5000 }') => `
215
+ const { DatabaseSync } = require('node:sqlite');
216
+ const db = new DatabaseSync(${JSON.stringify(databasePath)}, ${options});
217
+ `;
218
+ const plantCredential = (databasePath) => `${openDatabase(databasePath)}
219
+ const now = Date.now();
220
+ const insert = db.prepare('INSERT INTO credential (id, integration_id, label, value, active, time_created, time_updated) VALUES (?, ?, ?, ?, ?, ?, ?)');
221
+ insert.run('${DECOY_CREDENTIAL_ID}', 'openai', 'default', JSON.stringify({ type: 'oauth', methodID: 'chatgpt-browser', refresh: 'decoy-refresh-value', access: 'decoy-access-value', expires: now + 3600000 }), 1, now, now);
222
+ insert.run('${DECOY_CUSTOM_CREDENTIAL_ID}', 'acme-llm', 'default', JSON.stringify({ type: 'key', key: 'acme_live_decoy' }), 1, now, now);
223
+ db.close();
224
+ `;
225
+ const removeCredential = (databasePath) => `${openDatabase(databasePath)}
226
+ const { changes } = db.prepare('DELETE FROM credential WHERE id IN (?, ?)').run('${DECOY_CREDENTIAL_ID}', '${DECOY_CUSTOM_CREDENTIAL_ID}');
227
+ db.close();
228
+ console.log('removed:' + changes);
229
+ `;
230
+ // Every stored login, by integration and kind, read straight from the table. OpenCode lists only
231
+ // the integrations its catalog knows, so this is the check that sees a custom provider's key.
232
+ const readCredentials = (databasePath) => `${openDatabase(databasePath, '{ readOnly: true, timeout: 5000 }')}
233
+ const rows = db.prepare("SELECT integration_id AS integration, json_extract(value, '$.type') AS type FROM credential ORDER BY id").all();
234
+ db.close();
235
+ console.log(JSON.stringify(rows.map((row) => ({ integration: row.integration, type: row.type }))));
236
+ `;
237
+
204
238
  const sleep = (milliseconds) => new Promise((resolve) => { setTimeout(resolve, milliseconds); });
205
239
 
206
240
  const sha256 = (value) => `sha256:${crypto.createHash('sha256').update(value).digest('hex')}`;
@@ -458,7 +492,6 @@ export function runEscapeSuite(title, { enabled = true, setup }) {
458
492
  // Positive control: the metadata is real and complete enough to show the environment.
459
493
  expect(metadata).toContain('OPENCODE_DISABLE_AUTOUPDATE=1');
460
494
  expect(metadata).not.toContain(token);
461
- expect(metadata).not.toContain('OPENCODE_AUTH_CONTENT');
462
495
  });
463
496
 
464
497
  it('cannot steer the requests of the host through its own ~/.curlrc', async () => {
@@ -877,35 +910,74 @@ export function runEscapeSuite(title, { enabled = true, setup }) {
877
910
  // ever inside a space. Stage 2 puts none there, and this fails the day something does.
878
911
  it('holds no long-lived credential of the user\'s, anywhere the space can read', async () => {
879
912
  const search = () => shell(credentialSearch(spec.id));
913
+ const server = createSpaceServerChannel({ exec: place.exec });
914
+ const login = await server.request(spec.id, { method: 'POST', path: '/auth/session', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: await server.readToken(spec.id) }) });
915
+ expect(login.status).toBe(200);
916
+ const cookie = login.headers['set-cookie'][0].split(';')[0];
917
+ // What OpenCode itself holds: every connection of every integration, a stored login or a
918
+ // provider key it found in its own environment under one of its catalog's names.
919
+ const connections = async () => {
920
+ const answer = await server.request(spec.id, { path: '/api/integration', headers: { Cookie: cookie } });
921
+ expect(answer.status).toBe(200);
922
+ const integrations = JSON.parse(answer.body).data;
923
+ expect(integrations.length).toBeGreaterThan(0);
924
+ return integrations.flatMap((integration) => integration.connections.map((connection) => ({ integration: integration.id, ...connection })));
925
+ };
926
+ const database = `${SPACE_HOME}/.local/share/opencode/opencode.db`;
927
+ const storedCredentials = async () => {
928
+ const answer = await inside(['node', '--no-warnings', '-e', readCredentials(database)]);
929
+ expect(answer.code, answer.stderr).toBe(0);
930
+ return JSON.parse(answer.stdout);
931
+ };
880
932
  const decoyRecord = `${SPACE_HOME}/.local/share/opencode/auth.json`;
881
933
  const decoy = 'sk-decoy00000000000000000000';
882
934
 
935
+ // The clean search runs first. SQLite keeps a deleted row's bytes in its write-ahead log,
936
+ // so after the control below the database would hold the decoy's text for good.
937
+ const found = (await search()).stdout;
938
+ // Positive control of its own: the search ran and looked in all three places.
939
+ expect(found).toContain('--- files');
940
+ expect(found).toContain('--- environments');
941
+ expect(found).toContain('--- end');
942
+ expect(found).toContain('auth-record: absent');
943
+ expect(found.slice(found.indexOf('--- files'))).toBe('--- files\n--- environments\n--- end\n');
944
+ expect(await connections()).toEqual([]);
945
+ expect(await storedCredentials()).toEqual([]);
946
+
883
947
  // Positive control: the same search, with a credential of each shape planted where one
884
- // would live. It must find all three, or a clean answer below would mean nothing.
948
+ // would live. The oauth refresh record goes only into OpenCode's database, so a search
949
+ // that skips binary files fails here. The legacy auth.json, which OpenCode 2 imports once,
950
+ // holds nothing and only shows that its path is checked.
885
951
  const planted = await shell([
886
952
  `mkdir -p "$(dirname ${decoyRecord})"`,
887
- `printf '{"openai":{"type":"oauth","refresh":"decoy-refresh-value"}}' > ${decoyRecord}`,
953
+ `printf '{}' > ${decoyRecord}`,
888
954
  `printf -- '-----BEGIN OPENSSH PRIVATE KEY-----' > "$HOME/decoy-key"`,
889
955
  `DECOY_TOKEN=${decoy} sleep 30 & echo "decoy-pid:$!"`,
890
956
  ].join('; '));
891
957
  const decoyPid = /decoy-pid:(\d+)/.exec(planted.stdout)?.[1];
958
+ let removal;
892
959
  try {
960
+ const row = await inside(['node', '--no-warnings', '-e', plantCredential(database)]);
961
+ expect(row.code, row.stderr).toBe(0);
962
+ // OpenCode reads the row as a login, so this is where OpenCode 2 keeps them.
963
+ expect(await connections()).toEqual([{ integration: 'openai', type: 'credential', id: DECOY_CREDENTIAL_ID, label: 'default', method: 'oauth' }]);
964
+ // The custom provider's key is invisible to that listing, and the table read sees it.
965
+ expect(await storedCredentials()).toEqual([{ integration: 'openai', type: 'oauth' }, { integration: 'acme-llm', type: 'key' }]);
966
+
893
967
  const control = (await search()).stdout;
894
968
  expect(control).toContain('auth-record: present');
895
- expect(control).toMatch(/"refresh"\s*:\s*"/);
969
+ expect(control).toMatch(/opencode\.db(-wal)?:"refresh"\s*:\s*"/);
896
970
  expect(control).toContain('BEGIN OPENSSH PRIVATE KEY');
897
971
  expect(control).toContain(decoy);
898
972
  } finally {
973
+ removal = await inside(['node', '--no-warnings', '-e', removeCredential(database)]);
899
974
  await shell(`rm -f ${decoyRecord} "$HOME/decoy-key"; ${decoyPid ? `kill ${decoyPid} 2>/dev/null` : 'true'}; true`);
900
975
  }
901
-
902
- const found = (await search()).stdout;
903
- // Positive control of its own: the search ran and looked in all three places.
904
- expect(found).toContain('--- files');
905
- expect(found).toContain('--- environments');
906
- expect(found).toContain('--- end');
907
- expect(found).toContain('auth-record: absent');
908
- expect(found.slice(found.indexOf('--- files'))).toBe('--- files\n--- environments\n--- end\n');
976
+ // Checked after the finally, so a failed control above is the error that gets reported.
977
+ expect(removal.code, removal.stderr).toBe(0);
978
+ expect(removal.stdout).toBe('removed:2\n');
979
+ expect(await connections()).toEqual([]);
980
+ expect(await storedCredentials()).toEqual([]);
909
981
  }, 180_000);
910
982
 
911
983
  // One space is not enough to say anything about two. This makes a second one and looks
@@ -5,6 +5,8 @@
5
5
  // one container would pass nothing here.
6
6
 
7
7
  import crypto from 'node:crypto';
8
+ import http from 'node:http';
9
+ import net from 'node:net';
8
10
 
9
11
  import { SpaceError } from '../errors.js';
10
12
  import { ROLE_GATEKEEPER, ROLE_SPACE, requireSpaceId } from '../labels.js';
@@ -57,6 +59,14 @@ export function createMemoryPlace({ id = 'memory' } = {}) {
57
59
  // A container has a hostname of its own, as a real one does, so a caller can tell them apart.
58
60
  containers.set(`${spaceId}:${target}`, { hostname: crypto.randomBytes(6).toString('hex') });
59
61
  }
62
+ // The server inside, for `connect`: a loopback listener of this space's own that answers
63
+ // `/health` the way the real one does, with the space id so a caller can tell spaces apart.
64
+ const server = http.createServer((request, response) => {
65
+ response.setHeader('content-type', 'application/json');
66
+ response.end(JSON.stringify({ status: 'ok', isOpenCodeReady: true, spaceId, path: request.url }));
67
+ });
68
+ await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve); });
69
+ containers.get(`${spaceId}:${ROLE_SPACE}`).server = server;
60
70
  },
61
71
  list: async () => Array.from(spaces.values(), (space) => ({ ...space })),
62
72
  exec: async (spaceId, argv, options = {}) => {
@@ -84,12 +94,25 @@ export function createMemoryPlace({ id = 'memory' } = {}) {
84
94
  }
85
95
  return [process.execPath, '-e', CONTAINER_PROGRAM, hostname];
86
96
  },
97
+ // Added in stage 4a. A channel to the server inside, refused like `execArgv` when the space
98
+ // is stopped or gone: a plain socket to this space's own listener.
99
+ connect: async (spaceId) => {
100
+ const { server } = requireContainer(spaceId);
101
+ if (requireSpace(spaceId).state !== 'running') {
102
+ throw new SpaceError('space_not_running', `Space ${spaceId} is stopped`);
103
+ }
104
+ return net.connect({ host: '127.0.0.1', port: server.address().port });
105
+ },
87
106
  stop: async (spaceId) => { requireSpace(spaceId).state = 'exited'; },
88
107
  start: async (spaceId) => { requireSpace(spaceId).state = 'running'; },
89
108
  remove: async (spaceId) => {
90
109
  const removed = [];
91
110
  for (const target of TARGETS) {
92
- if (containers.delete(`${requireSpaceId(spaceId)}:${target}`)) removed.push({ kind: 'container', name: `${spaceId}-${target}` });
111
+ const container = containers.get(`${requireSpaceId(spaceId)}:${target}`);
112
+ if (!container) continue;
113
+ container.server?.close();
114
+ containers.delete(`${spaceId}:${target}`);
115
+ removed.push({ kind: 'container', name: `${spaceId}-${target}` });
93
116
  }
94
117
  if (spaces.delete(spaceId)) removed.push({ kind: 'space', name: spaceId });
95
118
  return { removed, failed: [] };
@@ -1,4 +1,4 @@
1
- export const REQUIRED_PLACE_METHODS = ['check', 'create', 'list', 'exec', 'execArgv', 'stop', 'start', 'remove', 'verify'];
1
+ export const REQUIRED_PLACE_METHODS = ['check', 'create', 'list', 'exec', 'execArgv', 'connect', 'stop', 'start', 'remove', 'verify'];
2
2
 
3
3
  export function createPlaceRegistry(initialPlaces = []) {
4
4
  const places = new Map();