@openchamber/web 1.14.0 → 1.15.0

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 (100) hide show
  1. package/bin/cli.test.js +8 -0
  2. package/bin/lib/DOCUMENTATION.md +3 -0
  3. package/bin/lib/cli-args.js +10 -0
  4. package/bin/lib/commands-connect-url.js +169 -22
  5. package/dist/assets/{DiagramView-CIaZCGUT.js → DiagramView-HR2xZxJ8.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
  7. package/dist/assets/{MultiRunWindow-Bsbr3i8y.js → MultiRunWindow-DlFUaNQK.js} +1 -1
  8. package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
  9. package/dist/assets/{SessionSwitcherDropdown-CLm6tF5n.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
  10. package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
  11. package/dist/assets/{TerminalView-DF7-jlam.js → TerminalView-D_9BAjtv.js} +3 -3
  12. package/dist/assets/es-cjUissX4.js +15 -0
  13. package/dist/assets/fr-DqbXnTdK.js +13 -0
  14. package/dist/assets/index-Dg0nmvQU.css +1 -0
  15. package/dist/assets/index-ltrmNGAf.js +2 -0
  16. package/dist/assets/ja-Cetyq6Eg.js +15 -0
  17. package/dist/assets/ko-DtunWisP.js +15 -0
  18. package/dist/assets/main-BC0m8s1v.js +236 -0
  19. package/dist/assets/main-DzNa8r0N.js +2 -0
  20. package/dist/assets/miniChat-BRYDE-Se.js +2 -0
  21. package/dist/assets/mobile-C3QJVA97.js +2 -0
  22. package/dist/assets/pl-DctGLgve.js +15 -0
  23. package/dist/assets/pt-BR-CXPhf78S.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
  25. package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
  27. package/dist/assets/uk-Bdrc-kqF.js +15 -0
  28. package/dist/assets/{useAppFontEffects-DTO332li.js → useAppFontEffects-DzBg8hrC.js} +132 -116
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
  31. package/dist/assets/zh-TW-CoqiQING.js +15 -0
  32. package/dist/index.html +4 -4
  33. package/dist/mini-chat.html +4 -4
  34. package/dist/mobile.html +4 -4
  35. package/package.json +2 -2
  36. package/server/index.js +157 -6
  37. package/server/lib/client-auth/pairing.js +308 -0
  38. package/server/lib/client-auth/pairing.test.js +142 -0
  39. package/server/lib/client-auth/remote-clients.js +65 -3
  40. package/server/lib/notifications/apns-runtime.js +9 -16
  41. package/server/lib/opencode/bootstrap-runtime.js +10 -0
  42. package/server/lib/opencode/core-routes.js +247 -6
  43. package/server/lib/opencode/core-routes.test.js +248 -9
  44. package/server/lib/opencode/feature-routes-runtime.js +10 -0
  45. package/server/lib/opencode/models-metadata.js +61 -0
  46. package/server/lib/opencode/network-runtime.js +14 -1
  47. package/server/lib/opencode/network-runtime.test.js +29 -9
  48. package/server/lib/opencode/openchamber-routes.js +7 -40
  49. package/server/lib/opencode/proxy.js +47 -6
  50. package/server/lib/opencode/settings-helpers.js +16 -0
  51. package/server/lib/opencode/settings-helpers.test.js +11 -0
  52. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  53. package/server/lib/opencode/shutdown-runtime.js +2 -0
  54. package/server/lib/package-manager.js +18 -5
  55. package/server/lib/relay/DOCUMENTATION.md +78 -0
  56. package/server/lib/relay/cross-compat.test.js +135 -0
  57. package/server/lib/relay/e2ee.js +341 -0
  58. package/server/lib/relay/e2ee.test.js +124 -0
  59. package/server/lib/relay/host-client.js +389 -0
  60. package/server/lib/relay/host-client.test.js +280 -0
  61. package/server/lib/relay/identity.js +73 -0
  62. package/server/lib/relay/identity.test.js +78 -0
  63. package/server/lib/relay/service.js +247 -0
  64. package/server/lib/relay/signing-key.js +50 -0
  65. package/server/lib/relay/tunnel-codec.js +373 -0
  66. package/server/lib/relay/tunnel-codec.test.js +58 -0
  67. package/server/lib/relay/tunnel-host.js +462 -0
  68. package/server/lib/session-assist/DOCUMENTATION.md +66 -0
  69. package/server/lib/session-assist/runtime.js +394 -0
  70. package/server/lib/small-model/DOCUMENTATION.md +78 -0
  71. package/server/lib/small-model/call.js +380 -0
  72. package/server/lib/small-model/catalog.js +13 -0
  73. package/server/lib/small-model/index.js +167 -0
  74. package/server/lib/small-model/resolve.js +131 -0
  75. package/server/lib/small-model/resolve.test.js +197 -0
  76. package/server/lib/small-model/routes.js +44 -0
  77. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  78. package/server/lib/ui-auth/ui-auth.js +10 -0
  79. package/server/opencode-proxy.test.js +38 -0
  80. package/dist/assets/MarkdownRendererImpl-DWgOeIpO.js +0 -7
  81. package/dist/assets/OnboardingScreen-3IAKkM5k.js +0 -1
  82. package/dist/assets/SettingsWindow-K-ErjehP.js +0 -1
  83. package/dist/assets/es-DQIFCjC2.js +0 -15
  84. package/dist/assets/fr-CJRav0LS.js +0 -13
  85. package/dist/assets/index-5eUDDB6w.js +0 -2
  86. package/dist/assets/index-CgpE7F8T.css +0 -1
  87. package/dist/assets/ja-CjAaqvHO.js +0 -15
  88. package/dist/assets/ko-BEbFxvrd.js +0 -15
  89. package/dist/assets/main-C2put7uQ.js +0 -2
  90. package/dist/assets/main-DuQEoz31.js +0 -214
  91. package/dist/assets/miniChat-o3AAQ-8r.js +0 -2
  92. package/dist/assets/mobile-X0421aWz.js +0 -2
  93. package/dist/assets/pl-D4kzai5T.js +0 -15
  94. package/dist/assets/pt-BR-9Sk3esQZ.js +0 -15
  95. package/dist/assets/renderElectronMiniChatApp-CdDj0ms1.js +0 -2
  96. package/dist/assets/renderMobileApp-cZ_HZKSe.js +0 -16
  97. package/dist/assets/runtimeEndpointReset-BYLVW9e7.js +0 -167
  98. package/dist/assets/uk-DW_dTfoO.js +0 -15
  99. package/dist/assets/zh-CN-r2_euV7U.js +0 -15
  100. package/dist/assets/zh-TW-BdPx3NWh.js +0 -15
@@ -0,0 +1,380 @@
1
+ import { readAuthFile, writeAuthFile } from '../opencode/auth.js';
2
+ import { getCatalogProvider } from './catalog.js';
3
+ import { getAuthEntryForProvider } from './resolve.js';
4
+
5
+ // Direct, non-streaming text generation against the provider APIs, replicating
6
+ // how OpenCode authenticates each of them (see the plugin auth loaders in the
7
+ // opencode repo). auth.json credentials never leave this process.
8
+
9
+ const REQUEST_TIMEOUT_MS = 60_000;
10
+ // Generous default: thinking models that can't be switched off (DeepSeek,
11
+ // Qwen, …) spend part of this budget on reasoning before the actual answer.
12
+ const DEFAULT_MAX_OUTPUT_TOKENS = 4_000;
13
+
14
+ const USER_AGENT = 'opencode/1.0 openchamber';
15
+
16
+ const CODEX_TOKEN_URL = 'https://auth.openai.com/oauth/token';
17
+ const CODEX_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
18
+ const CODEX_RESPONSES_URL = 'https://chatgpt.com/backend-api/codex/responses';
19
+
20
+ const httpError = async (response, provider) => {
21
+ const body = await response.text().catch(() => '');
22
+ const snippet = body ? `: ${body.slice(0, 300)}` : '';
23
+ return new Error(`${provider} request failed with ${response.status}${snippet}`);
24
+ };
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // OpenAI OAuth (ChatGPT plan / codex) token refresh — single-flight, with the
28
+ // refreshed token written back to auth.json exactly like OpenCode does.
29
+ // ---------------------------------------------------------------------------
30
+
31
+ let openaiRefreshPromise = null;
32
+
33
+ const decodeJwtClaims = (token) => {
34
+ try {
35
+ const payload = token.split('.')[1];
36
+ return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
37
+ } catch {
38
+ return null;
39
+ }
40
+ };
41
+
42
+ const extractChatgptAccountId = (accessToken) => {
43
+ const claims = decodeJwtClaims(accessToken);
44
+ const auth = claims?.['https://api.openai.com/auth'];
45
+ const value = auth?.chatgpt_account_id;
46
+ return typeof value === 'string' && value ? value : null;
47
+ };
48
+
49
+ const refreshOpenaiOauth = async (entry) => {
50
+ if (!openaiRefreshPromise) {
51
+ openaiRefreshPromise = (async () => {
52
+ const response = await fetch(CODEX_TOKEN_URL, {
53
+ method: 'POST',
54
+ headers: { 'Content-Type': 'application/json' },
55
+ body: JSON.stringify({
56
+ grant_type: 'refresh_token',
57
+ refresh_token: entry.refresh,
58
+ client_id: CODEX_CLIENT_ID,
59
+ }),
60
+ signal: AbortSignal.timeout(30_000),
61
+ });
62
+ if (!response.ok) {
63
+ throw await httpError(response, 'OpenAI token refresh');
64
+ }
65
+ const payload = await response.json();
66
+ const access = typeof payload?.access_token === 'string' ? payload.access_token : '';
67
+ if (!access) {
68
+ throw new Error('OpenAI token refresh returned no access token');
69
+ }
70
+ const refreshed = {
71
+ ...entry,
72
+ type: 'oauth',
73
+ access,
74
+ refresh: typeof payload?.refresh_token === 'string' && payload.refresh_token
75
+ ? payload.refresh_token
76
+ : entry.refresh,
77
+ expires: Date.now() + (Number(payload?.expires_in) > 0 ? Number(payload.expires_in) : 3600) * 1000,
78
+ };
79
+ const auth = readAuthFile();
80
+ auth.openai = refreshed;
81
+ writeAuthFile(auth);
82
+ return refreshed;
83
+ })().finally(() => {
84
+ openaiRefreshPromise = null;
85
+ });
86
+ }
87
+ return openaiRefreshPromise;
88
+ };
89
+
90
+ const ensureFreshOpenaiOauth = async (entry) => {
91
+ if (entry.access && Number(entry.expires) > Date.now()) {
92
+ return entry;
93
+ }
94
+ if (!entry.refresh) {
95
+ throw new Error('OpenAI OAuth entry has no refresh token');
96
+ }
97
+ return refreshOpenaiOauth(entry);
98
+ };
99
+
100
+ // ---------------------------------------------------------------------------
101
+ // Wire formats
102
+ // ---------------------------------------------------------------------------
103
+
104
+ const callOpenaiCompatible = async ({ baseURL, headers, modelID, prompt, system, maxOutputTokens, providerLabel, extraBody }) => {
105
+ const trimmedBase = baseURL.replace(/\/+$/, '');
106
+ const response = await fetch(`${trimmedBase}/chat/completions`, {
107
+ method: 'POST',
108
+ headers: {
109
+ 'Content-Type': 'application/json',
110
+ Accept: 'application/json',
111
+ ...headers,
112
+ },
113
+ body: JSON.stringify({
114
+ model: modelID,
115
+ messages: [
116
+ ...(system ? [{ role: 'system', content: system }] : []),
117
+ { role: 'user', content: prompt },
118
+ ],
119
+ max_tokens: maxOutputTokens,
120
+ stream: false,
121
+ ...(extraBody || {}),
122
+ }),
123
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
124
+ });
125
+ if (!response.ok) {
126
+ throw await httpError(response, providerLabel);
127
+ }
128
+ const payload = await response.json();
129
+ const message = payload?.choices?.[0]?.message;
130
+
131
+ // Providers disagree on the content shape: plain string, an array of
132
+ // typed parts, or (thinking models) an empty content with the budget spent
133
+ // on reasoning_content.
134
+ let text = '';
135
+ if (typeof message?.content === 'string') {
136
+ text = message.content;
137
+ } else if (Array.isArray(message?.content)) {
138
+ text = message.content
139
+ .map((part) => (typeof part?.text === 'string' ? part.text : ''))
140
+ .join('');
141
+ }
142
+ if (!text.trim() && typeof message?.reasoning_content === 'string' && message.reasoning_content.trim()) {
143
+ const finishReason = payload?.choices?.[0]?.finish_reason;
144
+ throw new Error(
145
+ `${providerLabel} spent the output budget on reasoning and returned no answer`
146
+ + (finishReason ? ` (finish_reason: ${finishReason})` : ''),
147
+ );
148
+ }
149
+ if (!text.trim()) {
150
+ throw new Error(`${providerLabel} returned no message content`);
151
+ }
152
+ return text;
153
+ };
154
+
155
+ const callAnthropic = async ({ apiKey, modelID, prompt, system, maxOutputTokens }) => {
156
+ const response = await fetch('https://api.anthropic.com/v1/messages', {
157
+ method: 'POST',
158
+ headers: {
159
+ 'Content-Type': 'application/json',
160
+ Accept: 'application/json',
161
+ 'x-api-key': apiKey,
162
+ 'anthropic-version': '2023-06-01',
163
+ },
164
+ body: JSON.stringify({
165
+ model: modelID,
166
+ max_tokens: maxOutputTokens,
167
+ ...(system ? { system } : {}),
168
+ messages: [{ role: 'user', content: prompt }],
169
+ }),
170
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
171
+ });
172
+ if (!response.ok) {
173
+ throw await httpError(response, 'Anthropic');
174
+ }
175
+ const payload = await response.json();
176
+ const text = (payload?.content || [])
177
+ .filter((part) => part?.type === 'text' && typeof part.text === 'string')
178
+ .map((part) => part.text)
179
+ .join('');
180
+ if (!text) {
181
+ throw new Error('Anthropic returned no text content');
182
+ }
183
+ return text;
184
+ };
185
+
186
+ const callGoogle = async ({ apiKey, modelID, prompt, system, maxOutputTokens }) => {
187
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(modelID)}:generateContent`;
188
+ const response = await fetch(url, {
189
+ method: 'POST',
190
+ headers: {
191
+ 'Content-Type': 'application/json',
192
+ Accept: 'application/json',
193
+ 'x-goog-api-key': apiKey,
194
+ },
195
+ body: JSON.stringify({
196
+ contents: [{ role: 'user', parts: [{ text: prompt }] }],
197
+ ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
198
+ // thinkingBudget 0 switches Gemini Flash thinking off; Flash is the only
199
+ // family the small-model resolver picks for Google.
200
+ generationConfig: { maxOutputTokens, thinkingConfig: { thinkingBudget: 0 } },
201
+ }),
202
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
203
+ });
204
+ if (!response.ok) {
205
+ throw await httpError(response, 'Google');
206
+ }
207
+ const payload = await response.json();
208
+ const text = (payload?.candidates?.[0]?.content?.parts || [])
209
+ .map((part) => (typeof part?.text === 'string' ? part.text : ''))
210
+ .join('');
211
+ if (!text) {
212
+ throw new Error('Google returned no text content');
213
+ }
214
+ return text;
215
+ };
216
+
217
+ // ChatGPT-plan traffic goes to the codex backend, which only speaks the
218
+ // streaming Responses API — collect the output_text deltas from the SSE body.
219
+ const callCodexResponses = async ({ accessToken, accountId, modelID, prompt, system }) => {
220
+ const response = await fetch(CODEX_RESPONSES_URL, {
221
+ method: 'POST',
222
+ headers: {
223
+ 'Content-Type': 'application/json',
224
+ Accept: 'text/event-stream',
225
+ Authorization: `Bearer ${accessToken}`,
226
+ ...(accountId ? { 'ChatGPT-Account-Id': accountId } : {}),
227
+ originator: 'opencode',
228
+ 'User-Agent': USER_AGENT,
229
+ },
230
+ body: JSON.stringify({
231
+ model: modelID,
232
+ ...(system ? { instructions: system } : {}),
233
+ input: [
234
+ {
235
+ type: 'message',
236
+ role: 'user',
237
+ content: [{ type: 'input_text', text: prompt }],
238
+ },
239
+ ],
240
+ // The codex backend rejects max_output_tokens (OpenCode forces it to
241
+ // undefined for this provider too).
242
+ stream: true,
243
+ store: false,
244
+ }),
245
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
246
+ });
247
+ if (!response.ok) {
248
+ throw await httpError(response, 'OpenAI (ChatGPT plan)');
249
+ }
250
+
251
+ const raw = await response.text();
252
+ let text = '';
253
+ let completedText = '';
254
+ for (const line of raw.split('\n')) {
255
+ if (!line.startsWith('data:')) continue;
256
+ const data = line.slice(5).trim();
257
+ if (!data || data === '[DONE]') continue;
258
+ let event;
259
+ try {
260
+ event = JSON.parse(data);
261
+ } catch {
262
+ continue;
263
+ }
264
+ if (event?.type === 'response.output_text.delta' && typeof event.delta === 'string') {
265
+ text += event.delta;
266
+ }
267
+ if (event?.type === 'response.output_text.done' && typeof event.text === 'string') {
268
+ completedText = event.text;
269
+ }
270
+ if (event?.type === 'response.failed' || event?.type === 'error') {
271
+ const message = event?.response?.error?.message || event?.message || 'response failed';
272
+ throw new Error(`OpenAI (ChatGPT plan) stream error: ${message}`);
273
+ }
274
+ }
275
+ const result = completedText || text;
276
+ if (!result) {
277
+ throw new Error('OpenAI (ChatGPT plan) returned no text output');
278
+ }
279
+ return result;
280
+ };
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // Dispatch
284
+ // ---------------------------------------------------------------------------
285
+
286
+ export async function callSmallModel({ auth, catalog, providerID, modelID, prompt, system, maxOutputTokens }) {
287
+ const tokens = Number(maxOutputTokens) > 0 ? Number(maxOutputTokens) : DEFAULT_MAX_OUTPUT_TOKENS;
288
+ const entry = getAuthEntryForProvider(auth, providerID);
289
+ if (!entry) {
290
+ throw new Error(`No OpenCode login found for provider "${providerID}"`);
291
+ }
292
+
293
+ if (providerID === 'github-copilot') {
294
+ // OpenCode uses the stored device-OAuth token directly as the bearer —
295
+ // access === refresh, no exchange, no expiry.
296
+ const token = entry.refresh || entry.access || entry.key;
297
+ if (!token) {
298
+ throw new Error('GitHub Copilot login has no token');
299
+ }
300
+ const baseURL = entry.enterpriseUrl
301
+ ? `https://copilot-api.${String(entry.enterpriseUrl).replace(/^https?:\/\//, '').replace(/\/+$/, '')}`
302
+ : 'https://api.githubcopilot.com';
303
+ return callOpenaiCompatible({
304
+ baseURL,
305
+ headers: {
306
+ Authorization: `Bearer ${token}`,
307
+ 'User-Agent': USER_AGENT,
308
+ 'Openai-Intent': 'conversation-edits',
309
+ 'x-initiator': 'agent',
310
+ 'X-GitHub-Api-Version': '2026-06-01',
311
+ },
312
+ modelID,
313
+ prompt,
314
+ system,
315
+ maxOutputTokens: tokens,
316
+ providerLabel: 'GitHub Copilot',
317
+ });
318
+ }
319
+
320
+ if (providerID === 'openai' && entry.type === 'oauth') {
321
+ const fresh = await ensureFreshOpenaiOauth(entry);
322
+ return callCodexResponses({
323
+ accessToken: fresh.access,
324
+ accountId: fresh.accountId || extractChatgptAccountId(fresh.access),
325
+ modelID,
326
+ prompt,
327
+ system,
328
+ });
329
+ }
330
+
331
+ const apiKey = entry.type === 'api' ? entry.key
332
+ : entry.type === 'wellknown' ? entry.token
333
+ : entry.access;
334
+ if (!apiKey) {
335
+ throw new Error(`OpenCode login for "${providerID}" has no usable credential`);
336
+ }
337
+
338
+ if (providerID === 'anthropic') {
339
+ return callAnthropic({ apiKey, modelID, prompt, system, maxOutputTokens: tokens });
340
+ }
341
+ if (providerID === 'google') {
342
+ return callGoogle({ apiKey, modelID, prompt, system, maxOutputTokens: tokens });
343
+ }
344
+
345
+ // Everything else: OpenAI-compatible chat completions against the catalog's
346
+ // base URL for that provider (openai itself included).
347
+ const provider = getCatalogProvider(catalog, providerID);
348
+ const baseURL = providerID === 'openai'
349
+ ? 'https://api.openai.com/v1'
350
+ : typeof provider?.api === 'string' && provider.api
351
+ ? provider.api
352
+ : null;
353
+ if (!baseURL) {
354
+ throw new Error(`Provider "${providerID}" has no known API base URL`);
355
+ }
356
+
357
+ // Thinking models burn the output budget on reasoning and leave content
358
+ // empty — disable thinking where a wire-format switch exists (mirrors
359
+ // OpenCode's smallOptions/variants special cases). There is NO universal
360
+ // parameter: unknown body fields 400 on some providers, so this stays an
361
+ // explicit allowlist. Models without a switch (DeepSeek, Qwen, Kimi, …)
362
+ // just get the generous output budget.
363
+ const lowerModel = modelID.toLowerCase();
364
+ const supportsThinkingToggle = providerID.includes('zai')
365
+ || providerID.includes('zhipu')
366
+ || lowerModel.includes('glm')
367
+ || lowerModel.includes('minimax-m3');
368
+ const extraBody = supportsThinkingToggle ? { thinking: { type: 'disabled' } } : undefined;
369
+
370
+ return callOpenaiCompatible({
371
+ baseURL,
372
+ headers: { Authorization: `Bearer ${apiKey}` },
373
+ modelID,
374
+ prompt,
375
+ system,
376
+ maxOutputTokens: tokens,
377
+ providerLabel: provider?.name || providerID,
378
+ extraBody,
379
+ });
380
+ }
@@ -0,0 +1,13 @@
1
+ import { getModelsMetadata } from '../opencode/models-metadata.js';
2
+
3
+ // The models.dev catalog is shared with the /api/openchamber/models-metadata
4
+ // route through one in-process cache — no extra fetches, no cache files.
5
+ export async function getModelCatalog() {
6
+ const { metadata } = await getModelsMetadata();
7
+ return metadata;
8
+ }
9
+
10
+ export function getCatalogProvider(catalog, providerID) {
11
+ const entry = catalog?.[providerID];
12
+ return entry && typeof entry === 'object' ? entry : null;
13
+ }
@@ -0,0 +1,167 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { readAuthFile } from '../opencode/auth.js';
5
+ import { readConfigLayers } from '../opencode/shared.js';
6
+ import { getModelCatalog } from './catalog.js';
7
+ import { resolveSmallModel, parseModelRef, isUsableAuthEntry, getAuthEntryForProvider } from './resolve.js';
8
+ import { callSmallModel } from './call.js';
9
+
10
+ const OPENCHAMBER_SETTINGS_FILE = path.join(
11
+ process.env.OPENCHAMBER_DATA_DIR
12
+ ? path.resolve(process.env.OPENCHAMBER_DATA_DIR)
13
+ : path.join(os.homedir(), '.config', 'openchamber'),
14
+ 'settings.json',
15
+ );
16
+
17
+ // OpenChamber's own settings: when the user unchecks "use default small model"
18
+ // their explicit override outranks every other resolution step.
19
+ const readSmallModelSettingsOverride = () => {
20
+ try {
21
+ const raw = fs.readFileSync(OPENCHAMBER_SETTINGS_FILE, 'utf8');
22
+ const settings = JSON.parse(raw);
23
+ if (!settings || typeof settings !== 'object') return null;
24
+ if (settings.smallModelUseDefault !== false) return null;
25
+ const override = typeof settings.smallModelOverride === 'string' ? settings.smallModelOverride.trim() : '';
26
+ return override || null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ };
31
+
32
+ // Rough safety clamp so a huge input never blows the model's context window.
33
+ // Token estimate is ~4 chars/token; when the catalog has no limit for the
34
+ // model (Copilot/codex utility models are not listed) a conservative default
35
+ // applies.
36
+ const DEFAULT_CONTEXT_TOKENS = 64_000;
37
+ const OUTPUT_RESERVE_TOKENS = 4_000;
38
+
39
+ const clampPromptToModelLimit = ({ prompt, catalog, providerID, modelID }) => {
40
+ const limit = catalog?.[providerID]?.models?.[modelID]?.limit;
41
+ const contextTokens = Number(limit?.context) > 0 ? Number(limit.context) : DEFAULT_CONTEXT_TOKENS;
42
+ const inputBudgetTokens = Math.max(1_000, contextTokens - OUTPUT_RESERVE_TOKENS);
43
+ const maxChars = inputBudgetTokens * 4;
44
+ if (prompt.length <= maxChars) {
45
+ return { prompt, truncated: false };
46
+ }
47
+ return { prompt: `${prompt.slice(0, maxChars)}…`, truncated: true };
48
+ };
49
+
50
+ const readConfiguredSmallModel = (workingDirectory) => {
51
+ try {
52
+ const { mergedConfig } = readConfigLayers(workingDirectory);
53
+ const value = mergedConfig?.small_model;
54
+ return typeof value === 'string' ? value : null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ };
59
+
60
+ /**
61
+ * Generates text with the user's small model, resolved and authenticated
62
+ * entirely server-side from the OpenCode config and auth store.
63
+ */
64
+ export async function generateSmallModelText({ prompt, system, maxOutputTokens, model, directory, preferredProviderID, preferredModelID, restrictToPreferredProvider = false }) {
65
+ if (typeof prompt !== 'string' || !prompt.trim()) {
66
+ throw Object.assign(new Error('prompt is required'), { statusCode: 400 });
67
+ }
68
+
69
+ const auth = readAuthFile();
70
+ const catalog = await getModelCatalog().catch(() => ({}));
71
+
72
+ const explicit = parseModelRef(model);
73
+ const resolved = explicit
74
+ ? { ...explicit, source: 'request' }
75
+ : resolveSmallModel({
76
+ auth,
77
+ catalog,
78
+ settingsSmallModel: readSmallModelSettingsOverride(),
79
+ configSmallModel: readConfiguredSmallModel(directory),
80
+ preferredProviderID,
81
+ preferredModelID,
82
+ });
83
+
84
+ if (!resolved) {
85
+ throw Object.assign(
86
+ new Error('No small model available — no authenticated provider has a suitable model'),
87
+ { statusCode: 404 },
88
+ );
89
+ }
90
+
91
+ // Callers with a session context can forbid silently switching providers:
92
+ // an explicit user choice (settings override, opencode config, request
93
+ // model) is always allowed, anything else must stay on the session's
94
+ // provider.
95
+ if (restrictToPreferredProvider
96
+ && !['settings', 'config', 'request'].includes(resolved.source)
97
+ && resolved.providerID !== preferredProviderID) {
98
+ throw Object.assign(
99
+ new Error('No small model available within the session provider'),
100
+ { statusCode: 404 },
101
+ );
102
+ }
103
+
104
+ const clamped = clampPromptToModelLimit({
105
+ prompt: prompt.trim(),
106
+ catalog,
107
+ providerID: resolved.providerID,
108
+ modelID: resolved.modelID,
109
+ });
110
+
111
+ const text = await callSmallModel({
112
+ auth,
113
+ catalog,
114
+ providerID: resolved.providerID,
115
+ modelID: resolved.modelID,
116
+ prompt: clamped.prompt,
117
+ system: typeof system === 'string' && system.trim() ? system.trim() : undefined,
118
+ maxOutputTokens,
119
+ });
120
+
121
+ return {
122
+ text: text.trim(),
123
+ providerID: resolved.providerID,
124
+ modelID: resolved.modelID,
125
+ source: resolved.source,
126
+ ...(clamped.truncated ? { inputTruncated: true } : {}),
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Provider ids with a usable OpenCode login — the set the small model can
132
+ * actually call. Used by the settings override picker to hide providers that
133
+ * would only ever fail (e.g. opencode free models without a token).
134
+ */
135
+ export function listAuthenticatedProviders() {
136
+ try {
137
+ const auth = readAuthFile();
138
+ const ids = new Set(
139
+ Object.keys(auth || {}).filter((providerID) => isUsableAuthEntry(auth[providerID])),
140
+ );
141
+ // The catalog id is github-copilot while legacy auth entries may sit
142
+ // under the copilot alias.
143
+ if (isUsableAuthEntry(getAuthEntryForProvider(auth, 'github-copilot'))) {
144
+ ids.add('github-copilot');
145
+ }
146
+ return Array.from(ids);
147
+ } catch {
148
+ return [];
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Reports which model would be used, without calling it.
154
+ */
155
+ export async function describeSmallModel({ directory, preferredProviderID, preferredModelID } = {}) {
156
+ const auth = readAuthFile();
157
+ const catalog = await getModelCatalog().catch(() => ({}));
158
+ const resolved = resolveSmallModel({
159
+ auth,
160
+ catalog,
161
+ settingsSmallModel: readSmallModelSettingsOverride(),
162
+ configSmallModel: readConfiguredSmallModel(directory),
163
+ preferredProviderID,
164
+ preferredModelID,
165
+ });
166
+ return resolved;
167
+ }
@@ -0,0 +1,131 @@
1
+ import { getCatalogProvider } from './catalog.js';
2
+
3
+ // Mirrors OpenCode's getSmallModel fallback chain:
4
+ // 1. `small_model` from the merged config layers ("provider/model").
5
+ // 2. GitHub Copilot's hidden utility models when Copilot is logged in.
6
+ // 3. Family-priority scan of the authenticated providers' catalog models.
7
+ const FAMILY_PRIORITY = ['gemini-flash', 'gpt-nano', 'claude-haiku'];
8
+ const COPILOT_UTILITY_MODELS = ['gpt-5.4-nano', 'gpt-4.1', 'gpt-4o', 'gpt-4o-mini'];
9
+ // The ChatGPT-plan codex backend only accepts a small allowlist of models
10
+ // (nano/API-key models are rejected with 400) — this is its cheapest one.
11
+ const OPENAI_OAUTH_SMALL_MODEL = 'gpt-5.4-mini';
12
+
13
+ const AUTH_PROVIDER_ALIASES = {
14
+ 'github-copilot': ['github-copilot', 'copilot'],
15
+ };
16
+
17
+ export function getAuthEntryForProvider(auth, providerID) {
18
+ const aliases = AUTH_PROVIDER_ALIASES[providerID] || [providerID];
19
+ for (const alias of aliases) {
20
+ const entry = auth?.[alias];
21
+ if (entry && typeof entry === 'object') {
22
+ return entry;
23
+ }
24
+ }
25
+ return null;
26
+ }
27
+
28
+ export function isUsableAuthEntry(entry) {
29
+ if (!entry || typeof entry !== 'object') return false;
30
+ if (entry.type === 'api') return typeof entry.key === 'string' && entry.key.length > 0;
31
+ if (entry.type === 'oauth') {
32
+ return (typeof entry.access === 'string' && entry.access.length > 0)
33
+ || (typeof entry.refresh === 'string' && entry.refresh.length > 0);
34
+ }
35
+ if (entry.type === 'wellknown') return typeof entry.token === 'string' && entry.token.length > 0;
36
+ return false;
37
+ }
38
+
39
+ export function parseModelRef(value) {
40
+ if (typeof value !== 'string') return null;
41
+ const trimmed = value.trim();
42
+ const slash = trimmed.indexOf('/');
43
+ if (slash <= 0 || slash === trimmed.length - 1) return null;
44
+ return {
45
+ providerID: trimmed.slice(0, slash),
46
+ modelID: trimmed.slice(slash + 1),
47
+ };
48
+ }
49
+
50
+ const pickByFamily = (models, family) => {
51
+ const matches = Object.values(models)
52
+ .filter((model) => model && typeof model === 'object' && model.family === family);
53
+ if (matches.length === 0) return null;
54
+ matches.sort((a, b) => String(b.release_date || '').localeCompare(String(a.release_date || '')));
55
+ return matches[0];
56
+ };
57
+
58
+ // Small-model candidates within ONE provider, by family priority. Copilot and
59
+ // ChatGPT-plan OpenAI have fixed small models that never appear in the
60
+ // catalog; everyone else is scanned through the catalog families.
61
+ const pickWithinProvider = (providerID, auth, catalog, family) => {
62
+ if (providerID === 'openai' && auth.openai?.type === 'oauth') {
63
+ return family === 'gpt-nano'
64
+ ? { providerID, modelID: OPENAI_OAUTH_SMALL_MODEL, source: 'codex-small' }
65
+ : null;
66
+ }
67
+ if (providerID === 'github-copilot') {
68
+ return family === 'gpt-nano'
69
+ ? { providerID, modelID: COPILOT_UTILITY_MODELS[0], source: 'copilot-utility' }
70
+ : null;
71
+ }
72
+ const provider = getCatalogProvider(catalog, providerID);
73
+ if (!provider || !provider.models || typeof provider.models !== 'object') return null;
74
+ const model = pickByFamily(provider.models, family);
75
+ return model?.id ? { providerID, modelID: model.id, source: 'family-scan' } : null;
76
+ };
77
+
78
+ export function resolveSmallModel({ auth, catalog, settingsSmallModel, configSmallModel, preferredProviderID, preferredModelID }) {
79
+ // OpenChamber's own setting (Settings → Sessions → Small Model override)
80
+ // outranks everything, including the OpenCode config.
81
+ const fromSettings = parseModelRef(settingsSmallModel);
82
+ if (fromSettings) {
83
+ return { ...fromSettings, source: 'settings' };
84
+ }
85
+
86
+ const explicit = parseModelRef(configSmallModel);
87
+ if (explicit) {
88
+ return { ...explicit, source: 'config' };
89
+ }
90
+
91
+ // Like OpenCode: when the caller has a session context, the utility call
92
+ // stays on the session's provider. Scan its families for a small model,
93
+ // otherwise run on the session's own model — never silently switch to a
94
+ // different provider's subscription.
95
+ const preferred = typeof preferredProviderID === 'string' && preferredProviderID
96
+ ? preferredProviderID
97
+ : null;
98
+ if (preferred && isUsableAuthEntry(getAuthEntryForProvider(auth, preferred))) {
99
+ for (const family of FAMILY_PRIORITY) {
100
+ const match = pickWithinProvider(preferred, auth, catalog, family);
101
+ if (match) return match;
102
+ }
103
+ if (typeof preferredModelID === 'string' && preferredModelID) {
104
+ return { providerID: preferred, modelID: preferredModelID, source: 'session-model' };
105
+ }
106
+ }
107
+
108
+ // No session context (or its provider has no usable login): scan all
109
+ // authenticated providers by family priority.
110
+ const authedProviders = Object.keys(auth || {}).filter((providerID) =>
111
+ providerID !== preferred && isUsableAuthEntry(auth[providerID]));
112
+
113
+ for (const family of FAMILY_PRIORITY) {
114
+ for (const providerID of authedProviders) {
115
+ const match = pickWithinProvider(providerID, auth, catalog, family);
116
+ if (match) return match;
117
+ }
118
+ }
119
+
120
+ // Copilot's utility fallback for legacy auth aliases the loop above missed.
121
+ const copilotEntry = getAuthEntryForProvider(auth, 'github-copilot');
122
+ if (isUsableAuthEntry(copilotEntry)) {
123
+ return {
124
+ providerID: 'github-copilot',
125
+ modelID: COPILOT_UTILITY_MODELS[0],
126
+ source: 'copilot-utility',
127
+ };
128
+ }
129
+
130
+ return null;
131
+ }