@openchamber/web 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/bin/lib/DOCUMENTATION.md +1 -1
  2. package/bin/lib/commands-connect-url.js +6 -5
  3. package/bin/lib/commands-tunnel.js +24 -5
  4. package/dist/assets/{CodeMirrorCommentWidgets-CmKmyb9T.js → CodeMirrorCommentWidgets-C_zL-eri.js} +1 -1
  5. package/dist/assets/{DiffView-8-PFpZ2p.js → DiffView-BeN2_YYF.js} +3 -3
  6. package/dist/assets/FilesView-CN34wm_N.js +17 -0
  7. package/dist/assets/{GitView-DNUSu00w.js → GitView-DLDazOo1.js} +4 -4
  8. package/dist/assets/{GuestAttachDialog-Cv6QzjHC.js → GuestAttachDialog-C0xe_Lyy.js} +1 -1
  9. package/dist/assets/{GuestSurfacePane-Bt3jB_Ye.js → GuestSurfacePane-BdaurnDr.js} +1 -1
  10. package/dist/assets/{JsonTreeView-BlyHTRhM.js → JsonTreeView-B1Xq-k2t.js} +1 -1
  11. package/dist/assets/LinearIssuesView-BryoAHow.js +1 -0
  12. package/dist/assets/{MarkdownImageGallery-2UXJF-5B.js → MarkdownImageGallery-DfuEoaGq.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-B_ZcWOvX.js +12 -0
  14. package/dist/assets/OnboardingScreen-C22bGmnP.js +1 -0
  15. package/dist/assets/{PatchDiff-ByvnbG5T.js → PatchDiff-0xd6UeFB.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BXieg0mH.js → PierreDiffViewer-BC950e3F.js} +3 -3
  17. package/dist/assets/PlanView-B7Xgihqk.js +5 -0
  18. package/dist/assets/PluginPane-2C71F8uF.js +3 -0
  19. package/dist/assets/SettingsView-m_zoFiaT.js +30 -0
  20. package/dist/assets/{SettingsWindow-BIz224xs.js → SettingsWindow-CofS020b.js} +1 -1
  21. package/dist/assets/{SubmoduleDiffSummary-CXKmlps9.js → SubmoduleDiffSummary-BSA9gnIO.js} +1 -1
  22. package/dist/assets/{ToolOutputDialog-BsgAK8xu.js → ToolOutputDialog-DprkVKcj.js} +7 -7
  23. package/dist/assets/{ToolPartDiffPreview-vdPObXOf.js → ToolPartDiffPreview-Dq0go_fX.js} +2 -2
  24. package/dist/assets/{VirtualizedFileDiff-BkFNKWS5.js → VirtualizedFileDiff-Kp8hKJdT.js} +1 -1
  25. package/dist/assets/WalkthroughView-DGnTzqIU.js +4 -0
  26. package/dist/assets/{appThemeRegistry-aHUNHoqP.js → appThemeRegistry-BdEHBA4s.js} +1 -1
  27. package/dist/assets/{commitAndPush-Bon9r94r.js → commitAndPush-LwtVa2Oc.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-DKqr_1AQ.js → computeVirtualFileMetrics-6V1xNpO9.js} +2 -2
  29. package/dist/assets/de-DlgBHUAI.js +10 -0
  30. package/dist/assets/es-BC8G41U8.js +16 -0
  31. package/dist/assets/fr-I0z3vVjy.js +14 -0
  32. package/dist/assets/index-CgR5rJq_.js +41 -0
  33. package/dist/assets/{index-DpFttslC.js → index-CmNPYddV.js} +1 -1
  34. package/dist/assets/index-adyy_sEk.css +1 -0
  35. package/dist/assets/{isDiffPlainText-kzAgpIgi.js → isDiffPlainText-1bXcWCrw.js} +1 -1
  36. package/dist/assets/{isFilePlainText-Uj6y-jzz.js → isFilePlainText-CBAppvy1.js} +1 -1
  37. package/dist/assets/ja-BIElEsY8.js +16 -0
  38. package/dist/assets/ko-DRnnHetA.js +16 -0
  39. package/dist/assets/{main-CbfMxn-I.js → main-CzjTMTfW.js} +2 -2
  40. package/dist/assets/main-DVX34beR.js +886 -0
  41. package/dist/assets/markdownCore-Cxbkn5NR.js +7 -0
  42. package/dist/assets/{miniChat-CiAKBC10.js → miniChat-CP68IL8Q.js} +2 -2
  43. package/dist/assets/{mobile-CsT4sJwC.js → mobile-BrlBrNfZ.js} +2 -2
  44. package/dist/assets/nl-DzUV-kwp.js +16 -0
  45. package/dist/assets/{patchFileDiff-DeaE08W0.js → patchFileDiff-pqRSHLHI.js} +2 -2
  46. package/dist/assets/pl-Bb-cb7k7.js +16 -0
  47. package/dist/assets/pt-BR-CyIWrTcE.js +16 -0
  48. package/dist/assets/renderElectronMiniChatApp-DKIilR7N.js +2 -0
  49. package/dist/assets/renderMobileApp-B0z6-x58.js +25 -0
  50. package/dist/assets/runtimeEndpointReset-uu1DBwLL.js +52 -0
  51. package/dist/assets/{scheduledTasksApi-BZCNJ588.js → scheduledTasksApi-BuzWT445.js} +1 -1
  52. package/dist/assets/{shikiHighlight-BSUEa3yF.js → shikiHighlight-BWGrY5YU.js} +1 -1
  53. package/dist/assets/{textMateThemeFromAppTheme-CsATFZIV.js → textMateThemeFromAppTheme-BSUFChBY.js} +1 -1
  54. package/dist/assets/tr-DXEDSoYO.js +7 -0
  55. package/dist/assets/uk-C8hN--q_.js +16 -0
  56. package/dist/assets/useAppFontEffects-Dsl_sLrj.js +7366 -0
  57. package/dist/assets/useInlineCommentController-d5vntsQ_.js +2 -0
  58. package/dist/assets/{useRootScrollLock-Cp1eFoM2.js → useRootScrollLock-2rd5Y6gR.js} +2 -2
  59. package/dist/assets/{vendor-base-ui-CsXYnR5c.js → vendor-base-ui-DnNniUWp.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-language-data-BwwommM0.js → vendor-codemirror-language-data-B1EetJur.js} +2 -2
  61. package/dist/assets/vendor-opencode-client-DSZl7jSi.js +12 -0
  62. package/dist/assets/{vendor-tanstack-react-virtual-ClYN8CzB.js → vendor-tanstack-react-virtual--0sBrLRh.js} +1 -1
  63. package/dist/assets/{vendor-tanstack-virtual-core-BewVQryB.js → vendor-tanstack-virtual-core-BoA4iGMw.js} +1 -1
  64. package/dist/assets/{vendor-zod-BSoePkpP.js → vendor-zod-CxRSdNoV.js} +4 -4
  65. package/dist/assets/{web-components-D3Yjr4Zx.js → web-components-ngpHPEDU.js} +1 -1
  66. package/dist/assets/zh-CN-CtzXdjMZ.js +16 -0
  67. package/dist/assets/zh-TW-Ds0CADSz.js +16 -0
  68. package/dist/index.html +5 -5
  69. package/dist/mini-chat.html +5 -5
  70. package/dist/mobile.html +5 -5
  71. package/package.json +5 -5
  72. package/server/index.js +82 -4
  73. package/server/lib/agent-tool/DOCUMENTATION.md +8 -1
  74. package/server/lib/agent-tool/runtime.js +13 -4
  75. package/server/lib/agent-tool/runtime.test.js +15 -0
  76. package/server/lib/context-obligatory/DOCUMENTATION.md +10 -7
  77. package/server/lib/context-obligatory/runtime.js +2 -1
  78. package/server/lib/context-obligatory/runtime.test.js +76 -30
  79. package/server/lib/dictation/DOCUMENTATION.md +4 -1
  80. package/server/lib/dictation/openai-compatible-session.js +7 -0
  81. package/server/lib/enterprise-mode.d.ts +30 -0
  82. package/server/lib/enterprise-mode.js +253 -0
  83. package/server/lib/enterprise-mode.test.js +247 -0
  84. package/server/lib/event-stream/translate-v2.js +6 -0
  85. package/server/lib/event-stream/translate-v2.test.js +6 -0
  86. package/server/lib/git/DOCUMENTATION.md +2 -1
  87. package/server/lib/git/routes.js +44 -1
  88. package/server/lib/git/routes.test.js +98 -1
  89. package/server/lib/git/service.js +146 -11
  90. package/server/lib/git/service.test.js +195 -0
  91. package/server/lib/github/routes.js +9 -19
  92. package/server/lib/github/routes.test.js +112 -0
  93. package/server/lib/guests/DOCUMENTATION.md +4 -2
  94. package/server/lib/guests/background.test.js +1 -1
  95. package/server/lib/guests/catalog.js +56 -2
  96. package/server/lib/guests/catalog.test.js +24 -1
  97. package/server/lib/guests/clone-network.test.js +52 -0
  98. package/server/lib/guests/clone.js +30 -4
  99. package/server/lib/guests/enterprise.js +68 -0
  100. package/server/lib/guests/enterprise.test.js +106 -0
  101. package/server/lib/guests/grant-scope.js +8 -2
  102. package/server/lib/guests/grant-scope.test.js +9 -0
  103. package/server/lib/guests/html-styles.js +16 -2
  104. package/server/lib/guests/html-styles.test.js +53 -4
  105. package/server/lib/guests/install.js +10 -0
  106. package/server/lib/guests/persist.js +1 -0
  107. package/server/lib/guests/routes.js +40 -5
  108. package/server/lib/guests/updates.js +9 -2
  109. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  110. package/server/lib/notifications/runtime.js +22 -8
  111. package/server/lib/notifications/trigger-runtime.test.js +45 -0
  112. package/server/lib/openchamber-sessions/session-metadata-store.js +27 -0
  113. package/server/lib/openchamber-sessions/session-metadata-store.test.js +18 -0
  114. package/server/lib/opencode/DOCUMENTATION.md +13 -9
  115. package/server/lib/opencode/auth-state-runtime.js +2 -2
  116. package/server/lib/opencode/config-paths.test.js +1 -0
  117. package/server/lib/opencode/env-runtime.js +26 -3
  118. package/server/lib/opencode/env-runtime.test.js +57 -0
  119. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  120. package/server/lib/opencode/hmr-state-runtime.js +4 -3
  121. package/server/lib/opencode/lifecycle.js +10 -5
  122. package/server/lib/opencode/lifecycle.test.js +6 -2
  123. package/server/lib/opencode/managed-config-file.js +2 -1
  124. package/server/lib/opencode/managed-config-file.test.js +18 -0
  125. package/server/lib/opencode/npm-registry-config.d.ts +1 -0
  126. package/server/lib/opencode/npm-registry-config.js +123 -0
  127. package/server/lib/opencode/npm-registry-config.test.js +167 -0
  128. package/server/lib/opencode/npm-registry.js +5 -6
  129. package/server/lib/opencode/npm-registry.test.js +30 -0
  130. package/server/lib/opencode/openchamber-routes.js +8 -0
  131. package/server/lib/opencode/project-icon-routes.js +2 -2
  132. package/server/lib/opencode/project-icon-routes.test.js +44 -0
  133. package/server/lib/opencode/provider-source-route.test.js +32 -0
  134. package/server/lib/opencode/routes.js +17 -2
  135. package/server/lib/opencode/settings-helpers.js +26 -3
  136. package/server/lib/opencode/settings-helpers.test.js +12 -5
  137. package/server/lib/opencode/settings-registry.json +35 -1
  138. package/server/lib/opencode/settings-runtime.js +1 -0
  139. package/server/lib/opencode/shutdown-runtime.js +2 -0
  140. package/server/lib/opencode/static-routes-runtime.js +9 -1
  141. package/server/lib/opencode/static-routes-runtime.test.js +58 -1
  142. package/server/lib/package-manager.js +4 -1
  143. package/server/lib/package-manager.test.js +24 -0
  144. package/server/lib/permission-auto-accept/DOCUMENTATION.md +23 -15
  145. package/server/lib/permission-auto-accept/modes.js +26 -0
  146. package/server/lib/permission-auto-accept/runtime.js +146 -40
  147. package/server/lib/permission-auto-accept/runtime.test.js +93 -9
  148. package/server/lib/quota/DOCUMENTATION.md +6 -0
  149. package/server/lib/quota/providers/zhipuai-coding-plan.js +74 -30
  150. package/server/lib/quota/providers/zhipuai-coding-plan.test.js +124 -0
  151. package/server/lib/relay/DOCUMENTATION.md +1 -1
  152. package/server/lib/relay/service.js +32 -12
  153. package/server/lib/relay/service.test.js +30 -0
  154. package/server/lib/routing/DOCUMENTATION.md +150 -41
  155. package/server/lib/routing/classifier.js +156 -0
  156. package/server/lib/routing/defaults.js +27 -0
  157. package/server/lib/routing/jev.js +5 -17
  158. package/server/lib/routing/routes.http.test.js +9 -0
  159. package/server/lib/routing/routes.js +27 -1
  160. package/server/lib/routing/runtime.js +199 -33
  161. package/server/lib/routing/runtime.test.js +299 -15
  162. package/server/lib/routing/store.js +57 -0
  163. package/server/lib/routing/store.test.js +37 -0
  164. package/server/lib/session-assist/DOCUMENTATION.md +17 -7
  165. package/server/lib/session-assist/context.js +42 -2
  166. package/server/lib/session-assist/context.test.js +38 -1
  167. package/server/lib/session-assist/runtime.js +57 -13
  168. package/server/lib/session-assist/runtime.test.js +45 -0
  169. package/server/lib/session-goal/DOCUMENTATION.md +47 -22
  170. package/server/lib/session-goal/audit.js +112 -0
  171. package/server/lib/session-goal/audit.test.js +58 -0
  172. package/server/lib/session-goal/runtime.js +113 -134
  173. package/server/lib/session-goal/runtime.test.js +146 -13
  174. package/server/lib/session-lineage.js +52 -0
  175. package/server/lib/session-lineage.test.js +45 -0
  176. package/server/lib/session-work/DOCUMENTATION.md +108 -0
  177. package/server/lib/session-work/questions.js +126 -0
  178. package/server/lib/session-work/runtime.js +278 -0
  179. package/server/lib/session-work/runtime.test.js +255 -0
  180. package/server/lib/session-work/state.js +48 -0
  181. package/server/lib/session-work/state.test.js +34 -0
  182. package/server/lib/small-model/DOCUMENTATION.md +14 -7
  183. package/server/lib/small-model/client.js +7 -4
  184. package/server/lib/small-model/index.js +11 -21
  185. package/server/lib/small-model/index.test.js +13 -26
  186. package/server/lib/spaces/DOCUMENTATION.md +79 -25
  187. package/server/lib/spaces/gatekeeper-channel.js +63 -11
  188. package/server/lib/spaces/gatekeeper-channel.test.js +34 -4
  189. package/server/lib/spaces/gatekeeper-program.cjs +64 -13
  190. package/server/lib/spaces/gatekeeper-program.test.js +115 -3
  191. package/server/lib/spaces/host.js +58 -13
  192. package/server/lib/spaces/host.test.js +34 -1
  193. package/server/lib/spaces/idle-stop.js +98 -0
  194. package/server/lib/spaces/idle-stop.test.js +130 -0
  195. package/server/lib/spaces/journey.js +427 -17
  196. package/server/lib/spaces/journey.test.js +592 -5
  197. package/server/lib/spaces/layout.js +27 -6
  198. package/server/lib/spaces/manager.test.js +1 -1
  199. package/server/lib/spaces/places/contract-suite.js +4 -2
  200. package/server/lib/spaces/places/docker-live-support.js +27 -4
  201. package/server/lib/spaces/places/docker.js +32 -5
  202. package/server/lib/spaces/places/docker.test.js +38 -8
  203. package/server/lib/spaces/places/escape-suite.js +32 -0
  204. package/server/lib/spaces/places/fake-docker.js +3 -1
  205. package/server/lib/spaces/places/grants.docker.live.test.js +197 -0
  206. package/server/lib/spaces/places/memory-place.js +3 -3
  207. package/server/lib/spaces/places/sessions.docker.live.test.js +4 -2
  208. package/server/lib/spaces/routes.js +49 -1
  209. package/server/lib/spaces/routes.test.js +31 -3
  210. package/server/lib/spaces/space-opencode.js +52 -0
  211. package/server/lib/spaces/space-opencode.test.js +41 -0
  212. package/server/lib/spaces/space-records.js +90 -2
  213. package/server/lib/spaces/space-records.test.js +58 -1
  214. package/server/lib/spaces/space-server.js +13 -1
  215. package/server/lib/spaces/space-server.test.js +13 -0
  216. package/server/lib/spaces/space-setup.js +173 -0
  217. package/server/lib/spaces/space-setup.test.js +174 -0
  218. package/server/lib/tts/DOCUMENTATION.md +3 -0
  219. package/server/lib/tts/base-url.js +8 -0
  220. package/server/lib/tts/routes.js +13 -1
  221. package/server/lib/tts/routes.test.js +26 -0
  222. package/server/lib/tunnels/DOCUMENTATION.md +2 -0
  223. package/server/lib/tunnels/routes.js +14 -0
  224. package/server/lib/tunnels/routes.test.js +26 -0
  225. package/server/lib/walkthrough/index.js +11 -7
  226. package/server/lib/walkthrough/jobs.test.js +8 -0
  227. package/server/lib/walkthrough/languages.js +1 -0
  228. package/server/lib/walkthrough/routes.js +7 -1
  229. package/dist/assets/FilesView-0Ie20mEk.js +0 -17
  230. package/dist/assets/LinearIssuesView-CSl2MUfA.js +0 -1
  231. package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +0 -12
  232. package/dist/assets/OnboardingScreen-CIdXJpfc.js +0 -1
  233. package/dist/assets/PlanView-DEIi3Q7M.js +0 -5
  234. package/dist/assets/PluginPane-BEPUWVho.js +0 -3
  235. package/dist/assets/SettingsView-CiNh-RbW.js +0 -30
  236. package/dist/assets/WalkthroughView-6oE-MuDL.js +0 -4
  237. package/dist/assets/de-CgAJ51z7.js +0 -10
  238. package/dist/assets/es-zGi_ravM.js +0 -16
  239. package/dist/assets/fr-CPfogrWx.js +0 -14
  240. package/dist/assets/index-CHfphYL3.js +0 -41
  241. package/dist/assets/index-DvMJ3w6V.css +0 -1
  242. package/dist/assets/ja-DMk6wd-U.js +0 -16
  243. package/dist/assets/ko-BFpzJ8jc.js +0 -16
  244. package/dist/assets/main-anyZFMIs.js +0 -896
  245. package/dist/assets/markdownCore-CmM47cAE.js +0 -7
  246. package/dist/assets/pl-VdRPcZrB.js +0 -16
  247. package/dist/assets/pt-BR-BRys_lOW.js +0 -16
  248. package/dist/assets/renderElectronMiniChatApp-C5677jy0.js +0 -2
  249. package/dist/assets/renderMobileApp-D4dBBAqQ.js +0 -25
  250. package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +0 -27
  251. package/dist/assets/tr-CA9ckNnm.js +0 -7
  252. package/dist/assets/uk-byjR-y8D.js +0 -16
  253. package/dist/assets/useAppFontEffects-BWQZ5DeI.js +0 -7341
  254. package/dist/assets/useInlineCommentController-DlFyVfBu.js +0 -2
  255. package/dist/assets/vendor-opencode-client-DYdsLbCM.js +0 -12
  256. package/dist/assets/zh-CN-DRabgxdG.js +0 -16
  257. package/dist/assets/zh-TW-rbY5c9UK.js +0 -16
@@ -15,6 +15,7 @@ import { EventEmitter } from 'events';
15
15
  import { randomUUID } from 'crypto';
16
16
 
17
17
  import { transcribeAudio } from '../tts/stt.js';
18
+ import { normalizeCustomOpenAIBaseURL } from '../tts/base-url.js';
18
19
  import { pcm16ToWav } from './audio.js';
19
20
 
20
21
  const OPENAI_COMPATIBLE_SAMPLE_RATE = 16000;
@@ -37,6 +38,12 @@ export class OpenAICompatibleTranscriptionSession extends EventEmitter {
37
38
  if (!this.config.baseURL) {
38
39
  throw new Error('Custom STT server URL is not configured');
39
40
  }
41
+ // Every transcription checks the URL again; refusing here tells the user
42
+ // before they dictate instead of after.
43
+ const url = normalizeCustomOpenAIBaseURL(this.config.baseURL);
44
+ if (url.error) {
45
+ throw new Error(url.error);
46
+ }
40
47
  if (!this.config.model) {
41
48
  throw new Error('STT model is not configured');
42
49
  }
@@ -0,0 +1,30 @@
1
+ export type EnterprisePolicySource = 'policy-file' | 'environment';
2
+
3
+ export interface EnterprisePolicyOptions {
4
+ platform?: NodeJS.Platform;
5
+ env?: NodeJS.ProcessEnv;
6
+ readFile?: (filePath: string) => string;
7
+ }
8
+
9
+ export interface EnterprisePolicy {
10
+ enterpriseMode: boolean;
11
+ source: EnterprisePolicySource | null;
12
+ organization: string | null;
13
+ policyError: string | null;
14
+ relayUrl: string | null;
15
+ jev: { url: string; model: string | null; apiKey: string | null } | null;
16
+ allowNetworkAccess: boolean;
17
+ allowedExtensions: string[];
18
+ allowLocalExtensions: boolean;
19
+ }
20
+
21
+ export type PublicEnterprisePolicy = Pick<EnterprisePolicy, 'enterpriseMode' | 'source' | 'organization' | 'policyError'> & { networkAccessBlocked: boolean };
22
+
23
+ export function policyFilePaths(options?: Pick<EnterprisePolicyOptions, 'platform' | 'env'>): string[];
24
+ export function readEnterprisePolicy(options?: EnterprisePolicyOptions): EnterprisePolicy;
25
+ export function isEnterpriseMode(options?: EnterprisePolicyOptions): boolean;
26
+ export function isNetworkAccessBlocked(options?: EnterprisePolicyOptions): boolean;
27
+ export const NETWORK_ACCESS_BLOCKED_ERROR: string;
28
+ export function publicEnterprisePolicy(options?: EnterprisePolicyOptions): PublicEnterprisePolicy;
29
+ export function isProviderConnectRequest(method: string, requestPath: string): boolean;
30
+ export const ENTERPRISE_MODE_ERROR: string;
@@ -0,0 +1,253 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { z } from 'zod';
5
+
6
+ /**
7
+ * Enterprise mode: an administrator's promise that conversation content goes
8
+ * only to the model providers configured in OpenCode. Two sources turn it on,
9
+ * and either one is enough:
10
+ * - the machine policy file (`policyFilePaths`), which only an administrator
11
+ * can write and a device manager can roll out; nothing a user sets can
12
+ * turn off what it turns on;
13
+ * - `OPENCHAMBER_ENTERPRISE_MODE=1` (or `true`) in the server's environment,
14
+ * which includes the login-shell snapshot. Meant for servers and containers,
15
+ * where the administrator owns the environment.
16
+ * Read at every use, so a changed file applies without a restart.
17
+ *
18
+ * The policy file also pins the self-hosted relay and the Jev endpoint, and
19
+ * can allow network access. Who decides those follows who turned the mode on:
20
+ * - the file turned it on: only the file's values count. The environment is
21
+ * the user's to edit, so a variable there must not reopen what the
22
+ * administrator left closed (point Jev at an endpoint of their own, say);
23
+ * - otherwise (the environment turned it on, or the mode is off): a value in
24
+ * the file wins over its variable, and the variable fills the gap.
25
+ * A file that exists but cannot be read or parsed turns enterprise mode on,
26
+ * pins nothing and allows nothing: a broken policy must not quietly lift the
27
+ * protection it was meant to give.
28
+ *
29
+ * Each feature that could send conversation content anywhere else checks it
30
+ * at its own server boundary:
31
+ * - Model providers come only from the OpenCode config: connecting one,
32
+ * signing in, adding a key or creating a custom provider through this
33
+ * server is refused (`opencode/routes.js`). OpenCode's `provider.use`
34
+ * policy is the real lock; this closes the way in through the app.
35
+ * - Jev classification is off, unless the administrator pinned their own
36
+ * endpoint (`routing/runtime.js`).
37
+ * - External tunnels are refused: their provider sees plain text (`tunnels`).
38
+ * - The private relay runs only on a pinned self-hosted endpoint
39
+ * (`relay/service.js`).
40
+ * - Speech and transcription go only to servers on this machine (`tts`,
41
+ * `dictation`).
42
+ * - Push notifications carry no message text or session name (`notifications`).
43
+ * - Update checks still run but never report usage (`package-manager.js`).
44
+ * - The server listens only on this machine unless network access is allowed
45
+ * (`allowNetworkAccess` / `OPENCHAMBER_ALLOW_NETWORK_ACCESS`): it refuses
46
+ * to start on a network address and drops connections from other machines
47
+ * (`../index.js`); the desktop shell binds loopback (`packages/electron`).
48
+ * Pairing a device then goes through a pinned relay only.
49
+ * - Extensions that could send what they see elsewhere (`network`, `origins`,
50
+ * `service`) install and run only from a Git repository the administrator
51
+ * listed (`allowedExtensions` / `OPENCHAMBER_ALLOWED_EXTENSIONS`), or from a
52
+ * local folder where `allowLocalExtensions` /
53
+ * `OPENCHAMBER_ALLOW_LOCAL_EXTENSIONS` allows it; see `guests/enterprise.js`.
54
+ * The VS Code extension host, which runs no OpenChamber server, reads the
55
+ * same policy through this module for the parts it has (provider connection,
56
+ * update checks).
57
+ */
58
+
59
+ const WINDOWS_PROGRAM_DATA = 'C:\\ProgramData';
60
+
61
+ /**
62
+ * Where the machine policy may live, most authoritative first. The paths are
63
+ * fixed on purpose: a location a user could redirect (an environment variable,
64
+ * a setting) would let them point it at an empty file. On Windows the
65
+ * `ProgramData` variable is consulted only after the fixed location, so
66
+ * redirecting it cannot hide a policy the administrator placed there.
67
+ */
68
+ export const policyFilePaths = ({ platform = process.platform, env = process.env } = {}) => {
69
+ if (platform === 'darwin') return ['/Library/Application Support/OpenChamber/policy.json'];
70
+ if (platform === 'win32') {
71
+ const fixed = path.win32.join(WINDOWS_PROGRAM_DATA, 'OpenChamber', 'policy.json');
72
+ const programData = (env.ProgramData ?? '').trim();
73
+ const fromEnv = programData ? path.win32.join(programData, 'OpenChamber', 'policy.json') : null;
74
+ return fromEnv && fromEnv.toLowerCase() !== fixed.toLowerCase() ? [fixed, fromEnv] : [fixed];
75
+ }
76
+ return ['/etc/openchamber/policy.json'];
77
+ };
78
+
79
+ // A blank string counts as unset, so a template with empty fields pins nothing.
80
+ const optionalText = z.string().trim().transform((value) => value || undefined).optional();
81
+
82
+ const policyFileSchema = z.object({
83
+ enterpriseMode: z.boolean().optional(),
84
+ organization: optionalText,
85
+ relayUrl: optionalText,
86
+ allowNetworkAccess: z.boolean().optional(),
87
+ // Git repository URLs, not package ids: a package names its own id, so a
88
+ // user could ship any code under an allowed one.
89
+ allowedExtensions: z.array(z.string().trim().min(1)).max(200).optional(),
90
+ allowLocalExtensions: z.boolean().optional(),
91
+ jev: z.object({ url: optionalText, model: optionalText, apiKey: optionalText }).optional(),
92
+ }).refine((policy) => !policy.jev || policy.jev.url || (!policy.jev.model && !policy.jev.apiKey), {
93
+ message: '"jev" needs a "url"',
94
+ path: ['jev'],
95
+ });
96
+
97
+ /** The file's content; throws an Error saying what is wrong with it. */
98
+ const parsePolicyFile = (text) => {
99
+ let raw;
100
+ try {
101
+ // Windows PowerShell 5 writes UTF-8 with a byte-order mark.
102
+ raw = JSON.parse(text.replace(/^\uFEFF/, ''));
103
+ } catch (error) {
104
+ throw new Error(`not valid JSON (${error.message})`);
105
+ }
106
+ const parsed = policyFileSchema.safeParse(raw);
107
+ if (!parsed.success) {
108
+ const issue = parsed.error.issues[0];
109
+ const field = issue.path.length > 0 ? `"${issue.path.join('.')}": ` : '';
110
+ throw new Error(`${field}${issue.message}`);
111
+ }
112
+ const { enterpriseMode, organization, relayUrl, allowNetworkAccess, allowedExtensions, allowLocalExtensions, jev } = parsed.data;
113
+ return {
114
+ enterpriseMode: enterpriseMode === true,
115
+ organization: organization ?? null,
116
+ relayUrl,
117
+ allowNetworkAccess,
118
+ allowedExtensions,
119
+ allowLocalExtensions,
120
+ jev: jev?.url ? { url: jev.url, model: jev.model ?? null, apiKey: jev.apiKey ?? null } : undefined,
121
+ };
122
+ };
123
+
124
+ const defaultReadFile = (filePath) => fs.readFileSync(filePath, 'utf8');
125
+
126
+ let lastWarning = null;
127
+ const warnOnce = (message) => {
128
+ if (message === lastWarning) return;
129
+ lastWarning = message;
130
+ console.warn(`[enterprise] ${message}`);
131
+ };
132
+
133
+ /**
134
+ * The machine policy file: `{ status: 'absent' }`, `{ status: 'ok', path,
135
+ * policy }`, or `{ status: 'invalid', path, error }` when it exists but cannot
136
+ * be used.
137
+ */
138
+ const readPolicyFile = ({ platform = process.platform, env = process.env, readFile = defaultReadFile } = {}) => {
139
+ for (const filePath of policyFilePaths({ platform, env })) {
140
+ let text;
141
+ try {
142
+ text = readFile(filePath);
143
+ } catch (error) {
144
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
145
+ const message = `cannot read ${filePath}: ${error?.message || error}`;
146
+ warnOnce(`${message}; enterprise mode stays on`);
147
+ return { status: 'invalid', path: filePath, error: message };
148
+ }
149
+ try {
150
+ return { status: 'ok', path: filePath, policy: parsePolicyFile(text) };
151
+ } catch (error) {
152
+ const message = `${filePath}: ${error.message}`;
153
+ warnOnce(`${message}; enterprise mode stays on`);
154
+ return { status: 'invalid', path: filePath, error: message };
155
+ }
156
+ }
157
+ return { status: 'absent' };
158
+ };
159
+
160
+ const envFlag = (env, name) => {
161
+ const value = (env[name] ?? '').trim().toLowerCase();
162
+ return value === '1' || value === 'true';
163
+ };
164
+
165
+ const envString = (env, name) => (env[name] ?? '').trim() || null;
166
+
167
+ const envList = (env, name) => (env[name] ?? '').split(',').map((entry) => entry.trim()).filter(Boolean);
168
+
169
+ /**
170
+ * The policy in effect, from the file and the environment together.
171
+ * `relayUrl` and `jev` are the raw pinned values; their consumers validate
172
+ * them and treat an invalid one as unset. `source` says where enterprise mode
173
+ * came from, for the UI and the logs.
174
+ */
175
+ export const readEnterprisePolicy = (options = {}) => {
176
+ const env = options.env ?? process.env;
177
+ const file = readPolicyFile(options);
178
+
179
+ if (file.status === 'invalid') {
180
+ return {
181
+ enterpriseMode: true,
182
+ source: 'policy-file',
183
+ organization: null,
184
+ policyError: file.error,
185
+ relayUrl: null,
186
+ jev: null,
187
+ allowNetworkAccess: false,
188
+ allowedExtensions: [],
189
+ allowLocalExtensions: false,
190
+ };
191
+ }
192
+
193
+ const fromFile = file.status === 'ok' ? file.policy : null;
194
+ const fileGoverns = fromFile?.enterpriseMode === true;
195
+ const enterpriseMode = fileGoverns || envFlag(env, 'OPENCHAMBER_ENTERPRISE_MODE');
196
+
197
+ // With the file in charge the environment adds nothing (see above).
198
+ const envJevUrl = fileGoverns ? null : envString(env, 'OPENCHAMBER_JEV_URL');
199
+ const jev = fromFile?.jev
200
+ ?? (envJevUrl
201
+ ? { url: envJevUrl, model: envString(env, 'OPENCHAMBER_JEV_MODEL'), apiKey: envString(env, 'OPENCHAMBER_JEV_API_KEY') }
202
+ : null);
203
+ const relayUrl = fromFile?.relayUrl ?? (fileGoverns ? null : envString(env, 'OPENCHAMBER_RELAY_URL'));
204
+ const allowNetworkAccess = fromFile?.allowNetworkAccess
205
+ ?? (fileGoverns ? false : envFlag(env, 'OPENCHAMBER_ALLOW_NETWORK_ACCESS'));
206
+ const allowedExtensions = fromFile?.allowedExtensions
207
+ ?? (fileGoverns ? [] : envList(env, 'OPENCHAMBER_ALLOWED_EXTENSIONS'));
208
+ const allowLocalExtensions = fromFile?.allowLocalExtensions
209
+ ?? (fileGoverns ? false : envFlag(env, 'OPENCHAMBER_ALLOW_LOCAL_EXTENSIONS'));
210
+
211
+ return {
212
+ enterpriseMode,
213
+ source: fileGoverns ? 'policy-file' : enterpriseMode ? 'environment' : null,
214
+ organization: fromFile?.organization ?? null,
215
+ policyError: null,
216
+ relayUrl,
217
+ jev,
218
+ allowNetworkAccess,
219
+ allowedExtensions,
220
+ allowLocalExtensions,
221
+ };
222
+ };
223
+
224
+ export const isEnterpriseMode = (options) => readEnterprisePolicy(options).enterpriseMode;
225
+
226
+ /** Whether enterprise mode keeps this server off the network (loopback only). */
227
+ export const isNetworkAccessBlocked = (options) => {
228
+ const policy = readEnterprisePolicy(options);
229
+ return policy.enterpriseMode && !policy.allowNetworkAccess;
230
+ };
231
+
232
+ export const NETWORK_ACCESS_BLOCKED_ERROR = 'Enterprise mode keeps OpenChamber on this machine: it does not listen on a network address. '
233
+ + 'An administrator can allow it with "allowNetworkAccess": true in the policy file, or OPENCHAMBER_ALLOW_NETWORK_ACCESS=1 where the environment turns enterprise mode on.';
234
+
235
+ /** What a client may know about the policy; pinned endpoints and keys stay on the server. */
236
+ export const publicEnterprisePolicy = (options) => {
237
+ const { enterpriseMode, source, organization, policyError, allowNetworkAccess } = readEnterprisePolicy(options);
238
+ return { enterpriseMode, source, organization, policyError, networkAccessBlocked: enterpriseMode && !allowNetworkAccess };
239
+ };
240
+
241
+ // OpenCode routes that connect a provider, sign in or add a key: every POST
242
+ // under `/api/integration/:id/connect` (key, oauth start and complete,
243
+ // command) and adding a well-known integration. Reads, cancelling an attempt
244
+ // and removing or switching an existing account stay allowed: they only
245
+ // narrow access.
246
+ const PROVIDER_CONNECT_PATH = /^\/api\/(?:integration\/[^/?]+\/connect(?:\/[^?]*)?|experimental\/integration\/wellknown)\/?(?:\?|$)/;
247
+
248
+ /** Whether a request to OpenCode would add a way to reach a model provider. */
249
+ export const isProviderConnectRequest = (method, requestPath) => (
250
+ String(method).toUpperCase() === 'POST' && PROVIDER_CONNECT_PATH.test(requestPath)
251
+ );
252
+
253
+ export const ENTERPRISE_MODE_ERROR = 'Not available in enterprise mode: this server keeps conversations with the model providers configured in OpenCode.';
@@ -0,0 +1,247 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import {
4
+ isEnterpriseMode,
5
+ isNetworkAccessBlocked,
6
+ isProviderConnectRequest,
7
+ policyFilePaths,
8
+ publicEnterprisePolicy,
9
+ readEnterprisePolicy,
10
+ } from './enterprise-mode.js';
11
+
12
+ const missing = () => {
13
+ throw Object.assign(new Error('no such file'), { code: 'ENOENT' });
14
+ };
15
+
16
+ /** A machine with `files` (path → content) and nothing else. */
17
+ const machine = (files, { platform = 'linux', env = {} } = {}) => ({
18
+ platform,
19
+ env,
20
+ readFile: (filePath) => {
21
+ if (!(filePath in files)) missing();
22
+ const content = files[filePath];
23
+ if (content instanceof Error) throw content;
24
+ return content;
25
+ },
26
+ });
27
+
28
+ const LINUX_POLICY = '/etc/openchamber/policy.json';
29
+
30
+ describe('enterprise policy', () => {
31
+ it('is off with no policy file and no environment variable', () => {
32
+ expect(readEnterprisePolicy(machine({}))).toEqual({
33
+ enterpriseMode: false,
34
+ source: null,
35
+ organization: null,
36
+ policyError: null,
37
+ relayUrl: null,
38
+ jev: null,
39
+ allowNetworkAccess: false,
40
+ allowedExtensions: [],
41
+ allowLocalExtensions: false,
42
+ });
43
+ });
44
+
45
+ it('turns on from the environment variable alone', () => {
46
+ const options = machine({}, { env: { OPENCHAMBER_ENTERPRISE_MODE: 'true' } });
47
+ expect(isEnterpriseMode(options)).toBe(true);
48
+ expect(readEnterprisePolicy(options).source).toBe('environment');
49
+ });
50
+
51
+ it('turns on from the policy file and carries its organization and pins', () => {
52
+ const policy = readEnterprisePolicy(machine({
53
+ [LINUX_POLICY]: JSON.stringify({
54
+ enterpriseMode: true,
55
+ organization: 'Acme',
56
+ relayUrl: 'wss://relay.acme.test/ws',
57
+ jev: { url: 'https://llm.acme.test/v1', model: 'acme-jev', apiKey: 'k' },
58
+ }),
59
+ }));
60
+ expect(policy).toEqual({
61
+ enterpriseMode: true,
62
+ source: 'policy-file',
63
+ organization: 'Acme',
64
+ policyError: null,
65
+ relayUrl: 'wss://relay.acme.test/ws',
66
+ jev: { url: 'https://llm.acme.test/v1', model: 'acme-jev', apiKey: 'k' },
67
+ allowNetworkAccess: false,
68
+ allowedExtensions: [],
69
+ allowLocalExtensions: false,
70
+ });
71
+ });
72
+
73
+ it('ignores the environment\'s pins and network allowance once the file turns enterprise mode on', () => {
74
+ const policy = readEnterprisePolicy(machine(
75
+ { [LINUX_POLICY]: '{"enterpriseMode": true}' },
76
+ { env: {
77
+ OPENCHAMBER_RELAY_URL: 'wss://my-relay.test/ws',
78
+ OPENCHAMBER_JEV_URL: 'https://my-endpoint.test',
79
+ OPENCHAMBER_ALLOW_NETWORK_ACCESS: '1',
80
+ } },
81
+ ));
82
+ expect(policy.relayUrl).toBeNull();
83
+ expect(policy.jev).toBeNull();
84
+ expect(policy.allowNetworkAccess).toBe(false);
85
+ });
86
+
87
+ it('takes the pins and network allowance from the environment when the environment turns it on', () => {
88
+ const policy = readEnterprisePolicy(machine({}, { env: {
89
+ OPENCHAMBER_ENTERPRISE_MODE: '1',
90
+ OPENCHAMBER_RELAY_URL: 'wss://relay.acme.test/ws',
91
+ OPENCHAMBER_ALLOW_NETWORK_ACCESS: 'true',
92
+ } }));
93
+ expect(policy.relayUrl).toBe('wss://relay.acme.test/ws');
94
+ expect(policy.allowNetworkAccess).toBe(true);
95
+ });
96
+
97
+ it('takes allowed extension repositories from the file, or from the environment only when the file does not govern', () => {
98
+ const env = { OPENCHAMBER_ALLOWED_EXTENSIONS: 'https://github.com/me/ext, https://github.com/me/other' };
99
+ expect(readEnterprisePolicy(machine({ [LINUX_POLICY]: '{"enterpriseMode": true}' }, { env })).allowedExtensions).toEqual([]);
100
+ expect(readEnterprisePolicy(machine({ [LINUX_POLICY]: '{"enterpriseMode": true, "allowedExtensions": ["https://github.com/acme/ext"]}' }, { env })).allowedExtensions)
101
+ .toEqual(['https://github.com/acme/ext']);
102
+ expect(readEnterprisePolicy(machine({}, { env: { ...env, OPENCHAMBER_ENTERPRISE_MODE: '1' } })).allowedExtensions)
103
+ .toEqual(['https://github.com/me/ext', 'https://github.com/me/other']);
104
+ });
105
+
106
+ describe('network access', () => {
107
+ it('is blocked in enterprise mode unless allowed', () => {
108
+ expect(isNetworkAccessBlocked(machine({ [LINUX_POLICY]: '{"enterpriseMode": true}' }))).toBe(true);
109
+ expect(isNetworkAccessBlocked(machine({ [LINUX_POLICY]: '{"enterpriseMode": true, "allowNetworkAccess": true}' }))).toBe(false);
110
+ expect(isNetworkAccessBlocked(machine({}, { env: { OPENCHAMBER_ENTERPRISE_MODE: '1' } }))).toBe(true);
111
+ expect(isNetworkAccessBlocked(machine({}, { env: { OPENCHAMBER_ENTERPRISE_MODE: '1', OPENCHAMBER_ALLOW_NETWORK_ACCESS: '1' } }))).toBe(false);
112
+ });
113
+
114
+ it('is never blocked outside enterprise mode', () => {
115
+ expect(isNetworkAccessBlocked(machine({}))).toBe(false);
116
+ });
117
+
118
+ it('stays blocked when the policy file is broken', () => {
119
+ expect(isNetworkAccessBlocked(machine({ [LINUX_POLICY]: '{"allowNetworkAccess": tru' }))).toBe(true);
120
+ });
121
+ });
122
+
123
+ it('cannot be turned off by the environment once the file turns it on', () => {
124
+ const options = machine(
125
+ { [LINUX_POLICY]: '{"enterpriseMode": true}' },
126
+ { env: { OPENCHAMBER_ENTERPRISE_MODE: '0' } },
127
+ );
128
+ expect(isEnterpriseMode(options)).toBe(true);
129
+ });
130
+
131
+ it('lets the environment turn it on when the file leaves it off', () => {
132
+ const options = machine(
133
+ { [LINUX_POLICY]: '{"enterpriseMode": false}' },
134
+ { env: { OPENCHAMBER_ENTERPRISE_MODE: '1' } },
135
+ );
136
+ expect(readEnterprisePolicy(options).source).toBe('environment');
137
+ });
138
+
139
+ it('prefers values from the file over their environment variables, and fills the gaps from the environment', () => {
140
+ const env = {
141
+ OPENCHAMBER_RELAY_URL: 'wss://env-relay.test/ws',
142
+ OPENCHAMBER_JEV_URL: 'https://env-jev.test',
143
+ OPENCHAMBER_JEV_MODEL: 'env-model',
144
+ };
145
+ const fileRelayOnly = readEnterprisePolicy(machine({ [LINUX_POLICY]: '{"relayUrl": "wss://file-relay.test/ws"}' }, { env }));
146
+ expect(fileRelayOnly.relayUrl).toBe('wss://file-relay.test/ws');
147
+ expect(fileRelayOnly.jev).toEqual({ url: 'https://env-jev.test', model: 'env-model', apiKey: null });
148
+
149
+ const fileJev = readEnterprisePolicy(machine({ [LINUX_POLICY]: '{"jev": {"url": "https://file-jev.test"}}' }, { env }));
150
+ // The file's endpoint comes whole: the environment's model does not mix into it.
151
+ expect(fileJev.jev).toEqual({ url: 'https://file-jev.test', model: null, apiKey: null });
152
+ });
153
+
154
+ it.each([
155
+ ['not JSON', '{enterpriseMode: true'],
156
+ ['not an object', '[true]'],
157
+ ['a non-boolean switch', '{"enterpriseMode": "yes"}'],
158
+ ['a non-string relay', '{"relayUrl": 42}'],
159
+ ['a Jev model without a URL', '{"jev": {"model": "m"}}'],
160
+ ])('keeps enterprise mode on and pins nothing when the file is %s', (_label, content) => {
161
+ const policy = readEnterprisePolicy(machine(
162
+ { [LINUX_POLICY]: content },
163
+ { env: { OPENCHAMBER_RELAY_URL: 'wss://env-relay.test/ws', OPENCHAMBER_JEV_URL: 'https://env-jev.test' } },
164
+ ));
165
+ expect(policy.enterpriseMode).toBe(true);
166
+ expect(policy.source).toBe('policy-file');
167
+ expect(policy.policyError).toContain(LINUX_POLICY);
168
+ expect(policy.relayUrl).toBeNull();
169
+ expect(policy.jev).toBeNull();
170
+ });
171
+
172
+ it('keeps enterprise mode on when the file exists but cannot be read', () => {
173
+ const denied = Object.assign(new Error('permission denied'), { code: 'EACCES' });
174
+ const policy = readEnterprisePolicy(machine({ [LINUX_POLICY]: denied }));
175
+ expect(policy.enterpriseMode).toBe(true);
176
+ expect(policy.policyError).toContain('permission denied');
177
+ });
178
+
179
+ it('reads a file saved with a byte-order mark', () => {
180
+ const policy = readEnterprisePolicy(machine({ [LINUX_POLICY]: '\uFEFF{"enterpriseMode": true, "organization": "Acme"}' }));
181
+ expect(policy.policyError).toBeNull();
182
+ expect(policy.organization).toBe('Acme');
183
+ });
184
+
185
+ it('ignores unknown keys so newer policy files still apply', () => {
186
+ expect(isEnterpriseMode(machine({ [LINUX_POLICY]: '{"enterpriseMode": true, "future": 1}' }))).toBe(true);
187
+ });
188
+
189
+ it('never exposes pinned endpoints or keys to clients', () => {
190
+ const policy = publicEnterprisePolicy(machine({
191
+ [LINUX_POLICY]: '{"enterpriseMode": true, "organization": "Acme", "jev": {"url": "https://x.test", "apiKey": "secret"}}',
192
+ }));
193
+ expect(policy).toEqual({ enterpriseMode: true, source: 'policy-file', organization: 'Acme', policyError: null, networkAccessBlocked: true });
194
+ });
195
+
196
+ describe('file location', () => {
197
+ it('is fixed per platform', () => {
198
+ expect(policyFilePaths({ platform: 'darwin', env: {} })).toEqual(['/Library/Application Support/OpenChamber/policy.json']);
199
+ expect(policyFilePaths({ platform: 'linux', env: {} })).toEqual([LINUX_POLICY]);
200
+ expect(policyFilePaths({ platform: 'win32', env: {} })).toEqual(['C:\\ProgramData\\OpenChamber\\policy.json']);
201
+ });
202
+
203
+ it('on Windows reads C:\\ProgramData first, so redirecting ProgramData cannot hide the policy', () => {
204
+ const env = { ProgramData: 'D:\\Elsewhere' };
205
+ expect(policyFilePaths({ platform: 'win32', env })).toEqual([
206
+ 'C:\\ProgramData\\OpenChamber\\policy.json',
207
+ 'D:\\Elsewhere\\OpenChamber\\policy.json',
208
+ ]);
209
+ const options = machine({
210
+ 'C:\\ProgramData\\OpenChamber\\policy.json': '{"enterpriseMode": true}',
211
+ 'D:\\Elsewhere\\OpenChamber\\policy.json': '{"enterpriseMode": false}',
212
+ }, { platform: 'win32', env });
213
+ expect(isEnterpriseMode(options)).toBe(true);
214
+ });
215
+
216
+ it('on Windows falls back to the ProgramData folder when the system drive is not C:', () => {
217
+ const options = machine(
218
+ { 'D:\\ProgramData\\OpenChamber\\policy.json': '{"enterpriseMode": true}' },
219
+ { platform: 'win32', env: { ProgramData: 'D:\\ProgramData' } },
220
+ );
221
+ expect(isEnterpriseMode(options)).toBe(true);
222
+ });
223
+ });
224
+
225
+ describe('provider-connect requests', () => {
226
+ it.each([
227
+ '/api/integration/openai/connect/key',
228
+ '/api/integration/openai/connect/key?directory=%2Fp',
229
+ '/api/integration/anthropic/connect/oauth',
230
+ '/api/integration/anthropic/connect/oauth/att_1/complete',
231
+ '/api/integration/github-copilot/connect/command',
232
+ '/api/experimental/integration/wellknown',
233
+ ])('refuses POST %s', (requestPath) => {
234
+ expect(isProviderConnectRequest('POST', requestPath)).toBe(true);
235
+ });
236
+
237
+ it.each([
238
+ ['GET', '/api/integration/anthropic/connect/oauth/att_1'],
239
+ ['DELETE', '/api/integration/anthropic/connect/oauth/att_1'],
240
+ ['GET', '/api/integration'],
241
+ ['POST', '/api/session'],
242
+ ['DELETE', '/api/credential/cred_1'],
243
+ ])('leaves %s %s alone', (method, requestPath) => {
244
+ expect(isProviderConnectRequest(method, requestPath)).toBe(false);
245
+ });
246
+ });
247
+ });
@@ -258,6 +258,12 @@ export function translateWireEvent(payload) {
258
258
  })];
