opencode-next 0.0.0-stage → 1.0.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/LICENSE +22 -0
- package/README.md +359 -2
- package/README.zh-TW.md +388 -0
- package/bin/login.mjs +71 -0
- package/bin/smoke.mjs +73 -0
- package/cordis.patch.yml +9 -0
- package/lib/adapter.js +574 -0
- package/lib/bun-transport.js +413 -0
- package/lib/bun-worker.mjs +77 -0
- package/lib/catalog.js +870 -0
- package/lib/client.js +396 -0
- package/lib/config.js +200 -0
- package/lib/constants.js +161 -0
- package/lib/context-window.js +117 -0
- package/lib/device-flow.js +263 -0
- package/lib/failures.js +475 -0
- package/lib/fallback.js +229 -0
- package/lib/go/adapter.js +434 -0
- package/lib/go/catalog.js +305 -0
- package/lib/go/client.js +647 -0
- package/lib/go/credentials.js +321 -0
- package/lib/go/service.js +643 -0
- package/lib/images.js +98 -0
- package/lib/index.js +408 -0
- package/lib/picker.js +126 -0
- package/lib/probe.js +309 -0
- package/lib/status.js +440 -0
- package/lib/store.js +434 -0
- package/lib/stream.js +271 -0
- package/lib/token-manager.js +560 -0
- package/lib/ui.js +4587 -0
- package/lib/web-api.js +876 -0
- package/package.json +69 -4
package/lib/adapter.js
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_FIRST_EVENT_MS,
|
|
3
|
+
DEFAULT_IMAGE_MAX_BYTES,
|
|
4
|
+
DEFAULT_IMAGE_PIXEL_BUDGET,
|
|
5
|
+
DEFAULT_STREAM_IDLE_MS,
|
|
6
|
+
OPENCODE_INFERENCE_URL,
|
|
7
|
+
PROVIDER,
|
|
8
|
+
PROVIDER_NAME
|
|
9
|
+
} from './constants.js';
|
|
10
|
+
import {
|
|
11
|
+
buildHeaders,
|
|
12
|
+
collectImageRefs,
|
|
13
|
+
convertMessages,
|
|
14
|
+
convertTools,
|
|
15
|
+
ensureFreeLaneTools,
|
|
16
|
+
prepareToolsWithAliases,
|
|
17
|
+
canonicalSessionId,
|
|
18
|
+
randomId,
|
|
19
|
+
stableProjectId
|
|
20
|
+
} from './client.js';
|
|
21
|
+
import { requestImageTarget, resolveImageDataUrls } from './images.js';
|
|
22
|
+
import { classifyHttpFailure, detectErrorType, toFailure } from './failures.js';
|
|
23
|
+
import { buildAttemptChain, canFallback } from './fallback.js';
|
|
24
|
+
import { parseOpenAiSseStream } from './stream.js';
|
|
25
|
+
import { executeBunFetch, lastInferenceReport, noteInference } from './bun-transport.js';
|
|
26
|
+
|
|
27
|
+
const HOST_RETRY_DELAYS_MS = Object.freeze([3000, 5000, 7000, 10000, 12000]);
|
|
28
|
+
|
|
29
|
+
export const SAFE_RETRY_POLICY = Object.freeze({
|
|
30
|
+
mode: 'normal',
|
|
31
|
+
// 交給 DSH host retry,讓 UI 顯示「已重試 n/5」並在重試耗盡後才顯示失敗。
|
|
32
|
+
// providerRetryAfterMs 提供精確的 3/5/7/10/12 秒;以下是 host 的安全上限/退路。
|
|
33
|
+
maxRetries: HOST_RETRY_DELAYS_MS.length,
|
|
34
|
+
retryableCodes: Object.freeze([
|
|
35
|
+
'EMPTY_RESPONSE',
|
|
36
|
+
'RATE_LIMIT',
|
|
37
|
+
'SERVER',
|
|
38
|
+
'TIMEOUT',
|
|
39
|
+
'TRANSPORT'
|
|
40
|
+
]),
|
|
41
|
+
initialDelayMs: HOST_RETRY_DELAYS_MS[0],
|
|
42
|
+
maxDelayMs: HOST_RETRY_DELAYS_MS.at(-1),
|
|
43
|
+
jitterRatio: 0
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
export class OpenCodeOAuthAdapter {
|
|
47
|
+
#catalog;
|
|
48
|
+
#tokenManager;
|
|
49
|
+
#config;
|
|
50
|
+
#hostRetryAttempts = new Map();
|
|
51
|
+
|
|
52
|
+
constructor(catalog, tokenManager, config = {}) {
|
|
53
|
+
this.#catalog = catalog;
|
|
54
|
+
this.#tokenManager = tokenManager;
|
|
55
|
+
this.#config = config;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Reap outstanding Bun relay children when DSH disposes this adapter. */
|
|
59
|
+
dispose() {
|
|
60
|
+
this.#config.bunTransport?.dispose?.();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 使用者設定的備援前三順位。
|
|
65
|
+
*
|
|
66
|
+
* 讀取失敗一律退回「關閉」:設定檔壞掉不該讓推論路徑跟著掛掉。
|
|
67
|
+
*/
|
|
68
|
+
#fallbackSettings() {
|
|
69
|
+
try {
|
|
70
|
+
return this.#config.fallback?.get?.() ?? { enabled: false, models: [] };
|
|
71
|
+
} catch {
|
|
72
|
+
return { enabled: false, models: [] };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 自動切換是否開啟(預設關閉)。
|
|
78
|
+
*
|
|
79
|
+
* 讀取失敗一律視為關閉:自動切換是「憑證已確定失效」才啟動的補救,
|
|
80
|
+
* 不能因為設定檔壞掉就自己打開。
|
|
81
|
+
*/
|
|
82
|
+
#autoSwitchSettings() {
|
|
83
|
+
try {
|
|
84
|
+
return this.#config.autoSwitch?.get?.() ?? { enabled: false };
|
|
85
|
+
} catch {
|
|
86
|
+
return { enabled: false };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 這次請求要依序嘗試的模型:主模型,加上(若開啟)可用的備援順位。 */
|
|
91
|
+
#attemptChain(primary, replacement = null) {
|
|
92
|
+
return buildAttemptChain({
|
|
93
|
+
primary,
|
|
94
|
+
settings: this.#fallbackSettings(),
|
|
95
|
+
isAvailable: (id) => this.#catalog.isAvailable(id),
|
|
96
|
+
replacement
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
providerInfo(provider) {
|
|
101
|
+
return {
|
|
102
|
+
id: provider || PROVIDER,
|
|
103
|
+
name: this.#config.providerName || PROVIDER_NAME
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Provider-owned retry policy. Conservative policy to protect IP reputation.
|
|
109
|
+
*/
|
|
110
|
+
providerRetryPolicy(_provider) {
|
|
111
|
+
return SAFE_RETRY_POLICY;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Provider-side image request pricing. 回傳 undefined 代表沿用 DSH 的中性估算。
|
|
116
|
+
*
|
|
117
|
+
* OpenCode 的免費通道是同一個閘道代理多個上游模型,各家視覺計費規則不同,我們
|
|
118
|
+
* 沒有可信的數字。與其編一個看起來精確、實際會誤導 token 計量的公式,不如明確
|
|
119
|
+
* 宣告「本路由不自訂圖片計價」,讓 DSH 用它自己的中性估算。
|
|
120
|
+
*/
|
|
121
|
+
imageRequestPricing(_provider, _model) {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 本轉接器送出請求時實際使用的圖片尺寸與位元組目標。
|
|
127
|
+
*
|
|
128
|
+
* 必須與 `stream()` 內 `resolveImageDataUrls()` 用的預算一致,否則截圖呼叫端
|
|
129
|
+
* 依這裡的尺寸算出的 handle 文字會跟真正送出的位元組對不上。
|
|
130
|
+
*/
|
|
131
|
+
imageRequestTarget(_provider, _model, image) {
|
|
132
|
+
return (
|
|
133
|
+
requestImageTarget(image, this.#pixelBudget(), this.#maxImageBytes()) ?? {
|
|
134
|
+
width: image?.width ?? 1,
|
|
135
|
+
height: image?.height ?? 1,
|
|
136
|
+
maxBytes: image?.bytes ?? 1
|
|
137
|
+
}
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
#pixelBudget() {
|
|
142
|
+
const configured = Number(this.#config.imagePixelBudget);
|
|
143
|
+
return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_IMAGE_PIXEL_BUDGET;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#maxImageBytes() {
|
|
147
|
+
const configured = Number(this.#config.imageMaxBytes);
|
|
148
|
+
return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_IMAGE_MAX_BYTES;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Bind one generation to a concrete dispatch. DSH expects { model, stream }.
|
|
153
|
+
* `signal` is optional cancellation for the adapter-owned model lookup.
|
|
154
|
+
*/
|
|
155
|
+
async prepareCall(provider, model, signal) {
|
|
156
|
+
return {
|
|
157
|
+
model: await this.resolveModel(provider, model, signal),
|
|
158
|
+
stream: (options) => this.stream(options)
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async listModels(provider) {
|
|
163
|
+
await this.#catalog.init();
|
|
164
|
+
return this.#catalog.describeAll(provider || PROVIDER);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async resolveModel(provider, modelId) {
|
|
168
|
+
await this.#catalog.init();
|
|
169
|
+
return this.#catalog.describe(provider || PROVIDER, modelId);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Main LlmAdapter stream generation method.
|
|
174
|
+
*
|
|
175
|
+
* 這裡只負責「依序試哪幾個模型」,真正的請求在 `#streamOnce()`。
|
|
176
|
+
*
|
|
177
|
+
* 備援的三條規則是刻意的:
|
|
178
|
+
*
|
|
179
|
+
* 1. **吐過內容就不再換。** 一旦已經 yield 給呼叫端,改用另一個模型重跑
|
|
180
|
+
* 會讓使用者看到兩段拼接的答案(前一個模型的前言 + 後一個模型的正文)。
|
|
181
|
+
* 寧可把原本的錯誤丟出去。
|
|
182
|
+
*
|
|
183
|
+
* 2. **只換「模型自己壞掉」的情況。** 判斷交給 `canFallback(reason)`:
|
|
184
|
+
* 400 模型下線、410 下架、404、地區封鎖、超時可以換;IP 被風控、
|
|
185
|
+
* 免費通道擋客戶端、授權失效則不換——那些換 30 個模型也不會好,
|
|
186
|
+
* 只會多送 30 次注定失敗的請求出去,讓這個 IP 更難看。
|
|
187
|
+
*
|
|
188
|
+
* 3. **使用者取消不算失敗。** 取消時直接往外丟,不消耗備援順位。
|
|
189
|
+
*/
|
|
190
|
+
async *stream(options) {
|
|
191
|
+
let chain = this.#attemptChain(options.model);
|
|
192
|
+
let emitted = false;
|
|
193
|
+
const sessionId = options.sessionId || canonicalSessionId(options.messages?.[0]?.content);
|
|
194
|
+
const retryKey = `${sessionId}:${options.model}`;
|
|
195
|
+
const now = Date.now();
|
|
196
|
+
for (const [key, state] of this.#hostRetryAttempts) {
|
|
197
|
+
if (now - state.updatedAt > 30 * 60 * 1000) this.#hostRetryAttempts.delete(key);
|
|
198
|
+
}
|
|
199
|
+
// 已試過的模型。上游中途建議替代模型時會改動 chain,這裡記著才不會重複。
|
|
200
|
+
const tried = new Set();
|
|
201
|
+
// 自動切換的回合狀態:每回合最多一次,且只有在還沒吐出任何 chunk 前才允許。
|
|
202
|
+
// 用共享物件往下傳,`#streamOnce` 才看得到「這個回合已經換過/已經有輸出」。
|
|
203
|
+
const turn = { emitted: false, switched: false };
|
|
204
|
+
for (let index = 0; index < chain.length; index++) {
|
|
205
|
+
const modelId = chain[index];
|
|
206
|
+
tried.add(modelId);
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
for await (const chunk of this.#streamOnce(options, modelId, turn)) {
|
|
210
|
+
emitted = true;
|
|
211
|
+
turn.emitted = true;
|
|
212
|
+
yield chunk;
|
|
213
|
+
}
|
|
214
|
+
this.#hostRetryAttempts.delete(retryKey);
|
|
215
|
+
return;
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (emitted) {
|
|
218
|
+
this.#hostRetryAttempts.delete(retryKey);
|
|
219
|
+
// 已交付回答內容的串流不可重播,否則 host retry 會把答案接成兩份。
|
|
220
|
+
// 移除 retry marker,確保 DSH 不會在部分內容後重跑整個 turn。
|
|
221
|
+
if (error?.failure?.code && SAFE_RETRY_POLICY.retryableCodes.includes(error.failure.code)) {
|
|
222
|
+
delete error.failure;
|
|
223
|
+
delete error.code;
|
|
224
|
+
delete error.reason;
|
|
225
|
+
}
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
if (options.signal?.aborted) {
|
|
229
|
+
this.#hostRetryAttempts.delete(retryKey);
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 所有 transient errors 交給 DSH host retry policy,讓 UI 顯示「已重試 n/5」。
|
|
234
|
+
// providerRetryAfterMs 是 DSH LlmFailure 官方欄位,可指定每一輪的精確等待時間。
|
|
235
|
+
// 注意:遇到 rate-limited (429) 時不要連發 5 次重試,避免短時間內打爆額度!
|
|
236
|
+
if (SAFE_RETRY_POLICY.retryableCodes.includes(error?.failure?.code) && error?.reason !== 'rate-limited') {
|
|
237
|
+
const state = this.#hostRetryAttempts.get(retryKey) ?? { count: 0, updatedAt: Date.now() };
|
|
238
|
+
if (state.count < HOST_RETRY_DELAYS_MS.length) {
|
|
239
|
+
error.failure.providerRetryAfterMs = HOST_RETRY_DELAYS_MS[state.count];
|
|
240
|
+
this.#hostRetryAttempts.set(retryKey, { count: state.count + 1, updatedAt: Date.now() });
|
|
241
|
+
} else {
|
|
242
|
+
// DSH 已用完五次 host retry;清掉狀態,讓使用者手動再送時重新從 3 秒開始。
|
|
243
|
+
this.#hostRetryAttempts.delete(retryKey);
|
|
244
|
+
}
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
this.#hostRetryAttempts.delete(retryKey);
|
|
249
|
+
if (!canFallback(error?.reason)) throw error;
|
|
250
|
+
|
|
251
|
+
// 410 會帶上游自己指名的替代模型。若使用者沒排到它、也還沒試過,
|
|
252
|
+
// 就把它接到隊尾——這是上游的建議,值得一試。
|
|
253
|
+
if (typeof error?.replacement === 'string' && !tried.has(error.replacement)) {
|
|
254
|
+
const settings = this.#fallbackSettings();
|
|
255
|
+
if (settings.enabled) chain = [...chain, error.replacement];
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// chain 可能剛被延長,所以 `isLast` 要以延長後的長度重算。
|
|
259
|
+
if (index === chain.length - 1) throw error;
|
|
260
|
+
console.warn(
|
|
261
|
+
`[opencode-next] model "${modelId}" failed (${error?.reason ?? 'unknown'}); `
|
|
262
|
+
+ `falling back to "${chain[index + 1]}"`
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 對單一模型送一次請求並把 SSE 串出去。 */
|
|
269
|
+
async *#streamOnce(options, modelId, turn) {
|
|
270
|
+
const model = this.#catalog.getModel(modelId) || {
|
|
271
|
+
id: modelId,
|
|
272
|
+
name: modelId,
|
|
273
|
+
defaultMaxTokens: 8192
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
// Session and request IDs
|
|
277
|
+
const sessionId = options.sessionId || canonicalSessionId(options.messages?.[0]?.content);
|
|
278
|
+
const requestId = randomId('req', 16);
|
|
279
|
+
// 專案 id 必須是穩定的 `prj_xxx` 形式;舊版直接送字面值 'opencode',
|
|
280
|
+
// 白白丟掉 buildHeaders 的雜湊預設。
|
|
281
|
+
const projectId = options.projectId || stableProjectId('opencode');
|
|
282
|
+
|
|
283
|
+
let credential = this.#tokenManager.acquireCredential
|
|
284
|
+
? await this.#tokenManager.acquireCredential()
|
|
285
|
+
: { token: await this.#tokenManager.getValidToken(), ...this.#tokenManager.credentialSnapshot?.() };
|
|
286
|
+
let token = credential.token;
|
|
287
|
+
|
|
288
|
+
// Map reasoning effort
|
|
289
|
+
let reasoningEffort;
|
|
290
|
+
if (options.reasoningEffort) {
|
|
291
|
+
reasoningEffort = options.reasoningEffort === 'off' ? 'none' : options.reasoningEffort;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const maxTokens = options.maxTokens || model.defaultMaxTokens || 8192;
|
|
295
|
+
|
|
296
|
+
// 圖片:先用 attachment service 讀成 data URI,再交給 convertMessages 內嵌。
|
|
297
|
+
// 路由不支援圖片時(catalog 的 inputModalities 沒有 'image')直接跳過讀取。
|
|
298
|
+
const imageSupported = model.inputModalities === undefined
|
|
299
|
+
|| model.inputModalities.includes('image');
|
|
300
|
+
let imageUrls = new Map();
|
|
301
|
+
if (imageSupported) {
|
|
302
|
+
const refs = collectImageRefs(options.messages || []);
|
|
303
|
+
if (refs.size > 0) {
|
|
304
|
+
imageUrls = await resolveImageDataUrls(refs, {
|
|
305
|
+
attachments: this.#config.resolveAttachments?.(),
|
|
306
|
+
pixelBudget: this.#pixelBudget(),
|
|
307
|
+
maxBytes: this.#maxImageBytes(),
|
|
308
|
+
signal: options.signal
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Convert caller tools and map to upstream names via safe aliases
|
|
314
|
+
const userTools = convertTools(options.tools);
|
|
315
|
+
const hasUserTools = Array.isArray(userTools) && userTools.length > 0;
|
|
316
|
+
const { tools, toUpstreamName, toDshName } = prepareToolsWithAliases(userTools);
|
|
317
|
+
|
|
318
|
+
const messages = convertMessages(options.messages || [], {
|
|
319
|
+
system: options.system,
|
|
320
|
+
imageUrls,
|
|
321
|
+
imageSupported,
|
|
322
|
+
toUpstreamName
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const bodyPayload = {
|
|
326
|
+
model: model.id,
|
|
327
|
+
messages,
|
|
328
|
+
stream: true,
|
|
329
|
+
stream_options: { include_usage: true },
|
|
330
|
+
max_completion_tokens: maxTokens,
|
|
331
|
+
tools,
|
|
332
|
+
...(hasUserTools ? {} : { tool_choice: 'none' }),
|
|
333
|
+
...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
|
|
334
|
+
...(options.temperature !== undefined ? { temperature: options.temperature } : {}),
|
|
335
|
+
...(Array.isArray(options.stop) && options.stop.length > 0 ? { stop: options.stop } : {})
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
const endpoint = this.#config.inferenceUrl || OPENCODE_INFERENCE_URL;
|
|
339
|
+
|
|
340
|
+
// 看門狗自己也要能切斷連線。
|
|
341
|
+
//
|
|
342
|
+
// 光是在本機放棄等待沒用:body 的 reader 還掛在那條連線上,上游 socket 不會
|
|
343
|
+
// 關,被放棄的請求會一路留到 TCP 超時。所以這裡把呼叫端的 signal 與看門狗的
|
|
344
|
+
// signal 併成一個,超時時直接 abort 掉 fetch。
|
|
345
|
+
const watchdog = createWatchdog(this.#firstEventMs(), this.#idleMs(), options.signal);
|
|
346
|
+
|
|
347
|
+
// 401 handling is deliberately narrow: refresh the exact dispatched account
|
|
348
|
+
// once; only a second 401 on that refreshed credential can rotate accounts.
|
|
349
|
+
// Every retry here is before yielding any content (the outer turn guard also
|
|
350
|
+
// prevents replay after partial output).
|
|
351
|
+
let res = null;
|
|
352
|
+
let attempts = 0;
|
|
353
|
+
|
|
354
|
+
try {
|
|
355
|
+
while (attempts < 3) {
|
|
356
|
+
attempts++;
|
|
357
|
+
const headers = buildHeaders(token, sessionId, requestId, projectId, credential.orgId);
|
|
358
|
+
|
|
359
|
+
try {
|
|
360
|
+
const useBun = this.#config.bunTransport?.enabled === true || this.#config.useBun === true;
|
|
361
|
+
const toolNames = Array.isArray(tools)
|
|
362
|
+
? tools.map((tool) => tool?.function?.name || tool?.name).filter(Boolean)
|
|
363
|
+
: [];
|
|
364
|
+
noteInference({
|
|
365
|
+
transport: useBun ? 'bun' : 'node',
|
|
366
|
+
model: model.id,
|
|
367
|
+
toolCount: toolNames.length,
|
|
368
|
+
tools: toolNames.slice(0, 16),
|
|
369
|
+
hasBash: toolNames.includes('bash'),
|
|
370
|
+
hasRead: toolNames.includes('read')
|
|
371
|
+
});
|
|
372
|
+
// BunTransport 啟用後若 Bun 啟動/協定失敗,應如實回報 transport error,
|
|
373
|
+
// 不能靜默退回 Node fetch 再製造相同的 429。
|
|
374
|
+
const fetchFn = useBun
|
|
375
|
+
? (u, init) => executeBunFetch(u, init, {
|
|
376
|
+
...this.#config.bunTransport,
|
|
377
|
+
anonymous: this.#config.anonymousChannel?.enabled === true
|
|
378
|
+
})
|
|
379
|
+
: fetch;
|
|
380
|
+
|
|
381
|
+
res = await fetchFn(`${endpoint}/chat/completions`, {
|
|
382
|
+
method: 'POST',
|
|
383
|
+
headers,
|
|
384
|
+
body: JSON.stringify(bodyPayload),
|
|
385
|
+
signal: watchdog.signal
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
if (res.status === 401 && attempts === 1) {
|
|
389
|
+
if (this.#tokenManager.refreshCredential) {
|
|
390
|
+
const refreshed = await this.#tokenManager.refreshCredential(credential);
|
|
391
|
+
if (refreshed?.stale || !refreshed?.token) break;
|
|
392
|
+
credential = refreshed;
|
|
393
|
+
token = refreshed.token;
|
|
394
|
+
} else {
|
|
395
|
+
token = await this.#tokenManager.refresh();
|
|
396
|
+
credential = { token, ...this.#tokenManager.credentialSnapshot?.() };
|
|
397
|
+
}
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
if (res.status === 401 && attempts === 2 && !turn.emitted && !turn.switched
|
|
402
|
+
&& credential.accountId && this.#autoSwitchSettings().enabled === true
|
|
403
|
+
&& this.#tokenManager.switchToNextAccount) {
|
|
404
|
+
const next = await this.#tokenManager.switchToNextAccount(credential.accountId, { version: credential.version });
|
|
405
|
+
if (next) {
|
|
406
|
+
turn.switched = true;
|
|
407
|
+
credential = await this.#tokenManager.acquireCredential();
|
|
408
|
+
token = credential.token;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
break;
|
|
414
|
+
} catch (err) {
|
|
415
|
+
if (options.signal?.aborted) throw err;
|
|
416
|
+
if (watchdog.timedOut()) throw watchdog.error();
|
|
417
|
+
throw toFailure(err, { code: 'TRANSPORT', reason: 'transport' });
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (!res || !res.ok) {
|
|
422
|
+
const errText = res ? await res.text() : 'No response from OpenCode server';
|
|
423
|
+
const errJson = (() => {
|
|
424
|
+
try {
|
|
425
|
+
return JSON.parse(errText);
|
|
426
|
+
} catch {
|
|
427
|
+
return null;
|
|
428
|
+
}
|
|
429
|
+
})();
|
|
430
|
+
|
|
431
|
+
let msg = errJson?.error?.message || errJson?.message || errText;
|
|
432
|
+
if (typeof msg === 'string' && msg.includes('Endpoint is unavailable')) {
|
|
433
|
+
msg = `${msg}(該模型上游端點目前維護/不可用,請切換其他在線模型)`;
|
|
434
|
+
}
|
|
435
|
+
const status = res ? res.status : 500;
|
|
436
|
+
|
|
437
|
+
// 403 有幾種完全不同的意思,靠 body 分辨(與 probe.js 共用同一份判斷)。
|
|
438
|
+
// 沒有這一步,使用者只看到一句 403,分不出「換模型就好」和「整個通道被擋」。
|
|
439
|
+
//
|
|
440
|
+
// 順序很重要:先看原始 body 的文字特徵,再看結構化的 `type`。
|
|
441
|
+
// 上游有時會把「IP 風控」那段說明包在 `FreeTierError` 的 body 裡,
|
|
442
|
+
// 若先採用 `type: "FreeTierError"`,就會把「你的網路出口被擋、請關 VPN」
|
|
443
|
+
// 誤導成「請求缺少必要欄位」——而那正是使用者最需要正確答案的時刻。
|
|
444
|
+
const structuredType = errJson?.error?.type || errJson?.type || null;
|
|
445
|
+
const errorType = detectErrorType(errText) || structuredType;
|
|
446
|
+
|
|
447
|
+
const classified = {
|
|
448
|
+
...classifyHttpFailure(status, errorType, {
|
|
449
|
+
// 410 會附上 `metadata.replacement`(實測 space-bunny-free →
|
|
450
|
+
// minimax-m3.1-flash-free)。把它帶進分類,提示就能直接說該換哪一個,
|
|
451
|
+
// 而不是只說「這個模型已下架」讓使用者自己找。
|
|
452
|
+
replacement: errJson?.metadata?.replacement ?? null,
|
|
453
|
+
// 400/429 都要靠原始 body 分辨錯誤類型。
|
|
454
|
+
rawText: errText
|
|
455
|
+
}),
|
|
456
|
+
status
|
|
457
|
+
};
|
|
458
|
+
const shape = lastInferenceReport() ?? {};
|
|
459
|
+
const toolList = Array.isArray(shape.tools) && shape.tools.length ? shape.tools.join(',') : 'none';
|
|
460
|
+
const error = new Error(`OpenCode OAuth inference failed (${status}): ${msg} [transport=${shape.transport || 'unknown'}; tools=${toolList}]`);
|
|
461
|
+
error.status = status;
|
|
462
|
+
// 備援迴圈靠它把上游指名的替代模型接到隊尾。
|
|
463
|
+
if (classified.replacement) error.replacement = classified.replacement;
|
|
464
|
+
|
|
465
|
+
// 一定要經由 toFailure 掛上 `.failure`:DSH 的 normalizeLlmFailure
|
|
466
|
+
// 只信任 `.failure`,單獨寫 `.code` 會被核銷成 `UNKNOWN`,
|
|
467
|
+
// 讓重試政策與錯誤提示同時失效。
|
|
468
|
+
throw toFailure(error, classified);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// 解析 SSE 時套上看門狗。
|
|
472
|
+
//
|
|
473
|
+
// 免費通道偶爾會在送出 200 之後完全沉默:連線還在、但一個 frame 都不來。
|
|
474
|
+
// 沒有超時的話整個回合就卡在那裡,使用者只看到轉圈圈,而 DSH 這端也拿不到
|
|
475
|
+
// 任何可以重試的錯誤。這裡把「等第一個事件」與「事件之間的閒置」分開計時:
|
|
476
|
+
// 前者用較短的 FIRST_EVENT,後者用 streamIdleTimeoutMs。
|
|
477
|
+
yield* withStreamWatchdog(parseOpenAiSseStream(res.body, { ...options, resolveToolName: toDshName }), watchdog);
|
|
478
|
+
} finally {
|
|
479
|
+
watchdog.dispose();
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
#idleMs() {
|
|
484
|
+
const configured = Number(this.#config.streamIdleTimeoutMs);
|
|
485
|
+
return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_STREAM_IDLE_MS;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
#firstEventMs() {
|
|
489
|
+
const idle = this.#idleMs();
|
|
490
|
+
return Math.min(DEFAULT_FIRST_EVENT_MS, idle);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* 建立一個「太久沒動靜就 abort」的控制器,並把呼叫端的 signal 串進來。
|
|
496
|
+
*
|
|
497
|
+
* 失敗會產生 `code = 'TIMEOUT'` 的錯誤,正好落在 `SAFE_RETRY_POLICY` 的
|
|
498
|
+
* retryableCodes 裡,所以上層會依政策重試,而不是把整個回合吊死。
|
|
499
|
+
*/
|
|
500
|
+
function createWatchdog(firstEventMs, idleMs, callerSignal) {
|
|
501
|
+
const controller = new AbortController();
|
|
502
|
+
let timer = null;
|
|
503
|
+
let armed = true;
|
|
504
|
+
let timeoutError = null;
|
|
505
|
+
|
|
506
|
+
const onCallerAbort = () => controller.abort(callerSignal?.reason);
|
|
507
|
+
if (callerSignal !== undefined) {
|
|
508
|
+
if (callerSignal.aborted) onCallerAbort();
|
|
509
|
+
else callerSignal.addEventListener('abort', onCallerAbort, { once: true });
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const arm = () => {
|
|
513
|
+
if (timer !== null) clearTimeout(timer);
|
|
514
|
+
const limit = armed ? firstEventMs : idleMs;
|
|
515
|
+
timer = setTimeout(() => {
|
|
516
|
+
timeoutError = new Error(
|
|
517
|
+
armed
|
|
518
|
+
? `OpenCode stream sent no first event within ${limit}ms`
|
|
519
|
+
: `OpenCode stream was idle for ${limit}ms`
|
|
520
|
+
);
|
|
521
|
+
|
|
522
|
+
// 這裡必須走 toFailure:只寫 `.code = 'TIMEOUT'` 的話,
|
|
523
|
+
// DSH 的 normalizeLlmFailure 會把它核銷成 `UNKNOWN`,
|
|
524
|
+
// 於是 SAFE_RETRY_POLICY 的 retryableCodes 永遠比對不到 TIMEOUT,
|
|
525
|
+
// 重試政策形同虛設——這正是看門狗原本「有做但沒生效」的原因。
|
|
526
|
+
//
|
|
527
|
+
// `reason` 讓備援迴圈知道「這個模型等到超時」,因而可以換下一個順位:
|
|
528
|
+
// 免費通道裡遲遲不送第一個事件的模型通常是該上游端點掛住,換一個就好。
|
|
529
|
+
toFailure(timeoutError, { code: 'TIMEOUT', reason: 'timeout', status: undefined });
|
|
530
|
+
controller.abort(timeoutError);
|
|
531
|
+
}, limit);
|
|
532
|
+
};
|
|
533
|
+
|
|
534
|
+
arm();
|
|
535
|
+
|
|
536
|
+
return {
|
|
537
|
+
signal: controller.signal,
|
|
538
|
+
/** 收到一個 chunk 後重置閒置計時,並解除「等首個事件」階段。 */
|
|
539
|
+
tick() {
|
|
540
|
+
armed = false;
|
|
541
|
+
arm();
|
|
542
|
+
},
|
|
543
|
+
timedOut: () => timeoutError !== null,
|
|
544
|
+
error: () => timeoutError ?? new Error('OpenCode stream aborted'),
|
|
545
|
+
dispose() {
|
|
546
|
+
if (timer !== null) clearTimeout(timer);
|
|
547
|
+
timer = null;
|
|
548
|
+
callerSignal?.removeEventListener?.('abort', onCallerAbort);
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* 把看門狗接到 AsyncIterable 上:每次拿到值就重置計時,超時由 fetch 那端的
|
|
555
|
+
* abort 傳播過來。
|
|
556
|
+
*/
|
|
557
|
+
async function* withStreamWatchdog(source, watchdog) {
|
|
558
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
559
|
+
try {
|
|
560
|
+
for (;;) {
|
|
561
|
+
if (watchdog.timedOut()) throw watchdog.error();
|
|
562
|
+
const next = await iterator.next();
|
|
563
|
+
if (next.done === true) return;
|
|
564
|
+
watchdog.tick();
|
|
565
|
+
yield next.value;
|
|
566
|
+
}
|
|
567
|
+
} catch (error) {
|
|
568
|
+
if (watchdog.timedOut()) throw watchdog.error();
|
|
569
|
+
if (watchdog.signal.aborted) throw error; // 使用者取消,不把它誤當成斷線重試。
|
|
570
|
+
if (error?.failure?.code) throw error;
|
|
571
|
+
// SSE body 在讀取途中 reset/terminated 時,補上 host retry policy 可辨識的碼。
|
|
572
|
+
throw toFailure(error, { code: 'TRANSPORT', reason: 'transport' });
|
|
573
|
+
}
|
|
574
|
+
}
|