opencode-next 0.0.0-stage → 1.0.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.
package/lib/client.js ADDED
@@ -0,0 +1,396 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ const CANONICAL_SESSION_PATTERN = /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
4
+ const BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
5
+
6
+ function base62Fixed(value, width) {
7
+ const base = 62n;
8
+ let n = value;
9
+ const out = new Array(width);
10
+ for (let i = width - 1; i >= 0; i--) {
11
+ out[i] = BASE62_ALPHABET.charAt(Number(n % base));
12
+ n /= base;
13
+ }
14
+ return out.join("");
15
+ }
16
+
17
+ function invertedTimestampHex(now = Date.now()) {
18
+ return (~(BigInt(now) * 4096n + 1n) & 281474976710655n).toString(16).padStart(12, "0");
19
+ }
20
+
21
+ export function canonicalSessionId(signal = '') {
22
+ if (typeof signal === 'string' && CANONICAL_SESSION_PATTERN.test(signal)) {
23
+ return signal;
24
+ }
25
+ const sum = crypto.createHash("sha256").update("ses\0" + String(signal || Date.now() + Math.random())).digest();
26
+ return `ses_${invertedTimestampHex()}${base62Fixed(BigInt("0x" + sum.subarray(6, 16).toString("hex")), 14)}`;
27
+ }
28
+
29
+ export function randomId(prefix = 'req', length = 16) {
30
+ const bytes = crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
31
+ return `${prefix}_${bytes}`;
32
+ }
33
+
34
+ export function stableProjectId(name = '') {
35
+ const value = typeof name === 'string' && name.trim() !== '' ? name.trim() : (process.cwd?.() || 'opencode');
36
+ return crypto.createHash('sha1').update(String(value)).digest('hex');
37
+ }
38
+
39
+ export function opencodeUserAgent(version = '2.0.32') {
40
+ return `opencode/latest/${version}/cli`;
41
+ }
42
+
43
+ /**
44
+ * OpenCode official v2 baseline tool names.
45
+ */
46
+ export const OFFICIAL_V2_TOOL_NAMES = Object.freeze([
47
+ 'edit', 'glob', 'grep', 'question', 'read', 'shell', 'skill', 'subagent', 'webfetch', 'websearch', 'write', 'execute'
48
+ ]);
49
+
50
+ export function makeOfficialTool(name) {
51
+ return {
52
+ type: 'function',
53
+ function: {
54
+ name,
55
+ description: `OpenCode official ${name} tool.`,
56
+ parameters: { type: 'object', properties: {} }
57
+ }
58
+ };
59
+ }
60
+
61
+ /**
62
+ * OpenCode upstream free-lane gate requires official baseline tools.
63
+ */
64
+ export function ensureFreeLaneTools(tools) {
65
+ const currentTools = Array.isArray(tools) ? [...tools] : [];
66
+ const existingNames = new Set(
67
+ currentTools.map((t) => (t.type === 'function' ? t.function?.name || t.name : t.name))
68
+ );
69
+
70
+ for (const gateName of OFFICIAL_V2_TOOL_NAMES) {
71
+ if (!existingNames.has(gateName)) {
72
+ currentTools.push(makeOfficialTool(gateName));
73
+ }
74
+ }
75
+
76
+ return currentTools;
77
+ }
78
+
79
+ /**
80
+ * 準備送往上游的工具陣列並建立雙向別名映射。
81
+ *
82
+ * 1. 包含官方 v2 必備的 12 個基線工具。
83
+ * 2. DSH 的工具映射為 oc_ext_${index},在 description 標註原名以保留模型調用判斷依據。
84
+ * 3. 回傳 { tools, toUpstreamName, toDshName }。
85
+ */
86
+ export function prepareToolsWithAliases(userTools) {
87
+ const upstreamTools = OFFICIAL_V2_TOOL_NAMES.map(name => makeOfficialTool(name));
88
+ const dshToUpstream = new Map();
89
+ const upstreamToDsh = new Map();
90
+
91
+ const rawList = Array.isArray(userTools) ? userTools : [];
92
+ rawList.forEach((t, idx) => {
93
+ const rawName = t.type === 'function' ? (t.function?.name || t.name) : t.name;
94
+ if (!rawName) return;
95
+
96
+ const alias = `oc_ext_${idx}`;
97
+ dshToUpstream.set(rawName, alias);
98
+ upstreamToDsh.set(alias, rawName);
99
+
100
+ const desc = t.function?.description || t.description || '';
101
+ const annotatedDesc = `[Tool: ${rawName}] ${desc}`.trim();
102
+ const params = t.function?.parameters || t.parameters || { type: 'object', properties: {} };
103
+
104
+ upstreamTools.push({
105
+ type: 'function',
106
+ function: {
107
+ name: alias,
108
+ description: annotatedDesc,
109
+ parameters: params
110
+ }
111
+ });
112
+ });
113
+
114
+ return {
115
+ tools: upstreamTools,
116
+ toUpstreamName: (dshName) => dshToUpstream.get(dshName) || dshName,
117
+ toDshName: (upstreamName) => upstreamToDsh.get(upstreamName) || upstreamName
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Builds the headers OpenCode expects for client affinity and verification.
123
+ */
124
+ export function buildHeaders(token, sessionId, requestId, projectId, orgId) {
125
+ const sid = canonicalSessionId(sessionId);
126
+ const rid = requestId || randomId('req', 16);
127
+ const pid = (projectId && projectId !== 'global') ? projectId : stableProjectId();
128
+ const authToken = token || 'public';
129
+
130
+ const headers = {
131
+ 'authorization': `Bearer ${authToken}`,
132
+ 'content-type': 'application/json',
133
+ 'accept': 'text/event-stream',
134
+ 'user-agent': opencodeUserAgent(),
135
+ 'x-opencode-client': 'cli',
136
+ 'x-opencode-session': sid,
137
+ 'x-opencode-session-id': sid,
138
+ 'x-session-affinity': sid,
139
+ 'x-session-id': sid,
140
+ 'x-opencode-request': rid,
141
+ 'x-opencode-project': pid
142
+ };
143
+
144
+ if (typeof orgId === 'string' && orgId.trim() !== '') {
145
+ headers['x-opencode-org-id'] = orgId.trim();
146
+ }
147
+
148
+ return headers;
149
+ }
150
+
151
+ /**
152
+ * 把內容區塊裡的純文字攤平。
153
+ *
154
+ * DSH 的訊息內容是 ContentBlock 陣列,不是字串。舊版遇到陣列直接
155
+ * `JSON.stringify`,於是模型看到的 system 提示詞是
156
+ * `[{"type":"text","text":"You are a coding agent…"}]` 這種 JSON 字面值——提示詞
157
+ * 完全失效,而且每次請求都白付一份 JSON 逸出字元的 token。這裡改成只取
158
+ * `text` 區塊並以換行接回人類可讀的文字。
159
+ */
160
+ export function flattenText(content) {
161
+ if (typeof content === 'string') return content;
162
+ if (!Array.isArray(content)) return '';
163
+ const parts = [];
164
+ for (const block of content) {
165
+ if (!block || typeof block !== 'object') continue;
166
+ if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text);
167
+ }
168
+ return parts.join('\n');
169
+ }
170
+
171
+ /** 從 DSH 的 image 區塊取出附件參照;形狀不符時回傳 null。 */
172
+ function imageAttachmentRef(block) {
173
+ const ref = block?.attachment;
174
+ if (!ref || typeof ref !== 'object') return null;
175
+ if (typeof ref.attachmentId !== 'string' || ref.attachmentId === '') return null;
176
+ return ref;
177
+ }
178
+
179
+ /** 穩定、可判讀的附件短摘要,用於佔位文字。 */
180
+ function attachmentDigest(ref) {
181
+ const id = typeof ref?.attachmentId === 'string' ? ref.attachmentId : '';
182
+ return id.startsWith('sha256:') ? id.slice(0, 15) : id.slice(0, 14);
183
+ }
184
+
185
+ /**
186
+ * 因請求預算被省略的圖片,改成模型看得懂身分的佔位文字。
187
+ *
188
+ * 關鍵是保留附件 id 前綴:模型後續對話裡若還提到這張圖,至少知道自己漏看了
189
+ * 哪一份,而不是完全空白。
190
+ */
191
+ export function offloadedImageText(ref) {
192
+ return `[image omitted to fit request image limits; attachment ${attachmentDigest(ref)}…]`;
193
+ }
194
+
195
+ /** 模型不接受圖片時的佔位文字。 */
196
+ export function textOnlyImageText(ref) {
197
+ return `[image omitted because this model accepts text only; attachment ${attachmentDigest(ref)}…]`;
198
+ }
199
+
200
+ /** DSH 的 file 區塊在 OpenAI 線路上沒有對應型別,退化成描述性 handle 文字。 */
201
+ export function fileHandleText(ref) {
202
+ const name = typeof ref?.name === 'string' && ref.name !== '' ? ` "${ref.name}"` : '';
203
+ const mediaType = typeof ref?.mediaType === 'string' ? ` ${ref.mediaType}` : '';
204
+ const bytes = Number.isFinite(ref?.bytes) ? ` ${ref.bytes} bytes` : '';
205
+ return `[file${name}${mediaType}${bytes}; attachment ${attachmentDigest(ref)}…]`;
206
+ }
207
+
208
+ /**
209
+ * 掃出訊息裡所有還會用到的圖片附件參照,讓呼叫端可以一次把位元組讀齊。
210
+ *
211
+ * 回傳 `Map<attachmentId, ref>`,同一張圖重複出現只讀一次。
212
+ */
213
+ export function collectImageRefs(dshMessages) {
214
+ const refs = new Map();
215
+ if (!Array.isArray(dshMessages)) return refs;
216
+ for (const msg of dshMessages) {
217
+ if (!msg || !Array.isArray(msg.content)) continue;
218
+ for (const block of msg.content) {
219
+ if (!block || block.type !== 'image' || block.offloaded === true) continue;
220
+ const ref = imageAttachmentRef(block);
221
+ if (ref !== null && !refs.has(ref.attachmentId)) refs.set(ref.attachmentId, ref);
222
+ }
223
+ }
224
+ return refs;
225
+ }
226
+
227
+ /**
228
+ * 把 DSH 訊息轉成 OpenAI 相容的 messages 陣列。
229
+ *
230
+ * `options`:
231
+ * - `system`:`GenerateOptions.system`。DSH 會把它跟開頭那幾則 system 訊息合併成
232
+ * 單一 system message(多則重複的 system 只是白燒 token)。
233
+ * - `imageUrls`:`Map<attachmentId, dataURI>`,由呼叫端用 attachment service 先讀好。
234
+ * - `imageSupported`:路由是否接受圖片;false 時圖片一律換成佔位文字。
235
+ */
236
+ export function convertMessages(dshMessages, options = {}) {
237
+ if (!Array.isArray(dshMessages)) return [];
238
+
239
+ const imageUrls = options.imageUrls instanceof Map ? options.imageUrls : new Map();
240
+ const imageSupported = options.imageSupported !== false;
241
+
242
+ const out = [];
243
+ const systemParts = [];
244
+ if (typeof options.system === 'string' && options.system.trim() !== '') {
245
+ systemParts.push(options.system);
246
+ }
247
+ let sawSystem = false;
248
+
249
+ /** 把一個 image 區塊轉成 OpenAI 的 image_url 片段,或退化成佔位文字。 */
250
+ function imageBlockPart(block) {
251
+ const ref = imageAttachmentRef(block);
252
+ if (ref === null) return null;
253
+ if (block.offloaded === true || !imageSupported) {
254
+ const text = block.offloaded === true ? offloadedImageText(ref) : textOnlyImageText(ref);
255
+ return { type: 'text', text };
256
+ }
257
+ const url = imageUrls.get(ref.attachmentId);
258
+ if (typeof url !== 'string' || url === '') return { type: 'text', text: textOnlyImageText(ref) };
259
+ return { type: 'image_url', image_url: { url } };
260
+ }
261
+
262
+ for (const msg of dshMessages) {
263
+ if (!msg) continue;
264
+
265
+ const role = msg.role === 'human' ? 'user' : msg.role;
266
+
267
+ // `developer` 是 OpenAI 新版模型取代 system 的角色,語意與擺放位置都與 system
268
+ // 相同。不一起處理的話它會掉出所有分支被靜默丟棄,整段指示憑空消失。
269
+ if (role === 'system' || role === 'developer') {
270
+ const text = flattenText(msg.content);
271
+ if (!sawSystem && out.length === 0) {
272
+ // 開頭的 system 訊息屬於同一段系統提示詞,跟 options.system 併成一則。
273
+ sawSystem = true;
274
+ if (text.trim() !== '' && !systemParts.includes(text)) systemParts.push(text);
275
+ continue;
276
+ }
277
+ if (text.trim() !== '') out.push({ role: 'system', content: text });
278
+ continue;
279
+ }
280
+
281
+ if (role === 'user') {
282
+ if (typeof msg.content === 'string') {
283
+ out.push({ role: 'user', content: msg.content });
284
+ continue;
285
+ }
286
+ if (!Array.isArray(msg.content)) continue;
287
+ const parts = [];
288
+ for (const block of msg.content) {
289
+ if (!block || typeof block !== 'object') continue;
290
+ if (block.type === 'text') {
291
+ parts.push({ type: 'text', text: block.text || '' });
292
+ } else if (block.type === 'image') {
293
+ const part = imageBlockPart(block);
294
+ if (part !== null) parts.push(part);
295
+ } else if (block.type === 'file') {
296
+ parts.push({ type: 'text', text: fileHandleText(block.attachment) });
297
+ }
298
+ }
299
+ if (parts.length === 0) continue; // 空訊息留著只會被上游拒收
300
+ out.push({
301
+ role: 'user',
302
+ content: parts.length === 1 && parts[0].type === 'text' ? parts[0].text : parts
303
+ });
304
+ continue;
305
+ }
306
+
307
+ if (role === 'assistant') {
308
+ let textContent = '';
309
+ let reasoningContent = '';
310
+ const toolCalls = [];
311
+ if (typeof msg.content === 'string') {
312
+ textContent = msg.content;
313
+ } else if (Array.isArray(msg.content)) {
314
+ for (const block of msg.content) {
315
+ if (!block || typeof block !== 'object') continue;
316
+ if (block.type === 'text') {
317
+ textContent += block.text || '';
318
+ } else if (block.type === 'reasoning') {
319
+ reasoningContent += block.text || '';
320
+ } else if (block.type === 'tool-call') {
321
+ const rawName = block.name;
322
+ const toolName = typeof options.toUpstreamName === 'function'
323
+ ? options.toUpstreamName(rawName)
324
+ : rawName;
325
+ toolCalls.push({
326
+ id: block.id,
327
+ type: 'function',
328
+ function: {
329
+ name: toolName,
330
+ arguments:
331
+ typeof block.arguments === 'string'
332
+ ? block.arguments
333
+ : JSON.stringify(block.arguments || {})
334
+ }
335
+ });
336
+ }
337
+ }
338
+ }
339
+ if (textContent === '' && toolCalls.length === 0) continue;
340
+ const assistantMsg = { role: 'assistant', content: textContent };
341
+ // 推理模型回放歷史時要求 assistant 帶回 reasoning_content,缺了會被上游 400。
342
+ if (reasoningContent !== '') assistantMsg.reasoning_content = reasoningContent;
343
+ if (toolCalls.length > 0) assistantMsg.tool_calls = toolCalls;
344
+ out.push(assistantMsg);
345
+ continue;
346
+ }
347
+
348
+ if (role === 'tool' || msg.toolCallId) {
349
+ let content = flattenText(msg.content);
350
+ // 工具結果裡夾帶的圖片在 OpenAI 的 tool 角色沒有位置,退化成佔位文字。
351
+ if (Array.isArray(msg.content)) {
352
+ const extras = [];
353
+ for (const block of msg.content) {
354
+ if (!block || typeof block !== 'object') continue;
355
+ if (block.type === 'image') {
356
+ const ref = imageAttachmentRef(block);
357
+ if (ref !== null) extras.push(textOnlyImageText(ref));
358
+ } else if (block.type === 'file') {
359
+ extras.push(fileHandleText(block.attachment));
360
+ }
361
+ }
362
+ if (extras.length > 0) content = [content, ...extras].filter(Boolean).join('\n');
363
+ }
364
+ out.push({
365
+ role: 'tool',
366
+ tool_call_id: msg.toolCallId || msg.id,
367
+ content
368
+ });
369
+ continue;
370
+ }
371
+ }
372
+
373
+ const systemText = systemParts.filter(Boolean).join('\n\n');
374
+ return systemText === '' ? out : [{ role: 'system', content: systemText }, ...out];
375
+ }
376
+
377
+ /**
378
+ * Converts DSH tool definitions to OpenAI functions schema.
379
+ */
380
+ export function convertTools(dshTools) {
381
+ if (!Array.isArray(dshTools) || dshTools.length === 0) return undefined;
382
+
383
+ return dshTools.map((t) => {
384
+ if (t.type === 'function' && t.function) {
385
+ return t;
386
+ }
387
+ return {
388
+ type: 'function',
389
+ function: {
390
+ name: t.name,
391
+ description: t.description || '',
392
+ parameters: t.parameters || { type: 'object', properties: {} }
393
+ }
394
+ };
395
+ });
396
+ }
package/lib/config.js ADDED
@@ -0,0 +1,200 @@
1
+ import {
2
+ PROVIDER,
3
+ PROVIDER_NAME,
4
+ GO_PROVIDER,
5
+ GO_PROVIDER_NAME,
6
+ GO_CREDENTIAL_ENV_VAR,
7
+ OPENCODE_INFERENCE_URL,
8
+ DEFAULT_STREAM_IDLE_MS,
9
+ DEFAULT_PROBE_INTERVAL_MS,
10
+ DEFAULT_CATALOG_POLL_MS,
11
+ DEFAULT_IMAGE_PIXEL_BUDGET,
12
+ DEFAULT_IMAGE_MAX_BYTES
13
+ } from './constants.js';
14
+
15
+ /**
16
+ * 取得 schemastery。
17
+ *
18
+ * 第一層是正規解——正常安裝(tgz / dsh plugin add)時,外掛位於 profile 的
19
+ * node_modules 底下,Node 會逐層往上找到同一個 node_modules,直接成功。
20
+ *
21
+ * 第二層是給**開發機**用的。以 junction 掛進 profile 時,Node 用 realpath 解析,
22
+ * 起點變成原始碼目錄,往上是使用者的專案資料夾,找不到 profile 的 node_modules,
23
+ * 於是第一層會失敗。這裡改用 DSH 執行階段提供的環境變數推出 profile 目錄,再用
24
+ * createRequire 從那個位置解析。**不使用硬編碼的使用者名稱**——那會把開發機的
25
+ * 使用者名稱編進要出貨的檔案,而且換一台電腦就必然失效。
26
+ *
27
+ * 第三層是內建 stub。少了 schemastery 只會失去欄位層級的驗證(min/max),
28
+ * 預設值仍然正確,所以外掛要能照常載入,不能因為這個套件缺席就掛掉。
29
+ */
30
+ let Schema = null;
31
+ try {
32
+ const mod = await import('@deepseek-ai/schemastery');
33
+ Schema = mod.default || mod;
34
+ } catch {
35
+ try {
36
+ const { createRequire } = await import('node:module');
37
+ const { join } = await import('node:path');
38
+ const home = process.env.DSH_HOME
39
+ || join(process.env.USERPROFILE || process.env.HOME || '', '.dsh');
40
+ const profileDir = process.env.DSH_PROFILE_DIR
41
+ || join(home, 'profiles', process.env.DSH_PROFILE || 'desktop');
42
+ // 借 profile 目錄當解析起點;路徑不存在時 createRequire 只是解析失敗,
43
+ // 不會丟出例外,所以這裡是安全的。
44
+ const require = createRequire(join(profileDir, '__dsh_resolve__.js'));
45
+ Schema = require('@deepseek-ai/schemastery');
46
+ if (Schema && Schema.default) Schema = Schema.default;
47
+ } catch {
48
+ // Fallback stub if schemastery is completely unavailable
49
+ const stub = (defaultValue) => ({
50
+ default: (v) => stub(v === undefined ? defaultValue : v),
51
+ description: () => stub(defaultValue),
52
+ min: () => stub(defaultValue),
53
+ '~standard': { validate: (val) => ({ value: val === undefined ? defaultValue : val }) }
54
+ });
55
+ Schema = {
56
+ object: (fields) => {
57
+ const obj = {
58
+ default: () => obj,
59
+ description: () => obj,
60
+ '~standard': {
61
+ validate: (val = {}) => {
62
+ const value = {};
63
+ for (const [key, field] of Object.entries(fields)) {
64
+ const res = field?.['~standard']?.validate?.(val[key]);
65
+ value[key] = res?.value;
66
+ }
67
+ return { value };
68
+ }
69
+ }
70
+ };
71
+ return obj;
72
+ },
73
+ string: () => stub(''),
74
+ number: () => stub(0),
75
+ boolean: () => stub(false)
76
+ };
77
+ }
78
+ }
79
+
80
+ export const Config = Schema.object({
81
+ providerId: Schema.string()
82
+ .default(PROVIDER)
83
+ .description('Provider ID in DSH (default: "opencode-next").'),
84
+
85
+ providerName: Schema.string()
86
+ .default(PROVIDER_NAME)
87
+ .description('Display name in DSH model picker.'),
88
+
89
+ inferenceUrl: Schema.string()
90
+ .default(OPENCODE_INFERENCE_URL)
91
+ .description('OpenCode OpenAI-compatible inference base URL.'),
92
+
93
+ credentialPath: Schema.string()
94
+ .default('')
95
+ .description('Optional custom path for saved OAuth tokens (empty means auto-detect from local OpenCode Desktop or ~/.dsh/opencode-next.token.json).'),
96
+
97
+ streamIdleTimeoutMs: Schema.number()
98
+ .min(1000)
99
+ .default(DEFAULT_STREAM_IDLE_MS)
100
+ .description('Timeout in milliseconds for stream idle watchdog.'),
101
+
102
+ autoDetectModels: Schema.boolean()
103
+ .default(true)
104
+ .description('Probe the free lane and advertise only models that actually respond. Keeps the picker in sync as OpenCode adds or retires free models.'),
105
+
106
+ probeIntervalMs: Schema.number()
107
+ .min(60000)
108
+ .default(DEFAULT_PROBE_INTERVAL_MS)
109
+ .description('How often to re-verify every model, in milliseconds (default: 6 hours). Retires models that stopped serving.'),
110
+
111
+ catalogPollMs: Schema.number()
112
+ .min(0)
113
+ .default(DEFAULT_CATALOG_POLL_MS)
114
+ .description('How often to re-fetch the catalog looking for newly published free models, in milliseconds (default: 15 minutes). Set to 0 to disable new-model polling.'),
115
+
116
+ probeCachePath: Schema.string()
117
+ .default('')
118
+ .description('Optional path for the availability cache (default: ~/.dsh/opencode-next.models.json).'),
119
+
120
+ imagePixelBudget: Schema.number()
121
+ .min(10000)
122
+ .default(DEFAULT_IMAGE_PIXEL_BUDGET)
123
+ .description('Pixel budget per request image (default: 640000, about 1050x610). Must stay fixed so attachment request variants stay cacheable.'),
124
+
125
+ imageMaxBytes: Schema.number()
126
+ .min(65536)
127
+ .default(DEFAULT_IMAGE_MAX_BYTES)
128
+ .description('Encoded byte target per request image (default: 2 MiB). Base64 images count toward the request body size.'),
129
+
130
+ autoSwitchAccounts: Schema.boolean()
131
+ .default(false)
132
+ .description('Switch to another saved account when the active account is still rejected with 401 after one refresh. Off by default; 429, 402, 400, network blocks and timeouts never rotate accounts.'),
133
+
134
+ bunTransport: Schema.object({
135
+ enabled: Schema.boolean().default(false),
136
+ bunPath: Schema.string().default(''),
137
+ clientVersion: Schema.string().default('2.0.32')
138
+ }).default({ enabled: false, bunPath: '', clientVersion: '2.0.32' })
139
+ .description('Opt in to Bun native fetch for OpenCode v2 anonymous inference compatibility. Requires a Bun runtime installed separately.'),
140
+
141
+ anonymousChannel: Schema.object({
142
+ enabled: Schema.boolean().default(false)
143
+ }).default({ enabled: false })
144
+ .description('Send inference without your account credential, using the public anonymous lane. Off by default. Unofficial usage the upstream does not promise to keep working.'),
145
+
146
+ goSubscription: Schema.object({
147
+ enabled: Schema.boolean().default(false),
148
+ providerId: Schema.string().default(GO_PROVIDER),
149
+ providerName: Schema.string().default(GO_PROVIDER_NAME),
150
+ credentialRef: Schema.string().default(GO_CREDENTIAL_ENV_VAR),
151
+ cachePath: Schema.string().default('')
152
+ }).default({
153
+ enabled: false,
154
+ providerId: GO_PROVIDER,
155
+ providerName: GO_PROVIDER_NAME,
156
+ credentialRef: GO_CREDENTIAL_ENV_VAR,
157
+ cachePath: ''
158
+ }).description('Opt in to the independent OpenCode Go subscription provider (off by default). Resolves the Console Personal API Key via DSH credential service or environment variable; never stores raw API keys.')
159
+ });
160
+
161
+ export function resolveConfig(raw = {}) {
162
+ if (Config && Config['~standard'] && typeof Config['~standard'].validate === 'function') {
163
+ const res = Config['~standard'].validate(raw);
164
+ if (res.issues) {
165
+ const msg = res.issues.map((i) => i.message).join('; ');
166
+ throw new Error(`opencode-next config error: ${msg}`);
167
+ }
168
+ return res.value;
169
+ }
170
+
171
+ return {
172
+ providerId: raw.providerId || PROVIDER,
173
+ providerName: raw.providerName || PROVIDER_NAME,
174
+ inferenceUrl: raw.inferenceUrl || OPENCODE_INFERENCE_URL,
175
+ credentialPath: raw.credentialPath || '',
176
+ streamIdleTimeoutMs: raw.streamIdleTimeoutMs || DEFAULT_STREAM_IDLE_MS,
177
+ autoDetectModels: raw.autoDetectModels ?? true,
178
+ probeIntervalMs: raw.probeIntervalMs || DEFAULT_PROBE_INTERVAL_MS,
179
+ catalogPollMs: raw.catalogPollMs ?? DEFAULT_CATALOG_POLL_MS,
180
+ probeCachePath: raw.probeCachePath || '',
181
+ imagePixelBudget: raw.imagePixelBudget || DEFAULT_IMAGE_PIXEL_BUDGET,
182
+ imageMaxBytes: raw.imageMaxBytes || DEFAULT_IMAGE_MAX_BYTES,
183
+ autoSwitchAccounts: raw.autoSwitchAccounts === true,
184
+ bunTransport: {
185
+ enabled: raw.bunTransport?.enabled === true,
186
+ bunPath: raw.bunTransport?.bunPath || '',
187
+ clientVersion: raw.bunTransport?.clientVersion || '2.0.32'
188
+ },
189
+ anonymousChannel: {
190
+ enabled: raw.anonymousChannel?.enabled === true
191
+ },
192
+ goSubscription: {
193
+ enabled: raw.goSubscription?.enabled === true,
194
+ providerId: raw.goSubscription?.providerId || GO_PROVIDER,
195
+ providerName: raw.goSubscription?.providerName || GO_PROVIDER_NAME,
196
+ credentialRef: raw.goSubscription?.credentialRef || GO_CREDENTIAL_ENV_VAR,
197
+ cachePath: raw.goSubscription?.cachePath || ''
198
+ }
199
+ };
200
+ }