@openchamber/web 1.24.0 → 1.24.1

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 (131) hide show
  1. package/bin/cli.test.js +7 -6
  2. package/bin/lib/cli-http.js +5 -1
  3. package/dist/assets/{CodeMirrorCommentWidgets-C9kV-n7r.js → CodeMirrorCommentWidgets-DvUH815P.js} +1 -1
  4. package/dist/assets/DiffView-DkC3xlRJ.js +4 -0
  5. package/dist/assets/{FilesView-vjJx7VaM.js → FilesView-D0bM9FVB.js} +6 -6
  6. package/dist/assets/GitView-Bxuv3dfP.js +6 -0
  7. package/dist/assets/GuestAttachDialog-B0u3Q5uO.js +1 -0
  8. package/dist/assets/{JsonTreeView-D_4G5X6-.js → JsonTreeView-BBVPFM5K.js} +1 -1
  9. package/dist/assets/{LinearIssuesView-1uKhePfH.js → LinearIssuesView-UI1FcSC8.js} +1 -1
  10. package/dist/assets/{MarkdownImageGallery-Ix7N_2wp.js → MarkdownImageGallery-CUJxH8Le.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-Deel_y5S.js → MarkdownRendererImpl-D5BZOg8X.js} +1 -1
  12. package/dist/assets/{OnboardingScreen-ToIakxb_.js → OnboardingScreen-5Gou9cGD.js} +1 -1
  13. package/dist/assets/{PatchDiff-BjMgezr1.js → PatchDiff-C4rE5k6z.js} +1 -1
  14. package/dist/assets/{PierreDiffViewer-53Ghfnlr.js → PierreDiffViewer-ByRVu6ss.js} +1 -1
  15. package/dist/assets/{PlanView-BGAzxDwD.js → PlanView-u2yi5XGJ.js} +4 -4
  16. package/dist/assets/PluginPane-QxjsKYeO.js +3 -0
  17. package/dist/assets/SettingsView-Fo5ZqMaT.js +29 -0
  18. package/dist/assets/SettingsWindow-HVDVANjJ.js +1 -0
  19. package/dist/assets/{SubmoduleDiffSummary--YFqK6Ih.js → SubmoduleDiffSummary-D3hzkybB.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-DRWBvdaJ.js → ToolOutputDialog-3J6IRayW.js} +6 -6
  21. package/dist/assets/{ToolPartDiffPreview-BxZJCU28.js → ToolPartDiffPreview-DarxPjSd.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-DCXjBGRf.js → VirtualizedFileDiff-CZgXWHjU.js} +4 -4
  23. package/dist/assets/{WalkthroughView-CfIPvWWa.js → WalkthroughView-wSpED5L4.js} +2 -2
  24. package/dist/assets/{appThemeRegistry-DDROzcUO.js → appThemeRegistry-Cf8KitzT.js} +1 -1
  25. package/dist/assets/commitAndPush-DZnzlhvc.js +1 -0
  26. package/dist/assets/{computeVirtualFileMetrics-DHgQIkUq.js → computeVirtualFileMetrics-VYnT_A2h.js} +1 -1
  27. package/dist/assets/{de-CX_f-T5U.js → de-BM_8EDD3.js} +4 -4
  28. package/dist/assets/{es-BERmWNn_.js → es-CxZjlqpo.js} +3 -3
  29. package/dist/assets/{fr-BjYYE_-z.js → fr-VCixCnMW.js} +4 -4
  30. package/dist/assets/{index-WjufPkIV.js → index-3U4CtS9b.js} +1 -1
  31. package/dist/assets/index-B9Hvzjwl.css +1 -0
  32. package/dist/assets/index-DLHQogv8.js +40 -0
  33. package/dist/assets/{isDiffPlainText-D9faP70y.js → isDiffPlainText-ImDG3Uhg.js} +1 -1
  34. package/dist/assets/{isFilePlainText-6qOcz5Ky.js → isFilePlainText-D_YDVYDb.js} +1 -1
  35. package/dist/assets/{ja-DxqeAk9N.js → ja-CZ5k_GyD.js} +4 -4
  36. package/dist/assets/{ko-Dty1aUod.js → ko-7YM3A1Xh.js} +4 -4
  37. package/dist/assets/{main-Bjcre_GE.js → main-CycplCph.js} +2 -2
  38. package/dist/assets/main-DFYTCx5o.js +896 -0
  39. package/dist/assets/markdownCore-DHvqMxPn.js +5 -0
  40. package/dist/assets/{miniChat-Dz_bPgMc.js → miniChat-DIQKfY2V.js} +2 -2
  41. package/dist/assets/{mobile-BbZPBJrK.js → mobile-BMwz5q-m.js} +2 -2
  42. package/dist/assets/{patchFileDiff-BvU6KOQC.js → patchFileDiff-DDQ6Rq5e.js} +3 -3
  43. package/dist/assets/{pl-CX-_ROkr.js → pl-BcgDO_w5.js} +4 -4
  44. package/dist/assets/{pt-BR-DhRR1arx.js → pt-BR-CU2u_1q5.js} +3 -3
  45. package/dist/assets/renderElectronMiniChatApp-3_d6g6CU.js +2 -0
  46. package/dist/assets/renderMobileApp-D0Y8DtkA.js +25 -0
  47. package/dist/assets/runtimeEndpointReset-DhC3REb2.js +25 -0
  48. package/dist/assets/{scheduledTasksApi-DW3xqMQ8.js → scheduledTasksApi-D8pq6gQz.js} +1 -1
  49. package/dist/assets/{shikiHighlight-DsxD9QEa.js → shikiHighlight-1imXsir9.js} +1 -1
  50. package/dist/assets/{textMateThemeFromAppTheme-Da7ed8qM.js → textMateThemeFromAppTheme-Dgqc63LZ.js} +1 -1
  51. package/dist/assets/tr-DuYhOzNe.js +7 -0
  52. package/dist/assets/{uk-CD21CXFV.js → uk-Cuk7-uvq.js} +3 -3
  53. package/dist/assets/{useAppFontEffects-hfv2s6mZ.js → useAppFontEffects-BItUWdo4.js} +147 -147
  54. package/dist/assets/{useInlineCommentController-BmtfVbo8.js → useInlineCommentController-CkbKsm7m.js} +2 -2
  55. package/dist/assets/useRootScrollLock-vmzxZjWA.js +2 -0
  56. package/dist/assets/{vendor-codemirror-language-data-BPMJpOpT.js → vendor-codemirror-language-data-BDyxuqK4.js} +2 -2
  57. package/dist/assets/{vendor-tanstack-react-virtual-g05Cx3z9.js → vendor-tanstack-react-virtual-ClYN8CzB.js} +1 -1
  58. package/dist/assets/{vendor-tanstack-virtual-core-Dubg10g5.js → vendor-tanstack-virtual-core-BewVQryB.js} +1 -1
  59. package/dist/assets/{web-components-U-hWbgJo.js → web-components-D7FinaeH.js} +1 -1
  60. package/dist/assets/{zh-CN-BWvlPHY-.js → zh-CN-CUWoiRHd.js} +3 -3
  61. package/dist/assets/{zh-TW-CRp5dJU2.js → zh-TW-CQ8EBSBN.js} +3 -3
  62. package/dist/index.html +3 -3
  63. package/dist/mini-chat.html +3 -3
  64. package/dist/mobile.html +3 -3
  65. package/package.json +4 -3
  66. package/server/index.js +26 -7
  67. package/server/lib/changelog/update-notes.js +2 -1
  68. package/server/lib/changelog/update-notes.test.js +19 -0
  69. package/server/lib/event-stream/DOCUMENTATION.md +23 -0
  70. package/server/lib/event-stream/delta-coalescer.js +0 -0
  71. package/server/lib/event-stream/delta-coalescer.test.js +292 -0
  72. package/server/lib/event-stream/global-hub.js +53 -23
  73. package/server/lib/event-stream/global-hub.test.js +160 -0
  74. package/server/lib/event-stream/global-ws-bridge.js +1 -0
  75. package/server/lib/event-stream/index.js +4 -0
  76. package/server/lib/git/DOCUMENTATION.md +17 -4
  77. package/server/lib/git/routes.js +1 -1
  78. package/server/lib/git/serial-refresh.js +93 -0
  79. package/server/lib/git/serial-refresh.test.js +112 -0
  80. package/server/lib/git/service.js +232 -62
  81. package/server/lib/git/service.test.js +273 -0
  82. package/server/lib/github/pr-status.js +5 -5
  83. package/server/lib/github/pr-status.test.js +1 -1
  84. package/server/lib/github/routes.js +4 -4
  85. package/server/lib/guests/DOCUMENTATION.md +5 -3
  86. package/server/lib/guests/background.test.js +83 -0
  87. package/server/lib/guests/catalog.js +20 -9
  88. package/server/lib/guests/catalog.test.js +5 -5
  89. package/server/lib/guests/routes.js +2 -2
  90. package/server/lib/message-queue/DOCUMENTATION.md +6 -0
  91. package/server/lib/message-queue/runtime.js +5 -0
  92. package/server/lib/message-queue/runtime.test.js +32 -1
  93. package/server/lib/opencode/feature-routes-runtime.js +5 -0
  94. package/server/lib/opencode/settings-helpers.js +3 -0
  95. package/server/lib/opencode/settings-registry.json +8 -0
  96. package/server/lib/permission-auto-accept/DOCUMENTATION.md +8 -0
  97. package/server/lib/permission-auto-accept/runtime.js +13 -0
  98. package/server/lib/permission-auto-accept/runtime.test.js +37 -1
  99. package/server/lib/routing/DOCUMENTATION.md +81 -0
  100. package/server/lib/routing/defaults.js +98 -0
  101. package/server/lib/routing/feature-flag.js +11 -0
  102. package/server/lib/routing/history.js +34 -0
  103. package/server/lib/routing/jev.js +98 -0
  104. package/server/lib/routing/routes.http.test.js +100 -0
  105. package/server/lib/routing/routes.js +81 -0
  106. package/server/lib/routing/runtime.js +217 -0
  107. package/server/lib/routing/runtime.test.js +188 -0
  108. package/server/lib/routing/store.js +249 -0
  109. package/server/lib/routing/store.test.js +96 -0
  110. package/server/lib/security/request-security.js +9 -5
  111. package/server/lib/security/request-security.test.js +37 -0
  112. package/server/lib/ui-auth/DOCUMENTATION.md +8 -0
  113. package/server/lib/ui-auth/session-cookie.js +51 -0
  114. package/server/lib/ui-auth/session-cookie.test.js +46 -0
  115. package/server/lib/ui-auth/ui-auth.js +13 -9
  116. package/server/lib/ui-auth/ui-auth.test.js +56 -0
  117. package/dist/assets/DiffView-B7YkbY-u.js +0 -4
  118. package/dist/assets/DirtyBranchSwitchDialog-CU0A93Zx.js +0 -1
  119. package/dist/assets/GitView-BLhlMYEY.js +0 -6
  120. package/dist/assets/GuestAttachDialog-B-fwE8r3.js +0 -3
  121. package/dist/assets/SettingsView-n2X-jfBB.js +0 -29
  122. package/dist/assets/SettingsWindow-Bi8LE9XI.js +0 -1
  123. package/dist/assets/index-DpzTz2UH.css +0 -1
  124. package/dist/assets/index-Dy8xgawx.js +0 -40
  125. package/dist/assets/main-BOYSXfYn.js +0 -896
  126. package/dist/assets/markdownCore-DPrwM1rU.js +0 -5
  127. package/dist/assets/renderElectronMiniChatApp-uNEUkeAI.js +0 -2
  128. package/dist/assets/renderMobileApp-BK1kFlcJ.js +0 -25
  129. package/dist/assets/runtimeEndpointReset-BULHvOwb.js +0 -25
  130. package/dist/assets/tr-cIQtYBpg.js +0 -7
  131. package/dist/assets/useRootScrollLock-Cwc4kSl2.js +0 -1
