@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
@@ -1,8 +1,9 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
- import { createRoutingRuntime, requestTextOf } from './runtime.js';
2
+ import { createRoutingRuntime, readOpenCodeKeys, requestTextOf } from './runtime.js';
3
3
  import { resolveEffectiveConfig } from './store.js';
4
4
  import { excerptHead, excerptHeadTail, turnsToHistory } from './history.js';
5
5
  import { createJevClient, decidePermission, decideRouting } from './jev.js';
6
+ import { classifierEndpoint, normalizeCustomEndpointUrl, resolveClassifier } from './classifier.js';
6
7
 
7
8
  const AUTO = { providerID: 'openchamber', id: 'auto' };
8
9
  const FALLBACK = { model: { providerID: 'anthropic', modelID: 'claude-sonnet-5' }, variant: 'medium' };
@@ -18,7 +19,7 @@ const readyConfig = () => {
18
19
  return config;
19
20
  };
20
21
 
21
- const makeRuntime = ({ config = readyConfig(), token = 'key', answers, askError } = {}) => {
22
+ const makeRuntime = ({ config = readyConfig(), token = 'key', classifierSource = null, customEndpoint = null, providerKeys = {}, zenPromotionActive = true, enterprise = false, pinned = null, answers, askError } = {}) => {
22
23
  const events = [];
23
24
  const store = {
24
25
  readConfig: vi.fn(async () => config),
@@ -26,6 +27,11 @@ const makeRuntime = ({ config = readyConfig(), token = 'key', answers, askError
26
27
  readToken: vi.fn(async () => token),
27
28
  writeToken: vi.fn(async () => undefined),
28
29
  clearToken: vi.fn(async () => undefined),
30
+ readClassifierSource: vi.fn(async () => classifierSource),
31
+ writeClassifierSource: vi.fn(async () => undefined),
32
+ readCustomEndpoint: vi.fn(async () => customEndpoint),
33
+ writeCustomEndpoint: vi.fn(async () => undefined),
34
+ clearCustomEndpoint: vi.fn(async () => undefined),
29
35
  };
30
36
  const jev = { ask: vi.fn(async () => { if (askError) throw askError; return { answers, ms: 12 }; }) };
31
37
  const runtime = createRoutingRuntime({
@@ -35,6 +41,10 @@ const makeRuntime = ({ config = readyConfig(), token = 'key', answers, askError
35
41
  broadcastGlobalUiEvent: (event) => events.push(event),
36
42
  store,
37
43
  jev,
44
+ readProviderKeys: () => ({ zenKey: null, openrouterKey: null, vercelKey: null, ...providerKeys }),
45
+ zenPromotionActive,
46
+ enterpriseMode: () => enterprise,
47
+ readPinnedEndpoint: () => pinned,
38
48
  });
39
49
  return { runtime, store, jev, events };
40
50
  };
@@ -135,29 +145,130 @@ describe('resolveAutoSelection', () => {
135
145
  });
136
146
 
137
147
  describe('jev endpoint', () => {
138
- const capture = async (token) => {
148
+ const capture = async (source, keys = {}) => {
139
149
  let call = null;
140
150
  const fetchImpl = async (url, init) => {
141
151
  call = { url, init };
142
152
  return { ok: true, status: 200, text: async () => JSON.stringify({ answers: {} }) };
143
153
  };
144
- await createJevClient({ fetchImpl }).ask({ state: 'x', questions: {} }, token);
154
+ await createJevClient({ fetchImpl }).ask({ state: 'x', questions: {} }, classifierEndpoint(source, keys));
145
155
  return { url: call.url, headers: call.init.headers, body: JSON.parse(call.init.body) };
146
156
  };
147
157
 
148
- it('sends a saved key to TypeSafe and falls back to the free model zen serves without one', async () => {
149
- const keyed = await capture('secret');
158
+ it('sends a TypeSafe key to TypeSafe, a Zen key to the paid zen model, and the promotion keyless', async () => {
159
+ const keyed = await capture('typesafe', { typesafeKey: 'secret' });
150
160
  expect(keyed.url).toBe('https://api.typesafe.ai/v1/systemone');
151
161
  expect(keyed.headers.authorization).toBe('Bearer secret');
152
162
  expect(keyed.body.model).toBe('jev-latest');
153
163
 
154
- const free = await capture(null);
164
+ const zen = await capture('zen-key', { zenKey: 'zen-secret' });
165
+ expect(zen.url).toBe('https://opencode.ai/zen/v1/systemone');
166
+ expect(zen.headers.authorization).toBe('Bearer zen-secret');
167
+ expect(zen.headers['x-opencode-client']).toBe('openchamber');
168
+ expect(zen.body.model).toBe('jev-1.13');
169
+
170
+ const free = await capture('zen-promo');
155
171
  expect(free.url).toBe('https://opencode.ai/zen/v1/systemone');
156
172
  expect(free.headers.authorization).toBeUndefined();
157
173
  // Zen counts our calls by this header, and does not know the `jev-latest` alias.
158
174
  expect(free.headers['x-opencode-client']).toBe('openchamber');
159
175
  expect(free.body.model).toBe('jev-1.13-free');
160
176
  });
177
+
178
+ it('sends the OpenCode-saved OpenRouter and Vercel keys to their System One routes, without the zen header', async () => {
179
+ const openrouter = await capture('openrouter', { openrouterKey: 'or-secret' });
180
+ expect(openrouter.url).toBe('https://openrouter.ai/api/v1/systemone');
181
+ expect(openrouter.headers.authorization).toBe('Bearer or-secret');
182
+ expect(openrouter.headers['x-opencode-client']).toBeUndefined();
183
+ expect(openrouter.body.model).toBe('jev-latest');
184
+
185
+ const vercel = await capture('vercel', { vercelKey: 'gw-secret' });
186
+ expect(vercel.url).toBe('https://ai-gateway.vercel.sh/typesafe/v1/systemone');
187
+ expect(vercel.headers.authorization).toBe('Bearer gw-secret');
188
+ expect(vercel.headers['x-opencode-client']).toBeUndefined();
189
+ expect(vercel.body.model).toBe('typesafe-ai/jev');
190
+ });
191
+
192
+ it('sends a custom endpoint its own URL and model, with the key as a bearer only when one is saved', async () => {
193
+ const url = 'https://jev.example.com/v1/systemone';
194
+ const keyed = await capture('custom', { customEndpoint: { url, model: 'jev-1.13', key: 'own-secret' } });
195
+ expect(keyed.url).toBe(url);
196
+ expect(keyed.body.model).toBe('jev-1.13');
197
+ expect(keyed.headers.authorization).toBe('Bearer own-secret');
198
+ expect(keyed.headers['x-opencode-client']).toBeUndefined();
199
+
200
+ const keyless = await capture('custom', { customEndpoint: { url, model: 'jev-latest' } });
201
+ expect(keyless.headers.authorization).toBeUndefined();
202
+ });
203
+ });
204
+
205
+ describe('normalizeCustomEndpointUrl', () => {
206
+ it('takes the full System One URL, an OpenAI-style /v1 base, or an API root', () => {
207
+ expect(normalizeCustomEndpointUrl(' https://openrouter.ai/api/v1/systemone/ ')).toBe('https://openrouter.ai/api/v1/systemone');
208
+ expect(normalizeCustomEndpointUrl('https://openrouter.ai/api/v1')).toBe('https://openrouter.ai/api/v1/systemone');
209
+ expect(normalizeCustomEndpointUrl('https://api.typesafe.ai')).toBe('https://api.typesafe.ai/v1/systemone');
210
+ expect(normalizeCustomEndpointUrl('http://127.0.0.1:8080/jev/')).toBe('http://127.0.0.1:8080/jev/v1/systemone');
211
+ });
212
+
213
+ it('refuses other schemes, credentials in the URL and non-URLs', () => {
214
+ expect(() => normalizeCustomEndpointUrl('ftp://example.com')).toThrow(expect.objectContaining({ status: 400 }));
215
+ expect(() => normalizeCustomEndpointUrl('file:///etc/passwd')).toThrow(expect.objectContaining({ status: 400 }));
216
+ expect(() => normalizeCustomEndpointUrl('https://user:secret@example.com/v1')).toThrow(expect.objectContaining({ status: 400 }));
217
+ expect(() => normalizeCustomEndpointUrl('example.com/v1')).toThrow(expect.objectContaining({ status: 400 }));
218
+ });
219
+ });
220
+
221
+ describe('resolveClassifier', () => {
222
+ it('defaults to a saved TypeSafe key, else off', () => {
223
+ expect(resolveClassifier({ selected: null, typesafeKey: 'k', zenKey: null, zenPromotionActive: true })).toMatchObject({ selected: 'typesafe', effective: 'typesafe' });
224
+ expect(resolveClassifier({ selected: null, typesafeKey: null, zenKey: 'z', openrouterKey: 'o', zenPromotionActive: true })).toMatchObject({ selected: 'off', effective: null });
225
+ });
226
+
227
+ it('keeps off off, whatever is usable', () => {
228
+ expect(resolveClassifier({ selected: 'off', typesafeKey: 'k', zenKey: 'z', zenPromotionActive: true }).effective).toBeNull();
229
+ });
230
+
231
+ it('falls back to the first usable key when the pick cannot be used, never to the promotion', () => {
232
+ expect(resolveClassifier({ selected: 'zen-promo', typesafeKey: null, zenKey: 'z', zenPromotionActive: false }).effective).toBe('zen-key');
233
+ expect(resolveClassifier({ selected: 'typesafe', typesafeKey: null, zenKey: null, zenPromotionActive: true }).effective).toBeNull();
234
+ expect(resolveClassifier({ selected: 'zen-promo', typesafeKey: null, zenKey: null, zenPromotionActive: false }).effective).toBeNull();
235
+ expect(resolveClassifier({ selected: 'zen-promo', typesafeKey: null, zenKey: 'z', vercelKey: 'v', zenPromotionActive: false }).effective).toBe('vercel');
236
+ expect(resolveClassifier({ selected: 'vercel', typesafeKey: null, openrouterKey: 'o', zenPromotionActive: true }).effective).toBe('openrouter');
237
+ });
238
+
239
+ it('keeps a usable OpenRouter or Vercel pick', () => {
240
+ expect(resolveClassifier({ selected: 'openrouter', typesafeKey: 'k', openrouterKey: 'o', zenPromotionActive: true }).effective).toBe('openrouter');
241
+ expect(resolveClassifier({ selected: 'vercel', vercelKey: 'v', zenPromotionActive: true }).effective).toBe('vercel');
242
+ });
243
+
244
+ it('uses a saved custom endpoint when picked, and falls back to it after TypeSafe and before OpenCode keys', () => {
245
+ const customEndpoint = { url: 'https://jev.example.com/v1/systemone', model: 'jev-latest' };
246
+ expect(resolveClassifier({ selected: 'custom', customEndpoint, openrouterKey: 'o', zenPromotionActive: true }).effective).toBe('custom');
247
+ expect(resolveClassifier({ selected: 'custom', customEndpoint: null, vercelKey: 'v', zenPromotionActive: true }).effective).toBe('vercel');
248
+ expect(resolveClassifier({ selected: 'custom', customEndpoint: null, zenPromotionActive: true }).effective).toBeNull();
249
+ expect(resolveClassifier({ selected: 'openrouter', customEndpoint, vercelKey: 'v', zenPromotionActive: true }).effective).toBe('custom');
250
+ expect(resolveClassifier({ selected: 'zen-key', typesafeKey: 'k', customEndpoint, zenPromotionActive: true }).effective).toBe('typesafe');
251
+ expect(resolveClassifier({ selected: 'off', customEndpoint, zenPromotionActive: true }).effective).toBeNull();
252
+ });
253
+ });
254
+
255
+ describe('readOpenCodeKeys', () => {
256
+ const env = { OPENROUTER_API_KEY: 'or-env', AI_GATEWAY_API_KEY: ' gw-env ' };
257
+
258
+ it('prefers a key saved in OpenCode and falls back to the variable OpenCode reads', () => {
259
+ const readAuth = () => ({
260
+ opencode: { type: 'api', key: 'zen' },
261
+ openrouter: { type: 'api', key: 'or-saved' },
262
+ vercel: { type: 'oauth', access: 'a', refresh: 'r', expires: 0 },
263
+ });
264
+ expect(readOpenCodeKeys({ readAuth, env })).toEqual({ zenKey: 'zen', openrouterKey: 'or-saved', vercelKey: 'gw-env' });
265
+ });
266
+
267
+ it('keeps the variables when the credential store cannot be read, and ignores blank ones', () => {
268
+ const readAuth = () => { throw new Error('locked'); };
269
+ expect(readOpenCodeKeys({ readAuth, env })).toEqual({ zenKey: null, openrouterKey: 'or-env', vercelKey: 'gw-env' });
270
+ expect(readOpenCodeKeys({ readAuth: () => ({}), env: { OPENROUTER_API_KEY: ' ' } })).toEqual({ zenKey: null, openrouterKey: null, vercelKey: null });
271
+ });
161
272
  });
162
273
 
163
274
  describe('auto sessions', () => {
@@ -185,28 +296,201 @@ describe('evaluatePermission', () => {
185
296
  expect(runtime.heldPermissions()).toEqual([]);
186
297
  });
187
298
 
188
- it('accepts when Jev is unreachable and tells the UI it skipped', async () => {
189
- const { runtime, events } = makeRuntime({ askError: Object.assign(new Error('Jev timed out after 4000ms'), { code: 'timeout' }) });
190
- expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'accept', skipped: 'Jev timed out after 4000ms' });
299
+ it('accepts a safe permission', async () => {
300
+ const { runtime } = makeRuntime({ answers: { ask: { noul: 0.1 }, kind: { choice: 'read_only' } } });
301
+ expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'accept', score: 0.1, kind: 'read_only' });
302
+ });
303
+
304
+ it('holds when Jev is unreachable, tells the UI why, and asks again next time', async () => {
305
+ const { runtime, events, jev } = makeRuntime({ askError: Object.assign(new Error('Jev timed out after 4000ms'), { code: 'timeout' }) });
306
+ expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'hold', skipped: 'Jev timed out after 4000ms' });
191
307
  expect(events.at(-1)).toMatchObject({ type: 'openchamber:routing.safety-skipped', properties: { permissionId: 'p1', error: 'Jev timed out after 4000ms' } });
308
+ await runtime.evaluatePermission(permission, '/repo');
309
+ expect(jev.ask).toHaveBeenCalledTimes(2);
310
+ expect(runtime.heldPermissions()).toEqual([]);
311
+ });
312
+
313
+ it('holds quietly without asking when no classification provider is usable', async () => {
314
+ const { runtime, jev, events } = makeRuntime({ token: null, zenPromotionActive: false, answers: {} });
315
+ expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'hold', unavailable: true });
316
+ expect(jev.ask).not.toHaveBeenCalled();
317
+ expect(events).toEqual([]);
192
318
  });
193
319
 
194
- it('accepts without asking when the safety net is off', async () => {
320
+ it('works whether or not Auto routing is on', async () => {
321
+ const config = readyConfig();
322
+ config.enabled = false;
323
+ config.safetyNet.enabled = false;
324
+ const { runtime, jev } = makeRuntime({ config, answers: { ask: { noul: 0.9 } } });
325
+ expect(await runtime.evaluatePermission(permission, '/repo')).toMatchObject({ action: 'hold', score: 0.9 });
326
+ expect(jev.ask).toHaveBeenCalledTimes(1);
327
+ });
328
+
329
+ it('reads the old global safety-net switch for the policy conversion', async () => {
330
+ expect(await makeRuntime({ answers: {} }).runtime.legacySafetyNetEnabled()).toBe(true);
195
331
  const off = readyConfig();
196
332
  off.safetyNet.enabled = false;
197
- const { runtime, jev } = makeRuntime({ config: off, answers: {} });
198
- expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'accept' });
333
+ expect(await makeRuntime({ config: off, answers: {} }).runtime.legacySafetyNetEnabled()).toBe(false);
334
+ });
335
+ });
336
+
337
+ describe('classifier pick', () => {
338
+ it('stores a known source and refuses an unknown one', async () => {
339
+ const { runtime, store } = makeRuntime({ answers: {} });
340
+ await runtime.setClassifierSource('zen-key');
341
+ expect(store.writeClassifierSource).toHaveBeenCalledWith('zen-key');
342
+ await runtime.setClassifierSource('openrouter');
343
+ expect(store.writeClassifierSource).toHaveBeenCalledWith('openrouter');
344
+ await runtime.setClassifierSource('off');
345
+ expect(store.writeClassifierSource).toHaveBeenCalledWith('off');
346
+ await expect(runtime.setClassifierSource('cloudflare')).rejects.toMatchObject({ status: 400 });
347
+ });
348
+
349
+ it('keeps Jev off in enterprise mode, whatever is picked or saved', async () => {
350
+ const { runtime, store, jev } = makeRuntime({ enterprise: true, classifierSource: 'typesafe', answers: { ask: { noul: 0.1 } } });
351
+ expect(await runtime.describe()).toMatchObject({ enterpriseMode: true, jevAvailable: false, autoReady: false, classification: { selected: 'off', effective: null } });
352
+ expect(await runtime.classifierEndpoint()).toBeNull();
353
+ await expect(runtime.setClassifierSource('zen-promo')).rejects.toMatchObject({ status: 403 });
354
+ await expect(runtime.setToken('secret')).rejects.toMatchObject({ status: 403 });
355
+ await runtime.setClassifierSource('off');
356
+ expect(store.writeClassifierSource).toHaveBeenCalledTimes(1);
357
+ expect(store.writeToken).not.toHaveBeenCalled();
199
358
  expect(jev.ask).not.toHaveBeenCalled();
200
359
  });
360
+
361
+ describe('an endpoint pinned in the server environment', () => {
362
+ const pinned = { url: 'https://jev.company.test/v1/systemone', model: 'jev-latest', key: 'org-secret' };
363
+ const saved = { url: 'https://mine.example.com/v1/systemone', model: 'jev-latest' };
364
+
365
+ it('replaces the saved one, cannot be edited, and never shows its key', async () => {
366
+ const { runtime, store } = makeRuntime({ pinned, customEndpoint: saved, classifierSource: 'custom', answers: {} });
367
+ const state = await runtime.describe();
368
+ expect(state.customEndpoint).toEqual({ url: pinned.url, model: 'jev-latest', keyPresent: true, pinned: true });
369
+ expect(JSON.stringify(state)).not.toContain('org-secret');
370
+ expect(await runtime.classifierEndpoint()).toMatchObject({ url: pinned.url, headers: { authorization: 'Bearer org-secret' } });
371
+ await expect(runtime.setCustomEndpoint({ url: saved.url, model: 'x' })).rejects.toMatchObject({ status: 409 });
372
+ await expect(runtime.clearCustomEndpoint()).rejects.toMatchObject({ status: 409 });
373
+ expect(store.writeCustomEndpoint).not.toHaveBeenCalled();
374
+ });
375
+
376
+ it('is the enterprise default, with Off as the only other choice', async () => {
377
+ const { runtime, store } = makeRuntime({ enterprise: true, pinned, classifierSource: 'typesafe', answers: {} });
378
+ expect(await runtime.describe()).toMatchObject({ jevAvailable: true, classification: { selected: 'custom', effective: 'custom' } });
379
+ await runtime.setClassifierSource('custom');
380
+ await runtime.setClassifierSource('off');
381
+ await expect(runtime.setClassifierSource('typesafe')).rejects.toMatchObject({ status: 403 });
382
+ expect(store.writeClassifierSource.mock.calls.map(([source]) => source)).toEqual(['custom', 'off']);
383
+
384
+ const off = makeRuntime({ enterprise: true, pinned, classifierSource: 'off', answers: {} });
385
+ expect(await off.runtime.describe()).toMatchObject({ jevAvailable: false, classification: { selected: 'off' } });
386
+ });
387
+ });
388
+
389
+ it('picks TypeSafe when a key is saved', async () => {
390
+ const { runtime, store } = makeRuntime({ answers: {} });
391
+ await runtime.setToken('secret');
392
+ expect(store.writeClassifierSource).toHaveBeenCalledWith('typesafe');
393
+ });
394
+
395
+ it('saves a custom endpoint with its URL normalized and picks it', async () => {
396
+ const { runtime, store } = makeRuntime({ answers: {} });
397
+ await runtime.setCustomEndpoint({ url: 'https://jev.example.com/v1/', model: ' jev-latest ', key: ' own-secret ' });
398
+ expect(store.writeCustomEndpoint).toHaveBeenCalledWith({ url: 'https://jev.example.com/v1/systemone', model: 'jev-latest', key: 'own-secret' });
399
+ expect(store.writeClassifierSource).toHaveBeenCalledWith('custom');
400
+ });
401
+
402
+ it('keeps the saved custom key when none is sent, and removes it on null', async () => {
403
+ const saved = { url: 'https://jev.example.com/v1/systemone', model: 'jev-latest', key: 'own-secret' };
404
+ const { runtime, store } = makeRuntime({ customEndpoint: saved, answers: {} });
405
+ await runtime.setCustomEndpoint({ url: saved.url, model: 'jev-1.13', key: '' });
406
+ expect(store.writeCustomEndpoint).toHaveBeenLastCalledWith({ ...saved, model: 'jev-1.13' });
407
+ await runtime.setCustomEndpoint({ url: saved.url, model: 'jev-1.13' });
408
+ expect(store.writeCustomEndpoint).toHaveBeenLastCalledWith({ ...saved, model: 'jev-1.13' });
409
+ const picksBefore = store.writeClassifierSource.mock.calls.length;
410
+ await runtime.setCustomEndpoint({ url: saved.url, model: 'jev-1.13', key: null });
411
+ expect(store.writeCustomEndpoint).toHaveBeenLastCalledWith({ url: saved.url, model: 'jev-1.13' });
412
+ // Removing the key alone leaves whatever provider the user picked.
413
+ expect(store.writeClassifierSource).toHaveBeenCalledTimes(picksBefore);
414
+ });
415
+
416
+ it('refuses a custom endpoint without a URL or model, or with an unsafe URL, and saves nothing', async () => {
417
+ const { runtime, store } = makeRuntime({ answers: {} });
418
+ await expect(runtime.setCustomEndpoint({ url: 'https://jev.example.com', model: '' })).rejects.toMatchObject({ status: 400 });
419
+ await expect(runtime.setCustomEndpoint({ model: 'jev-latest' })).rejects.toMatchObject({ status: 400 });
420
+ await expect(runtime.setCustomEndpoint({ url: 'file:///etc/hosts', model: 'jev-latest' })).rejects.toMatchObject({ status: 400 });
421
+ await expect(runtime.setCustomEndpoint({ url: 'https://me:pw@jev.example.com', model: 'jev-latest' })).rejects.toMatchObject({ status: 400 });
422
+ expect(store.writeCustomEndpoint).not.toHaveBeenCalled();
423
+ expect(store.writeClassifierSource).not.toHaveBeenCalled();
424
+ });
425
+
426
+ it('refuses a custom endpoint in enterprise mode', async () => {
427
+ const { runtime, store } = makeRuntime({ enterprise: true, answers: {} });
428
+ await expect(runtime.setCustomEndpoint({ url: 'https://jev.example.com', model: 'jev-latest', key: 'k' })).rejects.toMatchObject({ status: 403 });
429
+ await expect(runtime.setClassifierSource('custom')).rejects.toMatchObject({ status: 403 });
430
+ expect(store.writeCustomEndpoint).not.toHaveBeenCalled();
431
+ await runtime.clearCustomEndpoint();
432
+ expect(store.clearCustomEndpoint).toHaveBeenCalledTimes(1);
433
+ });
434
+
435
+ it('keeps Jev off in enterprise mode even with a custom endpoint picked', async () => {
436
+ const customEndpoint = { url: 'https://jev.example.com/v1/systemone', model: 'jev-latest' };
437
+ const { runtime } = makeRuntime({ enterprise: true, token: null, classifierSource: 'custom', customEndpoint, answers: {} });
438
+ expect(await runtime.classifierEndpoint()).toBeNull();
439
+ });
201
440
  });
202
441
 
203
442
  describe('describe', () => {
204
443
  it('reports Auto ready with an enabled config, a fallback and two categories, key or no key', async () => {
205
444
  expect((await makeRuntime({ answers: {} }).runtime.describe())).toMatchObject({ autoReady: true, tokenPresent: true, jevSource: 'typesafe' });
206
- // Without a key the free Jev model on zen answers, so Auto stays available.
207
- expect((await makeRuntime({ token: null, answers: {} }).runtime.describe())).toMatchObject({ autoReady: true, tokenPresent: false, jevSource: 'zen-free' });
445
+ // Without a key, a picked promotion answers, so Auto stays available.
446
+ expect((await makeRuntime({ token: null, classifierSource: 'zen-promo', answers: {} }).runtime.describe())).toMatchObject({ autoReady: true, jevAvailable: true, tokenPresent: false, jevSource: 'zen-free' });
447
+ // Nothing picked and no key: off, so no Jev and no Auto.
448
+ expect((await makeRuntime({ token: null, answers: {} }).runtime.describe())).toMatchObject({
449
+ autoReady: false,
450
+ jevAvailable: false,
451
+ classification: { selected: 'off', effective: null },
452
+ });
453
+ // No usable classification provider: no Jev, so no Auto.
454
+ expect((await makeRuntime({ token: null, classifierSource: 'zen-promo', zenPromotionActive: false, answers: {} }).runtime.describe())).toMatchObject({
455
+ autoReady: false,
456
+ jevAvailable: false,
457
+ classifier: { selected: 'zen-promo', effective: null },
458
+ });
208
459
  const one = readyConfig();
209
460
  one.categories = one.categories.map((c, i) => ({ ...c, enabled: i === 0 }));
210
461
  expect((await makeRuntime({ config: one, answers: {} }).runtime.describe()).autoReady).toBe(false);
211
462
  });
463
+
464
+ it('keeps `classifier` parseable for v2.0.2 clients and puts the full picture in `classification`', async () => {
465
+ const zen = await makeRuntime({ token: null, classifierSource: 'zen-promo', answers: {} }).runtime.describe();
466
+ expect(zen.classifier.sources.map((s) => s.id)).toEqual(['zen-promo', 'zen-key', 'typesafe']);
467
+ expect(zen.classification.sources.map((s) => s.id)).toEqual(['off', 'zen-promo', 'zen-key', 'openrouter', 'vercel', 'typesafe', 'custom']);
468
+
469
+ const off = await makeRuntime({ token: null, answers: {} }).runtime.describe();
470
+ expect(off.classifier).toBeNull();
471
+
472
+ const routed = await makeRuntime({ classifierSource: 'openrouter', providerKeys: { openrouterKey: 'o' }, answers: {} }).runtime.describe();
473
+ expect(routed.classifier).toBeNull();
474
+ expect(routed.classification).toMatchObject({ selected: 'openrouter', effective: 'openrouter' });
475
+ expect(routed.jevAvailable).toBe(true);
476
+ });
477
+
478
+ it('describes a custom endpoint without its key and hides it from v2.0.2 clients', async () => {
479
+ const customEndpoint = { url: 'https://jev.example.com/v1/systemone', model: 'jev-latest', key: 'own-secret' };
480
+ const state = await makeRuntime({ token: null, classifierSource: 'custom', customEndpoint, answers: {} }).runtime.describe();
481
+ expect(state.customEndpoint).toEqual({ url: customEndpoint.url, model: 'jev-latest', keyPresent: true, pinned: false });
482
+ expect(JSON.stringify(state)).not.toContain('own-secret');
483
+ expect(state.classifier).toBeNull();
484
+ expect(state.classification).toMatchObject({ selected: 'custom', effective: 'custom' });
485
+ expect(state.jevAvailable).toBe(true);
486
+
487
+ // Falling back onto the custom endpoint hides the legacy view too.
488
+ const fallback = await makeRuntime({ token: null, classifierSource: 'zen-key', customEndpoint, answers: {} }).runtime.describe();
489
+ expect(fallback.classification.effective).toBe('custom');
490
+ expect(fallback.classifier).toBeNull();
491
+
492
+ const none = await makeRuntime({ token: null, answers: {} }).runtime.describe();
493
+ expect(none.customEndpoint).toBeNull();
494
+ expect(none.classification.sources.find((s) => s.id === 'custom')).toEqual({ id: 'custom', usable: false });
495
+ });
212
496
  });
@@ -5,6 +5,10 @@
5
5
  * disabled built-in category, a user category, the fallback model, thresholds.
6
6
  * `routing-auth.json` holds the Jev API key alone, mode 0600, so the config
7
7
  * file can be read, shown and exported without carrying a secret.
8
+ * `classification.json` holds which classification provider answers Jev
9
+ * requests (see `classifier.js`). `classifier-endpoint.json` holds the custom
10
+ * System One endpoint (URL, model, optional key), mode 0600 like the key file;
11
+ * a file of its own so saving one never rewrites the other.
8
12
  *
9
13
  * Reads never throw on a missing file (a fresh install is the defaults); a
10
14
  * malformed file is an error, not an empty config, so a bad write cannot
@@ -20,6 +24,7 @@ import {
20
24
  THINKING_LEVELS,
21
25
  isAutoModel,
22
26
  } from './defaults.js';
27
+ import { CLASSIFIER_SOURCES, normalizeCustomEndpointUrl } from './classifier.js';
23
28
 
24
29
  const FILE_VERSION = 1;
25
30
  const CATEGORY_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
@@ -87,8 +92,29 @@ const effectiveConfigSchema = z.object({
87
92
 
88
93
  const authSchema = z.object({ token: z.string().min(1).max(4000) }).strict();
89
94
 
95
+ const classifierSchema = z.object({ version: z.literal(FILE_VERSION), source: z.enum(CLASSIFIER_SOURCES) }).strict();
96
+
97
+ const isNormalizedEndpointUrl = (url) => {
98
+ try {
99
+ return normalizeCustomEndpointUrl(url) === url;
100
+ } catch {
101
+ return false;
102
+ }
103
+ };
104
+
105
+ // A hand-edited URL that the setter would not have produced is not an endpoint.
106
+ const customEndpointSchema = z.object({
107
+ url: z.string().max(2000).refine(isNormalizedEndpointUrl, { message: 'Invalid endpoint URL' }),
108
+ model: z.string().trim().min(1).max(200),
109
+ key: z.string().min(1).max(4000).optional(),
110
+ }).strict();
111
+
112
+ const customEndpointFileSchema = z.object({ version: z.literal(FILE_VERSION), endpoint: customEndpointSchema }).strict();
113
+
90
114
  const routingConfigPath = (dataDir) => path.join(dataDir, 'routing.json');
91
115
  const routingAuthPath = (dataDir) => path.join(dataDir, 'routing-auth.json');
116
+ const classifierPath = (dataDir) => path.join(dataDir, 'classification.json');
117
+ const customEndpointPath = (dataDir) => path.join(dataDir, 'classifier-endpoint.json');
92
118
 
93
119
  const readJsonFile = async (file, schema) => {
94
120
  let raw;
@@ -219,6 +245,8 @@ export const parseEffectiveConfig = (input) => {
219
245
  export const createRoutingStore = ({ dataDir }) => {
220
246
  const configFile = routingConfigPath(dataDir);
221
247
  const authFile = routingAuthPath(dataDir);
248
+ const classifierFile = classifierPath(dataDir);
249
+ const customEndpointFile = customEndpointPath(dataDir);
222
250
  let writeChain = Promise.resolve();
223
251
  const serialize = (run) => {
224
252
  const next = writeChain.catch(() => undefined).then(run);
@@ -245,5 +273,34 @@ export const createRoutingStore = ({ dataDir }) => {
245
273
  clearToken: () => serialize(async () => {
246
274
  await fs.rm(authFile, { force: true });
247
275
  }),
276
+ /**
277
+ * The classification provider the user picked, or null before any pick.
278
+ * An unreadable file is treated as no pick: the default source still
279
+ * serves, and the next pick rewrites it.
280
+ */
281
+ readClassifierSource: async () => {
282
+ try {
283
+ return (await readJsonFile(classifierFile, classifierSchema))?.source ?? null;
284
+ } catch (error) {
285
+ console.warn('[routing] classification.json is unreadable:', error?.message ?? error);
286
+ return null;
287
+ }
288
+ },
289
+ writeClassifierSource: (source) => serialize(() => writeJsonFile(classifierFile, { version: FILE_VERSION, source })),
290
+ /** The custom endpoint, or null when none is saved. Unreadable reads as none, like the key file. */
291
+ readCustomEndpoint: async () => {
292
+ try {
293
+ return (await readJsonFile(customEndpointFile, customEndpointFileSchema))?.endpoint ?? null;
294
+ } catch (error) {
295
+ // V8 quotes the broken text in a JSON syntax error, and this file holds a key.
296
+ const reason = error instanceof SyntaxError ? 'malformed JSON' : error?.message ?? error;
297
+ console.warn('[routing] classifier-endpoint.json is unreadable:', reason);
298
+ return null;
299
+ }
300
+ },
301
+ writeCustomEndpoint: (endpoint) => serialize(() => writeJsonFile(customEndpointFile, { version: FILE_VERSION, endpoint }, 0o600)),
302
+ clearCustomEndpoint: () => serialize(async () => {
303
+ await fs.rm(customEndpointFile, { force: true });
304
+ }),
248
305
  };
249
306
  };
@@ -93,4 +93,41 @@ describe('routing store', () => {
93
93
  await store.clearToken();
94
94
  expect(await store.readToken()).toBeNull();
95
95
  });
96
+
97
+ it('round-trips the classifier pick and reads a broken file as no pick', async () => {
98
+ const dir = await tempDir();
99
+ const store = createRoutingStore({ dataDir: dir });
100
+ expect(await store.readClassifierSource()).toBeNull();
101
+ await store.writeClassifierSource('zen-key');
102
+ expect(await store.readClassifierSource()).toBe('zen-key');
103
+ await fs.writeFile(path.join(dir, 'classification.json'), '{"version":1,"source":"cloudflare"}');
104
+ expect(await store.readClassifierSource()).toBeNull();
105
+ await store.writeClassifierSource('custom');
106
+ expect(await store.readClassifierSource()).toBe('custom');
107
+ });
108
+
109
+ it('keeps the custom endpoint in its own 0600 file, round-trips it and clears it', async () => {
110
+ const dir = await tempDir();
111
+ const store = createRoutingStore({ dataDir: dir });
112
+ expect(await store.readCustomEndpoint()).toBeNull();
113
+ const endpoint = { url: 'https://jev.example.com/v1/systemone', model: 'jev-latest', key: 'own-secret' };
114
+ await store.writeCustomEndpoint(endpoint);
115
+ await store.writeToken('ts-secret');
116
+ expect(await store.readCustomEndpoint()).toEqual(endpoint);
117
+ expect(await store.readToken()).toBe('ts-secret');
118
+ const stat = await fs.stat(path.join(dir, 'classifier-endpoint.json'));
119
+ if (process.platform !== 'win32') expect(stat.mode & 0o777).toBe(0o600);
120
+ await store.writeCustomEndpoint({ url: endpoint.url, model: 'jev-1.13' });
121
+ expect(await store.readCustomEndpoint()).toEqual({ url: endpoint.url, model: 'jev-1.13' });
122
+ await store.clearCustomEndpoint();
123
+ expect(await store.readCustomEndpoint()).toBeNull();
124
+ expect(await store.readToken()).toBe('ts-secret');
125
+ });
126
+
127
+ it('reads a hand-edited custom endpoint with an unsafe URL as none', async () => {
128
+ const dir = await tempDir();
129
+ const store = createRoutingStore({ dataDir: dir });
130
+ await fs.writeFile(path.join(dir, 'classifier-endpoint.json'), JSON.stringify({ version: 1, endpoint: { url: 'file:///etc/hosts', model: 'jev-latest' } }));
131
+ expect(await store.readCustomEndpoint()).toBeNull();
132
+ });
96
133
  });
@@ -87,8 +87,16 @@ model context is small. Page/count bounds are not a network-byte quota.
87
87
 
88
88
  ## Generation and lifecycle
89
89
 
90
- 1. The server's existing global event fan-out calls `processPayload`. An idle
91
- event arms the 60-second quiet window. No history scan or startup backfill runs.
90
+ 1. The server's existing global event fan-out calls `processPayload`. At an
91
+ idle event the runtime first asks the injected `evaluateTurn` (the
92
+ session-work runtime, `../session-work/DOCUMENTATION.md`): one Jev call says
93
+ which enabled fields are worth the Small Model. It then arms the 60-second
94
+ quiet window for those fields only, and arms nothing when Jev ruled both out.
95
+ An unknown answer (no Jev, a failure) keeps every enabled field, so without
96
+ Jev nothing changes. A newer event drops a pending answer. A session that
97
+ `../session-lineage.js` knows to be a subsession arms nothing at all: no
98
+ gate, no timer, no read. No history scan or
99
+ startup backfill runs.
92
100
  2. Busy/retry events and newly created user messages clear pending work and
93
101
  abort in-flight reads/generation. Re-emitted old user updates do not cancel it.
94
102
  3. One generation runs per session. If a newer quiet window expires while an
@@ -117,7 +125,9 @@ No failed session blocks another session.
117
125
  ## Settings and consumers
118
126
 
119
127
  `sessionRecapEnabled` and `sessionSuggestionEnabled` default on and are checked
120
- before work and before writing. With both off there are no reads, model calls,
128
+ before work and before writing. The Jev gate is a cost filter under these same
129
+ switches, not a setting of its own: it reads the same three turns as the recap,
130
+ so a recap still follows a closing "thanks" after real work. With both off there are no reads, model calls,
121
131
  or writes. With one on, the shared recent context is still available, but only
122
132
  that field is requested. An empty suggestion does not erase a valid recap.
123
133
 
@@ -136,10 +146,10 @@ payloads written by an earlier process; the `time.idle` rule retires those.
136
146
  - `packages/ui/src/hooks/useSessionAssist.ts` adds live-status and settings gating.
137
147
  - `SessionRecapSpacer` shows the reminder in the reserved gap under the reply.
138
148
  - `SessionSuggestionChip` fills the composer; it never sends automatically.
139
- - Sidebar rows (`SessionNodeItem`, both Projects and Timeline) mark a session
140
- whose suggestion is still open with a small icon and the suggestion as its
141
- title, using the same freshness rule (`getOpenSessionSuggestion`). The marker hides while a turn runs, on the open session, and
142
- when `sessionSuggestionEnabled` is off.
149
+ - Sidebar rows (`SessionNodeItem`, Projects view) show the current recap in
150
+ the whole-row tooltip under the same freshness rule, hidden while a turn runs
151
+ and when `sessionRecapEnabled` is off. The sidebar no longer marks open
152
+ suggestions; the "In work" block is the sidebar's attention signal.
143
153
 
144
154
  Web, Electron, hosted mobile, and Capacitor use the server watcher. VS Code's
145
155
  extension-only runtime does not generate assists; shared UI can render payloads
@@ -110,6 +110,7 @@ function readMessage(message) {
110
110
  return {
111
111
  id: message.id,
112
112
  role,
113
+ created: Number.isFinite(message.time?.created) ? message.time.created : null,
113
114
  transparent: isTransparent(message),
114
115
  // v2 has no `parentID` on a message: a turn is the run of messages between
115
116
  // one user message and the assistant reply that follows it, which is what
@@ -134,7 +135,7 @@ function readMessage(message) {
134
135
  * about to send — v1 carried them as parts of that user message — so they are
135
136
  * folded into the next user message instead of opening a turn of their own.
136
137
  */
137
- function collectTurns(messages) {
138
+ function collectTurns(messages, limit = TURN_LIMIT) {
138
139
  const turns = [];
139
140
  let active = null;
140
141
  let attached = [];
@@ -158,7 +159,46 @@ function collectTurns(messages) {
158
159
  if (message.text) active.assistant = message;
159
160
  active.complete = message.complete && Boolean(message.text);
160
161
  }
161
- return turns.slice(-TURN_LIMIT);
162
+ return turns.slice(-limit);
163
+ }
164
+
165
+ const settledTurns = (messages) => collectTurns(messages, Infinity)
166
+ .filter((turn) => turn.complete)
167
+ .slice(-TURN_LIMIT);
168
+
169
+ /**
170
+ * The settled turns before a message that was just sent, oldest first: what a
171
+ * classifier reads next to the new request. The newest records may already
172
+ * hold that message (and nothing after it); a turn without a completed answer
173
+ * is not settled and is left out. Failure is thrown; an empty list means the
174
+ * session has no settled turn yet.
175
+ */
176
+ export async function loadSettledTurns({ readPage, signal }) {
177
+ let messages = [];
178
+ let cursor;
179
+ const cursors = new Set();
180
+ const ids = new Set();
181
+ for (let pageNumber = 0; pageNumber < MAX_PAGES; pageNumber++) {
182
+ signal.throwIfAborted();
183
+ const page = await readPage({ limit: PAGE_SIZE, cursor });
184
+ signal.throwIfAborted();
185
+ if (!Array.isArray(page?.data)) throw new Error('Session message page is unavailable');
186
+ const older = [];
187
+ for (const record of page.data) {
188
+ if (!record?.id || ids.has(record.id)) continue;
189
+ ids.add(record.id);
190
+ older.push(readMessage(record));
191
+ }
192
+ older.reverse();
193
+ messages = older.concat(messages);
194
+ const settled = settledTurns(messages);
195
+ const next = typeof page.cursor?.next === 'string' ? page.cursor.next : null;
196
+ if (settled.length === TURN_LIMIT || !next) return settled;
197
+ if (cursors.has(next)) throw new Error('Session message pagination made no progress');
198
+ cursors.add(next);
199
+ cursor = next;
200
+ }
201
+ return settledTurns(messages);
162
202
  }
163
203
 
164
204
  /** Failure is thrown; null means no eligible final answer within bounded history. */