mslxdff 0.1.231 → 0.1.233

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.
Files changed (117) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/package.json +1 -1
  3. package/src/auto.js +264 -254
  4. package/src/bench/cline-bench.js +42 -42
  5. package/src/bench/probe.js +70 -70
  6. package/src/bench/report.js +162 -162
  7. package/src/bench/runner.js +77 -77
  8. package/src/bench/via-probe.js +124 -124
  9. package/src/bench/via-routes.js +87 -87
  10. package/src/bench/workbuddy-bench.js +54 -54
  11. package/src/chat/engine.js +160 -160
  12. package/src/chat/gateway.js +163 -163
  13. package/src/chat/orchestrator.js +234 -234
  14. package/src/chat/prompt.js +70 -70
  15. package/src/chat/repl.js +88 -88
  16. package/src/chat/terminal.js +135 -135
  17. package/src/chat/tools.js +306 -306
  18. package/src/chat-pipeline/index.js +155 -145
  19. package/src/chat-pipeline/policy.js +84 -84
  20. package/src/cli/commands/group.js +266 -266
  21. package/src/cli/commands/model/picks.js +50 -50
  22. package/src/cli/commands/provider/bench-via.js +247 -247
  23. package/src/cli/commands/provider/bench.js +141 -141
  24. package/src/cli/commands/provider/index.js +139 -139
  25. package/src/cli/commands/provider/models.js +149 -149
  26. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  27. package/src/cli/commands/provider/raccoon-quota.js +156 -156
  28. package/src/cli/commands/sync.js +310 -310
  29. package/src/cli/status.js +279 -279
  30. package/src/daemon.js +246 -246
  31. package/src/model-capabilities/enrich.js +86 -86
  32. package/src/model-capabilities/index.js +183 -183
  33. package/src/model-capabilities/parse.js +70 -70
  34. package/src/model-trace.js +10 -2
  35. package/src/models.js +292 -225
  36. package/src/peers.js +345 -345
  37. package/src/providers/agentrouter.js +238 -238
  38. package/src/providers/base.js +164 -164
  39. package/src/providers/cline/auth.js +228 -228
  40. package/src/providers/cline/chat.js +307 -307
  41. package/src/providers/cline.js +2 -2
  42. package/src/providers/codearts/chat.js +207 -207
  43. package/src/providers/dispatcher.js +147 -147
  44. package/src/providers/globalqwenwork/cosy.js +123 -123
  45. package/src/providers/globalqwenwork/crypto.js +218 -218
  46. package/src/providers/globalqwenwork/http.js +20 -20
  47. package/src/providers/globalqwenwork/rsa.js +54 -54
  48. package/src/providers/globalqwenwork/sse.js +268 -268
  49. package/src/providers/globalqwenwork/stream.js +130 -130
  50. package/src/providers/globalqwenwork/upstream.js +122 -122
  51. package/src/providers/keyring.js +60 -60
  52. package/src/providers/qoder/account-store.js +18 -0
  53. package/src/providers/qoder/chat.js +292 -203
  54. package/src/providers/qoder/checkin.js +25 -12
  55. package/src/providers/qoder/index.js +311 -249
  56. package/src/providers/qoder/models.js +64 -2
  57. package/src/providers/qoder/oauth.js +42 -1
  58. package/src/providers/qoder/payload.js +116 -80
  59. package/src/providers/qoder/request.js +7 -2
  60. package/src/providers/qoder/session.js +26 -10
  61. package/src/providers/qoder/sse.js +233 -145
  62. package/src/providers/qoder/sticky.js +5 -2
  63. package/src/providers/qoder/wire-messages.js +242 -0
  64. package/src/providers/qwenwork/account-store.js +133 -133
  65. package/src/providers/qwenwork/constants.js +67 -67
  66. package/src/providers/qwenwork/cosy.js +120 -120
  67. package/src/providers/qwenwork/crypto.js +218 -218
  68. package/src/providers/qwenwork/http.js +20 -20
  69. package/src/providers/qwenwork/index.js +337 -337
  70. package/src/providers/qwenwork/payload.js +144 -144
  71. package/src/providers/qwenwork/rsa.js +54 -54
  72. package/src/providers/qwenwork/sse.js +268 -268
  73. package/src/providers/qwenwork/stream.js +130 -130
  74. package/src/providers/qwenwork/upstream.js +120 -120
  75. package/src/providers/qwenwork.js +1 -1
  76. package/src/providers/raccoon/chat.js +1 -1
  77. package/src/providers/raccoon/const.js +219 -202
  78. package/src/providers/raccoon/credits.js +285 -285
  79. package/src/providers/raccoon/index.js +15 -2
  80. package/src/providers/raccoon/models.js +68 -17
  81. package/src/providers/registry.js +89 -89
  82. package/src/providers/workbuddy/auth.js +16 -0
  83. package/src/providers/workbuddy/chat.js +298 -264
  84. package/src/providers/workbuddy/client-headers.js +148 -0
  85. package/src/providers/workbuddy/desktop-info.js +17 -1
  86. package/src/providers/workbuddy/models.js +8 -20
  87. package/src/providers/workbuddy/reshape.js +152 -152
  88. package/src/providers/workbuddy.js +2 -2
  89. package/src/reasoning.js +32 -32
  90. package/src/routes/chat/broadband-handler.js +80 -80
  91. package/src/routes/chat/gateway.js +46 -46
  92. package/src/routes/chat/relay-pipeline.js +282 -282
  93. package/src/routes/chat/via-route-handler.js +156 -156
  94. package/src/routes/hedge.js +260 -260
  95. package/src/routes/models-route.js +167 -167
  96. package/src/routes/peers.js +373 -373
  97. package/src/routes/stream.js +364 -347
  98. package/src/runtime/bootstrap.js +75 -75
  99. package/src/runtime/keep-warm.js +135 -135
  100. package/src/runtime/provider-gate.js +75 -75
  101. package/src/runtime/providers-setup.js +187 -187
  102. package/src/runtime/raccoon-checkin.js +175 -175
  103. package/src/server.js +85 -85
  104. package/src/state/schemas/allowlist.js +92 -92
  105. package/src/sync-opencode.js +280 -280
  106. package/src/transport/index.js +244 -244
  107. package/src/transport/pool.js +56 -56
  108. package/src/transport/retry.js +24 -24
  109. package/src/transport/sse.js +93 -93
  110. package/src/upstream-probe/display.js +52 -52
  111. package/src/upstream-probe/probe.js +49 -49
  112. package/src/upstream-probe/rotate.js +110 -110
  113. package/src/upstream-probe/start.js +45 -45
  114. package/src/upstream.js +355 -355
  115. package/docs/cli_help_mini.md +0 -148
  116. package/src/providers/AGENTS.md +0 -49
  117. package/src/routes/AGENTS.md +0 -37