@@ -0,0 +1,81 @@
1
+ /**
2
+ * `/api/routing` — configuration and the Jev key. Normal authenticated
3
+ * OpenChamber routes: do not add them to browser URL-token allowlists.
4
+ *
5
+ * `/api/session/:id/{prompt_async,prompt,command}` — the rewrite that turns
6
+ * `openchamber/auto` into a real model before the generic OpenCode proxy
7
+ * forwards the request. Registered ahead of the proxy; it parses the JSON body
8
+ * only while Auto can actually be selected, so a build without the flag pays
9
+ * nothing on the send path.
10
+ */
11
+ import express from 'express';
12
+ import { isRoutingFeatureAvailable } from './feature-flag.js';
13
+
14
+ const AUTO_SESSION_PATHS = [
15
+ '/api/session/:sessionId/prompt_async',
16
+ '/api/session/:sessionId/prompt',
17
+ '/api/session/:sessionId/command',
18
+ ];
19
+
20
+ const sendError = (res, error) => {
21
+ const status = Number.isInteger(error?.status) ? error.status : 500;
22
+ res.status(status).json({ error: error?.message ?? 'Routing request failed' });
23
+ };
24
+
25
+ export function registerRoutingRoutes(app, runtime) {
26
+ const unavailable = (res) => res.status(404).json({ error: 'Routing is not available in this build' });
27
+
28
+ app.get('/api/routing', async (_req, res) => {
29
+ try {
30
+ const state = await runtime.describe();
31
+ if (!state.available) return unavailable(res);
32
+ res.json({ ...state, heldPermissions: runtime.heldPermissions() });
33
+ } catch (error) {
34
+ sendError(res, error);
35
+ }
36
+ });
37
+
38
+ app.put('/api/routing', express.json({ limit: '256kb' }), async (req, res) => {
39
+ if (!isRoutingFeatureAvailable()) return unavailable(res);
40
+ try {
41
+ res.json(await runtime.updateConfig(req.body?.config));
42
+ } catch (error) {
43
+ sendError(res, error);
44
+ }
45
+ });
46
+
47
+ app.put('/api/routing/token', express.json({ limit: '16kb' }), async (req, res) => {
48
+ if (!isRoutingFeatureAvailable()) return unavailable(res);
49
+ try {
50
+ res.json(await runtime.setToken(req.body?.token));
51
+ } catch (error) {
52
+ sendError(res, error);
53
+ }
54
+ });
55
+
56
+ app.delete('/api/routing/token', async (_req, res) => {
57
+ if (!isRoutingFeatureAvailable()) return unavailable(res);
58
+ try {
59
+ res.json(await runtime.clearToken());
60
+ } catch (error) {
61
+ sendError(res, error);
62
+ }
63
+ });
64
+ }
65
+
66
+ export function registerRoutingPromptRewrite(app, runtime) {
67
+ const parseJson = express.json({ limit: '50mb' });
68
+ app.post(AUTO_SESSION_PATHS, (req, res, next) => {
69
+ if (!isRoutingFeatureAvailable()) return next();
70
+ const contentType = String(req.headers['content-type'] ?? '').toLowerCase();
71
+ if (!contentType.includes('application/json')) return next();
72
+ parseJson(req, res, (parseError) => {
73
+ if (parseError) return next(parseError);
74
+ const url = new URL(req.url, 'http://localhost');
75
+ const directory = url.searchParams.get('directory') || req.get('x-opencode-directory') || undefined;
76
+ runtime.resolvePromptBody(req.body, { sessionId: req.params.sessionId, directory })
77
+ .then(() => next())
78
+ .catch((error) => sendError(res, error));
79
+ });
80
+ });
81
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Owns Jev routing at runtime: whether Auto is ready, rewriting a prompt body
3
+ * that names the `openchamber/auto` model, and the safety net consulted before
4
+ * a permission is auto-accepted. Every failure path keeps the user's own
5
+ * behaviour: a prompt goes to the fallback model, a permission is accepted as
6
+ * auto-accept would have, and the UI is told why.
7
+ */
8
+ import { createOpencodeClient } from '@opencode-ai/sdk/v2';
9
+ import { z } from 'zod';
10
+ import { isRoutingFeatureAvailable } from './feature-flag.js';
11
+ import { BUILTIN_CATEGORIES, isAutoModel } from './defaults.js';
12
+ import { createRoutingStore, parseEffectiveConfig } from './store.js';
13
+ import { buildPermissionRequest, buildRoutingRequest, createJevClient, decidePermission, decideRouting } from './jev.js';
14
+ import { loadRoutingHistory } from './history.js';
15
+
16
+ const HISTORY_TIMEOUT_MS = 2500;
17
+ /** A held permission is remembered so reconnect reconciliation does not re-ask Jev. */
18
+ const PERMISSION_DECISION_TTL_MS = 15 * 60 * 1000;
19
+
20
+ const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
21
+
22
+ const textPartSchema = z.object({ type: z.literal('text'), text: z.string(), synthetic: z.boolean().optional() });
23
+ const commandBodySchema = z.object({ command: z.string(), arguments: z.string().optional() });
24
+ const promptBodySchema = z.object({ parts: z.array(z.unknown()).optional() });
25
+
26
+ /** The user's words for this send: text parts the composer authored, or the slash command. */
27
+ export const requestTextOf = (body) => {
28
+ const command = commandBodySchema.safeParse(body);
29
+ if (command.success) {
30
+ const args = command.data.arguments?.trim();
31
+ return `/${command.data.command}${args ? ` ${args}` : ''}`;
32
+ }
33
+ const prompt = promptBodySchema.safeParse(body);
34
+ const parts = prompt.success ? prompt.data.parts ?? [] : [];
35
+ return parts
36
+ .map((part) => textPartSchema.safeParse(part))
37
+ .filter((part) => part.success && !part.data.synthetic)
38
+ .map((part) => part.data.text)
39
+ .join('\n\n')
40
+ .trim();
41
+ };
42
+
43
+ export function createRoutingRuntime({
44
+ dataDir,
45
+ buildOpenCodeUrl,
46
+ getOpenCodeAuthHeaders,
47
+ broadcastGlobalUiEvent,
48
+ fetchImpl = fetch,
49
+ store = createRoutingStore({ dataDir }),
50
+ jev = createJevClient({ fetchImpl }),
51
+ now = Date.now,
52
+ }) {
53
+ const permissionDecisions = new Map();
54
+
55
+ const broadcast = (type, properties) => {
56
+ try {
57
+ broadcastGlobalUiEvent?.({ type, properties });
58
+ } catch (error) {
59
+ console.warn(`[routing] failed to broadcast ${type}:`, errorMessage(error));
60
+ }
61
+ };
62
+
63
+ const enabledCategories = (config) => config.categories.filter((category) => category.enabled);
64
+
65
+ /** What the client needs to decide whether to offer Auto and what the settings page shows. */
66
+ const describe = async () => {
67
+ const available = isRoutingFeatureAvailable();
68
+ if (!available) return { available: false, autoReady: false, tokenPresent: false, config: null, builtins: [] };
69
+ const [config, token] = await Promise.all([store.readConfig(), store.readToken()]);
70
+ const tokenPresent = Boolean(token);
71
+ const autoReady = config.enabled && tokenPresent && Boolean(config.fallback) && enabledCategories(config).length >= 2;
72
+ // Built-in text travels with the config so "Reset" in Settings restores the shipped wording.
73
+ return { available, autoReady, tokenPresent, config, builtins: BUILTIN_CATEGORIES };
74
+ };
75
+
76
+ const publishUpdated = async () => {
77
+ const state = await describe();
78
+ broadcast('openchamber:routing.updated', { available: state.available, autoReady: state.autoReady, tokenPresent: state.tokenPresent });
79
+ return state;
80
+ };
81
+
82
+ const readHistory = async ({ sessionId, directory }) => {
83
+ const baseUrl = buildOpenCodeUrl('/', '').replace(/\/$/, '');
84
+ const client = createOpencodeClient({ baseUrl, headers: getOpenCodeAuthHeaders(), throwOnError: true });
85
+ const signal = AbortSignal.timeout(HISTORY_TIMEOUT_MS);
86
+ return loadRoutingHistory({
87
+ signal,
88
+ readPage: (page) => client.session.messages({ sessionID: sessionId, directory, ...page }, { signal }),
89
+ });
90
+ };
91
+
92
+ // A category without a model of its own means "the fallback pair"; a variant
93
+ // only travels with the model it was chosen for.
94
+ const applyChoice = (body, config, choice) => {
95
+ const own = Boolean(choice?.model);
96
+ const model = own ? choice.model : config.fallback.model;
97
+ const variant = own ? choice.variant : config.fallback.variant;
98
+ // Keep the wire shape the route uses: a string on /command, an object on the prompt routes.
99
+ body.model = z.string().safeParse(body.model).success
100
+ ? `${model.providerID}/${model.modelID}`
101
+ : { providerID: model.providerID, modelID: model.modelID };
102
+ if (variant) body.variant = variant;
103
+ else delete body.variant;
104
+ if (choice?.agent) body.agent = choice.agent;
105
+ return { providerID: model.providerID, modelID: model.modelID, variant: variant ?? null, agent: choice?.agent ?? null };
106
+ };
107
+
108
+ /**
109
+ * Rewrites `body.model` in place when it is the Auto sentinel. Returns the
110
+ * decision that was applied, or null when the body named a real model.
111
+ * Throws only when Auto cannot be honoured at all (no fallback configured):
112
+ * the sentinel must never reach OpenCode.
113
+ */
114
+ const resolvePromptBody = async (body, { sessionId, directory }) => {
115
+ if (!isAutoModel(body?.model)) return null;
116
+ const state = await describe();
117
+ const config = state.config;
118
+ if (!config?.fallback) {
119
+ throw Object.assign(new Error('Auto routing is selected but no fallback model is configured'), { status: 400 });
120
+ }
121
+ const decision = { sessionId, at: now(), category: null, confidence: 0, reason: 'not-ready', ms: 0 };
122
+ if (state.autoReady) {
123
+ const request = requestTextOf(body);
124
+ let history = [];
125
+ try {
126
+ history = await readHistory({ sessionId, directory });
127
+ } catch (error) {
128
+ console.warn('[routing] history unavailable, routing on the request alone:', errorMessage(error));
129
+ }
130
+ try {
131
+ const token = await store.readToken();
132
+ const { answers, ms } = await jev.ask(buildRoutingRequest({ categories: enabledCategories(config), history, request }), token);
133
+ const result = decideRouting(answers.category, { categories: enabledCategories(config), minConfidence: config.minConfidence });
134
+ decision.category = result.category?.id ?? null;
135
+ decision.confidence = result.confidence;
136
+ decision.reason = result.reason;
137
+ decision.ms = ms;
138
+ Object.assign(decision, applyChoice(body, config, result.category));
139
+ } catch (error) {
140
+ decision.reason = 'error';
141
+ decision.error = errorMessage(error);
142
+ Object.assign(decision, applyChoice(body, config, null));
143
+ }
144
+ } else {
145
+ Object.assign(decision, applyChoice(body, config, null));
146
+ }
147
+ broadcast('openchamber:routing.decision', decision);
148
+ return decision;
149
+ };
150
+
151
+ /**
152
+ * Consulted by permission auto-accept before it replies. `accept` keeps the
153
+ * reply; `hold` leaves the request for the user; `skipped` is `accept` with
154
+ * a reason the UI surfaces (Jev unreachable, bad key).
155
+ */
156
+ const evaluatePermission = async (permission, directory) => {
157
+ if (!permission?.id) return { action: 'accept' };
158
+ const cached = permissionDecisions.get(permission.id);
159
+ if (cached && now() - cached.at < PERMISSION_DECISION_TTL_MS) return cached.result;
160
+ const state = await describe();
161
+ if (!state.available || !state.config?.enabled || !state.config.safetyNet.enabled || !state.tokenPresent) return { action: 'accept' };
162
+ let result;
163
+ try {
164
+ const token = await store.readToken();
165
+ const { answers } = await jev.ask(buildPermissionRequest(permission), token);
166
+ const verdict = decidePermission(answers, { threshold: state.config.safetyNet.threshold });
167
+ result = verdict.hold
168
+ ? { action: 'hold', score: verdict.score, kind: verdict.kind }
169
+ : { action: 'accept', score: verdict.score, kind: verdict.kind };
170
+ if (verdict.hold) {
171
+ broadcast('openchamber:routing.permission-held', {
172
+ permissionId: permission.id, sessionId: permission.sessionID, directory: directory ?? null, score: verdict.score, kind: verdict.kind,
173
+ });
174
+ }
175
+ } catch (error) {
176
+ result = { action: 'accept', skipped: errorMessage(error) };
177
+ broadcast('openchamber:routing.safety-skipped', {
178
+ permissionId: permission.id, sessionId: permission.sessionID, directory: directory ?? null, error: result.skipped,
179
+ });
180
+ }
181
+ permissionDecisions.set(permission.id, { at: now(), result });
182
+ return result;
183
+ };
184
+
185
+ const forgetPermission = (permissionId) => {
186
+ permissionDecisions.delete(permissionId);
187
+ };
188
+
189
+ const updateConfig = async (input) => {
190
+ const config = parseEffectiveConfig(input);
191
+ await store.writeConfig(config);
192
+ return publishUpdated();
193
+ };
194
+
195
+ const setToken = async (token) => {
196
+ const parsed = z.string().trim().min(1).max(4000).safeParse(token);
197
+ if (!parsed.success) throw Object.assign(new Error('A Jev API key is required'), { status: 400 });
198
+ await store.writeToken(parsed.data);
199
+ return publishUpdated();
200
+ };
201
+
202
+ const clearToken = async () => {
203
+ await store.clearToken();
204
+ return publishUpdated();
205
+ };
206
+
207
+ /** Held permissions the UI can read back after a reload. */
208
+ const heldPermissions = () => {
209
+ const held = [];
210
+ for (const [permissionId, entry] of permissionDecisions) {
211
+ if (entry.result.action === 'hold') held.push({ permissionId, score: entry.result.score, kind: entry.result.kind });
212
+ }
213
+ return held;
214
+ };
215
+
216
+ return { describe, resolvePromptBody, evaluatePermission, forgetPermission, heldPermissions, updateConfig, setToken, clearToken };
217
+ }
@@ -0,0 +1,188 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createRoutingRuntime, requestTextOf } from './runtime.js';
3
+ import { resolveEffectiveConfig } from './store.js';
4
+ import { excerptHead, excerptHeadTail, turnsToHistory } from './history.js';
5
+ import { decidePermission, decideRouting } from './jev.js';
6
+
7
+ const AUTO = { providerID: 'openchamber', modelID: 'auto' };
8
+ const FALLBACK = { model: { providerID: 'anthropic', modelID: 'claude-sonnet-5' }, variant: 'medium' };
9
+
10
+ const readyConfig = () => {
11
+ const config = resolveEffectiveConfig(null);
12
+ config.enabled = true;
13
+ config.fallback = FALLBACK;
14
+ config.safetyNet = { enabled: true, threshold: 0.6 };
15
+ config.categories = config.categories.map((c) => (c.id === 'hard'
16
+ ? { ...c, model: { providerID: 'openai', modelID: 'gpt-6-astra' }, variant: 'high', agent: 'plan' }
17
+ : c));
18
+ return config;
19
+ };
20
+
21
+ const makeRuntime = ({ config = readyConfig(), token = 'key', answers, askError, flag = '1' } = {}) => {
22
+ process.env.OPENCHAMBER_ROUTING_ENABLE = flag;
23
+ const events = [];
24
+ const store = {
25
+ readConfig: vi.fn(async () => config),
26
+ writeConfig: vi.fn(async (next) => next),
27
+ readToken: vi.fn(async () => token),
28
+ writeToken: vi.fn(async () => undefined),
29
+ clearToken: vi.fn(async () => undefined),
30
+ };
31
+ const jev = { ask: vi.fn(async () => { if (askError) throw askError; return { answers, ms: 12 }; }) };
32
+ const runtime = createRoutingRuntime({
33
+ dataDir: '/unused',
34
+ buildOpenCodeUrl: () => 'http://127.0.0.1:1/',
35
+ getOpenCodeAuthHeaders: () => ({}),
36
+ broadcastGlobalUiEvent: (event) => events.push(event),
37
+ store,
38
+ jev,
39
+ });
40
+ return { runtime, store, jev, events };
41
+ };
42
+
43
+ describe('requestTextOf', () => {
44
+ it('joins authored text parts and ignores synthetic ones and files', () => {
45
+ expect(requestTextOf({ parts: [
46
+ { type: 'text', text: 'fix the typo' },
47
+ { type: 'text', text: 'injected', synthetic: true },
48
+ { type: 'file', url: 'data:...' },
49
+ { type: 'text', text: 'in README' },
50
+ ] })).toBe('fix the typo\n\nin README');
51
+ });
52
+ it('renders a slash command with its arguments', () => {
53
+ expect(requestTextOf({ command: 'review', arguments: ' 3650 ' })).toBe('/review 3650');
54
+ });
55
+ });
56
+
57
+ describe('history excerpts', () => {
58
+ it('keeps the head of a user message and head plus tail of an answer', () => {
59
+ const long = 'a'.repeat(1000);
60
+ expect(excerptHead(long, 600)).toBe(`${'a'.repeat(600)} […]`);
61
+ expect(excerptHeadTail(`${'h'.repeat(400)}${'m'.repeat(400)}${'t'.repeat(400)}`, 300, 300)).toBe(`${'h'.repeat(300)} […] ${'t'.repeat(300)}`);
62
+ expect(excerptHead('short', 600)).toBe('short');
63
+ });
64
+ it('flattens the last three turns oldest first', () => {
65
+ const turns = [1, 2, 3, 4].map((n) => ({ user: { text: `u${n}` }, assistant: { text: `a${n}` } }));
66
+ expect(turnsToHistory(turns)).toEqual([
67
+ { role: 'user', text: 'u2' }, { role: 'assistant', text: 'a2' },
68
+ { role: 'user', text: 'u3' }, { role: 'assistant', text: 'a3' },
69
+ { role: 'user', text: 'u4' }, { role: 'assistant', text: 'a4' },
70
+ ]);
71
+ });
72
+ });
73
+
74
+ describe('decisions', () => {
75
+ const categories = readyConfig().categories;
76
+ it('routes a confident known category and falls back otherwise', () => {
77
+ expect(decideRouting({ choice: 'hard', confidence: 0.9 }, { categories, minConfidence: 0.6 }).reason).toBe('routed');
78
+ expect(decideRouting({ choice: 'hard', confidence: 0.4 }, { categories, minConfidence: 0.6 })).toMatchObject({ category: null, reason: 'low-confidence' });
79
+ expect(decideRouting({ choice: 'nope', confidence: 0.99 }, { categories, minConfidence: 0.6 })).toMatchObject({ category: null, reason: 'unknown-category' });
80
+ });
81
+ it('holds a permission at or above the threshold', () => {
82
+ expect(decidePermission({ ask: { noul: 0.61 }, kind: { choice: 'git_history' } }, { threshold: 0.6 })).toEqual({ hold: true, score: 0.61, kind: 'git_history' });
83
+ expect(decidePermission({ ask: { noul: 0.2 }, kind: { choice: 'read_only' } }, { threshold: 0.6 }).hold).toBe(false);
84
+ expect(() => decidePermission({}, { threshold: 0.6 })).toThrow(/ask score/);
85
+ });
86
+ });
87
+
88
+ describe('resolvePromptBody', () => {
89
+ it('leaves a real model untouched and does not consult Jev', async () => {
90
+ const { runtime, jev } = makeRuntime({ answers: {} });
91
+ const body = { model: { providerID: 'anthropic', modelID: 'claude-opus-5' }, parts: [] };
92
+ expect(await runtime.resolvePromptBody(body, { sessionId: 's1' })).toBeNull();
93
+ expect(body.model.modelID).toBe('claude-opus-5');
94
+ expect(jev.ask).not.toHaveBeenCalled();
95
+ });
96
+
97
+ it('rewrites the sentinel with the routed category model, variant and agent', async () => {
98
+ const { runtime, events } = makeRuntime({ answers: { category: { choice: 'hard', confidence: 0.97 } } });
99
+ const body = { model: AUTO, variant: 'low', agent: 'build', parts: [{ type: 'text', text: 'find the root cause' }] };
100
+ const decision = await runtime.resolvePromptBody(body, { sessionId: 's1' });
101
+ expect(body).toMatchObject({ model: { providerID: 'openai', modelID: 'gpt-6-astra' }, variant: 'high', agent: 'plan' });
102
+ expect(decision).toMatchObject({ category: 'hard', reason: 'routed', confidence: 0.97 });
103
+ expect(events.at(-1)).toMatchObject({ type: 'openchamber:routing.decision', properties: { sessionId: 's1', category: 'hard' } });
104
+ });
105
+
106
+ it('rewrites the string sentinel the command route sends, keeping the string shape', async () => {
107
+ const { runtime } = makeRuntime({ answers: { category: { choice: 'hard', confidence: 0.97 } } });
108
+ const body = { model: 'openchamber/auto', command: 'review', arguments: '3650' };
109
+ await runtime.resolvePromptBody(body, { sessionId: 's1' });
110
+ expect(body.model).toBe('openai/gpt-6-astra');
111
+ expect(body.agent).toBe('plan');
112
+ });
113
+
114
+ it('uses the fallback and keeps the composer agent when the category has no model', async () => {
115
+ const { runtime } = makeRuntime({ answers: { category: { choice: 'trivial', confidence: 0.99 } } });
116
+ const body = { model: AUTO, variant: 'high', agent: 'build', parts: [{ type: 'text', text: 'fix typo' }] };
117
+ await runtime.resolvePromptBody(body, { sessionId: 's1' });
118
+ expect(body).toMatchObject({ model: FALLBACK.model, variant: 'medium', agent: 'build' });
119
+ });
120
+
121
+ it('falls back on low confidence and on a Jev failure, and records why', async () => {
122
+ const low = makeRuntime({ answers: { category: { choice: 'hard', confidence: 0.3 } } });
123
+ const body = { model: AUTO, parts: [] };
124
+ expect((await low.runtime.resolvePromptBody(body, { sessionId: 's1' })).reason).toBe('low-confidence');
125
+ expect(body.model).toEqual(FALLBACK.model);
126
+
127
+ const failing = makeRuntime({ askError: Object.assign(new Error('Jev responded 401'), { status: 401 }) });
128
+ const body2 = { model: AUTO, parts: [] };
129
+ const decision = await failing.runtime.resolvePromptBody(body2, { sessionId: 's1' });
130
+ expect(decision).toMatchObject({ reason: 'error', error: 'Jev responded 401' });
131
+ expect(body2.model).toEqual(FALLBACK.model);
132
+ });
133
+
134
+ it('falls back without asking Jev while Auto is not ready, and refuses without a fallback', async () => {
135
+ const config = readyConfig();
136
+ config.enabled = false;
137
+ const notReady = makeRuntime({ config, answers: {} });
138
+ const body = { model: AUTO, parts: [] };
139
+ expect((await notReady.runtime.resolvePromptBody(body, { sessionId: 's1' })).reason).toBe('not-ready');
140
+ expect(body.model).toEqual(FALLBACK.model);
141
+ expect(notReady.jev.ask).not.toHaveBeenCalled();
142
+
143
+ const noFallback = makeRuntime({ config: { ...readyConfig(), fallback: null }, answers: {} });
144
+ await expect(noFallback.runtime.resolvePromptBody({ model: AUTO, parts: [] }, { sessionId: 's1' })).rejects.toMatchObject({ status: 400 });
145
+ });
146
+ });
147
+
148
+ describe('evaluatePermission', () => {
149
+ const permission = { id: 'p1', sessionID: 's1', permission: 'bash', patterns: ['git push --force'], metadata: { command: 'git push --force origin main' } };
150
+
151
+ it('holds a risky permission and remembers the decision', async () => {
152
+ const { runtime, jev, events } = makeRuntime({ answers: { ask: { noul: 0.9 }, kind: { choice: 'git_history' } } });
153
+ expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'hold', score: 0.9, kind: 'git_history' });
154
+ expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'hold', score: 0.9, kind: 'git_history' });
155
+ expect(jev.ask).toHaveBeenCalledTimes(1);
156
+ expect(events.filter((e) => e.type === 'openchamber:routing.permission-held')).toHaveLength(1);
157
+ expect(runtime.heldPermissions()).toEqual([{ permissionId: 'p1', score: 0.9, kind: 'git_history' }]);
158
+ runtime.forgetPermission('p1');
159
+ expect(runtime.heldPermissions()).toEqual([]);
160
+ });
161
+
162
+ it('accepts when Jev is unreachable and tells the UI it skipped', async () => {
163
+ const { runtime, events } = makeRuntime({ askError: Object.assign(new Error('Jev timed out after 4000ms'), { code: 'timeout' }) });
164
+ expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'accept', skipped: 'Jev timed out after 4000ms' });
165
+ expect(events.at(-1)).toMatchObject({ type: 'openchamber:routing.safety-skipped', properties: { permissionId: 'p1', error: 'Jev timed out after 4000ms' } });
166
+ });
167
+
168
+ it('accepts without asking when the safety net is off, the key is missing, or the flag is unset', async () => {
169
+ const off = readyConfig();
170
+ off.safetyNet.enabled = false;
171
+ for (const setup of [{ config: off }, { token: null }, { flag: '' }]) {
172
+ const { runtime, jev } = makeRuntime({ ...setup, answers: {} });
173
+ expect(await runtime.evaluatePermission(permission, '/repo')).toEqual({ action: 'accept' });
174
+ expect(jev.ask).not.toHaveBeenCalled();
175
+ }
176
+ });
177
+ });
178
+
179
+ describe('describe', () => {
180
+ it('reports Auto ready only with the flag, enabled config, key, fallback and two categories', async () => {
181
+ expect((await makeRuntime({ answers: {} }).runtime.describe()).autoReady).toBe(true);
182
+ expect((await makeRuntime({ token: null, answers: {} }).runtime.describe())).toMatchObject({ autoReady: false, tokenPresent: false });
183
+ const one = readyConfig();
184
+ one.categories = one.categories.map((c, i) => ({ ...c, enabled: i === 0 }));
185
+ expect((await makeRuntime({ config: one, answers: {} }).runtime.describe()).autoReady).toBe(false);
186
+ expect(await makeRuntime({ flag: '', answers: {} }).runtime.describe()).toEqual({ available: false, autoReady: false, tokenPresent: false, config: null, builtins: [] });
187
+ });
188
+ });