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/lib/probe.js ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Live availability probing for OpenCode's free-lane models.
3
+ *
4
+ * The public catalog advertises far more free models than the free lane
5
+ * actually serves: entries linger with `status: "deprecated"` while still
6
+ * answering 200 (e.g. cat-jam-free), and others look active yet return
7
+ * `Model is unavailable`. Availability therefore cannot be derived from
8
+ * metadata alone — it has to be observed.
9
+ *
10
+ * Each probe opens a real streaming request and cancels it as soon as the
11
+ * status line arrives, so a healthy model costs ~1-2s and a dead one
12
+ * ~0.3-1s. Probing is opt-in, concurrency-limited, and aborts early when the
13
+ * lane itself is unreachable from this network.
14
+ */
15
+
16
+ import {
17
+ OPENCODE_INFERENCE_URL,
18
+ PROBE_CONCURRENCY,
19
+ PROBE_MAX_TOKENS,
20
+ PROBE_TIMEOUT_MS
21
+ } from './constants.js';
22
+ import { buildHeaders, ensureFreeLaneTools, canonicalSessionId, randomId } from './client.js';
23
+ import {
24
+ classifyHttpFailure,
25
+ detectErrorType,
26
+ parseErrorType as parseErrorTypeShared
27
+ } from './failures.js';
28
+ import { executeBunFetch, resolveBunPath } from './bun-transport.js';
29
+
30
+ /**
31
+ * A 403 means one of two very different things, so the body decides:
32
+ *
33
+ * - `FreeTierError` — the lane refused the request outright (wrong client,
34
+ * non-streaming, blocked egress IP). Every remaining probe would fail the
35
+ * same way, so the run must stop.
36
+ * - `RegionError` — this one model is geo-restricted. The lane itself is
37
+ * healthy and other models must still be probed.
38
+ *
39
+ * 這份判斷現在與推論路徑共用 `failures.js`,避免探測說「可用」而實際推論
40
+ * 失敗的落差:兩邊只要有任一邊漏了 `errorType`,就會對同一個回應給出不同結論。
41
+ */
42
+ function classifyFailure(status, errorType, rawText = '') {
43
+ if (status === 'ERR') return { reachable: false, reason: 'transport' };
44
+ // 其餘交給共用的分類器,reason 直接沿用,確保兩條路徑的用詞一致。
45
+ //
46
+ // 這裡刻意不再自己攔 403:實測 `FreeTierError` 的 body 裡夾帶的正是
47
+ // 「你的網路出口有濫用流量」那段話,若在這層先用 `errorType` 判斷,就會
48
+ // 蓋掉共用分類器已經做好的「網路風控 vs 免費通道」區分,於是整輪探測
49
+ // 不會因為 IP 被擋而停手,白白多送 30 幾個注定失敗的請求出去。
50
+ //
51
+ // `rawText` 同理要往下傳:400 光看狀態碼分不出「上下文超限」、「模型不可用」
52
+ // 與「上游沒說原因」,三者在狀態頁上應該是三種不同的標籤。
53
+ const { reason, code } = classifyHttpFailure(status, errorType, { rawText });
54
+ return { reachable: isReachableReason(reason), reason, code };
55
+ }
56
+
57
+ /**
58
+ * 「這個失敗是否代表通道本身出了問題」。
59
+ *
60
+ * 判準刻意寫成「只有這幾種才算不可達」,其餘一律視為仍可達——這與重構前的
61
+ * 行為逐條相符(含未知狀態碼的 `http-<n>` 一律算可達),避免這次共用化
62
+ * 意外改變探測結果。
63
+ *
64
+ * 直覺是:探測失敗 ≠ 通道壞掉。429 或 400 只說明「這次沒問到」,模型與通道
65
+ * 都還在,繼續探測其餘模型才是對的;401/403/5xx 與帳號額度耗盡則代表通道或
66
+ * 授權本身有問題,再探下去只是白費請求。
67
+ */
68
+ const UNREACHABLE_REASONS = new Set([
69
+ 'transport',
70
+ 'unauthorized',
71
+ 'upstream-error',
72
+ 'free-lane-blocked',
73
+ 'forbidden',
74
+ // Exhausted account quota affects the lane/account, not an individual model;
75
+ // treat it as inconclusive so one 402 cannot retire the whole picker.
76
+ 'quota-exceeded',
77
+ // IP/網路出口被風控。這比 `free-lane-blocked` 更絕對:擋的是整條出口,
78
+ // 剩下 30 幾個模型再探也只會拿到同一段「abusive traffic」,白白多送請求
79
+ // 出去(還可能讓這個 IP 的評分更差),所以必須立刻停止整輪探測。
80
+ 'network-blocked'
81
+ ]);
82
+
83
+ function isReachableReason(reason) {
84
+ return !UNREACHABLE_REASONS.has(reason);
85
+ }
86
+
87
+ /** Extracts the upstream error type from a JSON error body. */
88
+ function parseErrorType(text) {
89
+ return parseErrorTypeShared(text);
90
+ }
91
+
92
+ /**
93
+ * 從回應標頭讀出「還要等多久」。
94
+ *
95
+ * 上游在 429 會送 `retry-after: 5397`(秒)。RFC 9110 也允許 HTTP-date 格式,
96
+ * 兩種都要吃。Bun transport 與 Node fetch 都是標準 `Headers`,所以同一份
97
+ * 邏輯兩邊通用。
98
+ *
99
+ * 讀不到就回 null——不要猜。猜錯會讓使用者以為「再等 5 分鐘就好」,然後
100
+ * 每五分鐘撞一次同樣的牆。
101
+ */
102
+ export function readRetryAfterMs(headers) {
103
+ if (!headers || typeof headers.get !== 'function') return null;
104
+ const raw = headers.get('retry-after');
105
+ if (typeof raw !== 'string' || !raw.trim()) return null;
106
+ const text = raw.trim();
107
+ // 純數字 = 秒數。
108
+ if (/^\d+$/.test(text)) {
109
+ const seconds = Number(text);
110
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : null;
111
+ }
112
+ // HTTP-date。
113
+ const when = Date.parse(text);
114
+ if (Number.isFinite(when)) {
115
+ const delta = when - Date.now();
116
+ return delta > 0 ? delta : 0;
117
+ }
118
+ return null;
119
+ }
120
+
121
+ /**
122
+ * Probes a single model. Resolves to a verdict describing whether the model
123
+ * served the request, and whether the lane stayed reachable.
124
+ */
125
+ export async function probeModel(token, modelId, options = {}) {
126
+ const endpoint = options.inferenceUrl || OPENCODE_INFERENCE_URL;
127
+ const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
128
+ const started = Date.now();
129
+
130
+ // 原始錯誤 body 要留到分類之後才用得到(400 得靠它分辨三種情況),
131
+ // 所以宣告在 try 外面,兩個分支都能填。
132
+ let bodyText = '';
133
+
134
+ const controller = new AbortController();
135
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
136
+
137
+ try {
138
+ const useBun = options.bunTransport?.enabled === true || options.useBun === true;
139
+ const fetchFn = (typeof options.fetch === 'function')
140
+ ? options.fetch
141
+ : (useBun
142
+ ? (u, init) => executeBunFetch(u, init, options.bunTransport)
143
+ : fetch);
144
+
145
+ const res = await fetchFn(`${endpoint}/chat/completions`, {
146
+ method: 'POST',
147
+ headers: buildHeaders(
148
+ token,
149
+ canonicalSessionId('probe-' + modelId),
150
+ randomId('req', 16),
151
+ 'prj_probe'
152
+ ),
153
+ body: JSON.stringify({
154
+ model: modelId,
155
+ stream: true,
156
+ messages: [{ role: 'user', content: 'ping' }],
157
+ max_tokens: options.maxTokens ?? PROBE_MAX_TOKENS,
158
+ tools: ensureFreeLaneTools([]),
159
+ tool_choice: 'none'
160
+ }),
161
+ signal: controller.signal
162
+ });
163
+
164
+ const status = res.status;
165
+ let errorType = null;
166
+ // 上游在 429 會帶 `retry-after`(實測值例如 5397 秒 ≈ 90 分鐘)。
167
+ // 這是「還要等多久」唯一的權威來源,比任何猜測都準。
168
+ let retryAfterMs = null;
169
+
170
+ if (status === 200) {
171
+ // Only the status line matters; release the socket immediately.
172
+ await res.body?.cancel?.().catch(() => {});
173
+ } else {
174
+ retryAfterMs = readRetryAfterMs(res.headers);
175
+ // Error bodies are small and carry the discriminator we need.
176
+ //
177
+ // 這一步必須是「文字優先、結構化 type 其次」:實測上游在 403 裡用的
178
+ // `type` 是 `FreeTierError`,但 `message` 講的是「這個 IP 有濫用流量」。
179
+ // 只看 type 會把「換網路才能解」誤判成「客戶端不合規」,而兩者接下來
180
+ // 該做的事完全不同。
181
+ const bodyText2 = await res.text().catch(() => '');
182
+ bodyText = bodyText2;
183
+ errorType = detectErrorType(bodyText2) || parseErrorType(bodyText2);
184
+ }
185
+
186
+ const { reachable, reason } = classifyFailure(status, errorType, bodyText);
187
+
188
+ return {
189
+ id: modelId,
190
+ ok: status === 200,
191
+ status,
192
+ errorType,
193
+ reachable,
194
+ ms: Date.now() - started,
195
+ reason,
196
+ // 額度解除的絕對時間(毫秒)。null 代表上游沒說或不是限流。
197
+ retryAfterMs,
198
+ retryAt: retryAfterMs === null ? null : Date.now() + retryAfterMs,
199
+ // 留一份原始回應給狀態頁顯示。
200
+ //
201
+ // 中文說明是我們的解讀,解讀可能錯(今天就錯過一次);原始文字不會,
202
+ // 而且可以直接拿去搜尋。使用者想自己查的時候,需要的是這個。
203
+ // 截斷是為了不讓某個模型回了整頁 HTML 就把狀態頁撐爆。
204
+ detail: bodyText ? bodyText.trim().slice(0, 300) : ''
205
+ };
206
+ } catch (err) {
207
+ const aborted = err?.name === 'AbortError' || controller.signal.aborted;
208
+ return {
209
+ id: modelId,
210
+ ok: false,
211
+ status: 'ERR',
212
+ errorType: null,
213
+ reachable: false,
214
+ ms: Date.now() - started,
215
+ reason: aborted ? 'timeout' : 'transport'
216
+ };
217
+ } finally {
218
+ clearTimeout(timer);
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Probes many models with bounded concurrency, preserving input order.
224
+ * `onProgress` receives (done, total, verdict) after each verdict.
225
+ *
226
+ * 熔斷(bail-out)是刻意的額度保護,但**必須說清楚它停在哪裡**。
227
+ *
228
+ * 原本 429 會讓整輪直接停止,且回傳的 `tested` 只算已跑完的筆數——呼叫端
229
+ * 因此無法分辨「46 個都驗過了」與「第 4 個撞到限流就收手」。使用者看到的
230
+ * 症狀是「可用 13,但只有 4 筆探測紀錄」,看起來像探測壞掉。
231
+ *
232
+ * 現在回傳 `stopped`(`rate-limited`/`unreachable`/`null`)與 `untested`
233
+ * (沒送出去的 model id)。呼叫端可以據此保留舊判定,而不是把沒驗過的
234
+ * 模型當成失敗。
235
+ */
236
+ export async function probeModels(token, modelIds, options = {}) {
237
+ const concurrency = Math.max(1, options.concurrency ?? PROBE_CONCURRENCY);
238
+ const results = new Array(modelIds.length);
239
+ let cursor = 0;
240
+ let done = 0;
241
+ let stop = false;
242
+ /** 為什麼停手:`rate-limited`(額度)或 `unreachable`(通道/網路)。 */
243
+ let stopped = null;
244
+ let stoppedBy = null;
245
+
246
+ const worker = async () => {
247
+ while (!stop) {
248
+ const index = cursor++;
249
+ if (index >= modelIds.length) return;
250
+
251
+ const verdict = await probeModel(token, modelIds[index], options);
252
+ results[index] = verdict;
253
+ done++;
254
+
255
+ // A blocked lane invalidates every remaining verdict, so bail out early.
256
+ if (!verdict.reachable) {
257
+ stop = true;
258
+ stopped = 'unreachable';
259
+ stoppedBy = verdict;
260
+ options.onProgress?.(done, modelIds.length, verdict);
261
+ return;
262
+ }
263
+
264
+ // 遇到 429 限流/額度已滿時立即熔斷停手,不再向剩下的模型發送請求,
265
+ // 避免在幾秒鐘內將帳號當天的剩餘額度完全耗盡。
266
+ //
267
+ // 注意:429 的 verdict 是 `reachable: true`(模型本身有效),所以這段
268
+ // 必須排在 reachable 判斷之後,否則會被上面攔走而記成「通道不可達」。
269
+ if (verdict.status === 429) {
270
+ stop = true;
271
+ stopped = 'rate-limited';
272
+ stoppedBy = verdict;
273
+ options.onProgress?.(done, modelIds.length, verdict);
274
+ return;
275
+ }
276
+
277
+ options.onProgress?.(done, modelIds.length, verdict);
278
+ }
279
+ };
280
+
281
+ await Promise.all(
282
+ Array.from({ length: Math.min(concurrency, modelIds.length) }, () => worker())
283
+ );
284
+
285
+ const settled = results.filter(Boolean);
286
+ const blocked = settled.some((r) => !r.reachable);
287
+ // 沒送出去的模型:呼叫端要保留它們的舊判定,不能當成失敗。
288
+ const testedIds = new Set(settled.map((r) => r.id));
289
+ const untested = modelIds.filter((id) => !testedIds.has(id));
290
+ // 上游在 429 上給的解除時間,取最遠的那一個(同一輪通常都一樣)。
291
+ const retryAt = settled.reduce(
292
+ (latest, r) => (Number.isFinite(r?.retryAt) && (latest === null || r.retryAt > latest) ? r.retryAt : latest),
293
+ null
294
+ );
295
+
296
+ return {
297
+ results: settled,
298
+ blocked,
299
+ blockedReason: blocked ? settled.find((r) => !r.reachable)?.reason : null,
300
+ tested: settled.length,
301
+ total: modelIds.length,
302
+ // 整輪是否被熔斷,以及是額度還是通道。null 代表跑完了。
303
+ stopped,
304
+ stoppedBy: stoppedBy ? { id: stoppedBy.id, status: stoppedBy.status, reason: stoppedBy.reason } : null,
305
+ // 額度解除的絕對時間(毫秒)。null 代表上游沒給。
306
+ retryAt,
307
+ untested
308
+ };
309
+ }