259
259
  }
260
260
 
261
+ // v2's own `session.compacted` is declared but never published; a finished
262
+ // compaction is announced only by `session.compaction.ended`.
263
+ case 'session.compaction.ended':
264
+ if (!sessionID) return [];
265
+ return [event('session.compacted', { sessionID })];
266
+
261
267
  // --- requests to the user -------------------------------------------------
262
268
 
263
269
  case 'permission.asked': {
@@ -50,6 +50,12 @@ describe('translateWireEvent', () => {
50
50
  });
51
51
  });
52
52
 
53
+ test('a finished compaction reads as session.compacted', () => {
54
+ expect(translateWireEvent(wire('session.compaction.ended', { sessionID: 's1', reason: 'auto', text: 'summary', recent: '' })))
55
+ .toEqual([expect.objectContaining({ type: 'session.compacted', properties: { sessionID: 's1', directory: '/repo' } })]);
56
+ expect(translateWireEvent(wire('session.compaction.started', { sessionID: 's1', reason: 'auto' }))).toEqual([]);
57
+ });
58
+
53
59
  test('rename, move and usage all read as session.updated', () => {
54
60
  expect(translateWireEvent(wire('session.renamed', { sessionID: 's1', title: 'New' }))[0])
55
61
  .toMatchObject({ type: 'session.updated', properties: { info: { id: 's1', title: 'New' } } });
@@ -58,7 +58,8 @@ The following functions are exported and used by the web server:
58
58
  - `subscribeWorktreeTopologyChanges(listener)`: Listener receives `{ directories, at }`, where `directories` are every directory of that repository the server has observed, so clients can map them onto registered projects. Returns an unsubscribe function.
59
59
  - `validateWorktreeCreate(directory, input)`: Validate worktree creation parameters (mode, branchName, startRef, upstream config).
60
60
  - `createWorktree(directory, input)`: Create a new worktree (supports 'new' and 'existing' modes, upstream setup). When the current tracked branch has no unpublished commits, the UI supplies its remote-tracking ref and this operation fetches that branch once before creating the worktree. A failed fetch falls back to the local branch and reports `sourceFetchFailed`; other remote start refs still require an existing local ref when their fetch fails. After populating the worktree, the repository's `post-checkout` hook runs once with git's standard arguments (null ref as previous HEAD, the checked-out HEAD, and flag `1`) from the worktree directory, mirroring `git worktree add` without `--no-checkout`; a missing or non-executable hook is skipped and a failing hook is logged as a warning, never failing worktree creation or the session bootstrap.
61
- - `removeWorktree(directory, input)`: Remove a worktree (optionally delete local branch).
61
+ - `removeWorktree(directory, input)`: Remove a worktree (optionally delete local branch). `--force` discards uncommitted work, so callers that must keep it snapshot first. A directory that is not a registered worktree is deleted only when it sits inside the managed worktree root; the VS Code runtime (`packages/vscode/src/gitService.ts`) applies the same guard. A registered linked worktree is released through the caller-injected `input.disposeInstance` hook after the match is confirmed and before `git worktree remove`, while the directory path still resolves; disposal is best-effort, so a failing hook is logged as a warning and never fails the removal. `DELETE /api/git/worktrees` builds that hook from the OpenCode URL/auth helpers injected into `registerGitRoutes`. The primary workspace and the orphan fallback never dispose, because neither is a registered linked worktree.
62
+ - `snapshotWorktree(directory, { ref })` (`POST /api/git/worktrees/snapshot`): Record the worktree's complete state (HEAD plus staged, unstaged and untracked-but-not-ignored files) as a commit whose parent is HEAD, stored at `ref`. Only `refs/openchamber/runs/<group>/<session>` refs are accepted, so snapshots never appear as branches or tags. A throwaway index (`GIT_INDEX_FILE`) keeps the real index, HEAD, branch and files untouched; the commit uses a fixed OpenChamber identity. Returns `{ ref, commit, head }`. Used by multi-run Keep and code fusion (`packages/ui/src/lib/multirun/DOCUMENTATION.md`); VS Code implements it in the bridge git runtime.
62
63
  - `isLinkedWorktree(directory)`: Check if directory is a linked worktree (not primary).
63
64
 
64
65
  ### Worktree topology change tracking
@@ -1,4 +1,28 @@
1
- export function registerGitRoutes(app, { emitWorktreeChanged } = {}) {
1
+ import { OpenCode } from '@opencode/client';
2
+
3
+ // A removal should not hang on an unresponsive OpenCode server: disposal is
4
+ // best-effort and `removeWorktree` swallows its failure.
5
+ const WORKTREE_INSTANCE_DISPOSE_TIMEOUT_MS = 5_000;
6
+
7
+ /**
8
+ * Builds the best-effort disposal hook handed to `removeWorktree`. The URL and
9
+ * auth headers are route dependencies, so this module never resolves the
10
+ * OpenCode runtime itself, and both are read at call time. OpenCode 2 has no
11
+ * instance route; evicting the location drops its cached services (file
12
+ * watchers, LSP, MCP), which is what held the worktree folder.
13
+ */
14
+ const createWorktreeInstanceDisposer = ({ buildOpenCodeUrl, getOpenCodeAuthHeaders }) => {
15
+ return async (worktreeDirectory) => {
16
+ const client = OpenCode.make({
17
+ baseUrl: buildOpenCodeUrl('/', '').replace(/\/$/, ''),
18
+ headers: getOpenCodeAuthHeaders(),
19
+ fetch: (input, init) => fetch(input, { ...init, signal: AbortSignal.timeout(WORKTREE_INSTANCE_DISPOSE_TIMEOUT_MS) }),
20
+ });
21
+ await client.debug.location.evict({ location: { directory: worktreeDirectory } });
22
+ };
23
+ };
24
+
25
+ export function registerGitRoutes(app, { emitWorktreeChanged, buildOpenCodeUrl, getOpenCodeAuthHeaders } = {}) {
2
26
  let gitLibraries = null;
3
27
  const getGitLibraries = async () => {
4
28
  if (!gitLibraries) {
@@ -42,6 +66,8 @@ export function registerGitRoutes(app, { emitWorktreeChanged } = {}) {
42
66
 
43
67
  const isNonRepoGitError = (error) => /not a git repository/i.test(extractGitErrorText(error));
44
68
 
69
+ const canDisposeWorktreeInstance = Boolean(buildOpenCodeUrl && getOpenCodeAuthHeaders);
70
+
45
71
  const nonRepoStatusPayload = () => ({
46
72
  isGitRepository: false,
47
73
  files: [],
@@ -1222,6 +1248,9 @@ export function registerGitRoutes(app, { emitWorktreeChanged } = {}) {
1222
1248
  const result = await removeWorktree(directory, {
1223
1249
  directory: worktreeDirectory,
1224
1250
  deleteLocalBranch: req.body?.deleteLocalBranch === true,
1251
+ disposeInstance: canDisposeWorktreeInstance
1252
+ ? createWorktreeInstanceDisposer({ buildOpenCodeUrl, getOpenCodeAuthHeaders })
1253
+ : undefined,
1225
1254
  });
1226
1255
  res.json({ success: Boolean(result) });
1227
1256
  } catch (error) {
@@ -1230,6 +1259,20 @@ export function registerGitRoutes(app, { emitWorktreeChanged } = {}) {
1230
1259
  }
1231
1260
  });
1232
1261
 
1262
+ app.post('/api/git/worktrees/snapshot', async (req, res) => {
1263
+ const { snapshotWorktree } = await getGitLibraries();
1264
+ try {
1265
+ const directory = resolveDirectoryQuery(req.query.directory);
1266
+ if (!directory) {
1267
+ return res.status(400).json({ error: 'directory parameter is required' });
1268
+ }
1269
+ res.json(await snapshotWorktree(directory, { ref: req.body?.ref }));
1270
+ } catch (error) {
1271
+ console.error('Failed to snapshot worktree:', error);
1272
+ res.status(500).json({ error: error.message || 'Failed to snapshot worktree' });
1273
+ }
1274
+ });
1275
+
1233
1276
  app.get('/api/git/worktree-type', async (req, res) => {
1234
1277
  const { isLinkedWorktree } = await getGitLibraries();
1235
1278
  try {