package/src/models.js CHANGED
@@ -1,227 +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 } from "node:fs";
5
- import { dirname } from "node:path";
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
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 lastAllowlistKey = "";
32
- async function currentAllowlistKey() {
33
- try {
34
- const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
35
- return providers.map((p) => {
36
- const allowAny = loadProviderAllowAnyModels(p.id) ? "any" : "block";
37
- return `${p.id}:${allowAny}:${loadProviderAllowedModels(p.id).join(",")}`;
38
- }).join("|");
39
- } catch {
40
- return "";
41
- }
42
- }
43
- async function aggLoad() {
44
- const all = [];
45
- for (const p of providers) {
46
- try {
47
- let list = (await p.listModels?.()) ?? [];
48
- // 白名单过滤:空名单且 allowAny=false → 该供应商不暴露任何模型(安全默认全拦,auto 直接跳过该供应商)
49
- try {
50
- const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
51
- const allowed = loadProviderAllowedModels(p.id);
52
- const allowAny = loadProviderAllowAnyModels(p.id);
53
- if (!allowed.length && !allowAny) {
54
- // 该供应商被全拦,auto 直接跳过整个供应商
55
- continue;
56
- }
57
- if (allowed.length) {
58
- const allowedSet = new Set(allowed);
59
- const { splitModelId } = await import("./providers/model-id.js");
60
- list = list.filter((m) => {
61
- if (!m || !m.id) return false;
62
- const { raw } = splitModelId(m.id, providers.map((x) => x.id));
63
- return allowedSet.has(String(raw || "").trim());
64
- });
65
- }
66
- } catch {}
67
- all.push(...list);
68
- } catch {
69
- // 单供应商取数失败不拖垮整体
70
- }
71
- }
72
- aggregate = { object: "list", data: all };
73
- try {
74
- lastAllowlistKey = await currentAllowlistKey();
75
- } catch {}
76
- if (cacheFile) persistModels(aggregate, cacheFile);
77
- return aggregate;
78
- }
79
- async function get() {
80
- const now = Date.now();
81
- if (aggregate && now - aggFetchedAt < ttlMs) {
82
- // 热更新白名单:allowlist 变化时,即使命中 TTL 也要重载(否则 clear 后仍返回旧过滤结果)
83
- try {
84
- const curKey = await currentAllowlistKey();
85
- if (curKey !== lastAllowlistKey) {
86
- const out = await aggLoad();
87
- aggFetchedAt = Date.now();
88
- return out;
89
- }
90
- } catch {}
91
- // 否则尝试在缓存上二次过滤(处理 allowlist 从空变非空等未触发重载的场景)
92
- try {
93
- const { loadProviderAllowedModels, loadProviderAllowAnyModels } = await import("./state.js");
94
- const { splitModelId } = await import("./providers/model-id.js");
95
- const filteredData = aggregate.data.filter((m) => {
96
- if (!m || !m.id) return false;
97
- const { provider, raw } = splitModelId(m.id, providers.map((x) => x.id));
98
- const allowed = loadProviderAllowedModels(provider);
99
- const allowAny = loadProviderAllowAnyModels(provider);
100
- if (!allowed.length && !allowAny) return false;
101
- if (!allowed.length) return true;
102
- return allowed.includes(String(raw || "").trim());
103
- });
104
- if (filteredData.length !== aggregate.data.length) return { ...aggregate, data: filteredData };
105
- return aggregate;
106
- } catch {
107
- return aggregate;
108
- }
109
- }
110
- const out = await aggLoad();
111
- aggFetchedAt = Date.now();
112
- return out;
113
- }
114
- return { get, startAutoRefresh: () => {}, stopAutoRefresh: () => {} };
115
- }
116
- let cache = null;
117
- let fetchedAt = 0;
118
- let inflight = null;
119
- let timer = null;
120
-
121
- async function load() {
122
- let data = await fetchUpstreamModels({ baseUrl, headers });
123
- // 白名单过滤:opencode 亦支持 allowlist
124
- try {
125
- const { loadProviderAllowedModels } = await import("./state.js");
126
- const allowed = loadProviderAllowedModels("opencode");
127
- if (allowed.length) {
128
- const allowedSet = new Set(allowed);
129
- data = { ...data, data: (data.data || []).filter((m) => m && m.id && allowedSet.has(String(m.id).trim())) };
130
- }
131
- } catch {}
132
- cache = data;
133
- fetchedAt = Date.now();
134
- if (cacheFile) persistModels(data, cacheFile);
135
- return data;
136
- }
137
-
138
- async function get() {
139
- const now = Date.now();
140
- if (cache && now - fetchedAt < ttlMs) return cache;
141
- if (inflight) return inflight;
142
-
143
- inflight = (async () => {
144
- try {
145
- return await load();
146
- } catch (err) {
147
- // serve stale on failure if we have it, else rethrow
148
- if (cache) return cache;
149
- throw err;
150
- } finally {
151
- inflight = null;
152
- }
153
- })();
154
- return inflight;
155
- }
156
-
157
- function startAutoRefresh(intervalMs = refreshMs) {
158
- if (timer) return stopAutoRefresh;
159
- timer = setInterval(() => {
160
- void load().catch(() => {
161
- // keep serving stale cache on background refresh failure
162
- });
163
- }, intervalMs);
164
- timer.unref?.();
165
- return stopAutoRefresh;
166
- }
167
-
168
- function stopAutoRefresh() {
169
- if (timer) {
170
- clearInterval(timer);
171
- timer = null;
172
- }
173
- }
174
-
175
- return { get, startAutoRefresh, stopAutoRefresh };
176
- }
177
-
178
- async function fetchUpstreamModels({ baseUrl, headers, connectTimeoutMs = 30_000 }) {
179
- const url = `${baseUrl}/zen/v1/models`;
180
- for (let attempt = 0; ; attempt++) {
181
- const res = await attemptFetch(url, headers, connectTimeoutMs);
182
- if (res instanceof Error) {
183
- if (attempt < NETWORK_RETRIES) continue;
184
- throw res;
185
- }
186
- if (isRetryable(res.status) && attempt < STATUS_RETRIES) {
187
- await sleep(2000);
188
- continue;
189
- }
190
- if (!res.ok) throw new Error(`models fetch failed: HTTP ${res.status}`);
191
- const json = await res.json().catch(() => ({}));
192
- const raw = Array.isArray(json) ? json : json.data ?? json.models ?? [];
193
- return { object: "list", data: filterFreeModels(raw) };
194
- }
195
- }
196
-
197
- async function attemptFetch(url, headers, connectTimeoutMs) {
198
- const controller = new AbortController();
199
- const timer = setTimeout(() => controller.abort(), connectTimeoutMs);
200
- try {
201
- return await compatFetch(url, { headers, signal: controller.signal });
202
- } catch (err) {
203
- return err;
204
- } finally {
205
- clearTimeout(timer);
206
- }
207
- }
208
-
209
- function isRetryable(status) {
210
- return status === 429 || status === 502 || status === 503 || status === 504;
211
- }
212
-
213
- function persistModels(data, cacheFile) {
214
- try {
215
- mkdirSync(dirname(cacheFile), { recursive: true });
216
- writeFileSync(cacheFile, JSON.stringify({ cachedAt: Date.now(), ...data }));
217
- } catch {
218
- // persistence is best-effort
219
- }
220
- }
221
-
222
- function sleep(ms) {
223
- return new Promise((r) => setTimeout(r, ms));
224
- }
225
-
226
- const NETWORK_RETRIES = 2;
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;
227
294
  const STATUS_RETRIES = 2;