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/LICENSE +22 -0
- package/README.md +339 -2
- package/README.zh-TW.md +368 -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/catalog.js
ADDED
|
@@ -0,0 +1,870 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import {
|
|
5
|
+
OPENCODE_MODELS_URL,
|
|
6
|
+
STATIC_FREE_MODELS
|
|
7
|
+
} from './constants.js';
|
|
8
|
+
|
|
9
|
+
let lastFetchTime = 0;
|
|
10
|
+
/**
|
|
11
|
+
* Shared across catalog instances in this process. Without it, a second
|
|
12
|
+
* instance would see a fresh `lastFetchTime`, skip the fetch, and silently
|
|
13
|
+
* fall back to the much smaller static list.
|
|
14
|
+
*/
|
|
15
|
+
let sharedCatalog = null;
|
|
16
|
+
const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
|
|
17
|
+
const CHANNEL_BLOCKED_REASONS = new Set([
|
|
18
|
+
'transport',
|
|
19
|
+
'unauthorized',
|
|
20
|
+
'upstream-error',
|
|
21
|
+
'free-lane-blocked',
|
|
22
|
+
'forbidden',
|
|
23
|
+
'network-blocked',
|
|
24
|
+
'quota-exceeded',
|
|
25
|
+
'endpoint-not-found'
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The catalog marks dropped models as `status: "deprecated"`, but that flag is
|
|
30
|
+
* unreliable in both directions: some deprecated entries still answer 200
|
|
31
|
+
* while some unmarked ones are gone. It is still a useful *hint*, so a
|
|
32
|
+
* deprecated model is never advertised unless probing confirms it works.
|
|
33
|
+
*/
|
|
34
|
+
export function isFreeCandidate(id, raw) {
|
|
35
|
+
const lower = String(id).toLowerCase();
|
|
36
|
+
if (lower.includes('-free')) return true;
|
|
37
|
+
if (lower === 'big-pickle') return true;
|
|
38
|
+
const cost = raw?.cost;
|
|
39
|
+
return Boolean(cost && cost.input === 0 && cost.output === 0);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Normalizes an OpenCode raw model metadata object into a DSH model descriptor.
|
|
44
|
+
*/
|
|
45
|
+
export function normalizeModel(id, raw) {
|
|
46
|
+
const name = raw?.name || id;
|
|
47
|
+
const rawContext = raw?.limit?.context;
|
|
48
|
+
const context = rawContext || 128000;
|
|
49
|
+
const contextSource = Number.isSafeInteger(rawContext) && rawContext > 0 ? 'opencode' : 'fallback';
|
|
50
|
+
const output = raw?.limit?.output || 8192;
|
|
51
|
+
|
|
52
|
+
let inputModalities = ['text'];
|
|
53
|
+
if (raw?.modalities?.input && Array.isArray(raw.modalities.input)) {
|
|
54
|
+
inputModalities = raw.modalities.input.filter((m) => m === 'text' || m === 'image');
|
|
55
|
+
} else if (raw?.attachment === true) {
|
|
56
|
+
inputModalities = ['text', 'image'];
|
|
57
|
+
}
|
|
58
|
+
if (inputModalities.length === 0) inputModalities = ['text'];
|
|
59
|
+
|
|
60
|
+
// OpenCode reports the exact effort values the upstream accepts. They vary
|
|
61
|
+
// per model and are authoritative: inventing values (e.g. adding "off"
|
|
62
|
+
// everywhere) makes the upstream reject the request with 400
|
|
63
|
+
// `[unsupported_value]`. Upstream spells "no reasoning" as "none"; DSH
|
|
64
|
+
// spells it "off", and adapter.js maps it back on the wire.
|
|
65
|
+
const effortValues = raw?.reasoning_options?.find?.((o) => o?.type === 'effort')?.values;
|
|
66
|
+
let efforts = [];
|
|
67
|
+
if (Array.isArray(effortValues) && effortValues.length > 0) {
|
|
68
|
+
efforts = [...new Set(effortValues.map((v) => (v === 'none' ? 'off' : String(v))))];
|
|
69
|
+
} else if (raw?.reasoning) {
|
|
70
|
+
// Reasoning is on but no effort list was published. These four are the
|
|
71
|
+
// values every such model has accepted in live probes.
|
|
72
|
+
efforts = ['off', 'low', 'medium', 'high'];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// DSH requires defaultEffort to be one of the advertised ids.
|
|
76
|
+
const defaultEffort = efforts.includes('medium')
|
|
77
|
+
? 'medium'
|
|
78
|
+
: efforts.includes('high')
|
|
79
|
+
? 'high'
|
|
80
|
+
: efforts[0];
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
id,
|
|
84
|
+
name,
|
|
85
|
+
contextWindow: context,
|
|
86
|
+
catalogContextWindow: context,
|
|
87
|
+
contextSource,
|
|
88
|
+
defaultMaxTokens: output,
|
|
89
|
+
inputModalities,
|
|
90
|
+
efforts,
|
|
91
|
+
defaultEffort: efforts.length ? defaultEffort : undefined,
|
|
92
|
+
deprecated: raw?.status === 'deprecated',
|
|
93
|
+
status: raw?.status || 'active'
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Fetches the public catalog and returns every free-lane candidate, including
|
|
99
|
+
* deprecated ones — availability is decided later by live probing.
|
|
100
|
+
*/
|
|
101
|
+
export async function fetchLiveCatalog() {
|
|
102
|
+
try {
|
|
103
|
+
const res = await fetch(OPENCODE_MODELS_URL, { signal: AbortSignal.timeout(15000) });
|
|
104
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
105
|
+
|
|
106
|
+
const data = await res.json();
|
|
107
|
+
const opencodeModels = data.opencode?.models || {};
|
|
108
|
+
|
|
109
|
+
const candidates = [];
|
|
110
|
+
for (const [id, raw] of Object.entries(opencodeModels)) {
|
|
111
|
+
if (isFreeCandidate(id, raw)) candidates.push(normalizeModel(id, raw));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (candidates.length > 0) {
|
|
115
|
+
candidates.sort((a, b) => {
|
|
116
|
+
const aDep = a.deprecated ? 1 : 0;
|
|
117
|
+
const bDep = b.deprecated ? 1 : 0;
|
|
118
|
+
if (aDep !== bDep) return aDep - bDep;
|
|
119
|
+
if (a.id.includes('deepseek') !== b.id.includes('deepseek')) {
|
|
120
|
+
return a.id.includes('deepseek') ? -1 : 1;
|
|
121
|
+
}
|
|
122
|
+
return a.name.localeCompare(b.name);
|
|
123
|
+
});
|
|
124
|
+
return candidates;
|
|
125
|
+
}
|
|
126
|
+
} catch (err) {
|
|
127
|
+
console.warn(
|
|
128
|
+
'[opencode-next] Failed to fetch live catalog, using static fallback:',
|
|
129
|
+
err.message
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return STATIC_FREE_MODELS;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Default location of the persisted availability cache. */
|
|
137
|
+
export function defaultProbeCachePath() {
|
|
138
|
+
return path.join(os.homedir(), '.dsh', 'opencode-next.models.json');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function readProbeCache(cachePath) {
|
|
142
|
+
try {
|
|
143
|
+
if (!fs.existsSync(cachePath)) return null;
|
|
144
|
+
const parsed = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
|
|
145
|
+
if (!parsed || !Array.isArray(parsed.available)) return null;
|
|
146
|
+
// Keep durable availability and failure streaks even when the results need
|
|
147
|
+
// re-verification. `isProbeFresh()` controls whether a fresh probe is due;
|
|
148
|
+
// discarding a stale cache here would reset hysteresis on every restart.
|
|
149
|
+
return parsed;
|
|
150
|
+
} catch {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function writeProbeCache(cachePath, payload) {
|
|
156
|
+
try {
|
|
157
|
+
fs.mkdirSync(path.dirname(cachePath), { recursive: true });
|
|
158
|
+
fs.writeFileSync(cachePath, JSON.stringify(payload, null, 2), 'utf8');
|
|
159
|
+
} catch (err) {
|
|
160
|
+
console.warn('[opencode-next] Could not persist availability cache:', err.message);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Model catalog with live availability tracking.
|
|
166
|
+
*
|
|
167
|
+
* `getModels()` returns picker-published models only. Before the first probe,
|
|
168
|
+
* the curated static subset is the only pre-verified set; new candidates remain hidden.
|
|
169
|
+
*/
|
|
170
|
+
export class ModelCatalog {
|
|
171
|
+
#models = [...STATIC_FREE_MODELS];
|
|
172
|
+
#available = null; // Set of confirmed ids, or null when unprobed
|
|
173
|
+
#knownIds = new Set(); // Every id we have ever probed or seen in the catalog
|
|
174
|
+
#failureStreaks = new Map(); // Consecutive model-specific failures; persisted across restarts
|
|
175
|
+
#lastProbe = 0; // Most recent complete or incremental result time, for diagnostics
|
|
176
|
+
#lastFullProbe = 0; // Only a complete sweep can make the startup cache fresh
|
|
177
|
+
#lastTruncation = null; // Last run that bailed out early (rate limit / blocked lane)
|
|
178
|
+
#probeResults = []; // Latest per-model verdicts (incremental runs preserve earlier rows)
|
|
179
|
+
#probeGeneration = 0; // Invalidates in-flight results after credential/account changes
|
|
180
|
+
#probeRuns = new Map(); // Per-generation active probe plus queued opposite-mode work
|
|
181
|
+
#cachePath;
|
|
182
|
+
#contextStore;
|
|
183
|
+
#pickerStore;
|
|
184
|
+
|
|
185
|
+
constructor(options = {}) {
|
|
186
|
+
this.#cachePath = options.probeCachePath || defaultProbeCachePath();
|
|
187
|
+
this.#contextStore = options.contextStore || null;
|
|
188
|
+
// 勾選名單:null 表示這個 catalog 沒接勾選功能,行為與舊版完全相同。
|
|
189
|
+
// 既有測試與 headless 用法不傳它,就不會被改變語意。
|
|
190
|
+
this.#pickerStore = options.pickerStore || null;
|
|
191
|
+
const cached = readProbeCache(this.#cachePath);
|
|
192
|
+
if (cached) {
|
|
193
|
+
this.#available = new Set(cached.available.filter((id) => typeof id === 'string'));
|
|
194
|
+
this.#lastProbe = Number.isFinite(cached.probedAt) ? cached.probedAt : 0;
|
|
195
|
+
// Legacy caches (including the previous v2 format) cannot tell whether
|
|
196
|
+
// `probedAt` came from a full or incremental sweep. Preserve availability,
|
|
197
|
+
// streaks, and row diagnostics, but force one full re-verification.
|
|
198
|
+
this.#lastFullProbe = Number.isFinite(cached.fullProbedAt) ? cached.fullProbedAt : 0;
|
|
199
|
+
if (Array.isArray(cached.results)) {
|
|
200
|
+
// v1 stored only the latest probe results. Use its sweep timestamp as
|
|
201
|
+
// the row timestamp while migrating; v2 stores it per model.
|
|
202
|
+
this.#probeResults = cached.results
|
|
203
|
+
.filter((r) => r && typeof r.id === 'string')
|
|
204
|
+
.map((r) => ({ ...r, probedAt: Number.isFinite(r.probedAt) ? r.probedAt : this.#lastProbe }));
|
|
205
|
+
}
|
|
206
|
+
if (Array.isArray(cached.knownIds)) {
|
|
207
|
+
this.#knownIds = new Set(cached.knownIds.filter((id) => typeof id === 'string'));
|
|
208
|
+
} else if (Array.isArray(cached.results)) {
|
|
209
|
+
// v1 already recorded one result per probed model. Recover the set so
|
|
210
|
+
// upgrading does not force an unnecessary incremental re-probe.
|
|
211
|
+
this.#knownIds = new Set(cached.results.map((r) => r?.id).filter((id) => typeof id === 'string'));
|
|
212
|
+
}
|
|
213
|
+
if (cached.failureStreaks && typeof cached.failureStreaks === 'object' && !Array.isArray(cached.failureStreaks)) {
|
|
214
|
+
for (const [id, count] of Object.entries(cached.failureStreaks)) {
|
|
215
|
+
if (Number.isSafeInteger(count) && count > 0) this.#failureStreaks.set(id, count);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
// 「上次探測只驗了一部分」也要跨重啟保留,否則畫面會以為整份都驗過。
|
|
219
|
+
if (cached.truncation && typeof cached.truncation === 'object') {
|
|
220
|
+
this.#lastTruncation = {
|
|
221
|
+
stopped: typeof cached.truncation.stopped === 'string' ? cached.truncation.stopped : 'unknown',
|
|
222
|
+
at: Number.isFinite(cached.truncation.at) ? cached.truncation.at : 0,
|
|
223
|
+
tested: Number.isFinite(cached.truncation.tested) ? cached.truncation.tested : 0,
|
|
224
|
+
total: Number.isFinite(cached.truncation.total) ? cached.truncation.total : 0,
|
|
225
|
+
stoppedBy: cached.truncation.stoppedBy ?? null,
|
|
226
|
+
retryAt: Number.isFinite(cached.truncation.retryAt) ? cached.truncation.retryAt : null
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
#withContext(model) {
|
|
233
|
+
const catalogContextWindow = model.catalogContextWindow ?? model.contextWindow;
|
|
234
|
+
const override = this.#contextStore?.getOverride?.(model.id) ?? null;
|
|
235
|
+
return {
|
|
236
|
+
...model,
|
|
237
|
+
catalogContextWindow,
|
|
238
|
+
contextWindow: override ?? catalogContextWindow,
|
|
239
|
+
contextOverride: override,
|
|
240
|
+
contextSource: override === null ? (model.contextSource || 'fallback') : 'custom'
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async init() {
|
|
245
|
+
// Reuse the process-wide fetch so every instance sees the full candidate
|
|
246
|
+
// list instead of a truncated static fallback.
|
|
247
|
+
if (sharedCatalog && Date.now() - lastFetchTime < CACHE_TTL_MS) {
|
|
248
|
+
if (this.#models.length < sharedCatalog.length) this.#models = sharedCatalog;
|
|
249
|
+
return this.getModels();
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const live = await fetchLiveCatalog();
|
|
253
|
+
if (live?.length) {
|
|
254
|
+
this.#models = live;
|
|
255
|
+
sharedCatalog = live;
|
|
256
|
+
lastFetchTime = Date.now();
|
|
257
|
+
}
|
|
258
|
+
return this.getModels();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Re-fetches the catalog and reports which candidate ids are new.
|
|
263
|
+
*
|
|
264
|
+
* This is the mechanism that surfaces brand-new free models: the catalog is
|
|
265
|
+
* cheap to fetch, so a scheduled refresh can spot an addition immediately
|
|
266
|
+
* and probe just that one model instead of the whole list.
|
|
267
|
+
*/
|
|
268
|
+
async refreshCatalog() {
|
|
269
|
+
const before = new Set(this.#models.map((m) => m.id));
|
|
270
|
+
const live = await fetchLiveCatalog();
|
|
271
|
+
|
|
272
|
+
if (!live?.length) return { added: [], removed: [], total: this.#models.length };
|
|
273
|
+
|
|
274
|
+
this.#models = live;
|
|
275
|
+
sharedCatalog = live;
|
|
276
|
+
lastFetchTime = Date.now();
|
|
277
|
+
|
|
278
|
+
const after = new Set(live.map((m) => m.id));
|
|
279
|
+
const added = [...after].filter((id) => !before.has(id));
|
|
280
|
+
const removed = [...before].filter((id) => !after.has(id));
|
|
281
|
+
|
|
282
|
+
return { added, removed, total: live.length };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Candidate ids never yet probed in any run. */
|
|
286
|
+
unseenCandidates() {
|
|
287
|
+
return this.#models.map((m) => m.id).filter((id) => !this.#knownIds.has(id));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Merges live catalog metadata into the current list without a refetch.
|
|
292
|
+
*/
|
|
293
|
+
setModels(models) {
|
|
294
|
+
if (Array.isArray(models) && models.length > 0) this.#models = models;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Every free candidate, regardless of probed availability. */
|
|
298
|
+
getCandidates() {
|
|
299
|
+
return this.#models.map((model) => this.#withContext(model));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Models safe to advertise in the picker.
|
|
304
|
+
*
|
|
305
|
+
* Before the first completed probe, only the statically verified candidates
|
|
306
|
+
* may be shown. New catalog entries must earn their way into the picker with
|
|
307
|
+
* a successful probe. An empty confirmed set stays empty: falling back to all
|
|
308
|
+
* candidates here would re-publish models explicitly hidden as unavailable.
|
|
309
|
+
*
|
|
310
|
+
* 勾選(manual 模式)是在「探測判定可用」之上再加一層使用者意願:
|
|
311
|
+
* 兩者都通過才發佈。勾選不取代探測——探測判定不可用的模型就算勾了也
|
|
312
|
+
* 不會出現,否則使用者會把明知不通的模型留在選擇器頂端。
|
|
313
|
+
*/
|
|
314
|
+
getModels() {
|
|
315
|
+
const byId = new Map(this.#models.map((m) => [m.id, m]));
|
|
316
|
+
let ids = this.#available
|
|
317
|
+
? this.#available
|
|
318
|
+
: new Set(STATIC_FREE_MODELS.filter((m) => byId.has(m.id)).map((m) => m.id));
|
|
319
|
+
const picker = this.#pickerStore?.get?.();
|
|
320
|
+
if (picker?.mode === 'manual') {
|
|
321
|
+
const shown = new Set(picker.shown);
|
|
322
|
+
ids = [...ids].filter((id) => shown.has(id));
|
|
323
|
+
}
|
|
324
|
+
const out = [];
|
|
325
|
+
for (const id of ids) {
|
|
326
|
+
const model = byId.get(id);
|
|
327
|
+
if (model) out.push(this.#withContext(model));
|
|
328
|
+
}
|
|
329
|
+
return out;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* 這個模型「現在」會不會出現在選擇器。
|
|
334
|
+
*
|
|
335
|
+
* getProbeResults() 的每一列都要帶上這個值,讓表格的勾選框反映事實,
|
|
336
|
+
* 而不是讓前端自己重複推導(推導錯了就會與發佈名單不一致)。
|
|
337
|
+
*/
|
|
338
|
+
willShow(modelId) {
|
|
339
|
+
if (!this.isAvailable(modelId)) return false;
|
|
340
|
+
const picker = this.#pickerStore?.get?.();
|
|
341
|
+
if (picker?.mode === 'manual') return picker.shown.includes(modelId);
|
|
342
|
+
return true;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 勾選功能的現狀,供狀態頁畫模式提示與按鈕。
|
|
347
|
+
* 沒接勾選功能時回傳 null,前端據此直接不畫這一欄也不會報錯。
|
|
348
|
+
*/
|
|
349
|
+
pickerState() {
|
|
350
|
+
if (!this.#pickerStore?.get) return null;
|
|
351
|
+
try {
|
|
352
|
+
const saved = this.#pickerStore.get();
|
|
353
|
+
// auto 模式下的 shown 沒有實質意義(顯示與否由探測決定),
|
|
354
|
+
// 帶出 auto 名單讓前端在第一次勾選的瞬間不會看到勾選狀態跳動。
|
|
355
|
+
const autoIds = this.#available
|
|
356
|
+
? [...this.#available]
|
|
357
|
+
: STATIC_FREE_MODELS.filter((m) => this.#models.some((c) => c.id === m.id)).map((m) => m.id);
|
|
358
|
+
return {
|
|
359
|
+
mode: saved.mode,
|
|
360
|
+
shown: saved.mode === 'manual' ? [...saved.shown] : autoIds
|
|
361
|
+
};
|
|
362
|
+
} catch {
|
|
363
|
+
return null;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* 設定單一模型的勾選意願。
|
|
369
|
+
*
|
|
370
|
+
* 第一次勾選會把 auto 名單整份快照成 shown 並切入手動模式:使用者看到
|
|
371
|
+
* 的勾選狀態不變,只是從今以後新模型不再自動加入。
|
|
372
|
+
*
|
|
373
|
+
* @returns {object|null} 勾選功能的最新狀態;id 不存在時回傳 null。
|
|
374
|
+
*/
|
|
375
|
+
setPickerShown(modelId, shown) {
|
|
376
|
+
if (!this.#pickerStore?.set) return null;
|
|
377
|
+
if (!this.getModel(modelId)) return null;
|
|
378
|
+
const saved = this.#pickerStore.get();
|
|
379
|
+
const base = saved.mode === 'manual'
|
|
380
|
+
? saved.shown
|
|
381
|
+
// auto → manual 的轉換快照:目前會顯示的整份名單。
|
|
382
|
+
: (this.#available
|
|
383
|
+
? [...this.#available]
|
|
384
|
+
: STATIC_FREE_MODELS.filter((m) => this.#models.some((c) => c.id === m.id)).map((m) => m.id));
|
|
385
|
+
const set = new Set(base);
|
|
386
|
+
if (shown) set.add(modelId);
|
|
387
|
+
else set.delete(modelId);
|
|
388
|
+
// 先寫入再讀狀態:pickerState() 讀的是 store 的現值,
|
|
389
|
+
// 若先讀後寫,回傳的會是舊名單。
|
|
390
|
+
this.#pickerStore.set({ mode: 'manual', shown: [...set] });
|
|
391
|
+
return this.pickerState();
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** 恢復自動管理模式:探測判定可用就顯示,新模型照舊自動加入。 */
|
|
395
|
+
resetPicker() {
|
|
396
|
+
if (!this.#pickerStore?.set) return null;
|
|
397
|
+
this.#pickerStore.set({ mode: 'auto', shown: [] });
|
|
398
|
+
return this.pickerState();
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
getModel(id) {
|
|
402
|
+
const model = this.#models.find((m) => m.id === id)
|
|
403
|
+
|| STATIC_FREE_MODELS.find((m) => m.id === id)
|
|
404
|
+
|| null;
|
|
405
|
+
return model ? this.#withContext(model) : null;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
isAvailable(id) {
|
|
409
|
+
if (this.#available) return this.#available.has(id);
|
|
410
|
+
return STATIC_FREE_MODELS.some((model) => model.id === id && this.#models.some((candidate) => candidate.id === id));
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* True when the last complete sweep is recent enough to skip a full probe.
|
|
415
|
+
* Incremental checks refresh per-model diagnostics but cannot postpone it.
|
|
416
|
+
*/
|
|
417
|
+
isProbeFresh(maxAgeMs) {
|
|
418
|
+
if (!this.#available || !this.#lastFullProbe) return false;
|
|
419
|
+
return Date.now() - this.#lastFullProbe < maxAgeMs;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Mark probe state as belonging to another account, without deleting it.
|
|
424
|
+
*
|
|
425
|
+
* 切換帳號或重新登入時原本呼叫 invalidateProbe(),那會把
|
|
426
|
+
* ~/.dsh/opencode-next.models.json 直接刪掉。但開機不再自動探測(見
|
|
427
|
+
* index.js),刪掉之後沒有任何東西會把它補回來——使用者下次打開設定頁
|
|
428
|
+
* 看到的就是「46 個候選、0 筆探測、整張表空白」,而且每次切帳號都重演。
|
|
429
|
+
*
|
|
430
|
+
* 探測結果記的是「這個模型 id 在免費通道上能不能用」,不是「這個帳號的
|
|
431
|
+
* 私有配額」。換帳號後重驗一次是合理的,把歷史紀錄整份丟掉則不是。
|
|
432
|
+
* 所以這裡只讓快取看起來不新鮮(強制下一輪重新驗證),資料留著。
|
|
433
|
+
*/
|
|
434
|
+
markProbeStale() {
|
|
435
|
+
this.#probeGeneration++;
|
|
436
|
+
this.#lastFullProbe = 0;
|
|
437
|
+
// 仍在跑的那一輪是舊帳號的結果,不能讓它寫回快取。
|
|
438
|
+
for (const [generation, state] of this.#probeRuns) {
|
|
439
|
+
if (generation === this.#probeGeneration) continue;
|
|
440
|
+
for (const queued of state.queue.splice(0)) {
|
|
441
|
+
queued.resolve(this.#invalidatedProbeResult());
|
|
442
|
+
}
|
|
443
|
+
if (!state.active && this.#probeRuns.get(generation) === state) {
|
|
444
|
+
this.#probeRuns.delete(generation);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return this.availabilitySummary();
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Invalidate probe state after a credential/account change.
|
|
452
|
+
*
|
|
453
|
+
* The cache must be removed as well as the in-memory state: otherwise a
|
|
454
|
+
* restart could reload the previous account's fresh availability and skip
|
|
455
|
+
* the first probe for the new account. Incrementing the generation also
|
|
456
|
+
* prevents an already-running old-token probe from recreating that cache.
|
|
457
|
+
*
|
|
458
|
+
* 只有在「憑證整個失效、不該再相信任何一列」時才該用這個。換帳號請用
|
|
459
|
+
* markProbeStale(),否則使用者會失去整份探測紀錄。
|
|
460
|
+
*/
|
|
461
|
+
invalidateProbe() {
|
|
462
|
+
this.#probeGeneration++;
|
|
463
|
+
this.#available = null;
|
|
464
|
+
this.#probeResults = [];
|
|
465
|
+
this.#failureStreaks.clear();
|
|
466
|
+
this.#lastProbe = 0;
|
|
467
|
+
this.#lastFullProbe = 0;
|
|
468
|
+
this.#lastTruncation = null;
|
|
469
|
+
this.#knownIds = new Set();
|
|
470
|
+
for (const [generation, state] of this.#probeRuns) {
|
|
471
|
+
if (generation === this.#probeGeneration) continue;
|
|
472
|
+
for (const queued of state.queue.splice(0)) {
|
|
473
|
+
queued.resolve(this.#invalidatedProbeResult());
|
|
474
|
+
}
|
|
475
|
+
if (!state.active && this.#probeRuns.get(generation) === state) {
|
|
476
|
+
this.#probeRuns.delete(generation);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
fs.unlinkSync(this.#cachePath);
|
|
481
|
+
} catch (err) {
|
|
482
|
+
if (err?.code !== 'ENOENT') {
|
|
483
|
+
console.warn('[opencode-next] Could not clear availability cache:', err.message);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
availabilitySummary() {
|
|
489
|
+
const candidates = this.#models.length;
|
|
490
|
+
const available = this.getModels().length;
|
|
491
|
+
return {
|
|
492
|
+
candidates,
|
|
493
|
+
available,
|
|
494
|
+
probedAt: this.#lastProbe || null,
|
|
495
|
+
// 上一輪是否提早熔斷、驗了幾個。null 代表最近一輪跑完或還沒跑過。
|
|
496
|
+
truncation: this.#lastTruncation ? { ...this.#lastTruncation } : null
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* 每個候選模型的最近一次探測結果,供狀態頁逐列顯示。
|
|
502
|
+
*
|
|
503
|
+
* 回傳的是一份拷貝:呼叫端(HTTP handler)不該有機會改到內部狀態。
|
|
504
|
+
* 尚未探測過的模型也會列出來並標成 `probed: false`,否則狀態頁在第一次
|
|
505
|
+
* 探測完成前會是一片空白,看起來像壞掉。
|
|
506
|
+
*/
|
|
507
|
+
getProbeResults() {
|
|
508
|
+
const byId = new Map(this.#probeResults.map((r) => [r.id, r]));
|
|
509
|
+
return this.#models.map((m) => {
|
|
510
|
+
const r = byId.get(m.id);
|
|
511
|
+
const effective = this.#withContext(m);
|
|
512
|
+
return {
|
|
513
|
+
id: m.id,
|
|
514
|
+
name: m.name,
|
|
515
|
+
contextWindow: effective.contextWindow,
|
|
516
|
+
catalogContextWindow: effective.catalogContextWindow,
|
|
517
|
+
contextOverride: effective.contextOverride,
|
|
518
|
+
contextSource: effective.contextSource,
|
|
519
|
+
// 上游目錄給的單次輸出上限(`limit.output`)。131 個免費模型全都有這個
|
|
520
|
+
// 欄位,但它原本只活在 describe() 裡,設定頁完全看不到——使用者問
|
|
521
|
+
// 「最大值是多少」時只能猜。這裡把它一起送出去。
|
|
522
|
+
maxOutputTokens: Number.isFinite(m.defaultMaxTokens) ? m.defaultMaxTokens : null,
|
|
523
|
+
probed: r !== undefined,
|
|
524
|
+
ok: r?.ok ?? false,
|
|
525
|
+
// 上游是否認得這個模型。
|
|
526
|
+
//
|
|
527
|
+
// `ok` 問的是「這次問到了嗎」,`valid` 問的是「這個模型存不存在、
|
|
528
|
+
// 有沒有被下架」。429(限流/額度用完)不給問,但上游已經指名回應
|
|
529
|
+
// 了這個 model id——模型有效,只是此刻排不進去。使用者要的分類就是
|
|
530
|
+
// 這個語意:可用=上游有效,不是能不能用。
|
|
531
|
+
valid: r === undefined ? false : Boolean(r.ok || r.status === 429),
|
|
532
|
+
status: r?.status ?? null,
|
|
533
|
+
ms: Number.isFinite(r?.ms) ? r.ms : null,
|
|
534
|
+
probedAt: Number.isFinite(r?.probedAt) ? r.probedAt : null,
|
|
535
|
+
reason: r?.reason ?? null,
|
|
536
|
+
errorType: r?.errorType ?? null,
|
|
537
|
+
// 上游原文,只給失敗的列用(成功時 probe 不讀 body,本來就沒有)。
|
|
538
|
+
detail: r?.detail ?? null,
|
|
539
|
+
available: this.isAvailable(m.id),
|
|
540
|
+
// 這一列現在會不會出現在選擇器(含使用者勾選的過濾)。
|
|
541
|
+
shown: this.willShow(m.id),
|
|
542
|
+
failureStreak: this.#failureStreaks.get(m.id) ?? 0
|
|
543
|
+
};
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Runs live availability probes; same-mode calls coalesce, while full and
|
|
549
|
+
* incremental sweeps are serialized within a generation.
|
|
550
|
+
*
|
|
551
|
+
* With `options.incremental`, only candidates that have never been probed
|
|
552
|
+
* are tested. New candidates enter the picker only on success; known models
|
|
553
|
+
* use a two-failure hysteresis, with 404/410 retirement applied immediately.
|
|
554
|
+
* A blocked or incomplete sweep is not a per-model verdict and changes no
|
|
555
|
+
* availability, failure streak, or diagnostic history.
|
|
556
|
+
*
|
|
557
|
+
* `probeFn(token, ids, options)` is injected so this class stays testable.
|
|
558
|
+
*/
|
|
559
|
+
async refreshAvailability(token, probeFn, options = {}) {
|
|
560
|
+
if (!token) throw new Error('A token is required to probe model availability.');
|
|
561
|
+
const generation = this.#probeGeneration;
|
|
562
|
+
const isScoped = Array.isArray(options.modelIds) && options.modelIds.length > 0;
|
|
563
|
+
const mode = isScoped ? `scoped:${[...options.modelIds].sort().join(',')}` : (options.incremental ? 'incremental' : 'full');
|
|
564
|
+
let state = this.#probeRuns.get(generation);
|
|
565
|
+
if (!state) {
|
|
566
|
+
state = { generation, active: null, queue: [] };
|
|
567
|
+
this.#probeRuns.set(generation, state);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
if (state.active?.mode === mode) return state.active.promise;
|
|
571
|
+
const queued = state.queue.find((entry) => entry.mode === mode);
|
|
572
|
+
if (queued) return queued.promise;
|
|
573
|
+
|
|
574
|
+
let resolve;
|
|
575
|
+
let reject;
|
|
576
|
+
const promise = new Promise((resolvePromise, rejectPromise) => {
|
|
577
|
+
resolve = resolvePromise;
|
|
578
|
+
reject = rejectPromise;
|
|
579
|
+
});
|
|
580
|
+
const entry = { generation, mode, token, probeFn, options, promise, resolve, reject };
|
|
581
|
+
if (state.active) state.queue.push(entry);
|
|
582
|
+
else this.#startProbeRun(state, entry);
|
|
583
|
+
return promise;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
#startProbeRun(state, entry) {
|
|
587
|
+
state.active = entry;
|
|
588
|
+
this.#executeAvailabilityProbe(entry.token, entry.probeFn, entry.options, entry.generation).then(
|
|
589
|
+
(result) => {
|
|
590
|
+
this.#finishProbeRun(state, entry);
|
|
591
|
+
entry.resolve(result);
|
|
592
|
+
},
|
|
593
|
+
(error) => {
|
|
594
|
+
this.#finishProbeRun(state, entry);
|
|
595
|
+
entry.reject(error);
|
|
596
|
+
}
|
|
597
|
+
);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
#finishProbeRun(state, entry) {
|
|
601
|
+
if (state.active !== entry) return;
|
|
602
|
+
state.active = null;
|
|
603
|
+
while (state.queue.length > 0) {
|
|
604
|
+
const next = state.queue.shift();
|
|
605
|
+
if (next.generation !== this.#probeGeneration) {
|
|
606
|
+
next.resolve(this.#invalidatedProbeResult());
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
this.#startProbeRun(state, next);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (this.#probeRuns.get(state.generation) === state) this.#probeRuns.delete(state.generation);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
#invalidatedProbeResult() {
|
|
616
|
+
return {
|
|
617
|
+
results: [],
|
|
618
|
+
blocked: false,
|
|
619
|
+
applied: false,
|
|
620
|
+
available: this.#available ? [...this.#available] : this.getModels().map((model) => model.id),
|
|
621
|
+
note: 'invalidated'
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
async #executeAvailabilityProbe(token, probeFn, options, probeGeneration) {
|
|
626
|
+
await this.init();
|
|
627
|
+
|
|
628
|
+
const incremental = Boolean(options.incremental);
|
|
629
|
+
const allIds = this.#models.map((m) => m.id);
|
|
630
|
+
const scoped = Array.isArray(options.modelIds) && options.modelIds.length > 0;
|
|
631
|
+
const ids = scoped
|
|
632
|
+
? allIds.filter((id) => options.modelIds.includes(id))
|
|
633
|
+
: (incremental ? this.unseenCandidates() : allIds);
|
|
634
|
+
const currentAvailable = () => this.#available
|
|
635
|
+
? [...this.#available]
|
|
636
|
+
: this.getModels().map((model) => model.id);
|
|
637
|
+
|
|
638
|
+
if (probeGeneration !== this.#probeGeneration) {
|
|
639
|
+
return { results: [], blocked: false, applied: false, available: currentAvailable(), note: 'invalidated' };
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
if (ids.length === 0) {
|
|
643
|
+
return {
|
|
644
|
+
results: [],
|
|
645
|
+
blocked: false,
|
|
646
|
+
blockedReason: null,
|
|
647
|
+
tested: 0,
|
|
648
|
+
total: 0,
|
|
649
|
+
applied: false,
|
|
650
|
+
available: currentAvailable(),
|
|
651
|
+
note: 'nothing-new-to-probe'
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const outcome = await probeFn(token, ids, options);
|
|
656
|
+
|
|
657
|
+
// A credential/account change while probing invalidates the old token's
|
|
658
|
+
// result and removes its persisted cache. Do not let this in-flight run
|
|
659
|
+
// write the previous account's state back to disk.
|
|
660
|
+
if (probeGeneration !== this.#probeGeneration) {
|
|
661
|
+
return {
|
|
662
|
+
...(outcome ?? { results: [], blocked: false }),
|
|
663
|
+
applied: false,
|
|
664
|
+
available: currentAvailable(),
|
|
665
|
+
note: 'invalidated'
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
const preliminaryResults = Array.isArray(outcome?.results) ? outcome.results : [];
|
|
670
|
+
const blockedReason = outcome?.blockedReason
|
|
671
|
+
?? preliminaryResults.find((result) => CHANNEL_BLOCKED_REASONS.has(result?.reason))?.reason
|
|
672
|
+
?? null;
|
|
673
|
+
// A blocked lane yields no trustworthy per-model verdicts. Even full
|
|
674
|
+
// arrays of 402 quota results cannot be committed as individual failures.
|
|
675
|
+
if (!outcome || outcome.blocked || blockedReason) {
|
|
676
|
+
return {
|
|
677
|
+
...(outcome ?? { results: [], blocked: true }),
|
|
678
|
+
blocked: true,
|
|
679
|
+
blockedReason,
|
|
680
|
+
applied: false,
|
|
681
|
+
available: currentAvailable(),
|
|
682
|
+
note: outcome?.note ?? 'channel-blocked'
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const results = preliminaryResults;
|
|
687
|
+
const requested = new Set(ids);
|
|
688
|
+
const byId = new Map();
|
|
689
|
+
let malformed = outcome.inconclusive === true;
|
|
690
|
+
for (const result of results) {
|
|
691
|
+
if (!result || typeof result.id !== 'string' || !requested.has(result.id)
|
|
692
|
+
|| typeof result.ok !== 'boolean' || byId.has(result.id)) {
|
|
693
|
+
malformed = true;
|
|
694
|
+
break;
|
|
695
|
+
}
|
|
696
|
+
byId.set(result.id, result);
|
|
697
|
+
}
|
|
698
|
+
const hasThrottled = results.some((r) => r.status === 429);
|
|
699
|
+
if (!hasThrottled && (byId.size !== ids.length
|
|
700
|
+
|| (Number.isFinite(outcome.tested) && outcome.tested !== ids.length)
|
|
701
|
+
|| (Number.isFinite(outcome.total) && outcome.total !== ids.length))) {
|
|
702
|
+
malformed = true;
|
|
703
|
+
}
|
|
704
|
+
if (malformed) {
|
|
705
|
+
return {
|
|
706
|
+
...outcome,
|
|
707
|
+
applied: false,
|
|
708
|
+
available: currentAvailable(),
|
|
709
|
+
note: outcome.note ?? 'inconclusive'
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// Before any completed sweep, only the static list is considered
|
|
714
|
+
// pre-verified. This gives existing picker entries hysteresis while new
|
|
715
|
+
// candidates still require an actual successful result.
|
|
716
|
+
if (!this.#available) {
|
|
717
|
+
const candidateIds = new Set(allIds);
|
|
718
|
+
this.#available = new Set(
|
|
719
|
+
STATIC_FREE_MODELS.filter((model) => candidateIds.has(model.id)).map((model) => model.id)
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
const wasAvailable = new Set(this.#available);
|
|
723
|
+
const probedAt = Date.now();
|
|
724
|
+
|
|
725
|
+
for (const id of ids) {
|
|
726
|
+
const result = byId.get(id);
|
|
727
|
+
if (!result) continue; // 熔斷提前中斷時,未 probe 的模型保留原本可用性狀態
|
|
728
|
+
this.#knownIds.add(id);
|
|
729
|
+
if (result.ok) {
|
|
730
|
+
this.#available.add(id);
|
|
731
|
+
this.#failureStreaks.delete(id);
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// 429 代表「上游認得這個模型,只是這次不給問」。
|
|
736
|
+
//
|
|
737
|
+
// 這是使用者明確要求的語意:可用=上游有效,不是當下問得到。限流、
|
|
738
|
+
// 速率超標、免費池暫時用完,上游都已經回應了這個 model id——模型存在、
|
|
739
|
+
// 沒被下架,只是此刻被擋。把它當成失敗踢出清單,等於因為別人擠滿櫃台
|
|
740
|
+
// 就宣稱這家店倒了。
|
|
741
|
+
//
|
|
742
|
+
// 所以:加入可用清單、清掉失敗計數。狀態欄仍會顯示「被限流(429)」,
|
|
743
|
+
// 使用者看得到它現在問不到,但它依然在選擇器裡、依然算有效。
|
|
744
|
+
if (result.status === 429) {
|
|
745
|
+
this.#available.add(id);
|
|
746
|
+
this.#failureStreaks.delete(id);
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// Only explicit retirement responses are authoritative. In particular,
|
|
751
|
+
// `unavailable` from a 400 body is not enough to drop a model at once.
|
|
752
|
+
if (result.status === 410 || result.reason === 'not-found' || result.reason === 'deprecated') {
|
|
753
|
+
this.#available.delete(id);
|
|
754
|
+
this.#failureStreaks.delete(id);
|
|
755
|
+
continue;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
const streak = (this.#failureStreaks.get(id) ?? 0) + 1;
|
|
759
|
+
this.#failureStreaks.set(id, streak);
|
|
760
|
+
if (streak >= 2) this.#available.delete(id);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
// Full sweeps cover every current candidate. Drop availability for ids no
|
|
764
|
+
// longer in the catalog, but keep their diagnostics/history for migration
|
|
765
|
+
// and for a future reappearance of the same candidate.
|
|
766
|
+
if (!incremental && !scoped && !hasThrottled) {
|
|
767
|
+
const currentIds = new Set(allIds);
|
|
768
|
+
for (const id of this.#available) {
|
|
769
|
+
if (!currentIds.has(id)) this.#available.delete(id);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
this.#lastProbe = probedAt;
|
|
774
|
+
if (!incremental && !scoped) this.#lastFullProbe = probedAt;
|
|
775
|
+
const updatedRows = results.map((result) => ({
|
|
776
|
+
id: result.id,
|
|
777
|
+
ok: result.ok,
|
|
778
|
+
status: result.status,
|
|
779
|
+
ms: result.ms,
|
|
780
|
+
reason: result.reason,
|
|
781
|
+
errorType: result.errorType,
|
|
782
|
+
detail: result.detail,
|
|
783
|
+
probedAt
|
|
784
|
+
}));
|
|
785
|
+
const diagnosticRows = new Map(this.#probeResults.map((result) => [result.id, result]));
|
|
786
|
+
for (const row of updatedRows) diagnosticRows.set(row.id, row);
|
|
787
|
+
this.#probeResults = [...diagnosticRows.values()];
|
|
788
|
+
|
|
789
|
+
const available = [...this.#available];
|
|
790
|
+
const added = available.filter((id) => !wasAvailable.has(id));
|
|
791
|
+
// 這一輪是不是被熔斷。要一起寫進快取,否則重啟後「只驗了 4 個」
|
|
792
|
+
// 這件事會消失,畫面又變成「46 個都驗過、13 個可用」的假象。
|
|
793
|
+
const truncated = outcome.stopped === 'rate-limited' || outcome.stopped === 'unreachable'
|
|
794
|
+
? {
|
|
795
|
+
stopped: outcome.stopped,
|
|
796
|
+
at: probedAt,
|
|
797
|
+
tested: outcome.tested ?? updatedRows.length,
|
|
798
|
+
total: ids.length,
|
|
799
|
+
stoppedBy: outcome.stoppedBy ?? null,
|
|
800
|
+
// 上游 429 附帶的解除時間。額度用完時這是唯一能講出「還要等多久」
|
|
801
|
+
// 的資訊;null 代表上游沒給,不要自己猜。
|
|
802
|
+
retryAt: Number.isFinite(outcome.retryAt) ? outcome.retryAt : null
|
|
803
|
+
}
|
|
804
|
+
: null;
|
|
805
|
+
this.#lastTruncation = truncated;
|
|
806
|
+
writeProbeCache(this.#cachePath, {
|
|
807
|
+
version: 2,
|
|
808
|
+
probedAt: this.#lastProbe,
|
|
809
|
+
fullProbedAt: this.#lastFullProbe,
|
|
810
|
+
available,
|
|
811
|
+
knownIds: [...this.#knownIds],
|
|
812
|
+
failureStreaks: Object.fromEntries(this.#failureStreaks),
|
|
813
|
+
...(truncated ? { truncation: truncated } : {}),
|
|
814
|
+
// Keep failure reason and upstream detail so a hidden model remains
|
|
815
|
+
// diagnosable after a restart. v1 caches without row timestamps migrate
|
|
816
|
+
// using the sweep-level `probedAt` above.
|
|
817
|
+
results: this.#probeResults.map(({ id, ok, status, ms, reason, errorType, detail, probedAt: rowTime }) => ({
|
|
818
|
+
id,
|
|
819
|
+
ok,
|
|
820
|
+
status,
|
|
821
|
+
ms,
|
|
822
|
+
probedAt: rowTime,
|
|
823
|
+
...(reason === undefined ? {} : { reason }),
|
|
824
|
+
...(errorType === undefined ? {} : { errorType }),
|
|
825
|
+
...(detail === undefined || detail === '' ? {} : { detail })
|
|
826
|
+
}))
|
|
827
|
+
});
|
|
828
|
+
|
|
829
|
+
return { ...outcome, applied: true, available, added };
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* Describes a model in DeepSeek Harness LlmAdapter format.
|
|
834
|
+
*/
|
|
835
|
+
describe(provider, modelId) {
|
|
836
|
+
const model = this.getModel(modelId) || {
|
|
837
|
+
id: modelId,
|
|
838
|
+
name: modelId,
|
|
839
|
+
contextWindow: 128000,
|
|
840
|
+
defaultMaxTokens: 8192,
|
|
841
|
+
inputModalities: ['text'],
|
|
842
|
+
efforts: [],
|
|
843
|
+
defaultEffort: undefined
|
|
844
|
+
};
|
|
845
|
+
|
|
846
|
+
return {
|
|
847
|
+
provider,
|
|
848
|
+
id: model.id,
|
|
849
|
+
name: model.name,
|
|
850
|
+
inputModalities: model.inputModalities,
|
|
851
|
+
context: { contextWindow: model.contextWindow },
|
|
852
|
+
defaultMaxTokens: model.defaultMaxTokens,
|
|
853
|
+
...(model.efforts?.length
|
|
854
|
+
? {
|
|
855
|
+
reasoning: {
|
|
856
|
+
efforts: model.efforts.map((level) => ({
|
|
857
|
+
id: level,
|
|
858
|
+
name: level.charAt(0).toUpperCase() + level.slice(1)
|
|
859
|
+
})),
|
|
860
|
+
...(model.defaultEffort ? { defaultEffort: model.defaultEffort } : {})
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
: {})
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
describeAll(provider) {
|
|
868
|
+
return this.getModels().map((m) => this.describe(provider, m.id));
|
|
869
|
+
}
|
|
870
|
+
}
|