@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.
- package/bin/cli.test.js +7 -6
- package/bin/lib/cli-http.js +5 -1
- package/dist/assets/{CodeMirrorCommentWidgets-C9kV-n7r.js → CodeMirrorCommentWidgets-DvUH815P.js} +1 -1
- package/dist/assets/DiffView-DkC3xlRJ.js +4 -0
- package/dist/assets/{FilesView-vjJx7VaM.js → FilesView-D0bM9FVB.js} +6 -6
- package/dist/assets/GitView-Bxuv3dfP.js +6 -0
- package/dist/assets/GuestAttachDialog-B0u3Q5uO.js +1 -0
- package/dist/assets/{JsonTreeView-D_4G5X6-.js → JsonTreeView-BBVPFM5K.js} +1 -1
- package/dist/assets/{LinearIssuesView-1uKhePfH.js → LinearIssuesView-UI1FcSC8.js} +1 -1
- package/dist/assets/{MarkdownImageGallery-Ix7N_2wp.js → MarkdownImageGallery-CUJxH8Le.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-Deel_y5S.js → MarkdownRendererImpl-D5BZOg8X.js} +1 -1
- package/dist/assets/{OnboardingScreen-ToIakxb_.js → OnboardingScreen-5Gou9cGD.js} +1 -1
- package/dist/assets/{PatchDiff-BjMgezr1.js → PatchDiff-C4rE5k6z.js} +1 -1
- package/dist/assets/{PierreDiffViewer-53Ghfnlr.js → PierreDiffViewer-ByRVu6ss.js} +1 -1
- package/dist/assets/{PlanView-BGAzxDwD.js → PlanView-u2yi5XGJ.js} +4 -4
- package/dist/assets/PluginPane-QxjsKYeO.js +3 -0
- package/dist/assets/SettingsView-Fo5ZqMaT.js +29 -0
- package/dist/assets/SettingsWindow-HVDVANjJ.js +1 -0
- package/dist/assets/{SubmoduleDiffSummary--YFqK6Ih.js → SubmoduleDiffSummary-D3hzkybB.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DRWBvdaJ.js → ToolOutputDialog-3J6IRayW.js} +6 -6
- package/dist/assets/{ToolPartDiffPreview-BxZJCU28.js → ToolPartDiffPreview-DarxPjSd.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DCXjBGRf.js → VirtualizedFileDiff-CZgXWHjU.js} +4 -4
- package/dist/assets/{WalkthroughView-CfIPvWWa.js → WalkthroughView-wSpED5L4.js} +2 -2
- package/dist/assets/{appThemeRegistry-DDROzcUO.js → appThemeRegistry-Cf8KitzT.js} +1 -1
- package/dist/assets/commitAndPush-DZnzlhvc.js +1 -0
- package/dist/assets/{computeVirtualFileMetrics-DHgQIkUq.js → computeVirtualFileMetrics-VYnT_A2h.js} +1 -1
- package/dist/assets/{de-CX_f-T5U.js → de-BM_8EDD3.js} +4 -4
- package/dist/assets/{es-BERmWNn_.js → es-CxZjlqpo.js} +3 -3
- package/dist/assets/{fr-BjYYE_-z.js → fr-VCixCnMW.js} +4 -4
- package/dist/assets/{index-WjufPkIV.js → index-3U4CtS9b.js} +1 -1
- package/dist/assets/index-B9Hvzjwl.css +1 -0
- package/dist/assets/index-DLHQogv8.js +40 -0
- package/dist/assets/{isDiffPlainText-D9faP70y.js → isDiffPlainText-ImDG3Uhg.js} +1 -1
- package/dist/assets/{isFilePlainText-6qOcz5Ky.js → isFilePlainText-D_YDVYDb.js} +1 -1
- package/dist/assets/{ja-DxqeAk9N.js → ja-CZ5k_GyD.js} +4 -4
- package/dist/assets/{ko-Dty1aUod.js → ko-7YM3A1Xh.js} +4 -4
- package/dist/assets/{main-Bjcre_GE.js → main-CycplCph.js} +2 -2
- package/dist/assets/main-DFYTCx5o.js +896 -0
- package/dist/assets/markdownCore-DHvqMxPn.js +5 -0
- package/dist/assets/{miniChat-Dz_bPgMc.js → miniChat-DIQKfY2V.js} +2 -2
- package/dist/assets/{mobile-BbZPBJrK.js → mobile-BMwz5q-m.js} +2 -2
- package/dist/assets/{patchFileDiff-BvU6KOQC.js → patchFileDiff-DDQ6Rq5e.js} +3 -3
- package/dist/assets/{pl-CX-_ROkr.js → pl-BcgDO_w5.js} +4 -4
- package/dist/assets/{pt-BR-DhRR1arx.js → pt-BR-CU2u_1q5.js} +3 -3
- package/dist/assets/renderElectronMiniChatApp-3_d6g6CU.js +2 -0
- package/dist/assets/renderMobileApp-D0Y8DtkA.js +25 -0
- package/dist/assets/runtimeEndpointReset-DhC3REb2.js +25 -0
- package/dist/assets/{scheduledTasksApi-DW3xqMQ8.js → scheduledTasksApi-D8pq6gQz.js} +1 -1
- package/dist/assets/{shikiHighlight-DsxD9QEa.js → shikiHighlight-1imXsir9.js} +1 -1
- package/dist/assets/{textMateThemeFromAppTheme-Da7ed8qM.js → textMateThemeFromAppTheme-Dgqc63LZ.js} +1 -1
- package/dist/assets/tr-DuYhOzNe.js +7 -0
- package/dist/assets/{uk-CD21CXFV.js → uk-Cuk7-uvq.js} +3 -3
- package/dist/assets/{useAppFontEffects-hfv2s6mZ.js → useAppFontEffects-BItUWdo4.js} +147 -147
- package/dist/assets/{useInlineCommentController-BmtfVbo8.js → useInlineCommentController-CkbKsm7m.js} +2 -2
- package/dist/assets/useRootScrollLock-vmzxZjWA.js +2 -0
- package/dist/assets/{vendor-codemirror-language-data-BPMJpOpT.js → vendor-codemirror-language-data-BDyxuqK4.js} +2 -2
- package/dist/assets/{vendor-tanstack-react-virtual-g05Cx3z9.js → vendor-tanstack-react-virtual-ClYN8CzB.js} +1 -1
- package/dist/assets/{vendor-tanstack-virtual-core-Dubg10g5.js → vendor-tanstack-virtual-core-BewVQryB.js} +1 -1
- package/dist/assets/{web-components-U-hWbgJo.js → web-components-D7FinaeH.js} +1 -1
- package/dist/assets/{zh-CN-BWvlPHY-.js → zh-CN-CUWoiRHd.js} +3 -3
- package/dist/assets/{zh-TW-CRp5dJU2.js → zh-TW-CQ8EBSBN.js} +3 -3
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +4 -3
- package/server/index.js +26 -7
- package/server/lib/changelog/update-notes.js +2 -1
- package/server/lib/changelog/update-notes.test.js +19 -0
- package/server/lib/event-stream/DOCUMENTATION.md +23 -0
- package/server/lib/event-stream/delta-coalescer.js +0 -0
- package/server/lib/event-stream/delta-coalescer.test.js +292 -0
- package/server/lib/event-stream/global-hub.js +53 -23
- package/server/lib/event-stream/global-hub.test.js +160 -0
- package/server/lib/event-stream/global-ws-bridge.js +1 -0
- package/server/lib/event-stream/index.js +4 -0
- package/server/lib/git/DOCUMENTATION.md +17 -4
- package/server/lib/git/routes.js +1 -1
- package/server/lib/git/serial-refresh.js +93 -0
- package/server/lib/git/serial-refresh.test.js +112 -0
- package/server/lib/git/service.js +232 -62
- package/server/lib/git/service.test.js +273 -0
- package/server/lib/github/pr-status.js +5 -5
- package/server/lib/github/pr-status.test.js +1 -1
- package/server/lib/github/routes.js +4 -4
- package/server/lib/guests/DOCUMENTATION.md +5 -3
- package/server/lib/guests/background.test.js +83 -0
- package/server/lib/guests/catalog.js +20 -9
- package/server/lib/guests/catalog.test.js +5 -5
- package/server/lib/guests/routes.js +2 -2
- package/server/lib/message-queue/DOCUMENTATION.md +6 -0
- package/server/lib/message-queue/runtime.js +5 -0
- package/server/lib/message-queue/runtime.test.js +32 -1
- package/server/lib/opencode/feature-routes-runtime.js +5 -0
- package/server/lib/opencode/settings-helpers.js +3 -0
- package/server/lib/opencode/settings-registry.json +8 -0
- package/server/lib/permission-auto-accept/DOCUMENTATION.md +8 -0
- package/server/lib/permission-auto-accept/runtime.js +13 -0
- package/server/lib/permission-auto-accept/runtime.test.js +37 -1
- package/server/lib/routing/DOCUMENTATION.md +81 -0
- package/server/lib/routing/defaults.js +98 -0
- package/server/lib/routing/feature-flag.js +11 -0
- package/server/lib/routing/history.js +34 -0
- package/server/lib/routing/jev.js +98 -0
- package/server/lib/routing/routes.http.test.js +100 -0
- package/server/lib/routing/routes.js +81 -0
- package/server/lib/routing/runtime.js +217 -0
- package/server/lib/routing/runtime.test.js +188 -0
- package/server/lib/routing/store.js +249 -0
- package/server/lib/routing/store.test.js +96 -0
- package/server/lib/security/request-security.js +9 -5
- package/server/lib/security/request-security.test.js +37 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +8 -0
- package/server/lib/ui-auth/session-cookie.js +51 -0
- package/server/lib/ui-auth/session-cookie.test.js +46 -0
- package/server/lib/ui-auth/ui-auth.js +13 -9
- package/server/lib/ui-auth/ui-auth.test.js +56 -0
- package/dist/assets/DiffView-B7YkbY-u.js +0 -4
- package/dist/assets/DirtyBranchSwitchDialog-CU0A93Zx.js +0 -1
- package/dist/assets/GitView-BLhlMYEY.js +0 -6
- package/dist/assets/GuestAttachDialog-B-fwE8r3.js +0 -3
- package/dist/assets/SettingsView-n2X-jfBB.js +0 -29
- package/dist/assets/SettingsWindow-Bi8LE9XI.js +0 -1
- package/dist/assets/index-DpzTz2UH.css +0 -1
- package/dist/assets/index-Dy8xgawx.js +0 -40
- package/dist/assets/main-BOYSXfYn.js +0 -896
- package/dist/assets/markdownCore-DPrwM1rU.js +0 -5
- package/dist/assets/renderElectronMiniChatApp-uNEUkeAI.js +0 -2
- package/dist/assets/renderMobileApp-BK1kFlcJ.js +0 -25
- package/dist/assets/runtimeEndpointReset-BULHvOwb.js +0 -25
- package/dist/assets/tr-cIQtYBpg.js +0 -7
- package/dist/assets/useRootScrollLock-Cwc4kSl2.js +0 -1
|
@@ -58,7 +58,7 @@ const createOpenCode = () => {
|
|
|
58
58
|
return { state, fetchImpl };
|
|
59
59
|
};
|
|
60
60
|
|
|
61
|
-
const createRuntime = ({ dataDir = makeDataDir(), openCode = createOpenCode(), knowledge = null, retryDelayMs } = {}) => {
|
|
61
|
+
const createRuntime = ({ dataDir = makeDataDir(), openCode = createOpenCode(), knowledge = null, retryDelayMs, resolvePromptBody } = {}) => {
|
|
62
62
|
let eventHandler = () => {};
|
|
63
63
|
let statusHandler = () => {};
|
|
64
64
|
const broadcasts = [];
|
|
@@ -79,6 +79,7 @@ const createRuntime = ({ dataDir = makeDataDir(), openCode = createOpenCode(), k
|
|
|
79
79
|
abortHoldMs: 50,
|
|
80
80
|
};
|
|
81
81
|
if (retryDelayMs) options.retryDelayMs = retryDelayMs;
|
|
82
|
+
if (resolvePromptBody) options.resolvePromptBody = resolvePromptBody;
|
|
82
83
|
const runtime = createMessageQueueRuntime(options);
|
|
83
84
|
return {
|
|
84
85
|
runtime,
|
|
@@ -95,6 +96,36 @@ const settle = async (ms = 30) => {
|
|
|
95
96
|
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
96
97
|
};
|
|
97
98
|
|
|
99
|
+
describe('auto routing', () => {
|
|
100
|
+
it('lets the routing hook rewrite the model of a queued prompt and a queued command', async () => {
|
|
101
|
+
const resolvePromptBody = vi.fn(async (body) => {
|
|
102
|
+
if (body.model?.modelID === 'auto') body.model = { providerID: 'openai', modelID: 'gpt-6-astra' };
|
|
103
|
+
if (body.model === 'openchamber/auto') body.model = 'openai/gpt-6-astra';
|
|
104
|
+
return null;
|
|
105
|
+
});
|
|
106
|
+
const { runtime, openCode, emit } = createRuntime({ resolvePromptBody });
|
|
107
|
+
runtime.start();
|
|
108
|
+
openCode.state.statuses = { [SESSION]: { type: 'busy' } };
|
|
109
|
+
openCode.state.commands = [{ name: 'review', template: 'Review $ARGUMENTS' }];
|
|
110
|
+
const auto = { providerID: 'openchamber', modelID: 'auto', agent: 'build' };
|
|
111
|
+
await runtime.enqueue(SESSION, DIRECTORY, item({ content: 'plain', text: 'plain', sendConfig: auto }));
|
|
112
|
+
await runtime.enqueue(SESSION, DIRECTORY, item({ content: '/review src', text: '/review src', sendConfig: auto }));
|
|
113
|
+
|
|
114
|
+
openCode.state.statuses = {};
|
|
115
|
+
emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
|
|
116
|
+
await settle();
|
|
117
|
+
emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
|
|
118
|
+
await settle();
|
|
119
|
+
|
|
120
|
+
expect(openCode.state.sent.map((entry) => entry.body.model)).toEqual([
|
|
121
|
+
{ providerID: 'openai', modelID: 'gpt-6-astra' },
|
|
122
|
+
'openai/gpt-6-astra',
|
|
123
|
+
]);
|
|
124
|
+
expect(resolvePromptBody).toHaveBeenCalledTimes(2);
|
|
125
|
+
expect(resolvePromptBody.mock.calls[0][1]).toEqual({ sessionId: SESSION, directory: DIRECTORY });
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
98
129
|
describe('parseQueuedItemInput', () => {
|
|
99
130
|
it('rejects an item the server could not deliver later', () => {
|
|
100
131
|
expect(() => parseQueuedItemInput({ content: 'x' })).toThrow(TypeError);
|
|
@@ -18,6 +18,7 @@ import { registerAgentMemoryRoutes } from '../agent-memory/routes.js';
|
|
|
18
18
|
import { registerSessionKnowledgeRoutes } from '../session-knowledge/routes.js';
|
|
19
19
|
import { registerPermissionAutoAcceptRoutes } from '../permission-auto-accept/runtime.js';
|
|
20
20
|
import { registerMessageQueueRoutes } from '../message-queue/runtime.js';
|
|
21
|
+
import { registerRoutingPromptRewrite, registerRoutingRoutes } from '../routing/routes.js';
|
|
21
22
|
import { registerConfigEntityRoutes } from './config-entity-routes.js';
|
|
22
23
|
import { registerSettingsUtilityRoutes } from './core-routes.js';
|
|
23
24
|
import { registerProjectIconRoutes } from './project-icon-routes.js';
|
|
@@ -141,6 +142,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
|
|
141
142
|
emitSessionCreatedEvent,
|
|
142
143
|
permissionAutoAcceptRuntime,
|
|
143
144
|
messageQueueRuntime,
|
|
145
|
+
routingRuntime,
|
|
144
146
|
openchamberVersion,
|
|
145
147
|
} = routeDependencies;
|
|
146
148
|
|
|
@@ -154,6 +156,9 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
|
|
154
156
|
|
|
155
157
|
registerPermissionAutoAcceptRoutes(app, permissionAutoAcceptRuntime);
|
|
156
158
|
registerMessageQueueRoutes(app, messageQueueRuntime);
|
|
159
|
+
registerRoutingRoutes(app, routingRuntime);
|
|
160
|
+
// Before the generic OpenCode proxy: turns `openchamber/auto` into a real model.
|
|
161
|
+
registerRoutingPromptRewrite(app, routingRuntime);
|
|
157
162
|
|
|
158
163
|
registerOpenCodeRoutes(app, {
|
|
159
164
|
crypto,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
|
|
3
3
|
import { isAgentMemoryFeatureAvailable } from '../agent-memory/feature-flag.js';
|
|
4
|
+
import { isRoutingFeatureAvailable } from '../routing/feature-flag.js';
|
|
4
5
|
|
|
5
6
|
// Generated from packages/ui/src/lib/settings/registry.ts by
|
|
6
7
|
// `bun run settings-registry:generate`; `registry.test.ts` fails when stale.
|
|
@@ -1013,6 +1014,8 @@ export const createSettingsHelpers = (dependencies) => {
|
|
|
1013
1014
|
// Tells the client whether agent memory exists in this build at all, so
|
|
1014
1015
|
// its settings row and panel tab can be absent rather than merely off.
|
|
1015
1016
|
agentMemoryFeatureAvailable: isAgentMemoryFeatureAvailable(),
|
|
1017
|
+
// Same idea for Jev routing: absent from the picker and Settings unless the build has it.
|
|
1018
|
+
routingFeatureAvailable: isRoutingFeatureAvailable(),
|
|
1016
1019
|
...(pwaAppName ? { pwaAppName } : {}),
|
|
1017
1020
|
pwaOrientation,
|
|
1018
1021
|
mobileKeyboardMode,
|
|
@@ -127,6 +127,10 @@
|
|
|
127
127
|
"scope": "instance",
|
|
128
128
|
"computed": true
|
|
129
129
|
},
|
|
130
|
+
"routingFeatureAvailable": {
|
|
131
|
+
"scope": "instance",
|
|
132
|
+
"computed": true
|
|
133
|
+
},
|
|
130
134
|
"openCodeUpdateToastDismissedVersion": {
|
|
131
135
|
"scope": "instance"
|
|
132
136
|
},
|
|
@@ -624,6 +628,10 @@
|
|
|
624
628
|
"scope": "device",
|
|
625
629
|
"local": true
|
|
626
630
|
},
|
|
631
|
+
"messageQueueExpanded": {
|
|
632
|
+
"scope": "device",
|
|
633
|
+
"local": true
|
|
634
|
+
},
|
|
627
635
|
"workStatusScrollTop": {
|
|
628
636
|
"scope": "device",
|
|
629
637
|
"local": true
|
|
@@ -16,6 +16,14 @@ Policy inheritance uses the nearest explicit session value. A child `false` ther
|
|
|
16
16
|
|
|
17
17
|
Unknown lineage and failed policy loads fail closed. A failed pending-permission fetch is distinct from an empty successful response and never clears policy state.
|
|
18
18
|
|
|
19
|
+
## Safety net
|
|
20
|
+
|
|
21
|
+
`evaluatePermission` (the routing runtime, `../routing/DOCUMENTATION.md`) is
|
|
22
|
+
consulted after the policy check and before the reply. `hold` counts the
|
|
23
|
+
request as handled without replying, so it stays on screen; `accept` replies as
|
|
24
|
+
before. A `permission.replied` event is passed to `onPermissionReplied` so the
|
|
25
|
+
routing runtime forgets its cached decision.
|
|
26
|
+
|
|
19
27
|
## Routes
|
|
20
28
|
|
|
21
29
|
- `GET /api/permission-auto-accept`
|
|
@@ -25,6 +25,10 @@ export function createPermissionAutoAcceptRuntime({
|
|
|
25
25
|
readSettingsFromDiskMigrated,
|
|
26
26
|
persistSettings,
|
|
27
27
|
broadcastGlobalUiEvent,
|
|
28
|
+
// The routing safety net: asked once per request before the automatic reply.
|
|
29
|
+
// `hold` leaves the request for the user; absent means every request is replied to.
|
|
30
|
+
evaluatePermission = null,
|
|
31
|
+
onPermissionReplied = null,
|
|
28
32
|
fetchImpl = fetch,
|
|
29
33
|
retryDelaysMs = RETRY_DELAYS_MS,
|
|
30
34
|
requestTimeoutMs = REQUEST_TIMEOUT_MS,
|
|
@@ -148,6 +152,10 @@ export function createPermissionAutoAcceptRuntime({
|
|
|
148
152
|
if (!permission?.id || !permission?.sessionID) return false;
|
|
149
153
|
await load();
|
|
150
154
|
if (!(await isSessionAutoAccepting(permission.sessionID, directory))) return false;
|
|
155
|
+
if (evaluatePermission) {
|
|
156
|
+
const verdict = await evaluatePermission(permission, directory);
|
|
157
|
+
if (verdict?.action === 'hold') return true;
|
|
158
|
+
}
|
|
151
159
|
await request(`/permission/${encodeURIComponent(permission.id)}/reply`, {
|
|
152
160
|
directory,
|
|
153
161
|
method: 'POST',
|
|
@@ -218,6 +226,11 @@ export function createPermissionAutoAcceptRuntime({
|
|
|
218
226
|
}
|
|
219
227
|
if (payload?.type === 'permission.asked') {
|
|
220
228
|
void processPermission(payload.properties, directory);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (payload?.type === 'permission.replied') {
|
|
232
|
+
const permissionId = payload.properties?.requestID;
|
|
233
|
+
if (typeof permissionId === 'string') onPermissionReplied?.(permissionId);
|
|
221
234
|
}
|
|
222
235
|
};
|
|
223
236
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { describe, expect, it, vi } from 'vitest';
|
|
2
2
|
import { createPermissionAutoAcceptRuntime } from './runtime.js';
|
|
3
3
|
|
|
4
|
-
const createRuntime = ({ stored, fetchImpl, retryDelaysMs = [0] } = {}) => {
|
|
4
|
+
const createRuntime = ({ stored, fetchImpl, retryDelaysMs = [0], evaluatePermission, onPermissionReplied } = {}) => {
|
|
5
5
|
let settings = stored ?? { permissionAutoAccept: { sessions: {} } };
|
|
6
6
|
let eventHandler;
|
|
7
7
|
let statusHandler;
|
|
@@ -16,6 +16,8 @@ const createRuntime = ({ stored, fetchImpl, retryDelaysMs = [0] } = {}) => {
|
|
|
16
16
|
persistSettings: async (changes) => { settings = { ...settings, ...changes }; },
|
|
17
17
|
fetchImpl: fetchImpl ?? vi.fn(async () => new Response('[]')),
|
|
18
18
|
retryDelaysMs,
|
|
19
|
+
evaluatePermission,
|
|
20
|
+
onPermissionReplied,
|
|
19
21
|
});
|
|
20
22
|
runtime.start();
|
|
21
23
|
return {
|
|
@@ -143,4 +145,38 @@ describe('permission auto-accept runtime', () => {
|
|
|
143
145
|
expect(fetchImpl.mock.calls.some(([url]) => new URL(url).searchParams.get('directory') === '/project')).toBe(true);
|
|
144
146
|
expect(await runtime.load()).toEqual({ sessions: { root: true }, revision: 1 });
|
|
145
147
|
});
|
|
148
|
+
|
|
149
|
+
it('leaves a request held by the safety net unanswered and forgets it once replied', async () => {
|
|
150
|
+
const fetchImpl = vi.fn(async () => new Response('[]'));
|
|
151
|
+
const verdicts = { held: { action: 'hold', score: 0.9, kind: 'git_history' }, safe: { action: 'accept', score: 0.1 } };
|
|
152
|
+
const evaluatePermission = vi.fn(async (permission) => verdicts[permission.id]);
|
|
153
|
+
const onPermissionReplied = vi.fn();
|
|
154
|
+
const { runtime, emit } = createRuntime({
|
|
155
|
+
stored: { permissionAutoAccept: { sessions: { root: true } } },
|
|
156
|
+
fetchImpl,
|
|
157
|
+
evaluatePermission,
|
|
158
|
+
onPermissionReplied,
|
|
159
|
+
});
|
|
160
|
+
await runtime.load();
|
|
161
|
+
|
|
162
|
+
emit({ type: 'permission.asked', properties: { id: 'held', sessionID: 'root', permission: 'bash', metadata: {} } });
|
|
163
|
+
emit({ type: 'permission.asked', properties: { id: 'safe', sessionID: 'root', permission: 'bash', metadata: {} } });
|
|
164
|
+
await flush();
|
|
165
|
+
|
|
166
|
+
const replies = fetchImpl.mock.calls.map(([url]) => String(url)).filter((url) => url.includes('/reply'));
|
|
167
|
+
expect(replies).toEqual(['http://opencode.test/permission/safe/reply?directory=%2Fproject']);
|
|
168
|
+
expect(evaluatePermission).toHaveBeenCalledTimes(2);
|
|
169
|
+
|
|
170
|
+
emit({ type: 'permission.replied', properties: { sessionID: 'root', requestID: 'held', reply: 'once' } });
|
|
171
|
+
expect(onPermissionReplied).toHaveBeenCalledWith('held');
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it('does not consult the safety net for sessions that are not auto-accepting', async () => {
|
|
175
|
+
const evaluatePermission = vi.fn(async () => ({ action: 'hold' }));
|
|
176
|
+
const { runtime, emit } = createRuntime({ evaluatePermission });
|
|
177
|
+
await runtime.load();
|
|
178
|
+
emit({ type: 'permission.asked', properties: { id: 'p', sessionID: 'manual', permission: 'bash', metadata: {} } });
|
|
179
|
+
await flush();
|
|
180
|
+
expect(evaluatePermission).not.toHaveBeenCalled();
|
|
181
|
+
});
|
|
146
182
|
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Routing
|
|
2
|
+
|
|
3
|
+
## Purpose
|
|
4
|
+
|
|
5
|
+
Jev model routing and the permission safety net. With the `openchamber/auto`
|
|
6
|
+
model selected, the server asks [Jev](https://docs.typesafe.ai) (TypeSafe's
|
|
7
|
+
System One decision model) which task category a message belongs to and sends
|
|
8
|
+
it with that category's model, thinking variant and agent. With the safety net
|
|
9
|
+
on, the same call decides whether an auto-accepted permission should stay on
|
|
10
|
+
screen for the user instead.
|
|
11
|
+
|
|
12
|
+
Dark by default: `OPENCHAMBER_ROUTING_ENABLE` (`feature-flag.js`, read per call)
|
|
13
|
+
gates the routes, the request rewrite, the settings page and the Auto row. VS
|
|
14
|
+
Code has no OpenChamber server and never offers Auto.
|
|
15
|
+
|
|
16
|
+
## Files
|
|
17
|
+
|
|
18
|
+
- `feature-flag.js` — the env gate.
|
|
19
|
+
- `defaults.js` — the Auto sentinel, Jev endpoint, built-in categories, the
|
|
20
|
+
question wording for routing and for the safety net, history excerpt limits.
|
|
21
|
+
- `store.js` — `routing.json` (only deviations from the built-ins) and
|
|
22
|
+
`routing-auth.json` (the Jev key alone, mode 0600) in the OpenChamber data
|
|
23
|
+
dir. `resolveEffectiveConfig` merges built-ins with stored overrides;
|
|
24
|
+
`toStoredConfig` is its inverse. A missing file is the defaults, a malformed
|
|
25
|
+
one throws.
|
|
26
|
+
- `jev.js` — request builders, answer parsing, the HTTP call with a timeout.
|
|
27
|
+
- `history.js` — the last three settled turns through session assist's
|
|
28
|
+
`loadAssistContext` (text parts only, attached quotes included, no files or
|
|
29
|
+
tool payloads), each user message cut to its head and each answer to head
|
|
30
|
+
plus tail. The new request is never cut.
|
|
31
|
+
- `runtime.js` — `createRoutingRuntime`: `describe`, `resolvePromptBody`,
|
|
32
|
+
`evaluatePermission`, config and token writes, event broadcasts.
|
|
33
|
+
- `routes.js` — `/api/routing` (GET, PUT), `/api/routing/token` (PUT, DELETE)
|
|
34
|
+
and `registerRoutingPromptRewrite`.
|
|
35
|
+
|
|
36
|
+
## Invariants
|
|
37
|
+
|
|
38
|
+
- The sentinel never reaches OpenCode. `resolvePromptBody` rewrites
|
|
39
|
+
`body.model` in place for `POST /api/session/:id/{prompt_async,prompt,command}`
|
|
40
|
+
ahead of the generic proxy (which replays a parsed body) and inside the
|
|
41
|
+
message queue's `sendItem`. Without a fallback model it throws 400 rather than
|
|
42
|
+
forwarding.
|
|
43
|
+
- Every failure keeps the user's own behaviour. A Jev error, timeout, unknown
|
|
44
|
+
category or low confidence routes to the fallback model; the decision carries
|
|
45
|
+
the reason. A safety-net failure accepts the permission exactly as auto-accept
|
|
46
|
+
would have and broadcasts `openchamber:routing.safety-skipped` with the error.
|
|
47
|
+
- A category without a model uses the fallback model *and* variant; a variant
|
|
48
|
+
only travels with the model it was chosen for. A category agent replaces the
|
|
49
|
+
composer's agent; an empty one keeps it.
|
|
50
|
+
- Auto is offered (`autoReady`) only with the flag, `enabled`, a saved key, a
|
|
51
|
+
fallback model and at least two enabled categories.
|
|
52
|
+
- Held permission decisions are cached for 15 minutes per request id so
|
|
53
|
+
reconnect reconciliation in `permission-auto-accept` does not re-ask Jev;
|
|
54
|
+
`permission.replied` forgets them.
|
|
55
|
+
- The rewrite parses JSON only while the flag is set, so a build without it
|
|
56
|
+
leaves the proxy stream untouched.
|
|
57
|
+
|
|
58
|
+
## Events
|
|
59
|
+
|
|
60
|
+
Broadcast on the OpenChamber control stream: `openchamber:routing.updated`
|
|
61
|
+
(availability), `openchamber:routing.decision` (per send),
|
|
62
|
+
`openchamber:routing.permission-held`, `openchamber:routing.safety-skipped`.
|
|
63
|
+
|
|
64
|
+
## UI
|
|
65
|
+
|
|
66
|
+
`packages/ui/src/stores/useRoutingStore.ts` projects `/api/routing` and these
|
|
67
|
+
events; `hooks/useRoutingSync.ts` keeps it current and shows the skipped-check
|
|
68
|
+
toast. `lib/routing/autoModel.ts` owns the sentinel; `useConfigStore` accepts it
|
|
69
|
+
as a valid selection while `autoReady`. `ModelPickerList` renders it as the
|
|
70
|
+
pinned `leadingEntry`; `ModelControls` hides the agent and thinking controls
|
|
71
|
+
while Auto is selected. `PermissionCard` shows the hold reason. Settings →
|
|
72
|
+
Routing (`components/sections/routing/RoutingPage.tsx`) edits the config with
|
|
73
|
+
debounced saves and manages the key.
|
|
74
|
+
|
|
75
|
+
## Tests
|
|
76
|
+
|
|
77
|
+
`store.test.js` (defaults, deviation round-trip, deleted built-ins, malformed
|
|
78
|
+
file, token file mode), `runtime.test.js` (request text, excerpts, decisions,
|
|
79
|
+
rewrite and fallback paths, safety net hold/skip/off), `routes.http.test.js`
|
|
80
|
+
(rewrite ahead of a stand-in proxy, routes, flag off). The queue and
|
|
81
|
+
auto-accept tests cover their hooks.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Built-in routing configuration. Everything here is the shipped default; the
|
|
3
|
+
* user's `routing.json` stores only deviations from it, so a later change to a
|
|
4
|
+
* built-in category reaches everyone who did not edit that category.
|
|
5
|
+
*
|
|
6
|
+
* Category descriptions are what Jev reads, verbatim, as the criteria of one
|
|
7
|
+
* choice question. Keep them about the reasoning a request demands, never about
|
|
8
|
+
* the length of the reply: that wording moved a long mechanical rename from
|
|
9
|
+
* "hard" to "trivial" in the lab runs.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { z } from 'zod';
|
|
13
|
+
|
|
14
|
+
const AUTO_PROVIDER_ID = 'openchamber';
|
|
15
|
+
const AUTO_MODEL_ID = 'auto';
|
|
16
|
+
|
|
17
|
+
const autoModelSchema = z.object({ providerID: z.literal(AUTO_PROVIDER_ID), modelID: z.literal(AUTO_MODEL_ID) });
|
|
18
|
+
const autoModelStringSchema = z.literal(`${AUTO_PROVIDER_ID}/${AUTO_MODEL_ID}`);
|
|
19
|
+
|
|
20
|
+
/** The command route carries the model as `provider/model`; the prompt routes as an object. */
|
|
21
|
+
export const isAutoModel = (model) => autoModelSchema.safeParse(model).success || autoModelStringSchema.safeParse(model).success;
|
|
22
|
+
|
|
23
|
+
export const JEV_API_ORIGIN = 'https://api.typesafe.ai';
|
|
24
|
+
export const JEV_API_PATH = '/v1/systemone';
|
|
25
|
+
export const JEV_MODEL = 'jev-latest';
|
|
26
|
+
|
|
27
|
+
/** Per-attempt timeout; the lab measured 250–700 ms warm, ~1 s on a cold TLS handshake. */
|
|
28
|
+
export const JEV_TIMEOUT_MS = 4000;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The third line keeps a hard turn from dragging its follow-ups up. With a
|
|
32
|
+
* plain "classify request only" wording, "дякую, все працює" after a hard fix
|
|
33
|
+
* came back hard at ~40% and "запуш" trivial at ~50%, both under the threshold,
|
|
34
|
+
* so the fallback model took them. Saying that history only resolves what the
|
|
35
|
+
* request refers to, and that finished work carries no weight, put them at
|
|
36
|
+
* 97% and ~75% trivial while "ok, do it" after a plan stayed implement and a
|
|
37
|
+
* regression report stayed hard (jev-router lab, test/follow-up-instructions.js).
|
|
38
|
+
*/
|
|
39
|
+
export const ROUTING_INSTRUCTIONS = [
|
|
40
|
+
'Pick the task category that best describes this coding request, judging the reasoning it demands rather than the length of the reply it asks for.',
|
|
41
|
+
'A request that wants a one-line answer to a hard debugging or design question is still hard; a long but mechanical edit is still trivial.',
|
|
42
|
+
'The thing to classify is `request`, the latest user message. Read `history` (earlier conversation, oldest first) only to understand what `request` refers to, then judge the reasoning `request` itself demands. Do not let the difficulty of work already done in `history` raise or lower the category.',
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Measured on 31 mixed bash/edit/mcp/webfetch permissions: this "should the agent
|
|
47
|
+
* ask" wording scored 28/31 at threshold 0.6 with every miss on the safe side,
|
|
48
|
+
* while "is it destructive" scored 23/31 and let through `brew install`, closing
|
|
49
|
+
* a PR, and edits to ~/.zshrc and ~/.ssh.
|
|
50
|
+
*/
|
|
51
|
+
export const SAFETY_INSTRUCTIONS = [
|
|
52
|
+
'An autonomous coding agent is about to perform this action inside a software project, and the user has allowed routine actions to proceed without asking.',
|
|
53
|
+
'Should the agent stop and ask the user first, instead of proceeding automatically?',
|
|
54
|
+
'Yes when the action is hard to undo, or reaches outside the project working tree (the system, the home directory, remote services, other people), or changes shared state others can see, or discards uncommitted work.',
|
|
55
|
+
"No for reading, searching, building, testing, installing project dependencies, ordinary commits, pushes and rebases of the agent's own branch, and file edits inside the project.",
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
/** Effect kinds reported alongside the hold decision; the UI shows the chosen one as the reason. */
|
|
59
|
+
export const SAFETY_KINDS = {
|
|
60
|
+
read_only: 'Reads, lists, searches, builds, tests, or fetches public information; changes nothing.',
|
|
61
|
+
writes_project: 'Creates or edits files inside the project in a way version control can undo.',
|
|
62
|
+
git_history: 'Rewrites, deletes, or force-pushes git history or branches, or discards uncommitted work.',
|
|
63
|
+
deletes_data: 'Deletes files or data outside version control, drops databases, or wipes directories.',
|
|
64
|
+
system_change: 'Installs, removes, or reconfigures software, services, or system settings.',
|
|
65
|
+
external_side_effect: 'Changes state in an external system: posts, sends, deploys, pays, closes, or deletes something remotely.',
|
|
66
|
+
data_exfiltration: 'Sends local files, secrets, or private data to an external host, or fetches and executes remote code.',
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** History excerpts: a user message keeps its head, an answer keeps head and tail. */
|
|
70
|
+
export const HISTORY_LIMITS = { turns: 3, user: 600, answerHead: 300, answerTail: 300 };
|
|
71
|
+
|
|
72
|
+
export const THINKING_LEVELS = ['off', 'low', 'medium', 'high'];
|
|
73
|
+
|
|
74
|
+
export const BUILTIN_CATEGORIES = [
|
|
75
|
+
{
|
|
76
|
+
id: 'trivial',
|
|
77
|
+
name: 'Trivial',
|
|
78
|
+
description: 'Trivial, mechanical, or purely factual work: rename a symbol, fix a typo, reformat, add a comment, answer a short factual question about a known file, run one obvious command and report the output. Not for anything requiring design judgement or multi-file reasoning.',
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
id: 'research',
|
|
82
|
+
name: 'Research',
|
|
83
|
+
description: 'Read and explain existing code or behaviour without changing it: explain how a module works, find where something is implemented, summarise what a change does. Not for requests that ask for edits or a plan.',
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
id: 'implement',
|
|
87
|
+
name: 'Implement',
|
|
88
|
+
description: 'Ordinary engineering with a clear, bounded shape: implement a well-specified function, endpoint, or component; write or fix tests for existing behaviour; a localised bug fix where the cause is already understood. Not for open-ended architecture, subtle concurrency, or unknown-cause debugging.',
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: 'hard',
|
|
92
|
+
name: 'Hard',
|
|
93
|
+
description: 'Hard reasoning, ambiguity, planning, or high blast radius: debug a failure whose cause is unknown, plan or design a change across several modules, security, auth, concurrency, data-migration, or money-handling logic. Not for work a competent mid-level engineer would finish without thinking hard.',
|
|
94
|
+
},
|
|
95
|
+
];
|
|
96
|
+
|
|
97
|
+
export const DEFAULT_MIN_CONFIDENCE = 0.6;
|
|
98
|
+
export const DEFAULT_SAFETY_THRESHOLD = 0.6;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether Jev model routing exists at all in this build.
|
|
3
|
+
*
|
|
4
|
+
* The feature ships dark, the same way agent memory does: with the flag unset
|
|
5
|
+
* there is no Auto row in the model picker, no settings page, no routes and no
|
|
6
|
+
* request rewriting. Read per call so only the process environment decides.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const TRUTHY = new Set(['1', 'true', 'yes', 'on']);
|
|
10
|
+
|
|
11
|
+
export const isRoutingFeatureAvailable = () => TRUTHY.has((process.env.OPENCHAMBER_ROUTING_ENABLE ?? '').trim().toLowerCase());
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversation Jev sees next to the new request: the last settled turns,
|
|
3
|
+
* read the same way session assist reads them (text parts only, attached
|
|
4
|
+
* quotes included, tool payloads and files never), then cut down per message.
|
|
5
|
+
* A user message keeps its head, where the task usually sits; an answer keeps
|
|
6
|
+
* head and tail, where the finding and the outcome sit. The new request itself
|
|
7
|
+
* is never cut.
|
|
8
|
+
*/
|
|
9
|
+
import { loadAssistContext } from '../session-assist/context.js';
|
|
10
|
+
import { HISTORY_LIMITS } from './defaults.js';
|
|
11
|
+
|
|
12
|
+
export const excerptHead = (text, limit) => (text.length <= limit ? text : `${text.slice(0, limit).trimEnd()} […]`);
|
|
13
|
+
|
|
14
|
+
export const excerptHeadTail = (text, head, tail) =>
|
|
15
|
+
(text.length <= head + tail ? text : `${text.slice(0, head).trimEnd()} […] ${text.slice(-tail).trimStart()}`);
|
|
16
|
+
|
|
17
|
+
export const turnsToHistory = (turns, limits = HISTORY_LIMITS) => {
|
|
18
|
+
const history = [];
|
|
19
|
+
for (const turn of turns.slice(-limits.turns)) {
|
|
20
|
+
if (turn.user?.text) history.push({ role: 'user', text: excerptHead(turn.user.text, limits.user) });
|
|
21
|
+
if (turn.assistant?.text) history.push({ role: 'assistant', text: excerptHeadTail(turn.assistant.text, limits.answerHead, limits.answerTail) });
|
|
22
|
+
}
|
|
23
|
+
return history;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Empty when the session has no settled answer yet (a new session, or one
|
|
28
|
+
* interrupted mid-turn) — routing then judges the request on its own. A read
|
|
29
|
+
* failure is thrown so the caller can decide; it is not an empty history.
|
|
30
|
+
*/
|
|
31
|
+
export const loadRoutingHistory = async ({ readPage, signal }) => {
|
|
32
|
+
const context = await loadAssistContext({ readPage, signal });
|
|
33
|
+
return context ? turnsToHistory(context.turns) : [];
|
|
34
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Jev side of routing: request shapes and the HTTP call. Pure builders are
|
|
3
|
+
* exported so the decision logic can be tested without a network.
|
|
4
|
+
*/
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import {
|
|
7
|
+
JEV_API_ORIGIN,
|
|
8
|
+
JEV_API_PATH,
|
|
9
|
+
JEV_MODEL,
|
|
10
|
+
JEV_TIMEOUT_MS,
|
|
11
|
+
ROUTING_INSTRUCTIONS,
|
|
12
|
+
SAFETY_INSTRUCTIONS,
|
|
13
|
+
SAFETY_KINDS,
|
|
14
|
+
} from './defaults.js';
|
|
15
|
+
|
|
16
|
+
export const buildRoutingRequest = ({ categories, history, request }) => {
|
|
17
|
+
const criteria = {};
|
|
18
|
+
for (const category of categories) criteria[category.id] = category.description;
|
|
19
|
+
return {
|
|
20
|
+
model: JEV_MODEL,
|
|
21
|
+
state: { history, request },
|
|
22
|
+
questions: { category: { type: 'choice', instructions: ROUTING_INSTRUCTIONS, criteria } },
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** `permission` is what OpenCode reported: the tool kind, its patterns and its metadata. */
|
|
27
|
+
export const buildPermissionRequest = (permission) => ({
|
|
28
|
+
model: JEV_MODEL,
|
|
29
|
+
state: {
|
|
30
|
+
permission: {
|
|
31
|
+
type: permission.permission,
|
|
32
|
+
patterns: permission.patterns,
|
|
33
|
+
metadata: permission.metadata,
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
questions: {
|
|
37
|
+
ask: { type: 'noul', instructions: SAFETY_INSTRUCTIONS },
|
|
38
|
+
kind: { type: 'choice', instructions: 'What is the most significant effect of this action?', criteria: SAFETY_KINDS },
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const choiceAnswerSchema = z.object({ choice: z.string(), confidence: z.number() });
|
|
43
|
+
const noulAnswerSchema = z.object({ noul: z.number() });
|
|
44
|
+
const permissionAnswersSchema = z.object({
|
|
45
|
+
ask: noulAnswerSchema,
|
|
46
|
+
kind: z.object({ choice: z.string() }).partial().optional(),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Maps a Jev answer onto the category to use. Anything short of a confident,
|
|
51
|
+
* known, enabled category is the fallback; the reason says which.
|
|
52
|
+
*/
|
|
53
|
+
export const decideRouting = (answer, { categories, minConfidence }) => {
|
|
54
|
+
const parsed = choiceAnswerSchema.safeParse(answer);
|
|
55
|
+
if (!parsed.success) return { category: null, reason: 'unknown-category', confidence: 0 };
|
|
56
|
+
const category = categories.find((c) => c.id === parsed.data.choice) ?? null;
|
|
57
|
+
if (!category) return { category: null, reason: 'unknown-category', confidence: parsed.data.confidence };
|
|
58
|
+
if (parsed.data.confidence < minConfidence) return { category: null, reason: 'low-confidence', confidence: parsed.data.confidence };
|
|
59
|
+
return { category, reason: 'routed', confidence: parsed.data.confidence };
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export const decidePermission = (answers, { threshold }) => {
|
|
63
|
+
const parsed = permissionAnswersSchema.safeParse(answers);
|
|
64
|
+
if (!parsed.success) throw new Error('Jev answer is missing the ask score');
|
|
65
|
+
const score = parsed.data.ask.noul;
|
|
66
|
+
return { hold: score >= threshold, score, kind: parsed.data.kind?.choice ?? null };
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const responseSchema = z.object({ answers: z.record(z.string(), z.unknown()) });
|
|
70
|
+
|
|
71
|
+
export const createJevClient = ({ fetchImpl = fetch, timeoutMs = JEV_TIMEOUT_MS } = {}) => ({
|
|
72
|
+
/** Resolves to the parsed answers; throws with `status` on an HTTP error and `code: 'timeout'` on abort. */
|
|
73
|
+
ask: async (request, token) => {
|
|
74
|
+
const abort = new AbortController();
|
|
75
|
+
const timer = setTimeout(() => abort.abort(), timeoutMs);
|
|
76
|
+
const started = Date.now();
|
|
77
|
+
try {
|
|
78
|
+
const response = await fetchImpl(JEV_API_ORIGIN + JEV_API_PATH, {
|
|
79
|
+
method: 'POST',
|
|
80
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
81
|
+
body: JSON.stringify(request),
|
|
82
|
+
signal: abort.signal,
|
|
83
|
+
});
|
|
84
|
+
const text = await response.text();
|
|
85
|
+
if (!response.ok) {
|
|
86
|
+
throw Object.assign(new Error(`Jev responded ${response.status}`), { status: response.status });
|
|
87
|
+
}
|
|
88
|
+
const body = responseSchema.safeParse(JSON.parse(text));
|
|
89
|
+
if (!body.success) throw new Error('Jev response has no answers');
|
|
90
|
+
return { answers: body.data.answers, ms: Date.now() - started };
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error?.name === 'AbortError') throw Object.assign(new Error(`Jev timed out after ${timeoutMs}ms`), { code: 'timeout' });
|
|
93
|
+
throw error;
|
|
94
|
+
} finally {
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
});
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import request from 'supertest';
|
|
3
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
4
|
+
|
|
5
|
+
import { registerRoutingPromptRewrite, registerRoutingRoutes } from './routes.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The prompt rewrite sits in front of the generic OpenCode proxy, which
|
|
9
|
+
* replays `req.body` when a middleware parsed it. These tests mount the
|
|
10
|
+
* rewrite ahead of a stand-in proxy that records what it would forward.
|
|
11
|
+
*/
|
|
12
|
+
const createApp = ({ flag = '1', resolvePromptBody } = {}) => {
|
|
13
|
+
process.env.OPENCHAMBER_ROUTING_ENABLE = flag;
|
|
14
|
+
const forwarded = [];
|
|
15
|
+
const runtime = {
|
|
16
|
+
resolvePromptBody: resolvePromptBody ?? vi.fn(async (body) => {
|
|
17
|
+
if (body.model?.modelID === 'auto') body.model = { providerID: 'openai', modelID: 'gpt-6-astra' };
|
|
18
|
+
return null;
|
|
19
|
+
}),
|
|
20
|
+
describe: async () => ({ available: true, autoReady: true, tokenPresent: true, config: null, builtins: [] }),
|
|
21
|
+
heldPermissions: () => [],
|
|
22
|
+
updateConfig: vi.fn(async () => ({ available: true })),
|
|
23
|
+
setToken: vi.fn(async () => ({ available: true, tokenPresent: true })),
|
|
24
|
+
clearToken: vi.fn(async () => ({ available: true, tokenPresent: false })),
|
|
25
|
+
};
|
|
26
|
+
const app = express();
|
|
27
|
+
registerRoutingRoutes(app, runtime);
|
|
28
|
+
registerRoutingPromptRewrite(app, runtime);
|
|
29
|
+
// Stand-in for the OpenCode proxy: a parsed body arrives as `req.body`, an
|
|
30
|
+
// untouched stream arrives as raw bytes.
|
|
31
|
+
app.use('/api', (req, res) => {
|
|
32
|
+
if (req.body !== undefined) {
|
|
33
|
+
forwarded.push({ path: req.path, parsed: true, body: req.body });
|
|
34
|
+
return res.status(204).end();
|
|
35
|
+
}
|
|
36
|
+
let raw = '';
|
|
37
|
+
req.on('data', (chunk) => { raw += chunk; });
|
|
38
|
+
req.on('end', () => {
|
|
39
|
+
forwarded.push({ path: req.path, parsed: false, raw });
|
|
40
|
+
res.status(204).end();
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
return { app, runtime, forwarded };
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
afterEach(() => {
|
|
47
|
+
delete process.env.OPENCHAMBER_ROUTING_ENABLE;
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe('routing prompt rewrite', () => {
|
|
51
|
+
it('rewrites the Auto sentinel on prompt_async and passes the directory along', async () => {
|
|
52
|
+
const { app, runtime, forwarded } = createApp();
|
|
53
|
+
await request(app)
|
|
54
|
+
.post('/api/session/s1/prompt_async?directory=%2Frepo')
|
|
55
|
+
.send({ model: { providerID: 'openchamber', modelID: 'auto' }, parts: [{ type: 'text', text: 'hi' }] })
|
|
56
|
+
.expect(204);
|
|
57
|
+
expect(forwarded).toEqual([{ path: '/session/s1/prompt_async', parsed: true, body: { model: { providerID: 'openai', modelID: 'gpt-6-astra' }, parts: [{ type: 'text', text: 'hi' }] } }]);
|
|
58
|
+
expect(runtime.resolvePromptBody).toHaveBeenCalledWith(expect.anything(), { sessionId: 's1', directory: '/repo' });
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('leaves the stream untouched when the flag is off or the body is not JSON', async () => {
|
|
62
|
+
const off = createApp({ flag: '' });
|
|
63
|
+
await request(off.app).post('/api/session/s1/prompt').send({ model: { providerID: 'openchamber', modelID: 'auto' } }).expect(204);
|
|
64
|
+
expect(off.forwarded[0].parsed).toBe(false);
|
|
65
|
+
expect(off.runtime.resolvePromptBody).not.toHaveBeenCalled();
|
|
66
|
+
|
|
67
|
+
const text = createApp();
|
|
68
|
+
await request(text.app).post('/api/session/s1/command').set('content-type', 'text/plain').send('raw').expect(204);
|
|
69
|
+
expect(text.forwarded[0]).toEqual({ path: '/session/s1/command', parsed: false, raw: 'raw' });
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('answers with the runtime error instead of forwarding an unresolved sentinel', async () => {
|
|
73
|
+
const { app, forwarded } = createApp({
|
|
74
|
+
resolvePromptBody: vi.fn(async () => { throw Object.assign(new Error('no fallback'), { status: 400 }); }),
|
|
75
|
+
});
|
|
76
|
+
const response = await request(app).post('/api/session/s1/prompt_async').send({ model: { providerID: 'openchamber', modelID: 'auto' } });
|
|
77
|
+
expect(response.status).toBe(400);
|
|
78
|
+
expect(response.body).toEqual({ error: 'no fallback' });
|
|
79
|
+
expect(forwarded).toEqual([]);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe('routing routes', () => {
|
|
84
|
+
it('serves state, saves config and manages the token', async () => {
|
|
85
|
+
const { app, runtime } = createApp();
|
|
86
|
+
const state = await request(app).get('/api/routing').expect(200);
|
|
87
|
+
expect(state.body).toMatchObject({ available: true, autoReady: true, heldPermissions: [] });
|
|
88
|
+
await request(app).put('/api/routing').send({ config: { enabled: true } }).expect(200);
|
|
89
|
+
expect(runtime.updateConfig).toHaveBeenCalledWith({ enabled: true });
|
|
90
|
+
await request(app).put('/api/routing/token').send({ token: 'ts-key' }).expect(200);
|
|
91
|
+
expect(runtime.setToken).toHaveBeenCalledWith('ts-key');
|
|
92
|
+
await request(app).delete('/api/routing/token').expect(200);
|
|
93
|
+
expect(runtime.clearToken).toHaveBeenCalled();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('is absent without the feature flag', async () => {
|
|
97
|
+
const { app } = createApp({ flag: '' });
|
|
98
|
+
await request(app).put('/api/routing/token').send({ token: 'x' }).expect(404);
|
|
99
|
+
});
|
|
100
|
+
});
|