@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.
- package/bin/lib/DOCUMENTATION.md +1 -1
- package/bin/lib/commands-connect-url.js +6 -5
- package/bin/lib/commands-tunnel.js +24 -5
- package/dist/assets/{CodeMirrorCommentWidgets-CmKmyb9T.js → CodeMirrorCommentWidgets-C_zL-eri.js} +1 -1
- package/dist/assets/{DiffView-8-PFpZ2p.js → DiffView-BeN2_YYF.js} +3 -3
- package/dist/assets/FilesView-CN34wm_N.js +17 -0
- package/dist/assets/{GitView-DNUSu00w.js → GitView-DLDazOo1.js} +4 -4
- package/dist/assets/{GuestAttachDialog-Cv6QzjHC.js → GuestAttachDialog-C0xe_Lyy.js} +1 -1
- package/dist/assets/{GuestSurfacePane-Bt3jB_Ye.js → GuestSurfacePane-BdaurnDr.js} +1 -1
- package/dist/assets/{JsonTreeView-BlyHTRhM.js → JsonTreeView-B1Xq-k2t.js} +1 -1
- package/dist/assets/LinearIssuesView-BryoAHow.js +1 -0
- package/dist/assets/{MarkdownImageGallery-2UXJF-5B.js → MarkdownImageGallery-DfuEoaGq.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-B_ZcWOvX.js +12 -0
- package/dist/assets/OnboardingScreen-C22bGmnP.js +1 -0
- package/dist/assets/{PatchDiff-ByvnbG5T.js → PatchDiff-0xd6UeFB.js} +1 -1
- package/dist/assets/{PierreDiffViewer-BXieg0mH.js → PierreDiffViewer-BC950e3F.js} +3 -3
- package/dist/assets/PlanView-B7Xgihqk.js +5 -0
- package/dist/assets/PluginPane-2C71F8uF.js +3 -0
- package/dist/assets/SettingsView-m_zoFiaT.js +30 -0
- package/dist/assets/{SettingsWindow-BIz224xs.js → SettingsWindow-CofS020b.js} +1 -1
- package/dist/assets/{SubmoduleDiffSummary-CXKmlps9.js → SubmoduleDiffSummary-BSA9gnIO.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BsgAK8xu.js → ToolOutputDialog-DprkVKcj.js} +7 -7
- package/dist/assets/{ToolPartDiffPreview-vdPObXOf.js → ToolPartDiffPreview-Dq0go_fX.js} +2 -2
- package/dist/assets/{VirtualizedFileDiff-BkFNKWS5.js → VirtualizedFileDiff-Kp8hKJdT.js} +1 -1
- package/dist/assets/WalkthroughView-DGnTzqIU.js +4 -0
- package/dist/assets/{appThemeRegistry-aHUNHoqP.js → appThemeRegistry-BdEHBA4s.js} +1 -1
- package/dist/assets/{commitAndPush-Bon9r94r.js → commitAndPush-LwtVa2Oc.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DKqr_1AQ.js → computeVirtualFileMetrics-6V1xNpO9.js} +2 -2
- package/dist/assets/de-DlgBHUAI.js +10 -0
- package/dist/assets/es-BC8G41U8.js +16 -0
- package/dist/assets/fr-I0z3vVjy.js +14 -0
- package/dist/assets/index-CgR5rJq_.js +41 -0
- package/dist/assets/{index-DpFttslC.js → index-CmNPYddV.js} +1 -1
- package/dist/assets/index-adyy_sEk.css +1 -0
- package/dist/assets/{isDiffPlainText-kzAgpIgi.js → isDiffPlainText-1bXcWCrw.js} +1 -1
- package/dist/assets/{isFilePlainText-Uj6y-jzz.js → isFilePlainText-CBAppvy1.js} +1 -1
- package/dist/assets/ja-BIElEsY8.js +16 -0
- package/dist/assets/ko-DRnnHetA.js +16 -0
- package/dist/assets/{main-CbfMxn-I.js → main-CzjTMTfW.js} +2 -2
- package/dist/assets/main-DVX34beR.js +886 -0
- package/dist/assets/markdownCore-Cxbkn5NR.js +7 -0
- package/dist/assets/{miniChat-CiAKBC10.js → miniChat-CP68IL8Q.js} +2 -2
- package/dist/assets/{mobile-CsT4sJwC.js → mobile-BrlBrNfZ.js} +2 -2
- package/dist/assets/nl-DzUV-kwp.js +16 -0
- package/dist/assets/{patchFileDiff-DeaE08W0.js → patchFileDiff-pqRSHLHI.js} +2 -2
- package/dist/assets/pl-Bb-cb7k7.js +16 -0
- package/dist/assets/pt-BR-CyIWrTcE.js +16 -0
- package/dist/assets/renderElectronMiniChatApp-DKIilR7N.js +2 -0
- package/dist/assets/renderMobileApp-B0z6-x58.js +25 -0
- package/dist/assets/runtimeEndpointReset-uu1DBwLL.js +52 -0
- package/dist/assets/{scheduledTasksApi-BZCNJ588.js → scheduledTasksApi-BuzWT445.js} +1 -1
- package/dist/assets/{shikiHighlight-BSUEa3yF.js → shikiHighlight-BWGrY5YU.js} +1 -1
- package/dist/assets/{textMateThemeFromAppTheme-CsATFZIV.js → textMateThemeFromAppTheme-BSUFChBY.js} +1 -1
- package/dist/assets/tr-DXEDSoYO.js +7 -0
- package/dist/assets/uk-C8hN--q_.js +16 -0
- package/dist/assets/useAppFontEffects-Dsl_sLrj.js +7366 -0
- package/dist/assets/useInlineCommentController-d5vntsQ_.js +2 -0
- package/dist/assets/{useRootScrollLock-Cp1eFoM2.js → useRootScrollLock-2rd5Y6gR.js} +2 -2
- package/dist/assets/{vendor-base-ui-CsXYnR5c.js → vendor-base-ui-DnNniUWp.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-BwwommM0.js → vendor-codemirror-language-data-B1EetJur.js} +2 -2
- package/dist/assets/vendor-opencode-client-DSZl7jSi.js +12 -0
- package/dist/assets/{vendor-tanstack-react-virtual-ClYN8CzB.js → vendor-tanstack-react-virtual--0sBrLRh.js} +1 -1
- package/dist/assets/{vendor-tanstack-virtual-core-BewVQryB.js → vendor-tanstack-virtual-core-BoA4iGMw.js} +1 -1
- package/dist/assets/{vendor-zod-BSoePkpP.js → vendor-zod-CxRSdNoV.js} +4 -4
- package/dist/assets/{web-components-D3Yjr4Zx.js → web-components-ngpHPEDU.js} +1 -1
- package/dist/assets/zh-CN-CtzXdjMZ.js +16 -0
- package/dist/assets/zh-TW-Ds0CADSz.js +16 -0
- package/dist/index.html +5 -5
- package/dist/mini-chat.html +5 -5
- package/dist/mobile.html +5 -5
- package/package.json +5 -5
- package/server/index.js +82 -4
- package/server/lib/agent-tool/DOCUMENTATION.md +8 -1
- package/server/lib/agent-tool/runtime.js +13 -4
- package/server/lib/agent-tool/runtime.test.js +15 -0
- package/server/lib/context-obligatory/DOCUMENTATION.md +10 -7
- package/server/lib/context-obligatory/runtime.js +2 -1
- package/server/lib/context-obligatory/runtime.test.js +76 -30
- package/server/lib/dictation/DOCUMENTATION.md +4 -1
- package/server/lib/dictation/openai-compatible-session.js +7 -0
- package/server/lib/enterprise-mode.d.ts +30 -0
- package/server/lib/enterprise-mode.js +253 -0
- package/server/lib/enterprise-mode.test.js +247 -0
- package/server/lib/event-stream/translate-v2.js +6 -0
- package/server/lib/event-stream/translate-v2.test.js +6 -0
- package/server/lib/git/DOCUMENTATION.md +2 -1
- package/server/lib/git/routes.js +44 -1
- package/server/lib/git/routes.test.js +98 -1
- package/server/lib/git/service.js +146 -11
- package/server/lib/git/service.test.js +195 -0
- package/server/lib/github/routes.js +9 -19
- package/server/lib/github/routes.test.js +112 -0
- package/server/lib/guests/DOCUMENTATION.md +4 -2
- package/server/lib/guests/background.test.js +1 -1
- package/server/lib/guests/catalog.js +56 -2
- package/server/lib/guests/catalog.test.js +24 -1
- package/server/lib/guests/clone-network.test.js +52 -0
- package/server/lib/guests/clone.js +30 -4
- package/server/lib/guests/enterprise.js +68 -0
- package/server/lib/guests/enterprise.test.js +106 -0
- package/server/lib/guests/grant-scope.js +8 -2
- package/server/lib/guests/grant-scope.test.js +9 -0
- package/server/lib/guests/html-styles.js +16 -2
- package/server/lib/guests/html-styles.test.js +53 -4
- package/server/lib/guests/install.js +10 -0
- package/server/lib/guests/persist.js +1 -0
- package/server/lib/guests/routes.js +40 -5
- package/server/lib/guests/updates.js +9 -2
- package/server/lib/notifications/DOCUMENTATION.md +1 -1
- package/server/lib/notifications/runtime.js +22 -8
- package/server/lib/notifications/trigger-runtime.test.js +45 -0
- package/server/lib/openchamber-sessions/session-metadata-store.js +27 -0
- package/server/lib/openchamber-sessions/session-metadata-store.test.js +18 -0
- package/server/lib/opencode/DOCUMENTATION.md +13 -9
- package/server/lib/opencode/auth-state-runtime.js +2 -2
- package/server/lib/opencode/config-paths.test.js +1 -0
- package/server/lib/opencode/env-runtime.js +26 -3
- package/server/lib/opencode/env-runtime.test.js +57 -0
- package/server/lib/opencode/feature-routes-runtime.js +2 -0
- package/server/lib/opencode/hmr-state-runtime.js +4 -3
- package/server/lib/opencode/lifecycle.js +10 -5
- package/server/lib/opencode/lifecycle.test.js +6 -2
- package/server/lib/opencode/managed-config-file.js +2 -1
- package/server/lib/opencode/managed-config-file.test.js +18 -0
- package/server/lib/opencode/npm-registry-config.d.ts +1 -0
- package/server/lib/opencode/npm-registry-config.js +123 -0
- package/server/lib/opencode/npm-registry-config.test.js +167 -0
- package/server/lib/opencode/npm-registry.js +5 -6
- package/server/lib/opencode/npm-registry.test.js +30 -0
- package/server/lib/opencode/openchamber-routes.js +8 -0
- package/server/lib/opencode/project-icon-routes.js +2 -2
- package/server/lib/opencode/project-icon-routes.test.js +44 -0
- package/server/lib/opencode/provider-source-route.test.js +32 -0
- package/server/lib/opencode/routes.js +17 -2
- package/server/lib/opencode/settings-helpers.js +26 -3
- package/server/lib/opencode/settings-helpers.test.js +12 -5
- package/server/lib/opencode/settings-registry.json +35 -1
- package/server/lib/opencode/settings-runtime.js +1 -0
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/opencode/static-routes-runtime.js +9 -1
- package/server/lib/opencode/static-routes-runtime.test.js +58 -1
- package/server/lib/package-manager.js +4 -1
- package/server/lib/package-manager.test.js +24 -0
- package/server/lib/permission-auto-accept/DOCUMENTATION.md +23 -15
- package/server/lib/permission-auto-accept/modes.js +26 -0
- package/server/lib/permission-auto-accept/runtime.js +146 -40
- package/server/lib/permission-auto-accept/runtime.test.js +93 -9
- package/server/lib/quota/DOCUMENTATION.md +6 -0
- package/server/lib/quota/providers/zhipuai-coding-plan.js +74 -30
- package/server/lib/quota/providers/zhipuai-coding-plan.test.js +124 -0
- package/server/lib/relay/DOCUMENTATION.md +1 -1
- package/server/lib/relay/service.js +32 -12
- package/server/lib/relay/service.test.js +30 -0
- package/server/lib/routing/DOCUMENTATION.md +150 -41
- package/server/lib/routing/classifier.js +156 -0
- package/server/lib/routing/defaults.js +27 -0
- package/server/lib/routing/jev.js +5 -17
- package/server/lib/routing/routes.http.test.js +9 -0
- package/server/lib/routing/routes.js +27 -1
- package/server/lib/routing/runtime.js +199 -33
- package/server/lib/routing/runtime.test.js +299 -15
- package/server/lib/routing/store.js +57 -0
- package/server/lib/routing/store.test.js +37 -0
- package/server/lib/session-assist/DOCUMENTATION.md +17 -7
- package/server/lib/session-assist/context.js +42 -2
- package/server/lib/session-assist/context.test.js +38 -1
- package/server/lib/session-assist/runtime.js +57 -13
- package/server/lib/session-assist/runtime.test.js +45 -0
- package/server/lib/session-goal/DOCUMENTATION.md +47 -22
- package/server/lib/session-goal/audit.js +112 -0
- package/server/lib/session-goal/audit.test.js +58 -0
- package/server/lib/session-goal/runtime.js +113 -134
- package/server/lib/session-goal/runtime.test.js +146 -13
- package/server/lib/session-lineage.js +52 -0
- package/server/lib/session-lineage.test.js +45 -0
- package/server/lib/session-work/DOCUMENTATION.md +108 -0
- package/server/lib/session-work/questions.js +126 -0
- package/server/lib/session-work/runtime.js +278 -0
- package/server/lib/session-work/runtime.test.js +255 -0
- package/server/lib/session-work/state.js +48 -0
- package/server/lib/session-work/state.test.js +34 -0
- package/server/lib/small-model/DOCUMENTATION.md +14 -7
- package/server/lib/small-model/client.js +7 -4
- package/server/lib/small-model/index.js +11 -21
- package/server/lib/small-model/index.test.js +13 -26
- package/server/lib/spaces/DOCUMENTATION.md +79 -25
- package/server/lib/spaces/gatekeeper-channel.js +63 -11
- package/server/lib/spaces/gatekeeper-channel.test.js +34 -4
- package/server/lib/spaces/gatekeeper-program.cjs +64 -13
- package/server/lib/spaces/gatekeeper-program.test.js +115 -3
- package/server/lib/spaces/host.js +58 -13
- package/server/lib/spaces/host.test.js +34 -1
- package/server/lib/spaces/idle-stop.js +98 -0
- package/server/lib/spaces/idle-stop.test.js +130 -0
- package/server/lib/spaces/journey.js +427 -17
- package/server/lib/spaces/journey.test.js +592 -5
- package/server/lib/spaces/layout.js +27 -6
- package/server/lib/spaces/manager.test.js +1 -1
- package/server/lib/spaces/places/contract-suite.js +4 -2
- package/server/lib/spaces/places/docker-live-support.js +27 -4
- package/server/lib/spaces/places/docker.js +32 -5
- package/server/lib/spaces/places/docker.test.js +38 -8
- package/server/lib/spaces/places/escape-suite.js +32 -0
- package/server/lib/spaces/places/fake-docker.js +3 -1
- package/server/lib/spaces/places/grants.docker.live.test.js +197 -0
- package/server/lib/spaces/places/memory-place.js +3 -3
- package/server/lib/spaces/places/sessions.docker.live.test.js +4 -2
- package/server/lib/spaces/routes.js +49 -1
- package/server/lib/spaces/routes.test.js +31 -3
- package/server/lib/spaces/space-opencode.js +52 -0
- package/server/lib/spaces/space-opencode.test.js +41 -0
- package/server/lib/spaces/space-records.js +90 -2
- package/server/lib/spaces/space-records.test.js +58 -1
- package/server/lib/spaces/space-server.js +13 -1
- package/server/lib/spaces/space-server.test.js +13 -0
- package/server/lib/spaces/space-setup.js +173 -0
- package/server/lib/spaces/space-setup.test.js +174 -0
- package/server/lib/tts/DOCUMENTATION.md +3 -0
- package/server/lib/tts/base-url.js +8 -0
- package/server/lib/tts/routes.js +13 -1
- package/server/lib/tts/routes.test.js +26 -0
- package/server/lib/tunnels/DOCUMENTATION.md +2 -0
- package/server/lib/tunnels/routes.js +14 -0
- package/server/lib/tunnels/routes.test.js +26 -0
- package/server/lib/walkthrough/index.js +11 -7
- package/server/lib/walkthrough/jobs.test.js +8 -0
- package/server/lib/walkthrough/languages.js +1 -0
- package/server/lib/walkthrough/routes.js +7 -1
- package/dist/assets/FilesView-0Ie20mEk.js +0 -17
- package/dist/assets/LinearIssuesView-CSl2MUfA.js +0 -1
- package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +0 -12
- package/dist/assets/OnboardingScreen-CIdXJpfc.js +0 -1
- package/dist/assets/PlanView-DEIi3Q7M.js +0 -5
- package/dist/assets/PluginPane-BEPUWVho.js +0 -3
- package/dist/assets/SettingsView-CiNh-RbW.js +0 -30
- package/dist/assets/WalkthroughView-6oE-MuDL.js +0 -4
- package/dist/assets/de-CgAJ51z7.js +0 -10
- package/dist/assets/es-zGi_ravM.js +0 -16
- package/dist/assets/fr-CPfogrWx.js +0 -14
- package/dist/assets/index-CHfphYL3.js +0 -41
- package/dist/assets/index-DvMJ3w6V.css +0 -1
- package/dist/assets/ja-DMk6wd-U.js +0 -16
- package/dist/assets/ko-BFpzJ8jc.js +0 -16
- package/dist/assets/main-anyZFMIs.js +0 -896
- package/dist/assets/markdownCore-CmM47cAE.js +0 -7
- package/dist/assets/pl-VdRPcZrB.js +0 -16
- package/dist/assets/pt-BR-BRys_lOW.js +0 -16
- package/dist/assets/renderElectronMiniChatApp-C5677jy0.js +0 -2
- package/dist/assets/renderMobileApp-D4dBBAqQ.js +0 -25
- package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +0 -27
- package/dist/assets/tr-CA9ckNnm.js +0 -7
- package/dist/assets/uk-byjR-y8D.js +0 -16
- package/dist/assets/useAppFontEffects-BWQZ5DeI.js +0 -7341
- package/dist/assets/useInlineCommentController-DlFyVfBu.js +0 -2
- package/dist/assets/vendor-opencode-client-DYdsLbCM.js +0 -12
- package/dist/assets/zh-CN-DRabgxdG.js +0 -16
- package/dist/assets/zh-TW-rbY5c9UK.js +0 -16
|
@@ -14,18 +14,22 @@
|
|
|
14
14
|
// Arguments: <space-facing bind host> <corridor port> <window port> <control port>
|
|
15
15
|
// [<window deadline in ms>]. They are arguments so that the container command and the tests run
|
|
16
16
|
// the very same program; the last one lets a test watch a deadline pass without waiting five
|
|
17
|
-
// minutes for it. None of them changes a decision this program makes.
|
|
17
|
+
// minutes for it. None of them changes a decision this program makes. The bind host is an
|
|
18
|
+
// address, or the path of a file that holds one: the container command names the file, and the
|
|
19
|
+
// host writes the gatekeeper's own address on the space's network into it before the program,
|
|
20
|
+
// because the host knows that address and this program has no say in where it listens.
|
|
18
21
|
//
|
|
19
22
|
// Everything the space sends is hostile input. Nothing it can send may end the process:
|
|
20
23
|
// a crash of the gatekeeper is a denial of service the agent could trigger at will.
|
|
21
24
|
|
|
22
25
|
const dns = require('node:dns');
|
|
26
|
+
const fs = require('node:fs');
|
|
23
27
|
const http = require('node:http');
|
|
24
28
|
const https = require('node:https');
|
|
25
29
|
const net = require('node:net');
|
|
26
30
|
const os = require('node:os');
|
|
27
31
|
|
|
28
|
-
const [
|
|
32
|
+
const [bindArgument, corridorPort, windowPort, controlPort, windowDeadline, corridorCap, windowCap, controlCap] = process.argv.slice(2);
|
|
29
33
|
|
|
30
34
|
/**
|
|
31
35
|
* A cap given on the command line, or the production number when there is none.
|
|
@@ -105,6 +109,34 @@ const GRANT_ID_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
|
|
|
105
109
|
const HEADER_NAME_PATTERN = /^[A-Za-z0-9-]{1,64}$/;
|
|
106
110
|
const MAX_SECRET_LENGTH = 8192;
|
|
107
111
|
|
|
112
|
+
/**
|
|
113
|
+
* The address the corridor and the window listen on. An argument that starts with `/` is the
|
|
114
|
+
* file the host wrote beside this program, holding the gatekeeper's own address on the space's
|
|
115
|
+
* network; anything else is the address itself, which is what the tests pass. Whichever it is,
|
|
116
|
+
* it must be the address of one interface: a file that is missing or empty, or anything that is
|
|
117
|
+
* not an address or names every interface, ends the program. On a Linux Docker host every local
|
|
118
|
+
* process can reach the bridge, and a window that listens there spends the user's key for anyone
|
|
119
|
+
* on the machine. That includes a gatekeeper made before stage 5b, whose command still says
|
|
120
|
+
* `0.0.0.0` and whose checker never compared the command: it no longer starts, and such a
|
|
121
|
+
* space has to be made again. Failing to start is the safe answer.
|
|
122
|
+
*/
|
|
123
|
+
function readBindHost(argument) {
|
|
124
|
+
const given = String(argument ?? '');
|
|
125
|
+
let text = given;
|
|
126
|
+
if (given.startsWith('/')) {
|
|
127
|
+
try {
|
|
128
|
+
text = fs.readFileSync(given, 'utf8').trim();
|
|
129
|
+
} catch (error) {
|
|
130
|
+
console.error(`gatekeeper: cannot read the bind address from ${given} (${error.code || error.message})`);
|
|
131
|
+
process.exit(2);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (net.isIP(text) === 0 || text === '0.0.0.0' || text === '::') {
|
|
135
|
+
console.error(`gatekeeper: ${given} is not the address of one interface`);
|
|
136
|
+
process.exit(2);
|
|
137
|
+
}
|
|
138
|
+
return text;
|
|
139
|
+
}
|
|
108
140
|
// Everything the host sets, in memory only. Never a file, never an environment variable,
|
|
109
141
|
// never an argument, never a label. A restart starts from "nothing is allowed".
|
|
110
142
|
let networkMode = 'allowlist';
|
|
@@ -606,9 +638,9 @@ const answerJson = (response, status, body) => {
|
|
|
606
638
|
* The gatekeeper's own listeners are not an upstream. A grant is the host's decision, and the
|
|
607
639
|
* user's private network is a legitimate place for one, so only this refusal stands in the way.
|
|
608
640
|
*
|
|
609
|
-
* Every address this container has, not only loopback: the corridor and the window
|
|
610
|
-
*
|
|
611
|
-
*
|
|
641
|
+
* Every address this container has, not only loopback: the corridor and the window listen on
|
|
642
|
+
* the gatekeeper's address on the inner network, and a grant pointing there, or at any other
|
|
643
|
+
* address of its own, would feed the window into itself until its 64 sockets out were gone.
|
|
612
644
|
*/
|
|
613
645
|
const ownListenerPorts = new Set([Number(corridorPort), Number(windowPort), Number(controlPort)]);
|
|
614
646
|
const ownAddresses = new Set(Object.values(os.networkInterfaces())
|
|
@@ -667,13 +699,18 @@ async function serveWindow(request, response) {
|
|
|
667
699
|
return;
|
|
668
700
|
}
|
|
669
701
|
|
|
670
|
-
// Whatever the space sent as credentials goes, and the grant's own header takes its place.
|
|
702
|
+
// Whatever the space sent as credentials goes, and the grant's own header takes its place. A
|
|
703
|
+
// grant without a secret, an opened domain, adds nothing: the upstream sees the request as the
|
|
704
|
+
// space made it, less the credential headers.
|
|
671
705
|
const headers = { ...request.headers };
|
|
672
706
|
for (const name of Object.keys(headers)) {
|
|
673
|
-
|
|
707
|
+
const lower = name.toLowerCase();
|
|
708
|
+
if (['authorization', 'x-api-key', 'proxy-authorization'].includes(lower) || lower === grant.header) delete headers[name];
|
|
674
709
|
}
|
|
675
710
|
headers.host = upstream.host;
|
|
676
|
-
|
|
711
|
+
if (grant.secret !== null) {
|
|
712
|
+
headers[grant.header] = grant.header === 'authorization' ? `Bearer ${grant.secret}` : grant.secret;
|
|
713
|
+
}
|
|
677
714
|
|
|
678
715
|
record('window', normalizeName(upstream.hostname), port, 'allow');
|
|
679
716
|
const transport = upstream.protocol === 'https:' ? https : http;
|
|
@@ -759,13 +796,19 @@ function setNetwork(body) {
|
|
|
759
796
|
return null;
|
|
760
797
|
}
|
|
761
798
|
|
|
799
|
+
/**
|
|
800
|
+
* A grant with a secret names the header that carries it; a grant without one, an opened domain,
|
|
801
|
+
* names no header and the window adds nothing. A body with a header and no secret, or a secret
|
|
802
|
+
* and no header, is refused: either the grant hides a credential or it does not.
|
|
803
|
+
*/
|
|
762
804
|
function addGrant(body) {
|
|
763
805
|
const id = asText(body.id);
|
|
764
|
-
const header = asText(body.header);
|
|
765
|
-
const secret = asText(body.secret);
|
|
766
806
|
if (!GRANT_ID_PATTERN.test(id)) return 'a grant id is 1 to 64 letters, digits, dots, dashes or underscores';
|
|
767
|
-
|
|
768
|
-
|
|
807
|
+
const withSecret = body.secret !== undefined || body.header !== undefined;
|
|
808
|
+
const header = withSecret ? asText(body.header).toLowerCase() : null;
|
|
809
|
+
const secret = withSecret ? asText(body.secret) : null;
|
|
810
|
+
if (withSecret && !HEADER_NAME_PATTERN.test(header)) return 'a header name is 1 to 64 letters, digits or dashes';
|
|
811
|
+
if (withSecret && (secret.length === 0 || secret.length > MAX_SECRET_LENGTH)) return 'a grant with a header needs a secret';
|
|
769
812
|
let upstream;
|
|
770
813
|
try {
|
|
771
814
|
upstream = new URL(asText(body.upstream));
|
|
@@ -784,6 +827,12 @@ async function serveControl(request, response) {
|
|
|
784
827
|
answerJson(response, 200, { ready: true, mode: networkMode, domains: allowedDomains.size, grants: grants.size });
|
|
785
828
|
return;
|
|
786
829
|
}
|
|
830
|
+
if (request.method === 'GET' && path === '/policy') {
|
|
831
|
+
// What the host last said, so it can tell a gatekeeper that forgot from one that remembers.
|
|
832
|
+
// Ids and names only: a secret is never read back, not even by the host.
|
|
833
|
+
answerJson(response, 200, { mode: networkMode, domains: Array.from(allowedDomains), grants: Array.from(grants.keys()) });
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
787
836
|
if (request.method === 'GET' && path === '/journal') {
|
|
788
837
|
// Since when: the journal is memory only, so the host says that nothing older exists.
|
|
789
838
|
answerJson(response, 200, { records: journal.slice(), dropped: journalDropped, since: STARTED_AT });
|
|
@@ -877,6 +926,8 @@ const control = makeServer('control', MAX_CONTROL_CONNECTIONS, (request, respons
|
|
|
877
926
|
const listen = (server, port, host) => new Promise((resolve) => { server.listen(Number(port), host, resolve); });
|
|
878
927
|
|
|
879
928
|
async function main() {
|
|
929
|
+
// Here and not at the top: requiring this file from a test must not read the runner's argv.
|
|
930
|
+
const bindHost = readBindHost(bindArgument);
|
|
880
931
|
if (!bindHost || !corridorPort || !windowPort || !controlPort) {
|
|
881
932
|
console.error('gatekeeper: arguments are <bind host> <corridor port> <window port> <control port>');
|
|
882
933
|
process.exit(2);
|
|
@@ -913,5 +964,5 @@ function describeFailure(error) {
|
|
|
913
964
|
if (require.main === module) {
|
|
914
965
|
main();
|
|
915
966
|
} else {
|
|
916
|
-
module.exports = { chooseAddress, isBlockedAddress, isDomainName, joinSockets, parseIPv4, parseIPv6, refuseTarget, setNetwork, splitTarget, walksOutOfGrant };
|
|
967
|
+
module.exports = { addGrant, chooseAddress, isBlockedAddress, isDomainName, joinSockets, parseIPv4, parseIPv6, refuseTarget, setNetwork, splitTarget, walksOutOfGrant };
|
|
917
968
|
}
|
|
@@ -4,13 +4,14 @@
|
|
|
4
4
|
// The corridor refuses every address that leads back to a machine, so a tunnel that really
|
|
5
5
|
// carries bytes cannot be tested from here. The escape suite does that inside real containers.
|
|
6
6
|
|
|
7
|
-
import { spawn } from 'node:child_process';
|
|
7
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
8
8
|
import crypto from 'node:crypto';
|
|
9
9
|
import http from 'node:http';
|
|
10
10
|
import net from 'node:net';
|
|
11
11
|
import os from 'node:os';
|
|
12
|
-
import { readFileSync } from 'node:fs';
|
|
12
|
+
import fs, { readFileSync } from 'node:fs';
|
|
13
13
|
import { createRequire } from 'node:module';
|
|
14
|
+
import path from 'node:path';
|
|
14
15
|
import { fileURLToPath } from 'node:url';
|
|
15
16
|
|
|
16
17
|
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
|
|
@@ -748,6 +749,28 @@ describe('gatekeeper program', () => {
|
|
|
748
749
|
expect(answer.body).not.toContain(SECRET);
|
|
749
750
|
});
|
|
750
751
|
|
|
752
|
+
it('adds no header for a grant without a secret, and still takes away what the space sent', async () => {
|
|
753
|
+
expect((await control('POST', '/grants', { id: 'open-registry', upstream: `http://127.0.0.1:${upstreamPort}/npm` })).status).toBe(200);
|
|
754
|
+
const answer = await throughWindow('/model/open-registry/-/package/left-pad', {
|
|
755
|
+
authorization: 'Bearer sk-fake-inside',
|
|
756
|
+
'x-api-key': 'sk-fake-inside',
|
|
757
|
+
'x-keep-me': 'yes',
|
|
758
|
+
});
|
|
759
|
+
expect(answer.status).toBe(200);
|
|
760
|
+
const request = seen.at(-1);
|
|
761
|
+
expect(request.url).toBe('/npm/-/package/left-pad');
|
|
762
|
+
expect(request.headers.authorization).toBeUndefined();
|
|
763
|
+
expect(request.headers['x-api-key']).toBeUndefined();
|
|
764
|
+
expect(request.headers['x-keep-me']).toBe('yes');
|
|
765
|
+
expect(Object.keys(request.headers).some((name) => /key|auth|token/i.test(name))).toBe(false);
|
|
766
|
+
});
|
|
767
|
+
|
|
768
|
+
it('takes the grant\'s own header name away too, so a placeholder the space sends never reaches the upstream', async () => {
|
|
769
|
+
expect((await control('POST', '/grants', { id: 'google', upstream: `http://127.0.0.1:${upstreamPort}/v1`, header: 'X-Goog-Api-Key', secret: SECRET })).status).toBe(200);
|
|
770
|
+
await throughWindow('/model/google/models', { 'X-Goog-Api-Key': 'space-window' });
|
|
771
|
+
expect(seen.at(-1).headers['x-goog-api-key']).toBe(SECRET);
|
|
772
|
+
});
|
|
773
|
+
|
|
751
774
|
it('sends a bearer token for an OpenAI-style grant', async () => {
|
|
752
775
|
await throughWindow('/model/openai/responses');
|
|
753
776
|
expect(seen.at(-1).headers.authorization).toBe(`Bearer ${SECRET}`);
|
|
@@ -873,7 +896,9 @@ describe('gatekeeper program', () => {
|
|
|
873
896
|
['a numeric last label on the allowlist', '/network', { mode: 'allowlist', domains: ['1.1.1'] }],
|
|
874
897
|
['a hex last label on the allowlist', '/network', { mode: 'allowlist', domains: ['a.com.0x2'] }],
|
|
875
898
|
['a single-label name on the allowlist', '/network', { mode: 'allowlist', domains: ['localhost'] }],
|
|
876
|
-
['a grant
|
|
899
|
+
['a grant with a header and no secret', '/grants', { id: 'x', upstream: 'https://api.example.com', header: 'authorization' }],
|
|
900
|
+
['a grant with a secret and no header', '/grants', { id: 'x', upstream: 'https://api.example.com', secret: SECRET }],
|
|
901
|
+
['a grant with an empty secret', '/grants', { id: 'x', upstream: 'https://api.example.com', header: 'authorization', secret: '' }],
|
|
877
902
|
['a grant with an id that is not one', '/grants', { id: '../../etc', upstream: 'https://api.example.com', header: 'authorization', secret: SECRET }],
|
|
878
903
|
['a grant with a header name that is not one', '/grants', { id: 'x', upstream: 'https://api.example.com', header: 'a: b', secret: SECRET }],
|
|
879
904
|
['a grant whose upstream is not a URL', '/grants', { id: 'x', upstream: 'not a url', header: 'authorization', secret: SECRET }],
|
|
@@ -883,6 +908,14 @@ describe('gatekeeper program', () => {
|
|
|
883
908
|
expect(answer.status).toBe(400);
|
|
884
909
|
});
|
|
885
910
|
|
|
911
|
+
it('says what it holds: the mode, the names and the grant ids, and never a secret', async () => {
|
|
912
|
+
expect((await control('POST', '/network', { mode: 'allowlist', domains: ['Example.com.', 'example.org'] })).status).toBe(200);
|
|
913
|
+
const policy = JSON.parse((await control('GET', '/policy')).body);
|
|
914
|
+
expect(policy).toMatchObject({ mode: 'allowlist', domains: ['example.com', 'example.org'] });
|
|
915
|
+
expect(policy.grants).toEqual(expect.arrayContaining(['anthropic', 'openai']));
|
|
916
|
+
expect(JSON.stringify(policy)).not.toContain(SECRET);
|
|
917
|
+
});
|
|
918
|
+
|
|
886
919
|
it('answers 404 for anything else and 400 for a body that is not JSON', async () => {
|
|
887
920
|
expect((await control('GET', '/grants')).status).toBe(404);
|
|
888
921
|
expect((await control('POST', '/anything')).status).toBe(404);
|
|
@@ -1343,6 +1376,85 @@ describe('the rules of the gatekeeper program', () => {
|
|
|
1343
1376
|
});
|
|
1344
1377
|
});
|
|
1345
1378
|
|
|
1379
|
+
describe('the gatekeeper program and its bind address', () => {
|
|
1380
|
+
const folders = [];
|
|
1381
|
+
afterAll(() => { for (const folder of folders) fs.rmSync(folder, { recursive: true, force: true }); });
|
|
1382
|
+
|
|
1383
|
+
/** Starts the program with `bind` as its first argument and waits for it to listen or to leave. */
|
|
1384
|
+
const startWith = (bind, ports = ['0', '0', '0']) => new Promise((resolve) => {
|
|
1385
|
+
const child = spawn(process.execPath, [PROGRAM, bind, ...ports.map(String)], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
1386
|
+
let output = '';
|
|
1387
|
+
const finish = (outcome) => { resolve({ ...outcome, output, stop: () => child.kill() }); };
|
|
1388
|
+
child.stdout.on('data', (chunk) => { output += chunk; if (output.includes('gatekeeper: corridor')) finish({ exited: null }); });
|
|
1389
|
+
child.stderr.on('data', (chunk) => { output += chunk; });
|
|
1390
|
+
child.on('exit', (code) => finish({ exited: code }));
|
|
1391
|
+
});
|
|
1392
|
+
|
|
1393
|
+
/** One TCP connect: `connected` or the error code. */
|
|
1394
|
+
const tryConnect = (host, port) => new Promise((resolve) => {
|
|
1395
|
+
const socket = net.connect({ host, port });
|
|
1396
|
+
socket.setTimeout(3000, () => { socket.destroy(); resolve('timeout'); });
|
|
1397
|
+
socket.on('connect', () => { socket.destroy(); resolve('connected'); });
|
|
1398
|
+
socket.on('error', (error) => resolve(error.code));
|
|
1399
|
+
});
|
|
1400
|
+
|
|
1401
|
+
it('listens on the address the file beside it holds, and on nothing else', async () => {
|
|
1402
|
+
const other = ownAddress();
|
|
1403
|
+
// Without a second address of this machine there is nothing to be refused on.
|
|
1404
|
+
expect(other, 'this machine has no address but loopback').not.toBe('127.0.0.1');
|
|
1405
|
+
const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-gatekeeper-bind-'));
|
|
1406
|
+
folders.push(folder);
|
|
1407
|
+
const file = path.join(folder, 'bind');
|
|
1408
|
+
fs.writeFileSync(file, '127.0.0.1\n');
|
|
1409
|
+
const ports = [await freePort(), await freePort(), await freePort()];
|
|
1410
|
+
const started = await startWith(file, ports);
|
|
1411
|
+
try {
|
|
1412
|
+
expect(started.exited).toBeNull();
|
|
1413
|
+
// Positive control: the address in the file answers on both listeners the space uses.
|
|
1414
|
+
expect(await tryConnect('127.0.0.1', ports[0])).toBe('connected');
|
|
1415
|
+
expect(await tryConnect('127.0.0.1', ports[1])).toBe('connected');
|
|
1416
|
+
// Another address of the same machine does not: the program did not listen everywhere.
|
|
1417
|
+
expect(await tryConnect(other, ports[0])).toBe('ECONNREFUSED');
|
|
1418
|
+
expect(await tryConnect(other, ports[1])).toBe('ECONNREFUSED');
|
|
1419
|
+
} finally {
|
|
1420
|
+
started.stop();
|
|
1421
|
+
}
|
|
1422
|
+
});
|
|
1423
|
+
|
|
1424
|
+
it('reads no bind file when it is required rather than run, whatever the runner\'s arguments are', () => {
|
|
1425
|
+
// `node -e` puts its own arguments from argv[1], so the path lands where the program reads its bind argument.
|
|
1426
|
+
// A runner whose first argument is a path would otherwise have its file read, and a
|
|
1427
|
+
// missing one would end the test process.
|
|
1428
|
+
const required = spawnSync(process.execPath, ['-e', `require(${JSON.stringify(PROGRAM)}); console.log('still here')`, 'runner', '/no/such/bind/file'], { encoding: 'utf8' });
|
|
1429
|
+
expect(required.status).toBe(0);
|
|
1430
|
+
expect(required.stdout).toContain('still here');
|
|
1431
|
+
});
|
|
1432
|
+
|
|
1433
|
+
// A gatekeeper made before stage 5b has `0.0.0.0` in its command rather than the file.
|
|
1434
|
+
it.each(['0.0.0.0', '::', 'gatekeeper'])('does not start when it is told to listen on %j directly', async (bind) => {
|
|
1435
|
+
const started = await startWith(bind);
|
|
1436
|
+
expect(started.exited).toBe(2);
|
|
1437
|
+
expect(started.output).not.toContain('gatekeeper: corridor');
|
|
1438
|
+
});
|
|
1439
|
+
|
|
1440
|
+
it.each([
|
|
1441
|
+
['is missing', null],
|
|
1442
|
+
['is empty', ''],
|
|
1443
|
+
['names every interface', '0.0.0.0'],
|
|
1444
|
+
['names every IPv6 interface', '::'],
|
|
1445
|
+
['is not an address', 'gatekeeper'],
|
|
1446
|
+
])('does not start when the bind file %s', async (title, content) => {
|
|
1447
|
+
const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-gatekeeper-bind-'));
|
|
1448
|
+
folders.push(folder);
|
|
1449
|
+
const file = path.join(folder, 'bind');
|
|
1450
|
+
if (content !== null) fs.writeFileSync(file, content);
|
|
1451
|
+
const started = await startWith(file);
|
|
1452
|
+
expect(started.exited).toBe(2);
|
|
1453
|
+
expect(started.output).toContain('gatekeeper:');
|
|
1454
|
+
expect(started.output).not.toContain('gatekeeper: corridor');
|
|
1455
|
+
});
|
|
1456
|
+
});
|
|
1457
|
+
|
|
1346
1458
|
describe('the gatekeeper program as a file', () => {
|
|
1347
1459
|
const source = readFileSync(PROGRAM, 'utf8');
|
|
1348
1460
|
|
|
@@ -15,6 +15,7 @@ import { z } from 'zod';
|
|
|
15
15
|
import { createCodeIn } from './code-in.js';
|
|
16
16
|
import { createCodeOut } from './code-out.js';
|
|
17
17
|
import { createSpaceDispatcher } from './dispatcher.js';
|
|
18
|
+
import { SpaceError } from './errors.js';
|
|
18
19
|
import { createGatekeeperChannel } from './gatekeeper-channel.js';
|
|
19
20
|
import { createHostGit } from './host-git.js';
|
|
20
21
|
import { createSpaceJourney } from './journey.js';
|
|
@@ -23,6 +24,7 @@ import { spaceProjectPath } from './layout.js';
|
|
|
23
24
|
import { createSpaceManager } from './manager.js';
|
|
24
25
|
import { createSpaceRecords } from './space-records.js';
|
|
25
26
|
import { createSpaceEventSources } from './space-events.js';
|
|
27
|
+
import { createSpaceOpenCode } from './space-opencode.js';
|
|
26
28
|
import { createSpaceSessionIndex, mergeSessionLists } from './space-sessions.js';
|
|
27
29
|
import { createSpaceWebSocketForwarder } from './websocket.js';
|
|
28
30
|
import { createDockerPlace } from './places/docker.js';
|
|
@@ -42,9 +44,52 @@ const SESSION_PAGE_LIMIT = 100;
|
|
|
42
44
|
const SESSION_MAX_PAGES = 10;
|
|
43
45
|
const SESSION_LIST_TIMEOUT_MS = 10_000;
|
|
44
46
|
const MAX_SESSION_LIST_BYTES = 8 * 1024 * 1024;
|
|
47
|
+
// The server inside restarts its OpenCode and answers once it is ready again, which on a slow
|
|
48
|
+
// machine takes a while; past this the restart is reported as not answered.
|
|
49
|
+
const RESTART_OPENCODE_TIMEOUT_MS = 180_000;
|
|
50
|
+
const MAX_RESTART_ANSWER_BYTES = 64 * 1024;
|
|
51
|
+
// A managed OpenCode that restarted; an external one answers `success` with no restart at all.
|
|
52
|
+
const restartedSchema = z.object({ success: z.literal(true), requiresReload: z.literal(true) });
|
|
45
53
|
// The cursor of a next page, as the server inside names it; anything else ends the read.
|
|
46
54
|
const nextCursorSchema = z.string().min(1);
|
|
47
55
|
|
|
56
|
+
// A body from inside, read up to a cap and never past it.
|
|
57
|
+
const readBody = (response, cap) => new Promise((resolve, reject) => {
|
|
58
|
+
const chunks = [];
|
|
59
|
+
let size = 0;
|
|
60
|
+
response.on('data', (chunk) => {
|
|
61
|
+
size += chunk.length;
|
|
62
|
+
if (size > cap) { response.destroy(); reject(new Error(`the answer exceeds ${cap} bytes`)); return; }
|
|
63
|
+
chunks.push(chunk);
|
|
64
|
+
});
|
|
65
|
+
response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
66
|
+
response.on('error', reject);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Asks the server inside a space to restart the OpenCode it manages, the route its own settings
|
|
71
|
+
* use for that, over the dispatcher's `requestInside`. The answer comes from inside and is
|
|
72
|
+
* data: anything but a 200 that says OpenCode was restarted is a failure, and its text never
|
|
73
|
+
* travels further than a code.
|
|
74
|
+
*/
|
|
75
|
+
export const restartOpenCodeInside = async (requestInside, spaceId) => {
|
|
76
|
+
const response = await requestInside(spaceId, {
|
|
77
|
+
method: 'POST',
|
|
78
|
+
path: '/api/config/reload',
|
|
79
|
+
headers: { accept: 'application/json', 'content-length': '0' },
|
|
80
|
+
timeoutMs: RESTART_OPENCODE_TIMEOUT_MS,
|
|
81
|
+
});
|
|
82
|
+
let succeeded = false;
|
|
83
|
+
try {
|
|
84
|
+
succeeded = response.statusCode === 200 && restartedSchema.safeParse(JSON.parse(await readBody(response, MAX_RESTART_ANSWER_BYTES))).success;
|
|
85
|
+
} catch {
|
|
86
|
+
succeeded = false;
|
|
87
|
+
} finally {
|
|
88
|
+
response.destroy();
|
|
89
|
+
}
|
|
90
|
+
if (!succeeded) throw new SpaceError('opencode_restart_failed', `OpenCode inside the space did not restart (status ${response.statusCode}).`);
|
|
91
|
+
};
|
|
92
|
+
|
|
48
93
|
/**
|
|
49
94
|
* The installation id that labels this host's spaces, so two installations that share a Docker
|
|
50
95
|
* daemon never see each other's. Made once, at the first start with the switch on, and kept in
|
|
@@ -71,7 +116,8 @@ export function readOrCreateOwner(dataDir) {
|
|
|
71
116
|
* for the tests; `runCommand` and `openCommandStream` are the two ways this module starts a
|
|
72
117
|
* process, injectable for the same reason. `listProjectDirectories` answers the host's registered
|
|
73
118
|
* project paths, so a space's project label can be resolved to the project it was made for;
|
|
74
|
-
* without it every space is marked as of an unknown project.
|
|
119
|
+
* without it every space is marked as of an unknown project. `readIdleStop` and `saveIdleStop`
|
|
120
|
+
* read and keep the user's idle stop setting in the host's settings.
|
|
75
121
|
*/
|
|
76
122
|
export function createSpacesHost({
|
|
77
123
|
dataDir,
|
|
@@ -79,6 +125,8 @@ export function createSpacesHost({
|
|
|
79
125
|
gitPath = 'git',
|
|
80
126
|
hostEnvironment = process.env,
|
|
81
127
|
listProjectDirectories = async () => [],
|
|
128
|
+
readIdleStop,
|
|
129
|
+
saveIdleStop,
|
|
82
130
|
runCommand = runCommandProcess,
|
|
83
131
|
openCommandStream = openCommandStreamProcess,
|
|
84
132
|
place = null,
|
|
@@ -103,6 +151,7 @@ export function createSpacesHost({
|
|
|
103
151
|
const codeIn = createCodeIn({ git, place: dockerPlace });
|
|
104
152
|
const codeOut = createCodeOut({ git, place: dockerPlace });
|
|
105
153
|
const records = createSpaceRecords({ dataDir, logger });
|
|
154
|
+
const spaceOpenCode = createSpaceOpenCode({ exec: dockerPlace.exec });
|
|
106
155
|
|
|
107
156
|
const listSpaces = () => manager.listSpaces({ placeId: dockerPlace.id });
|
|
108
157
|
const dispatcher = createSpaceDispatcher({
|
|
@@ -188,24 +237,20 @@ export function createSpacesHost({
|
|
|
188
237
|
codeIn,
|
|
189
238
|
codeOut,
|
|
190
239
|
records,
|
|
240
|
+
spaceOpenCode,
|
|
241
|
+
serverInside,
|
|
242
|
+
restartOpenCodeInside: (spaceId) => restartOpenCodeInside(dispatcher.requestInside, spaceId),
|
|
191
243
|
listProjectDirectories,
|
|
244
|
+
// A key named by an environment variable is read from the host's own environment, now, and
|
|
245
|
+
// its value is kept nowhere (decision 5).
|
|
246
|
+
readHostSecret: (name) => hostEnvironment[name],
|
|
247
|
+
readIdleStop,
|
|
248
|
+
saveIdleStop,
|
|
192
249
|
announce: (spaceId, payload) => { hub?.injectEvent({ payload, directory: 'global', spaceId }); },
|
|
193
250
|
onSpacesChanged: () => { void refresh().catch(() => {}); },
|
|
194
251
|
logger,
|
|
195
252
|
});
|
|
196
253
|
|
|
197
|
-
const readBody = (response, cap) => new Promise((resolve, reject) => {
|
|
198
|
-
const chunks = [];
|
|
199
|
-
let size = 0;
|
|
200
|
-
response.on('data', (chunk) => {
|
|
201
|
-
size += chunk.length;
|
|
202
|
-
if (size > cap) { response.destroy(); reject(new Error(`the list exceeds ${cap} bytes`)); return; }
|
|
203
|
-
chunks.push(chunk);
|
|
204
|
-
});
|
|
205
|
-
response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
206
|
-
response.on('error', reject);
|
|
207
|
-
});
|
|
208
|
-
|
|
209
254
|
/** One space's whole session list, page by page, or as much of it as the page cap allows. */
|
|
210
255
|
const readSpaceSessions = async (spaceId) => {
|
|
211
256
|
const records = [];
|
|
@@ -8,7 +8,9 @@ import path from 'node:path';
|
|
|
8
8
|
import express from 'express';
|
|
9
9
|
import { afterEach, describe, expect, it } from 'vitest';
|
|
10
10
|
|
|
11
|
-
import {
|
|
11
|
+
import { Readable } from 'node:stream';
|
|
12
|
+
|
|
13
|
+
import { createSpacesHost, readOrCreateOwner, restartOpenCodeInside } from './host.js';
|
|
12
14
|
import { hashProjectDirectory } from './labels.js';
|
|
13
15
|
import { createMemoryPlace } from './places/memory-place.js';
|
|
14
16
|
|
|
@@ -46,6 +48,37 @@ describe('readOrCreateOwner', () => {
|
|
|
46
48
|
});
|
|
47
49
|
});
|
|
48
50
|
|
|
51
|
+
describe('restartOpenCodeInside', () => {
|
|
52
|
+
// The server inside, as the dispatcher hands back its answer: a status and a body to read.
|
|
53
|
+
const answering = (statusCode, body) => {
|
|
54
|
+
const asked = [];
|
|
55
|
+
const requestInside = async (spaceId, request) => {
|
|
56
|
+
asked.push({ spaceId, ...request });
|
|
57
|
+
return Object.assign(Readable.from([Buffer.from(body)]), { statusCode });
|
|
58
|
+
};
|
|
59
|
+
return { asked, requestInside };
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
it('asks the server inside for the reload its own settings use, and resolves when it says it succeeded', async () => {
|
|
63
|
+
const { asked, requestInside } = answering(200, JSON.stringify({ success: true, requiresReload: true }));
|
|
64
|
+
await restartOpenCodeInside(requestInside, 'a1b2c3d4e5f6');
|
|
65
|
+
expect(asked).toEqual([expect.objectContaining({ spaceId: 'a1b2c3d4e5f6', method: 'POST', path: '/api/config/reload' })]);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it.each([
|
|
69
|
+
['an error status', 500, JSON.stringify({ success: false, error: 'boom' })],
|
|
70
|
+
['a 200 that does not say it succeeded', 200, JSON.stringify({ success: 'yes' })],
|
|
71
|
+
['an OpenCode it does not manage, which it did not restart', 200, JSON.stringify({ success: true, requiresReload: false, requiresManualRestart: true })],
|
|
72
|
+
['a body that is not JSON', 200, 'restarted'],
|
|
73
|
+
['a body past the cap', 200, JSON.stringify({ success: true, padding: 'x'.repeat(70 * 1024) })],
|
|
74
|
+
])('reports %s as a failed restart, with no text from inside', async (_name, status, body) => {
|
|
75
|
+
const { requestInside } = answering(status, body);
|
|
76
|
+
const failure = await restartOpenCodeInside(requestInside, 'a1b2c3d4e5f6').catch((error) => error);
|
|
77
|
+
expect(failure).toMatchObject({ code: 'opencode_restart_failed' });
|
|
78
|
+
expect(failure.message).not.toContain('boom');
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
49
82
|
describe('createSpacesHost', () => {
|
|
50
83
|
it('starts no process of its own when it is made, and answers through the place it was given', async () => {
|
|
51
84
|
let started = 0;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// The idle stop of a space (DESIGN.md, decision 11): the server inside a space stops itself after
|
|
2
|
+
// the hours of the user's setting with no session working, and the container stops with it,
|
|
3
|
+
// because the server is what the container runs. The timer lives inside, so it works while
|
|
4
|
+
// OpenChamber is closed ("Dispatcher, sessions, events", last line). Files stay in the volumes.
|
|
5
|
+
//
|
|
6
|
+
// The host writes the setting into a file in the space's HOME at every start and whenever the user
|
|
7
|
+
// changes it; the server inside reads that file at every check. The agent can change the file, or
|
|
8
|
+
// keep a session busy, and so keep its space running: the idle stop saves the user's memory, it
|
|
9
|
+
// restricts nothing, and nothing here is a boundary.
|
|
10
|
+
//
|
|
11
|
+
// This module runs on both sides: the host parses the setting with the schema, and the server
|
|
12
|
+
// inside a space runs the timer, only when the space's environment names the file.
|
|
13
|
+
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
|
|
18
|
+
const IDLE_STOP_MIN_HOURS = 1;
|
|
19
|
+
const IDLE_STOP_MAX_HOURS = 168;
|
|
20
|
+
export const DEFAULT_IDLE_STOP = Object.freeze({ enabled: true, hours: 4 });
|
|
21
|
+
|
|
22
|
+
export const idleStopSchema = z.object({
|
|
23
|
+
enabled: z.boolean(),
|
|
24
|
+
hours: z.number().int().min(IDLE_STOP_MIN_HOURS).max(IDLE_STOP_MAX_HOURS),
|
|
25
|
+
}).strict();
|
|
26
|
+
|
|
27
|
+
/** The setting as `settings.json` holds it, or the default when it is missing or not readable. */
|
|
28
|
+
export const readIdleStopSetting = (value) => {
|
|
29
|
+
const parsed = idleStopSchema.safeParse(value);
|
|
30
|
+
return parsed.success ? parsed.data : { ...DEFAULT_IDLE_STOP };
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
34
|
+
const CHECK_INTERVAL_MS = 60 * 1000;
|
|
35
|
+
// The real file is about 30 bytes. The agent owns it and can make it anything, a FIFO among them,
|
|
36
|
+
// which a plain read would wait on forever, with the server's event loop stuck behind it.
|
|
37
|
+
const MAX_SETTING_BYTES = 1024;
|
|
38
|
+
const WORKING = new Set(['busy', 'retry']);
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* `settingsPath` is the file the host writes, `readSessionStates()` the server's own live status
|
|
42
|
+
* by session, `{ [id]: { status, lastUpdateAt } }`, `readPendingRequests()` the permission asks
|
|
43
|
+
* and forms still waiting for an answer by session, and `stopSpace()` ends the server. A session
|
|
44
|
+
* that is working counts as activity now, and every status change counts at the time it came, so
|
|
45
|
+
* a turn that began and ended between two checks is not missed. A session that waits for the
|
|
46
|
+
* user's answer stays busy in OpenCode's status the whole time; it counts as idle (the
|
|
47
|
+
* maintainer's call of 2026-09-28), so its memory is given back when nobody answers. A missing or unreadable file
|
|
48
|
+
* stops nothing: the host writes it at every start, and a space must never stop on a guess.
|
|
49
|
+
*/
|
|
50
|
+
export function createIdleStop({ settingsPath, readSessionStates, readPendingRequests = () => ({}), stopSpace, now = Date.now, logger = console }) {
|
|
51
|
+
let lastActive = now();
|
|
52
|
+
let stopping = false;
|
|
53
|
+
|
|
54
|
+
const readSetting = async () => {
|
|
55
|
+
try {
|
|
56
|
+
const stat = await fs.promises.lstat(settingsPath);
|
|
57
|
+
if (!stat.isFile() || stat.size > MAX_SETTING_BYTES) return null;
|
|
58
|
+
const parsed = idleStopSchema.safeParse(JSON.parse(await fs.promises.readFile(settingsPath, 'utf8')));
|
|
59
|
+
return parsed.success ? parsed.data : null;
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const noteActivity = () => {
|
|
66
|
+
const current = now();
|
|
67
|
+
const pending = readPendingRequests();
|
|
68
|
+
const waiting = (sessionId) => (pending[sessionId]?.permissions?.length ?? 0) + (pending[sessionId]?.forms?.length ?? 0) > 0;
|
|
69
|
+
for (const [sessionId, state] of Object.entries(readSessionStates())) {
|
|
70
|
+
if (WORKING.has(state.status) && !waiting(sessionId)) lastActive = current;
|
|
71
|
+
else if (state.lastUpdateAt > lastActive) lastActive = Math.min(state.lastUpdateAt, current);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** One check. Resolves true when it stopped the space. */
|
|
76
|
+
const check = async () => {
|
|
77
|
+
if (stopping) return false;
|
|
78
|
+
noteActivity();
|
|
79
|
+
const setting = await readSetting();
|
|
80
|
+
if (!setting?.enabled || now() - lastActive < setting.hours * HOUR_MS) return false;
|
|
81
|
+
stopping = true;
|
|
82
|
+
logger.log?.(`[spaces] no session worked for ${setting.hours} hours; the space stops itself`);
|
|
83
|
+
await stopSpace();
|
|
84
|
+
return true;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
return { check };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Checks once a minute for the life of the server. Answers the function that ends it. */
|
|
91
|
+
export function startIdleStop(options) {
|
|
92
|
+
const idleStop = createIdleStop(options);
|
|
93
|
+
const timer = setInterval(() => {
|
|
94
|
+
idleStop.check().catch((error) => { options.logger?.warn?.(`[spaces] the idle check failed: ${error?.message ?? error}`); });
|
|
95
|
+
}, CHECK_INTERVAL_MS);
|
|
96
|
+
timer.unref?.();
|
|
97
|
+
return () => clearInterval(timer);
|
|
98
|
+
}
|