mslxdff 0.1.236 → 0.1.238
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/bin/mslxdff.js +3 -3
- package/package.json +1 -1
- package/src/auto.js +264 -264
- package/src/autostart.js +62 -15
- package/src/bench/cline-bench.js +42 -42
- package/src/bench/probe.js +70 -70
- package/src/bench/report.js +162 -162
- package/src/bench/runner.js +77 -77
- package/src/bench/via-probe.js +124 -124
- package/src/bench/via-routes.js +87 -87
- package/src/bench/workbuddy-bench.js +54 -54
- package/src/chat/engine.js +160 -160
- package/src/chat/gateway.js +163 -163
- package/src/chat/orchestrator.js +234 -234
- package/src/chat/prompt.js +70 -70
- package/src/chat/repl.js +88 -88
- package/src/chat/terminal.js +135 -135
- package/src/chat/tools.js +306 -306
- package/src/chat-pipeline/index.js +155 -155
- package/src/chat-pipeline/policy.js +84 -84
- package/src/cli/commands/group.js +266 -266
- package/src/cli/commands/model/picks.js +50 -50
- package/src/cli/commands/provider/bench-via.js +247 -247
- package/src/cli/commands/provider/bench.js +141 -141
- package/src/cli/commands/provider/index.js +139 -139
- package/src/cli/commands/provider/keys-guard.js +20 -0
- package/src/cli/commands/provider/models.js +149 -149
- package/src/cli/commands/provider/qwenwork-login.js +119 -119
- package/src/cli/commands/provider/raccoon-quota.js +156 -156
- package/src/cli/commands/sync.js +310 -310
- package/src/cli/status.js +282 -282
- package/src/daemon.js +246 -246
- package/src/model-capabilities/enrich.js +86 -86
- package/src/model-capabilities/index.js +183 -183
- package/src/model-capabilities/parse.js +70 -70
- package/src/models.js +293 -293
- package/src/peers.js +389 -389
- package/src/providers/agentrouter.js +238 -238
- package/src/providers/base.js +164 -164
- package/src/providers/cline/auth.js +228 -228
- package/src/providers/cline/chat.js +307 -307
- package/src/providers/cline.js +2 -2
- package/src/providers/codearts/chat.js +207 -207
- package/src/providers/codearts/const.js +12 -5
- package/src/providers/codearts/models.js +23 -5
- package/src/providers/dispatcher.js +147 -147
- package/src/providers/globalqwenwork/cosy.js +123 -123
- package/src/providers/globalqwenwork/crypto.js +218 -218
- package/src/providers/globalqwenwork/http.js +20 -20
- package/src/providers/globalqwenwork/rsa.js +54 -54
- package/src/providers/globalqwenwork/sse.js +268 -268
- package/src/providers/globalqwenwork/stream.js +130 -130
- package/src/providers/globalqwenwork/upstream.js +122 -122
- package/src/providers/keyring.js +60 -60
- package/src/providers/qoder/chat.js +292 -292
- package/src/providers/qoder/index.js +311 -311
- package/src/providers/qoder/sse.js +233 -233
- package/src/providers/qwenwork/account-store.js +133 -133
- package/src/providers/qwenwork/constants.js +67 -67
- package/src/providers/qwenwork/cosy.js +120 -120
- package/src/providers/qwenwork/crypto.js +218 -218
- package/src/providers/qwenwork/http.js +20 -20
- package/src/providers/qwenwork/index.js +337 -337
- package/src/providers/qwenwork/payload.js +144 -144
- package/src/providers/qwenwork/rsa.js +54 -54
- package/src/providers/qwenwork/sse.js +268 -268
- package/src/providers/qwenwork/stream.js +130 -130
- package/src/providers/qwenwork/upstream.js +120 -120
- package/src/providers/qwenwork.js +1 -1
- package/src/providers/raccoon/const.js +219 -219
- package/src/providers/raccoon/credits.js +285 -285
- package/src/providers/registry.js +89 -89
- package/src/providers/workbuddy/chat.js +298 -298
- package/src/providers/workbuddy/reshape.js +152 -152
- package/src/providers/workbuddy.js +2 -2
- package/src/reasoning.js +32 -32
- package/src/routes/chat/broadband-handler.js +80 -80
- package/src/routes/chat/gateway.js +46 -46
- package/src/routes/chat/relay-pipeline.js +282 -282
- package/src/routes/chat/via-route-handler.js +158 -158
- package/src/routes/hedge.js +260 -260
- package/src/routes/models-route.js +167 -167
- package/src/routes/peers.js +373 -373
- package/src/routes/stream.js +364 -364
- package/src/runtime/bootstrap.js +75 -75
- package/src/runtime/keep-warm.js +135 -135
- package/src/runtime/provider-gate.js +75 -75
- package/src/runtime/providers-setup.js +187 -187
- package/src/runtime/raccoon-checkin.js +175 -175
- package/src/runtime/server-lifecycle.js +34 -10
- package/src/server.js +85 -85
- package/src/state/schemas/allowlist.js +92 -92
- package/src/sync-opencode.js +280 -280
- package/src/transport/index.js +244 -244
- package/src/transport/pool.js +56 -56
- package/src/transport/retry.js +24 -24
- package/src/transport/sse.js +93 -93
- package/src/upstream-probe/display.js +52 -52
- package/src/upstream-probe/probe.js +49 -49
- package/src/upstream-probe/rotate.js +110 -110
- package/src/upstream-probe/start.js +45 -45
- package/src/upstream.js +355 -355
- package/docs/cli_help_mini.md +0 -149
- package/src/providers/AGENTS.md +0 -49
- package/src/routes/AGENTS.md +0 -37
package/src/models.js
CHANGED
|
@@ -1,294 +1,294 @@
|
|
|
1
|
-
const KNOWN_FREE_OPENCODE_MODELS = ["big-pickle"];
|
|
2
|
-
const CACHE_TTL_MS = 2 * 60 * 60 * 1000;
|
|
3
|
-
const DEFAULT_REFRESH_MS = 2 * 60 * 60 * 1000;
|
|
4
|
-
import { mkdirSync, writeFileSync, readFileSync } from "node:fs";
|
|
5
|
-
import { dirname } from "node:path";
|
|
6
|
-
import { compatFetch } from "./compat.js";
|
|
7
|
-
|
|
8
|
-
export function isFreeModel(id) {
|
|
9
|
-
return (typeof id === "string" && id.endsWith("-free")) ||
|
|
10
|
-
KNOWN_FREE_OPENCODE_MODELS.includes(id);
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export function filterFreeModels(list) {
|
|
14
|
-
const seen = new Set();
|
|
15
|
-
const out = [];
|
|
16
|
-
for (const m of list || []) {
|
|
17
|
-
if (!(m && m.id)) continue;
|
|
18
|
-
if (!isFreeModel(m.id)) continue;
|
|
19
|
-
if (seen.has(m.id)) continue;
|
|
20
|
-
seen.add(m.id);
|
|
21
|
-
out.push(m);
|
|
22
|
-
}
|
|
23
|
-
return out;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export function createModelsService({ baseUrl, headers, ttlMs = CACHE_TTL_MS, refreshMs = DEFAULT_REFRESH_MS, cacheFile, providers } = {}) {
|
|
27
|
-
// 多供应商聚合模式:给 `providers` 数组,则缓存并返回所有供应商的模型列表
|
|
28
|
-
if (providers?.length) {
|
|
29
|
-
let aggregate = null;
|
|
30
|
-
let aggFetchedAt = 0;
|
|
31
|
-
let aggInflight = null;
|
|
32
|
-
let aggTimer = null;
|
|
33
|
-
let lastAllowlistKey = "";
|
|
34
|
-
// 冷启动预热:读上一次 persist 的磁盘目录当首值(真机取证:全目录拉取烧 20-26s,
|
|
35
|
-
// 首个 candidatesFor 冷等全程)。aggFetchedAt 用磁盘记录的真实时间;get 对
|
|
36
|
-
// 「有旧值」的情形一律 stale-while-revalidate(立即返回 + 后台刷),主请求零等待。
|
|
37
|
-
if (cacheFile) {
|
|
38
|
-
try {
|
|
39
|
-
const raw = JSON.parse(readFileSync(cacheFile, "utf8"));
|
|
40
|
-
if (Array.isArray(raw?.data)) {
|
|
41
|
-
aggregate = { object: "list", data: raw.data };
|
|
42
|
-
aggFetchedAt = Number(raw.cachedAt) || 0;
|
|
43
|
-
}
|
|
44
|
-
} catch { /* 无缓存/坏档:按冷处理 */ }
|
|
45
|
-
}
|
|
46
|
-
async function currentAllowlistKey() {
|
|
47
|
-
try {
|
|
48
|
-
const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
|
|
49
|
-
return providers.map((p) => {
|
|
50
|
-
const allowAny = loadProviderAllowAnyModels(p.id) ? "any" : "block";
|
|
51
|
-
return `${p.id}:${allowAny}:${loadProviderAllowedModels(p.id).join(",")}`;
|
|
52
|
-
}).join("|");
|
|
53
|
-
} catch {
|
|
54
|
-
return "";
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
async function aggLoad() {
|
|
58
|
-
const all = [];
|
|
59
|
-
// 单供应商拉取失败时沿用旧缓存里它的段(取证教训:此前失败=整段消失,
|
|
60
|
-
// 且 2h TTL 内无人再拉(startAutoRefresh 曾是空函数),目录会长期缺一大块)。
|
|
61
|
-
const prevByProvider = new Map();
|
|
62
|
-
for (const m of aggregate?.data || []) {
|
|
63
|
-
const pid = typeof m?.id === "string" ? m.id.split("/")[0] : "";
|
|
64
|
-
if (!pid) continue;
|
|
65
|
-
if (!prevByProvider.has(pid)) prevByProvider.set(pid, []);
|
|
66
|
-
prevByProvider.get(pid).push(m);
|
|
67
|
-
}
|
|
68
|
-
for (const p of providers) {
|
|
69
|
-
try {
|
|
70
|
-
let list = (await p.listModels?.()) ?? [];
|
|
71
|
-
// 白名单过滤:空名单且 allowAny=false → 该供应商不暴露任何模型(安全默认全拦,auto 直接跳过该供应商)
|
|
72
|
-
try {
|
|
73
|
-
const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
|
|
74
|
-
const allowed = loadProviderAllowedModels(p.id);
|
|
75
|
-
const allowAny = loadProviderAllowAnyModels(p.id);
|
|
76
|
-
if (!allowed.length && !allowAny) {
|
|
77
|
-
// 该供应商被全拦,auto 直接跳过整个供应商
|
|
78
|
-
continue;
|
|
79
|
-
}
|
|
80
|
-
if (allowed.length) {
|
|
81
|
-
const allowedSet = new Set(allowed);
|
|
82
|
-
const { splitModelId } = await import("./providers/model-id.js");
|
|
83
|
-
list = list.filter((m) => {
|
|
84
|
-
if (!m || !m.id) return false;
|
|
85
|
-
const { raw } = splitModelId(m.id, providers.map((x) => x.id));
|
|
86
|
-
return allowedSet.has(String(raw || "").trim());
|
|
87
|
-
});
|
|
88
|
-
}
|
|
89
|
-
} catch {}
|
|
90
|
-
all.push(...list);
|
|
91
|
-
} catch {
|
|
92
|
-
// 单供应商取数失败不拖垮整体:有旧数据则保留旧数据
|
|
93
|
-
const prev = prevByProvider.get(p.id);
|
|
94
|
-
if (prev?.length) all.push(...prev);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
aggregate = { object: "list", data: all };
|
|
98
|
-
try {
|
|
99
|
-
lastAllowlistKey = await currentAllowlistKey();
|
|
100
|
-
} catch {}
|
|
101
|
-
if (cacheFile) persistModels(aggregate, cacheFile);
|
|
102
|
-
return aggregate;
|
|
103
|
-
}
|
|
104
|
-
// 对当前 aggregate(含磁盘 stale 值)做白名单二次过滤后返回;过滤失败回原值。
|
|
105
|
-
async function aggSnapshot() {
|
|
106
|
-
try {
|
|
107
|
-
const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
|
|
108
|
-
const { splitModelId } = await import("./providers/model-id.js");
|
|
109
|
-
const filteredData = aggregate.data.filter((m) => {
|
|
110
|
-
if (!m || !m.id) return false;
|
|
111
|
-
const { provider, raw } = splitModelId(m.id, providers.map((x) => x.id));
|
|
112
|
-
const allowed = loadProviderAllowedModels(provider);
|
|
113
|
-
const allowAny = loadProviderAllowAnyModels(provider);
|
|
114
|
-
if (!allowed.length && !allowAny) return false;
|
|
115
|
-
if (!allowed.length) return true;
|
|
116
|
-
return allowed.includes(String(raw || "").trim());
|
|
117
|
-
});
|
|
118
|
-
if (filteredData.length !== aggregate.data.length) return { ...aggregate, data: filteredData };
|
|
119
|
-
return aggregate;
|
|
120
|
-
} catch {
|
|
121
|
-
return aggregate;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
function aggRefreshInBackground() {
|
|
125
|
-
void aggLoadShared().then(() => { aggFetchedAt = Date.now(); }).catch(() => {});
|
|
126
|
-
}
|
|
127
|
-
async function get() {
|
|
128
|
-
const now = Date.now();
|
|
129
|
-
const fresh = aggregate && now - aggFetchedAt < ttlMs;
|
|
130
|
-
if (fresh) {
|
|
131
|
-
// 热更新白名单:allowlist 变化时,即使命中 TTL 也要重载(否则 clear 后仍返回旧过滤结果)
|
|
132
|
-
try {
|
|
133
|
-
const curKey = await currentAllowlistKey();
|
|
134
|
-
if (curKey !== lastAllowlistKey) {
|
|
135
|
-
const out = await aggLoadShared();
|
|
136
|
-
aggFetchedAt = Date.now();
|
|
137
|
-
return out;
|
|
138
|
-
}
|
|
139
|
-
} catch {}
|
|
140
|
-
return aggSnapshot();
|
|
141
|
-
}
|
|
142
|
-
// 有旧值(含冷启动磁盘 stale):立即返回 + 后台刷新,主请求零等待。
|
|
143
|
-
// 取证教训:全目录拉取 20-26s,此前冷路径同步阻塞整个首请求。
|
|
144
|
-
if (aggregate) {
|
|
145
|
-
aggRefreshInBackground();
|
|
146
|
-
return aggSnapshot();
|
|
147
|
-
}
|
|
148
|
-
// 完全无值(首次冷跑):只能等这一趟。
|
|
149
|
-
const out = await aggLoadShared();
|
|
150
|
-
aggFetchedAt = Date.now();
|
|
151
|
-
return out;
|
|
152
|
-
}
|
|
153
|
-
// 并发去重:aggLoad 要遍历全部供应商拉目录(真机实测 20-26s),
|
|
154
|
-
// 无去重时赛马/后台任务并发触发就各烧各的(真机日志实证同窗口重复 3 次)。
|
|
155
|
-
function aggLoadShared() {
|
|
156
|
-
if (aggInflight) return aggInflight;
|
|
157
|
-
aggInflight = (async () => {
|
|
158
|
-
try {
|
|
159
|
-
return await aggLoad();
|
|
160
|
-
} catch (e) {
|
|
161
|
-
// 失败保旧:有旧聚合就回退旧值,绝不让半次刷新把目录清空
|
|
162
|
-
if (aggregate) return aggregate;
|
|
163
|
-
throw e;
|
|
164
|
-
} finally {
|
|
165
|
-
aggInflight = null;
|
|
166
|
-
}
|
|
167
|
-
})();
|
|
168
|
-
return aggInflight;
|
|
169
|
-
}
|
|
170
|
-
function aggStartAutoRefresh(intervalMs = refreshMs) {
|
|
171
|
-
if (aggTimer) return aggStopAutoRefresh;
|
|
172
|
-
aggTimer = setInterval(() => {
|
|
173
|
-
void aggLoadShared().then(() => { aggFetchedAt = Date.now(); }).catch(() => {});
|
|
174
|
-
}, intervalMs);
|
|
175
|
-
aggTimer.unref?.();
|
|
176
|
-
return aggStopAutoRefresh;
|
|
177
|
-
}
|
|
178
|
-
function aggStopAutoRefresh() {
|
|
179
|
-
if (aggTimer) { clearInterval(aggTimer); aggTimer = null; }
|
|
180
|
-
}
|
|
181
|
-
return { get, startAutoRefresh: aggStartAutoRefresh, stopAutoRefresh: aggStopAutoRefresh };
|
|
182
|
-
}
|
|
183
|
-
let cache = null;
|
|
184
|
-
let fetchedAt = 0;
|
|
185
|
-
let inflight = null;
|
|
186
|
-
let timer = null;
|
|
187
|
-
|
|
188
|
-
async function load() {
|
|
189
|
-
let data = await fetchUpstreamModels({ baseUrl, headers });
|
|
190
|
-
// 白名单过滤:opencode 亦支持 allowlist
|
|
191
|
-
try {
|
|
192
|
-
const { loadProviderAllowedModels } = await import("./state.js");
|
|
193
|
-
const allowed = loadProviderAllowedModels("opencode");
|
|
194
|
-
if (allowed.length) {
|
|
195
|
-
const allowedSet = new Set(allowed);
|
|
196
|
-
data = { ...data, data: (data.data || []).filter((m) => m && m.id && allowedSet.has(String(m.id).trim())) };
|
|
197
|
-
}
|
|
198
|
-
} catch {}
|
|
199
|
-
cache = data;
|
|
200
|
-
fetchedAt = Date.now();
|
|
201
|
-
if (cacheFile) persistModels(data, cacheFile);
|
|
202
|
-
return data;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
async function get() {
|
|
206
|
-
const now = Date.now();
|
|
207
|
-
if (cache && now - fetchedAt < ttlMs) return cache;
|
|
208
|
-
if (inflight) return inflight;
|
|
209
|
-
|
|
210
|
-
inflight = (async () => {
|
|
211
|
-
try {
|
|
212
|
-
return await load();
|
|
213
|
-
} catch (err) {
|
|
214
|
-
// serve stale on failure if we have it, else rethrow
|
|
215
|
-
if (cache) return cache;
|
|
216
|
-
throw err;
|
|
217
|
-
} finally {
|
|
218
|
-
inflight = null;
|
|
219
|
-
}
|
|
220
|
-
})();
|
|
221
|
-
return inflight;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
function startAutoRefresh(intervalMs = refreshMs) {
|
|
225
|
-
if (timer) return stopAutoRefresh;
|
|
226
|
-
timer = setInterval(() => {
|
|
227
|
-
void load().catch(() => {
|
|
228
|
-
// keep serving stale cache on background refresh failure
|
|
229
|
-
});
|
|
230
|
-
}, intervalMs);
|
|
231
|
-
timer.unref?.();
|
|
232
|
-
return stopAutoRefresh;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
function stopAutoRefresh() {
|
|
236
|
-
if (timer) {
|
|
237
|
-
clearInterval(timer);
|
|
238
|
-
timer = null;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
return { get, startAutoRefresh, stopAutoRefresh };
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
async function fetchUpstreamModels({ baseUrl, headers, connectTimeoutMs = 30_000 }) {
|
|
246
|
-
const url = `${baseUrl}/zen/v1/models`;
|
|
247
|
-
for (let attempt = 0; ; attempt++) {
|
|
248
|
-
const res = await attemptFetch(url, headers, connectTimeoutMs);
|
|
249
|
-
if (res instanceof Error) {
|
|
250
|
-
if (attempt < NETWORK_RETRIES) continue;
|
|
251
|
-
throw res;
|
|
252
|
-
}
|
|
253
|
-
if (isRetryable(res.status) && attempt < STATUS_RETRIES) {
|
|
254
|
-
await sleep(2000);
|
|
255
|
-
continue;
|
|
256
|
-
}
|
|
257
|
-
if (!res.ok) throw new Error(`models fetch failed: HTTP ${res.status}`);
|
|
258
|
-
const json = await res.json().catch(() => ({}));
|
|
259
|
-
const raw = Array.isArray(json) ? json : json.data ?? json.models ?? [];
|
|
260
|
-
return { object: "list", data: filterFreeModels(raw) };
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
async function attemptFetch(url, headers, connectTimeoutMs) {
|
|
265
|
-
const controller = new AbortController();
|
|
266
|
-
const timer = setTimeout(() => controller.abort(), connectTimeoutMs);
|
|
267
|
-
try {
|
|
268
|
-
return await compatFetch(url, { headers, signal: controller.signal });
|
|
269
|
-
} catch (err) {
|
|
270
|
-
return err;
|
|
271
|
-
} finally {
|
|
272
|
-
clearTimeout(timer);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
function isRetryable(status) {
|
|
277
|
-
return status === 429 || status === 502 || status === 503 || status === 504;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
function persistModels(data, cacheFile) {
|
|
281
|
-
try {
|
|
282
|
-
mkdirSync(dirname(cacheFile), { recursive: true });
|
|
283
|
-
writeFileSync(cacheFile, JSON.stringify({ cachedAt: Date.now(), ...data }));
|
|
284
|
-
} catch {
|
|
285
|
-
// persistence is best-effort
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function sleep(ms) {
|
|
290
|
-
return new Promise((r) => setTimeout(r, ms));
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
const NETWORK_RETRIES = 2;
|
|
1
|
+
const KNOWN_FREE_OPENCODE_MODELS = ["big-pickle"];
|
|
2
|
+
const CACHE_TTL_MS = 2 * 60 * 60 * 1000;
|
|
3
|
+
const DEFAULT_REFRESH_MS = 2 * 60 * 60 * 1000;
|
|
4
|
+
import { mkdirSync, writeFileSync, readFileSync } from "node:fs";
|
|
5
|
+
import { dirname } from "node:path";
|
|
6
|
+
import { compatFetch } from "./compat.js";
|
|
7
|
+
|
|
8
|
+
export function isFreeModel(id) {
|
|
9
|
+
return (typeof id === "string" && id.endsWith("-free")) ||
|
|
10
|
+
KNOWN_FREE_OPENCODE_MODELS.includes(id);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function filterFreeModels(list) {
|
|
14
|
+
const seen = new Set();
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const m of list || []) {
|
|
17
|
+
if (!(m && m.id)) continue;
|
|
18
|
+
if (!isFreeModel(m.id)) continue;
|
|
19
|
+
if (seen.has(m.id)) continue;
|
|
20
|
+
seen.add(m.id);
|
|
21
|
+
out.push(m);
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createModelsService({ baseUrl, headers, ttlMs = CACHE_TTL_MS, refreshMs = DEFAULT_REFRESH_MS, cacheFile, providers } = {}) {
|
|
27
|
+
// 多供应商聚合模式:给 `providers` 数组,则缓存并返回所有供应商的模型列表
|
|
28
|
+
if (providers?.length) {
|
|
29
|
+
let aggregate = null;
|
|
30
|
+
let aggFetchedAt = 0;
|
|
31
|
+
let aggInflight = null;
|
|
32
|
+
let aggTimer = null;
|
|
33
|
+
let lastAllowlistKey = "";
|
|
34
|
+
// 冷启动预热:读上一次 persist 的磁盘目录当首值(真机取证:全目录拉取烧 20-26s,
|
|
35
|
+
// 首个 candidatesFor 冷等全程)。aggFetchedAt 用磁盘记录的真实时间;get 对
|
|
36
|
+
// 「有旧值」的情形一律 stale-while-revalidate(立即返回 + 后台刷),主请求零等待。
|
|
37
|
+
if (cacheFile) {
|
|
38
|
+
try {
|
|
39
|
+
const raw = JSON.parse(readFileSync(cacheFile, "utf8"));
|
|
40
|
+
if (Array.isArray(raw?.data)) {
|
|
41
|
+
aggregate = { object: "list", data: raw.data };
|
|
42
|
+
aggFetchedAt = Number(raw.cachedAt) || 0;
|
|
43
|
+
}
|
|
44
|
+
} catch { /* 无缓存/坏档:按冷处理 */ }
|
|
45
|
+
}
|
|
46
|
+
async function currentAllowlistKey() {
|
|
47
|
+
try {
|
|
48
|
+
const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
|
|
49
|
+
return providers.map((p) => {
|
|
50
|
+
const allowAny = loadProviderAllowAnyModels(p.id) ? "any" : "block";
|
|
51
|
+
return `${p.id}:${allowAny}:${loadProviderAllowedModels(p.id).join(",")}`;
|
|
52
|
+
}).join("|");
|
|
53
|
+
} catch {
|
|
54
|
+
return "";
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async function aggLoad() {
|
|
58
|
+
const all = [];
|
|
59
|
+
// 单供应商拉取失败时沿用旧缓存里它的段(取证教训:此前失败=整段消失,
|
|
60
|
+
// 且 2h TTL 内无人再拉(startAutoRefresh 曾是空函数),目录会长期缺一大块)。
|
|
61
|
+
const prevByProvider = new Map();
|
|
62
|
+
for (const m of aggregate?.data || []) {
|
|
63
|
+
const pid = typeof m?.id === "string" ? m.id.split("/")[0] : "";
|
|
64
|
+
if (!pid) continue;
|
|
65
|
+
if (!prevByProvider.has(pid)) prevByProvider.set(pid, []);
|
|
66
|
+
prevByProvider.get(pid).push(m);
|
|
67
|
+
}
|
|
68
|
+
for (const p of providers) {
|
|
69
|
+
try {
|
|
70
|
+
let list = (await p.listModels?.()) ?? [];
|
|
71
|
+
// 白名单过滤:空名单且 allowAny=false → 该供应商不暴露任何模型(安全默认全拦,auto 直接跳过该供应商)
|
|
72
|
+
try {
|
|
73
|
+
const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
|
|
74
|
+
const allowed = loadProviderAllowedModels(p.id);
|
|
75
|
+
const allowAny = loadProviderAllowAnyModels(p.id);
|
|
76
|
+
if (!allowed.length && !allowAny) {
|
|
77
|
+
// 该供应商被全拦,auto 直接跳过整个供应商
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (allowed.length) {
|
|
81
|
+
const allowedSet = new Set(allowed);
|
|
82
|
+
const { splitModelId } = await import("./providers/model-id.js");
|
|
83
|
+
list = list.filter((m) => {
|
|
84
|
+
if (!m || !m.id) return false;
|
|
85
|
+
const { raw } = splitModelId(m.id, providers.map((x) => x.id));
|
|
86
|
+
return allowedSet.has(String(raw || "").trim());
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
} catch {}
|
|
90
|
+
all.push(...list);
|
|
91
|
+
} catch {
|
|
92
|
+
// 单供应商取数失败不拖垮整体:有旧数据则保留旧数据
|
|
93
|
+
const prev = prevByProvider.get(p.id);
|
|
94
|
+
if (prev?.length) all.push(...prev);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
aggregate = { object: "list", data: all };
|
|
98
|
+
try {
|
|
99
|
+
lastAllowlistKey = await currentAllowlistKey();
|
|
100
|
+
} catch {}
|
|
101
|
+
if (cacheFile) persistModels(aggregate, cacheFile);
|
|
102
|
+
return aggregate;
|
|
103
|
+
}
|
|
104
|
+
// 对当前 aggregate(含磁盘 stale 值)做白名单二次过滤后返回;过滤失败回原值。
|
|
105
|
+
async function aggSnapshot() {
|
|
106
|
+
try {
|
|
107
|
+
const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
|
|
108
|
+
const { splitModelId } = await import("./providers/model-id.js");
|
|
109
|
+
const filteredData = aggregate.data.filter((m) => {
|
|
110
|
+
if (!m || !m.id) return false;
|
|
111
|
+
const { provider, raw } = splitModelId(m.id, providers.map((x) => x.id));
|
|
112
|
+
const allowed = loadProviderAllowedModels(provider);
|
|
113
|
+
const allowAny = loadProviderAllowAnyModels(provider);
|
|
114
|
+
if (!allowed.length && !allowAny) return false;
|
|
115
|
+
if (!allowed.length) return true;
|
|
116
|
+
return allowed.includes(String(raw || "").trim());
|
|
117
|
+
});
|
|
118
|
+
if (filteredData.length !== aggregate.data.length) return { ...aggregate, data: filteredData };
|
|
119
|
+
return aggregate;
|
|
120
|
+
} catch {
|
|
121
|
+
return aggregate;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function aggRefreshInBackground() {
|
|
125
|
+
void aggLoadShared().then(() => { aggFetchedAt = Date.now(); }).catch(() => {});
|
|
126
|
+
}
|
|
127
|
+
async function get() {
|
|
128
|
+
const now = Date.now();
|
|
129
|
+
const fresh = aggregate && now - aggFetchedAt < ttlMs;
|
|
130
|
+
if (fresh) {
|
|
131
|
+
// 热更新白名单:allowlist 变化时,即使命中 TTL 也要重载(否则 clear 后仍返回旧过滤结果)
|
|
132
|
+
try {
|
|
133
|
+
const curKey = await currentAllowlistKey();
|
|
134
|
+
if (curKey !== lastAllowlistKey) {
|
|
135
|
+
const out = await aggLoadShared();
|
|
136
|
+
aggFetchedAt = Date.now();
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
} catch {}
|
|
140
|
+
return aggSnapshot();
|
|
141
|
+
}
|
|
142
|
+
// 有旧值(含冷启动磁盘 stale):立即返回 + 后台刷新,主请求零等待。
|
|
143
|
+
// 取证教训:全目录拉取 20-26s,此前冷路径同步阻塞整个首请求。
|
|
144
|
+
if (aggregate) {
|
|
145
|
+
aggRefreshInBackground();
|
|
146
|
+
return aggSnapshot();
|
|
147
|
+
}
|
|
148
|
+
// 完全无值(首次冷跑):只能等这一趟。
|
|
149
|
+
const out = await aggLoadShared();
|
|
150
|
+
aggFetchedAt = Date.now();
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
// 并发去重:aggLoad 要遍历全部供应商拉目录(真机实测 20-26s),
|
|
154
|
+
// 无去重时赛马/后台任务并发触发就各烧各的(真机日志实证同窗口重复 3 次)。
|
|
155
|
+
function aggLoadShared() {
|
|
156
|
+
if (aggInflight) return aggInflight;
|
|
157
|
+
aggInflight = (async () => {
|
|
158
|
+
try {
|
|
159
|
+
return await aggLoad();
|
|
160
|
+
} catch (e) {
|
|
161
|
+
// 失败保旧:有旧聚合就回退旧值,绝不让半次刷新把目录清空
|
|
162
|
+
if (aggregate) return aggregate;
|
|
163
|
+
throw e;
|
|
164
|
+
} finally {
|
|
165
|
+
aggInflight = null;
|
|
166
|
+
}
|
|
167
|
+
})();
|
|
168
|
+
return aggInflight;
|
|
169
|
+
}
|
|
170
|
+
function aggStartAutoRefresh(intervalMs = refreshMs) {
|
|
171
|
+
if (aggTimer) return aggStopAutoRefresh;
|
|
172
|
+
aggTimer = setInterval(() => {
|
|
173
|
+
void aggLoadShared().then(() => { aggFetchedAt = Date.now(); }).catch(() => {});
|
|
174
|
+
}, intervalMs);
|
|
175
|
+
aggTimer.unref?.();
|
|
176
|
+
return aggStopAutoRefresh;
|
|
177
|
+
}
|
|
178
|
+
function aggStopAutoRefresh() {
|
|
179
|
+
if (aggTimer) { clearInterval(aggTimer); aggTimer = null; }
|
|
180
|
+
}
|
|
181
|
+
return { get, startAutoRefresh: aggStartAutoRefresh, stopAutoRefresh: aggStopAutoRefresh };
|
|
182
|
+
}
|
|
183
|
+
let cache = null;
|
|
184
|
+
let fetchedAt = 0;
|
|
185
|
+
let inflight = null;
|
|
186
|
+
let timer = null;
|
|
187
|
+
|
|
188
|
+
async function load() {
|
|
189
|
+
let data = await fetchUpstreamModels({ baseUrl, headers });
|
|
190
|
+
// 白名单过滤:opencode 亦支持 allowlist
|
|
191
|
+
try {
|
|
192
|
+
const { loadProviderAllowedModels } = await import("./state.js");
|
|
193
|
+
const allowed = loadProviderAllowedModels("opencode");
|
|
194
|
+
if (allowed.length) {
|
|
195
|
+
const allowedSet = new Set(allowed);
|
|
196
|
+
data = { ...data, data: (data.data || []).filter((m) => m && m.id && allowedSet.has(String(m.id).trim())) };
|
|
197
|
+
}
|
|
198
|
+
} catch {}
|
|
199
|
+
cache = data;
|
|
200
|
+
fetchedAt = Date.now();
|
|
201
|
+
if (cacheFile) persistModels(data, cacheFile);
|
|
202
|
+
return data;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function get() {
|
|
206
|
+
const now = Date.now();
|
|
207
|
+
if (cache && now - fetchedAt < ttlMs) return cache;
|
|
208
|
+
if (inflight) return inflight;
|
|
209
|
+
|
|
210
|
+
inflight = (async () => {
|
|
211
|
+
try {
|
|
212
|
+
return await load();
|
|
213
|
+
} catch (err) {
|
|
214
|
+
// serve stale on failure if we have it, else rethrow
|
|
215
|
+
if (cache) return cache;
|
|
216
|
+
throw err;
|
|
217
|
+
} finally {
|
|
218
|
+
inflight = null;
|
|
219
|
+
}
|
|
220
|
+
})();
|
|
221
|
+
return inflight;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function startAutoRefresh(intervalMs = refreshMs) {
|
|
225
|
+
if (timer) return stopAutoRefresh;
|
|
226
|
+
timer = setInterval(() => {
|
|
227
|
+
void load().catch(() => {
|
|
228
|
+
// keep serving stale cache on background refresh failure
|
|
229
|
+
});
|
|
230
|
+
}, intervalMs);
|
|
231
|
+
timer.unref?.();
|
|
232
|
+
return stopAutoRefresh;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function stopAutoRefresh() {
|
|
236
|
+
if (timer) {
|
|
237
|
+
clearInterval(timer);
|
|
238
|
+
timer = null;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return { get, startAutoRefresh, stopAutoRefresh };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function fetchUpstreamModels({ baseUrl, headers, connectTimeoutMs = 30_000 }) {
|
|
246
|
+
const url = `${baseUrl}/zen/v1/models`;
|
|
247
|
+
for (let attempt = 0; ; attempt++) {
|
|
248
|
+
const res = await attemptFetch(url, headers, connectTimeoutMs);
|
|
249
|
+
if (res instanceof Error) {
|
|
250
|
+
if (attempt < NETWORK_RETRIES) continue;
|
|
251
|
+
throw res;
|
|
252
|
+
}
|
|
253
|
+
if (isRetryable(res.status) && attempt < STATUS_RETRIES) {
|
|
254
|
+
await sleep(2000);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (!res.ok) throw new Error(`models fetch failed: HTTP ${res.status}`);
|
|
258
|
+
const json = await res.json().catch(() => ({}));
|
|
259
|
+
const raw = Array.isArray(json) ? json : json.data ?? json.models ?? [];
|
|
260
|
+
return { object: "list", data: filterFreeModels(raw) };
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function attemptFetch(url, headers, connectTimeoutMs) {
|
|
265
|
+
const controller = new AbortController();
|
|
266
|
+
const timer = setTimeout(() => controller.abort(), connectTimeoutMs);
|
|
267
|
+
try {
|
|
268
|
+
return await compatFetch(url, { headers, signal: controller.signal });
|
|
269
|
+
} catch (err) {
|
|
270
|
+
return err;
|
|
271
|
+
} finally {
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function isRetryable(status) {
|
|
277
|
+
return status === 429 || status === 502 || status === 503 || status === 504;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function persistModels(data, cacheFile) {
|
|
281
|
+
try {
|
|
282
|
+
mkdirSync(dirname(cacheFile), { recursive: true });
|
|
283
|
+
writeFileSync(cacheFile, JSON.stringify({ cachedAt: Date.now(), ...data }));
|
|
284
|
+
} catch {
|
|
285
|
+
// persistence is best-effort
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function sleep(ms) {
|
|
290
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const NETWORK_RETRIES = 2;
|
|
294
294
|
const STATUS_RETRIES = 2;
|