mslxdff 0.1.161 → 0.1.163

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 (116) hide show
  1. package/bin/mslxdff.js +4 -4
  2. package/package.json +1 -1
  3. package/src/auto.js +254 -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 +127 -126
  19. package/src/chat-pipeline/policy.js +76 -76
  20. package/src/cli/commands/group.js +249 -249
  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 +126 -126
  25. package/src/cli/commands/provider/models.js +142 -142
  26. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  27. package/src/cli/commands/stats.js +21 -9
  28. package/src/cli/commands/sync.js +232 -232
  29. package/src/cli/format.js +1 -0
  30. package/src/cli/help.js +1 -1
  31. package/src/cli/status.js +279 -279
  32. package/src/daemon.js +101 -101
  33. package/src/model-capabilities/enrich.js +86 -86
  34. package/src/model-capabilities/index.js +183 -183
  35. package/src/model-capabilities/parse.js +70 -70
  36. package/src/model-trace.js +4 -3
  37. package/src/models.js +225 -225
  38. package/src/providers/cline/auth.js +228 -228
  39. package/src/providers/cline/chat.js +307 -307
  40. package/src/providers/cline.js +2 -2
  41. package/src/providers/dispatcher.js +26 -14
  42. package/src/providers/globalqwenwork/cosy.js +123 -123
  43. package/src/providers/globalqwenwork/crypto.js +218 -218
  44. package/src/providers/globalqwenwork/http.js +20 -20
  45. package/src/providers/globalqwenwork/rsa.js +54 -54
  46. package/src/providers/globalqwenwork/sse.js +268 -268
  47. package/src/providers/globalqwenwork/stream.js +130 -130
  48. package/src/providers/globalqwenwork/upstream.js +122 -122
  49. package/src/providers/globalworkbuddy/account-store.js +198 -0
  50. package/src/providers/globalworkbuddy/auth.js +97 -0
  51. package/src/providers/globalworkbuddy/catalog.js +138 -0
  52. package/src/providers/globalworkbuddy/constants.js +73 -0
  53. package/src/providers/globalworkbuddy/device-auth.js +120 -0
  54. package/src/providers/globalworkbuddy/errors.js +98 -0
  55. package/src/providers/globalworkbuddy/headers.js +89 -0
  56. package/src/providers/globalworkbuddy/models.js +96 -0
  57. package/src/providers/globalworkbuddy/payload.js +80 -0
  58. package/src/providers/keyring.js +60 -60
  59. package/src/providers/qoder/aggregate.js +12 -3
  60. package/src/providers/qoder/chat.js +200 -183
  61. package/src/providers/qoder/index.js +249 -230
  62. package/src/providers/qoder/models.js +7 -3
  63. package/src/providers/qoder/payload.js +7 -1
  64. package/src/providers/qoder/request.js +2 -1
  65. package/src/providers/qoder/sse.js +145 -103
  66. package/src/providers/qoder/stream.js +16 -4
  67. package/src/providers/qwenwork/account-store.js +133 -133
  68. package/src/providers/qwenwork/constants.js +67 -67
  69. package/src/providers/qwenwork/cosy.js +120 -120
  70. package/src/providers/qwenwork/crypto.js +218 -218
  71. package/src/providers/qwenwork/http.js +20 -20
  72. package/src/providers/qwenwork/index.js +327 -327
  73. package/src/providers/qwenwork/payload.js +142 -142
  74. package/src/providers/qwenwork/rsa.js +54 -54
  75. package/src/providers/qwenwork/sse.js +268 -268
  76. package/src/providers/qwenwork/stream.js +130 -130
  77. package/src/providers/qwenwork/upstream.js +120 -120
  78. package/src/providers/qwenwork.js +1 -1
  79. package/src/providers/registry.js +74 -74
  80. package/src/providers/workbuddy/chat.js +248 -248
  81. package/src/providers/workbuddy/reshape.js +152 -152
  82. package/src/providers/workbuddy.js +2 -2
  83. package/src/reasoning.js +32 -32
  84. package/src/routes/chat/exhausted-handler.js +13 -2
  85. package/src/routes/chat/gateway.js +46 -46
  86. package/src/routes/chat/relay-pipeline.js +292 -276
  87. package/src/routes/chat/via-route-handler.js +146 -146
  88. package/src/routes/hedge.js +255 -255
  89. package/src/routes/models-route.js +167 -167
  90. package/src/routes/peers.js +273 -273
  91. package/src/routes/stream-scan.js +22 -5
  92. package/src/routes/stream.js +385 -386
  93. package/src/runtime/bootstrap.js +45 -45
  94. package/src/runtime/provider-gate.js +34 -34
  95. package/src/runtime/providers-setup.js +165 -165
  96. package/src/runtime/server-lifecycle.js +5 -6
  97. package/src/server.js +69 -64
  98. package/src/state/schemas/allowlist.js +92 -92
  99. package/src/sync-opencode.js +280 -280
  100. package/src/talk-full-redact.js +129 -0
  101. package/src/talk-full.js +130 -0
  102. package/src/talk-log.js +42 -15
  103. package/src/transport/index.js +244 -244
  104. package/src/transport/pool.js +56 -56
  105. package/src/transport/retry.js +24 -24
  106. package/src/transport/sse.js +93 -93
  107. package/src/upstream-engine/sdk/responses.js +5 -0
  108. package/src/upstream-probe/display.js +52 -52
  109. package/src/upstream-probe/probe.js +49 -49
  110. package/src/upstream-probe/rotate.js +110 -110
  111. package/src/upstream-probe/start.js +45 -45
  112. package/src/upstream.js +289 -289
  113. package/src/usage/report.js +14 -8
  114. package/docs/cli_help_mini.md +0 -135
  115. package/src/providers/AGENTS.md +0 -46
  116. package/src/routes/AGENTS.md +0 -37
@@ -1,327 +1,327 @@
1
- // qwenwork provider 门面:多号 keyring 轮转 + 401/403 refresh 重试 + 额度长冷却换号。
2
- // 协议细节全部下沉到 cosy/upstream/payload/sse/stream;这里只做编排(对齐 qoder/index.js 形状)。
3
- // Note: 为何独立 provider 而非 qoder 的新 region — 见 docs/adr/0037-qwenwork-independent-provider.md
4
- import { loadProviderKeys, loadProviderConfig } from "../../state.js";
5
- import { listAccountDocs, accountFromBlob, updateQwenworkTokens } from "./account-store.js";
6
- import { createKeyRing } from "../keyring.js";
7
- import { envInt } from "../base.js";
8
- import { compatFetch, timeoutSignal } from "../../compat.js";
9
- import { joinModelId } from "../model-id.js";
10
- import { buildBody, mapModel } from "./payload.js";
11
- import { chatRequest, modelList, refreshDeviceToken, expiryUnix, userInfo } from "./upstream.js";
12
- import { invalidateSession } from "./cosy.js";
13
- import { collectSync, isCreditsExhausted, creditsExhaustedText } from "./sse.js";
14
- import { transformStream } from "./stream.js";
15
- import { KNOWN_MODELS, MODELS_CACHE_MS, CHAT_URL } from "./constants.js";
16
-
17
- function hostOf(url) {
18
- try { return new URL(String(url)).host; } catch { return "-"; }
19
- }
20
-
21
- function errRes(status, msg, type = "upstream_error", extra = {}) {
22
- return new Response(JSON.stringify({ error: { message: msg, type } }), {
23
- status,
24
- headers: { "Content-Type": "application/json", ...extra },
25
- });
26
- }
27
-
28
- export function createQwenworkProvider({
29
- id = "qwenwork",
30
- apiKeys,
31
- file,
32
- fetchImpl,
33
- cooldownMs = envInt("MSLXDFF_QWENWORK_COOLDOWN_MS", 30_000),
34
- quotaCooldownMs = envInt("MSLXDFF_QWENWORK_QUOTA_COOLDOWN_MS", 3600_000),
35
- connectTimeoutMs = Number(process.env.MSLXDFF_QWENWORK_TIMEOUT_MS) || 120_000,
36
- } = {}) {
37
- // 单测隔离(MSLXDFF_TEST=1 / NODE_ENV=test / --test 进程):state 与 auth 目录走测试替身,
38
- // 与你个人真实账号完全隔离(防止单测把真号读进来、把真 refreshToken 写回去)。
39
- // 实测教训:构造传了 `apiKeys: []`,门面却从 `~/.config/mslxdff/state.json` 读出真号 → 无号测试打了现网。
40
- const testIsolated = process.env.MSLXDFF_TEST === "1" || process.env.NODE_ENV === "test" || String(process.execArgv || []).includes("--test") || process.argv.slice(1).some((a) => String(a).includes("--test"));
41
- const keys = (() => {
42
- if (testIsolated && file === undefined && apiKeys !== undefined) {
43
- return [...new Set((Array.isArray(apiKeys) ? apiKeys : []).map((k) => String(k).trim()).filter(Boolean))];
44
- }
45
- if (Array.isArray(apiKeys) && apiKeys.length) return [...new Set(apiKeys.map((k) => String(k).trim()).filter(Boolean))];
46
- try { return loadProviderKeys(id, file ? { file } : {}); } catch { return []; }
47
- })();
48
- let authList = [];
49
- if (!testIsolated) {
50
- try { authList = loadProviderConfig(id, file ? { file } : {})?.auths || []; } catch {}
51
- try {
52
- const docs = listAccountDocs();
53
- for (const d of docs) {
54
- const row = authList.find((a) => String(a?.uid) === String(d.uid));
55
- if (!row) authList.push({ uid: d.uid, refreshToken: d.doc?.auth?.refreshToken || "", name: d.doc?.account?.name || "" });
56
- }
57
- } catch {}
58
- }
59
- const ring = createKeyRing(keys, { cooldownMs });
60
- const exhaustedByQuota = new Set();
61
- if (!fetchImpl) fetchImpl = compatFetch;
62
- const cdbg = (...a) => { if (process.env.QWENWORK_DEBUG === "1") console.log("[qwenwork-chat]", ...a); };
63
-
64
- // blob → 上游 account(含 uid/nickname/email,供 COSY 身份 payload 用)
65
- function accountFor(key) {
66
- const blob = accountFromBlob(key);
67
- if (!blob?.accessToken) return null;
68
- const auth = authList.find((a) => String(a?.refreshToken || "") === String(blob.refreshToken || "")) || {};
69
- let doc = null;
70
- try {
71
- const docs = listAccountDocs();
72
- doc = docs.find((d) => String(d.uid) === String(auth.uid)) || docs.find((d) => d.doc?.auth?.refreshToken === blob.refreshToken) || null;
73
- } catch {}
74
- return {
75
- id: auth.uid || doc?.uid || "",
76
- uid: auth.uid || doc?.uid || "",
77
- nickname: auth.name || doc?.doc?.account?.name || "",
78
- email: doc?.doc?.account?.email || "",
79
- accessToken: blob.accessToken,
80
- refreshToken: blob.refreshToken || auth.refreshToken || doc?.doc?.auth?.refreshToken || "",
81
- };
82
- }
83
-
84
- function withEcho(res, account, upstreamStatus) {
85
- try {
86
- res.headers.set("x-mslxdff-upstream", hostOf(CHAT_URL));
87
- if (account?.uid) res.headers.set("x-mslxdff-qwenwork-account", String(account.uid).slice(-8));
88
- if (upstreamStatus) res.headers.set("x-mslxdff-qwenwork-upstream-status", String(upstreamStatus));
89
- } catch {}
90
- return res;
91
- }
92
- function withQuota(res) {
93
- try { res.headers.set("x-mslxdff-qwenwork-quota", "1"); } catch {}
94
- return res;
95
- }
96
-
97
- async function tryRefresh(account) {
98
- if (!account?.refreshToken) return false;
99
- try {
100
- const data = await refreshDeviceToken(account.refreshToken, fetchImpl);
101
- const access = data.token || data.device_token;
102
- const refresh = data.refresh_token || account.refreshToken;
103
- const expiresAt = expiryUnix(data);
104
- account.accessToken = access;
105
- account.refreshToken = refresh;
106
- try { await updateQwenworkTokens({ uid: account.uid, accessToken: access, refreshToken: refresh, expiresAt, file }); }
107
- catch { invalidateSession(account); }
108
- // 同步 ring 里的 blob(token 轮换后旧 blob 即失效)
109
- try {
110
- const oldKey = ring.keys.find((k) => { const b = accountFromBlob(k); return b && b.refreshToken === data.refresh_token; }) || null;
111
- const newBlob = JSON.stringify({ device_token: access, refresh_token: refresh });
112
- const cur = ring.keys.find((k) => accountFromBlob(k)?.accessToken === account.accessToken);
113
- if (cur) ring.replace(cur, newBlob);
114
- else if (oldKey) ring.replace(oldKey, newBlob);
115
- } catch {}
116
- return true;
117
- } catch (e) {
118
- cdbg(`[refresh-fail] uid=${String(account.uid).slice(-8)} ${String(e?.message || e).slice(0, 160)}`);
119
- return false;
120
- }
121
- }
122
-
123
- async function chat(body, opts) {
124
- const stream = body?.stream !== false;
125
- const wantModel = typeof body?.model === "string" && body.model.startsWith("qwenwork/")
126
- ? body.model.slice("qwenwork/".length)
127
- : (body?.model || "flash");
128
- const modelKey = mapModel(wantModel);
129
- const stripped = { ...body, model: wantModel };
130
- const total = ring.keys.length;
131
- // 构造参数无号但 auth 目录有号(如测试注入单测环境或 state 被外部改写):不视为"无号",
132
- // 直接按 401 引导 login——调用方先 login 落盘再 chat,这与各 provider 门面语义一致
133
- if (!total) {
134
- return errRes(401, "qwenwork: 无可用账号 — 先跑 mslxdff -provider qwenwork login", "auth_error");
135
- }
136
- let lastRes = null;
137
- const refreshed = new Set();
138
- for (let hop = 0; hop <= total; hop++) {
139
- const key = ring.next();
140
- if (!key) break;
141
- if (exhaustedByQuota.has(key)) {
142
- if (ring.isCooling(key)) {
143
- if (ring.available() > 0) continue;
144
- break;
145
- }
146
- exhaustedByQuota.delete(key);
147
- }
148
- let account = accountFor(key);
149
- if (!account) { try { ring.onError(key); } catch {} continue; }
150
- // 身份缺失(手动配 key、未走 login)时补一次 userinfo:COSY 身份 payload 的 uid/name/email 为空
151
- // 会被上游判 `code 101 Signature invalid`(实测:同 token 空身份 403、有身份 200)。补上后才签名。
152
- if (!account.uid) {
153
- try {
154
- const info = await userInfo(account.accessToken, fetchImpl);
155
- if (info?.id) account.uid = String(info.id);
156
- if (info?.name) account.nickname = String(info.name);
157
- if (info?.email) account.email = String(info.email);
158
- if (account.uid) {
159
- try {
160
- const { saveQwenworkAccount } = await import("./account-store.js");
161
- await saveQwenworkAccount({ uid: account.uid, accessToken: account.accessToken, refreshToken: account.refreshToken || "", name: account.nickname || "", email: account.email || "", file });
162
- } catch {}
163
- }
164
- } catch (e) {
165
- cdbg(`[identity-enrich-fail] ${String(e?.message || e).slice(0, 160)}`);
166
- }
167
- if (!account.uid) { try { ring.onError(key); } catch {} lastRes = withEcho(errRes(401, "qwenwork: 账号身份缺失且 userinfo 失败,该 key 不可用", "auth_error"), account, 401); continue; }
168
- }
169
- const bodyStr = buildBody(stripped, modelKey);
170
- let upRes;
171
- try {
172
- upRes = await chatRequest(account, modelKey, bodyStr, timeoutSignal(connectTimeoutMs), fetchImpl);
173
- } catch (e) {
174
- try { ring.onError(key); } catch {}
175
- lastRes = withEcho(errRes(502, `qwenwork: 上游连接失败 ${String(e?.message || e).slice(0, 200)}`), account, 502);
176
- continue;
177
- }
178
- if (!upRes.ok) {
179
- const text = await upRes.text().catch(() => "");
180
- const quota = isCreditsExhausted(upRes.status, text);
181
- if (quota) {
182
- try { ring.onError(key, quotaCooldownMs); } catch {}
183
- exhaustedByQuota.add(key);
184
- lastRes = withQuota(withEcho(errRes(429, `qwenwork: 账号积分耗尽 ${text.slice(0, 200)}`, "quota_exhausted"), account, upRes.status));
185
- if (ring.available() > 0) continue;
186
- break;
187
- }
188
- if ((upRes.status === 401 || upRes.status === 403) && account.refreshToken && !refreshed.has(key)) {
189
- refreshed.add(key);
190
- const ok = await tryRefresh(account);
191
- if (ok) { hop -= 1; continue; }
192
- try { ring.onError(key); } catch {}
193
- lastRes = withEcho(errRes(upRes.status, `qwenwork: 授权失效 ${text.slice(0, 200)}`, "auth_error"), account, upRes.status);
194
- continue;
195
- }
196
- try { ring.onError(key); } catch {}
197
- lastRes = withEcho(errRes(upRes.status >= 500 ? 502 : upRes.status, `qwenwork: 上游 ${upRes.status} ${text.slice(0, 200)}`), account, upRes.status);
198
- if (ring.available() > 0 && (upRes.status === 429 || upRes.status >= 500)) continue;
199
- return lastRes;
200
- }
201
- // 200:流内仍可能裹着业务错(信封 statusCodeValue / code),非流式聚合时由 collectSync 判决;
202
- // 流式路径照原作者 transform 透传(错误帧由 sse.handleLine 转成流内 error 事件)。
203
- if (stream) {
204
- const out = new Response(transformStream(upRes.body, wantModel, () => {}), {
205
- status: 200,
206
- headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" },
207
- });
208
- return withEcho(out, account, 0);
209
- }
210
- const result = await collectSync(upRes.body, wantModel);
211
- if (result.error) {
212
- if (creditsExhaustedText(result.error)) {
213
- try { ring.onError(key, quotaCooldownMs); } catch {}
214
- exhaustedByQuota.add(key);
215
- lastRes = withQuota(withEcho(errRes(429, `qwenwork: 账号积分耗尽 ${result.error}`, "quota_exhausted"), account, 429));
216
- if (ring.available() > 0) continue;
217
- break;
218
- }
219
- try { ring.onError(key); } catch {}
220
- lastRes = withEcho(errRes(502, `qwenwork: 上游流内错误 ${result.error}`), account, 502);
221
- continue;
222
- }
223
- const completion = result.completion;
224
- completion.model = wantModel;
225
- return withEcho(new Response(JSON.stringify(completion), { status: 200, headers: { "Content-Type": "application/json" } }), account, 0);
226
- }
227
- if (total > 0 && ring.keys.every((k) => exhaustedByQuota.has(k))) {
228
- return errRes(429, "qwenwork: 所有账号积分已用完,请更换账号或等待额度恢复", "quota_exhausted", { "x-mslxdff-qwenwork-quota-exhausted": "1" });
229
- }
230
- if (lastRes) return lastRes;
231
- if (!ring.available()) {
232
- return errRes(429, "qwenwork: 账号暂不可用(上游限流/排队冷却中),请稍后重试", "all_cooling", { "x-mslxdff-qwenwork-all-cooling": "1" });
233
- }
234
- return errRes(401, "qwenwork: 无可用账号 — 先跑 mslxdff -provider qwenwork login", "auth_error");
235
- }
236
-
237
- // 全号聚合:逐号拉 qwork 切片求并集(单号 3 个,多号互相印证)
238
- let cache = null;
239
- let fetchedAt = 0;
240
- function eachAccount() {
241
- const out = [];
242
- const seen = new Set();
243
- const push = (key, auth) => {
244
- const account = accountFor(key);
245
- if (!account?.accessToken || seen.has(account.accessToken)) return;
246
- seen.add(account.accessToken);
247
- out.push(account);
248
- };
249
- for (const k of keys) {
250
- const blob = accountFromBlob(k);
251
- if (!blob?.accessToken) continue;
252
- const auth = authList.find((a) => String(a?.refreshToken || "") === String(blob.refreshToken || "")) || {};
253
- push(k, auth);
254
- }
255
- if (!out.length) {
256
- try {
257
- for (const { uid, doc } of listAccountDocs()) {
258
- const a = doc?.auth || {};
259
- if (!a.accessToken) continue;
260
- const account = { id: uid, uid, nickname: doc?.account?.name || "", email: doc?.account?.email || "", accessToken: a.accessToken, refreshToken: a.refreshToken || "" };
261
- if (seen.has(account.accessToken)) continue;
262
- seen.add(account.accessToken);
263
- out.push(account);
264
- }
265
- } catch {}
266
- }
267
- return out;
268
- }
269
-
270
- async function listModels() {
271
- const now = Date.now();
272
- if (cache && now - fetchedAt < MODELS_CACHE_MS) return cache;
273
- const accounts = eachAccount();
274
- if (!accounts.length) return [];
275
- const seen = new Set();
276
- const out = [];
277
- for (const account of accounts) {
278
- try {
279
- const list = await modelList(account, fetchImpl);
280
- for (const m of list) {
281
- if (!m?.key || seen.has(m.key)) continue;
282
- seen.add(m.key);
283
- out.push({
284
- id: joinModelId(id, m.key),
285
- object: "model",
286
- created: 1753600000,
287
- owned_by: "qwenwork",
288
- name: m.name || m.key,
289
- context_length: m.maxInputTokens || 0,
290
- price_factor: m.priceFactor || 0,
291
- is_reasoning: !!m.isReasoning,
292
- });
293
- }
294
- } catch {}
295
- }
296
- if (out.length) { cache = out; fetchedAt = now; }
297
- // 取数失败时用实测快照兜底(目录恒为 3 个,不会空)
298
- if (!out.length && !cache) {
299
- return KNOWN_MODELS.map((m) => ({
300
- id: joinModelId(id, m.key),
301
- object: "model",
302
- created: 1753600000,
303
- owned_by: "qwenwork",
304
- name: m.name,
305
- context_length: 1000000,
306
- price_factor: m.priceFactor,
307
- is_reasoning: true,
308
- }));
309
- }
310
- return out.length ? out : (cache || []);
311
- }
312
-
313
- async function preheat() {
314
- try {
315
- const list = await listModels();
316
- return list.length ? { ok: true } : { ok: false, error: "no account" };
317
- } catch (e) { return { ok: false, error: String(e?.message || e).slice(0, 120) }; }
318
- }
319
-
320
- async function close() {}
321
- async function chatWithKeys(body, keysOverride, opts) {
322
- const tmp = createQwenworkProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, quotaCooldownMs, connectTimeoutMs });
323
- return tmp.chat(body, opts);
324
- }
325
-
326
- return { id, chat, chatWithKeys, listModels, preheat, close, keyRing: ring, baseUrl: "qwenwork://native" };
327
- }
1
+ // qwenwork provider 门面:多号 keyring 轮转 + 401/403 refresh 重试 + 额度长冷却换号。
2
+ // 协议细节全部下沉到 cosy/upstream/payload/sse/stream;这里只做编排(对齐 qoder/index.js 形状)。
3
+ // Note: 为何独立 provider 而非 qoder 的新 region — 见 docs/adr/0037-qwenwork-independent-provider.md
4
+ import { loadProviderKeys, loadProviderConfig } from "../../state.js";
5
+ import { listAccountDocs, accountFromBlob, updateQwenworkTokens } from "./account-store.js";
6
+ import { createKeyRing } from "../keyring.js";
7
+ import { envInt } from "../base.js";
8
+ import { compatFetch, timeoutSignal } from "../../compat.js";
9
+ import { joinModelId } from "../model-id.js";
10
+ import { buildBody, mapModel } from "./payload.js";
11
+ import { chatRequest, modelList, refreshDeviceToken, expiryUnix, userInfo } from "./upstream.js";
12
+ import { invalidateSession } from "./cosy.js";
13
+ import { collectSync, isCreditsExhausted, creditsExhaustedText } from "./sse.js";
14
+ import { transformStream } from "./stream.js";
15
+ import { KNOWN_MODELS, MODELS_CACHE_MS, CHAT_URL } from "./constants.js";
16
+
17
+ function hostOf(url) {
18
+ try { return new URL(String(url)).host; } catch { return "-"; }
19
+ }
20
+
21
+ function errRes(status, msg, type = "upstream_error", extra = {}) {
22
+ return new Response(JSON.stringify({ error: { message: msg, type } }), {
23
+ status,
24
+ headers: { "Content-Type": "application/json", ...extra },
25
+ });
26
+ }
27
+
28
+ export function createQwenworkProvider({
29
+ id = "qwenwork",
30
+ apiKeys,
31
+ file,
32
+ fetchImpl,
33
+ cooldownMs = envInt("MSLXDFF_QWENWORK_COOLDOWN_MS", 30_000),
34
+ quotaCooldownMs = envInt("MSLXDFF_QWENWORK_QUOTA_COOLDOWN_MS", 3600_000),
35
+ connectTimeoutMs = Number(process.env.MSLXDFF_QWENWORK_TIMEOUT_MS) || 120_000,
36
+ } = {}) {
37
+ // 单测隔离(MSLXDFF_TEST=1 / NODE_ENV=test / --test 进程):state 与 auth 目录走测试替身,
38
+ // 与你个人真实账号完全隔离(防止单测把真号读进来、把真 refreshToken 写回去)。
39
+ // 实测教训:构造传了 `apiKeys: []`,门面却从 `~/.config/mslxdff/state.json` 读出真号 → 无号测试打了现网。
40
+ const testIsolated = process.env.MSLXDFF_TEST === "1" || process.env.NODE_ENV === "test" || String(process.execArgv || []).includes("--test") || process.argv.slice(1).some((a) => String(a).includes("--test"));
41
+ const keys = (() => {
42
+ if (testIsolated && file === undefined && apiKeys !== undefined) {
43
+ return [...new Set((Array.isArray(apiKeys) ? apiKeys : []).map((k) => String(k).trim()).filter(Boolean))];
44
+ }
45
+ if (Array.isArray(apiKeys) && apiKeys.length) return [...new Set(apiKeys.map((k) => String(k).trim()).filter(Boolean))];
46
+ try { return loadProviderKeys(id, file ? { file } : {}); } catch { return []; }
47
+ })();
48
+ let authList = [];
49
+ if (!testIsolated) {
50
+ try { authList = loadProviderConfig(id, file ? { file } : {})?.auths || []; } catch {}
51
+ try {
52
+ const docs = listAccountDocs();
53
+ for (const d of docs) {
54
+ const row = authList.find((a) => String(a?.uid) === String(d.uid));
55
+ if (!row) authList.push({ uid: d.uid, refreshToken: d.doc?.auth?.refreshToken || "", name: d.doc?.account?.name || "" });
56
+ }
57
+ } catch {}
58
+ }
59
+ const ring = createKeyRing(keys, { cooldownMs });
60
+ const exhaustedByQuota = new Set();
61
+ if (!fetchImpl) fetchImpl = compatFetch;
62
+ const cdbg = (...a) => { if (process.env.QWENWORK_DEBUG === "1") console.log("[qwenwork-chat]", ...a); };
63
+
64
+ // blob → 上游 account(含 uid/nickname/email,供 COSY 身份 payload 用)
65
+ function accountFor(key) {
66
+ const blob = accountFromBlob(key);
67
+ if (!blob?.accessToken) return null;
68
+ const auth = authList.find((a) => String(a?.refreshToken || "") === String(blob.refreshToken || "")) || {};
69
+ let doc = null;
70
+ try {
71
+ const docs = listAccountDocs();
72
+ doc = docs.find((d) => String(d.uid) === String(auth.uid)) || docs.find((d) => d.doc?.auth?.refreshToken === blob.refreshToken) || null;
73
+ } catch {}
74
+ return {
75
+ id: auth.uid || doc?.uid || "",
76
+ uid: auth.uid || doc?.uid || "",
77
+ nickname: auth.name || doc?.doc?.account?.name || "",
78
+ email: doc?.doc?.account?.email || "",
79
+ accessToken: blob.accessToken,
80
+ refreshToken: blob.refreshToken || auth.refreshToken || doc?.doc?.auth?.refreshToken || "",
81
+ };
82
+ }
83
+
84
+ function withEcho(res, account, upstreamStatus) {
85
+ try {
86
+ res.headers.set("x-mslxdff-upstream", hostOf(CHAT_URL));
87
+ if (account?.uid) res.headers.set("x-mslxdff-qwenwork-account", String(account.uid).slice(-8));
88
+ if (upstreamStatus) res.headers.set("x-mslxdff-qwenwork-upstream-status", String(upstreamStatus));
89
+ } catch {}
90
+ return res;
91
+ }
92
+ function withQuota(res) {
93
+ try { res.headers.set("x-mslxdff-qwenwork-quota", "1"); } catch {}
94
+ return res;
95
+ }
96
+
97
+ async function tryRefresh(account) {
98
+ if (!account?.refreshToken) return false;
99
+ try {
100
+ const data = await refreshDeviceToken(account.refreshToken, fetchImpl);
101
+ const access = data.token || data.device_token;
102
+ const refresh = data.refresh_token || account.refreshToken;
103
+ const expiresAt = expiryUnix(data);
104
+ account.accessToken = access;
105
+ account.refreshToken = refresh;
106
+ try { await updateQwenworkTokens({ uid: account.uid, accessToken: access, refreshToken: refresh, expiresAt, file }); }
107
+ catch { invalidateSession(account); }
108
+ // 同步 ring 里的 blob(token 轮换后旧 blob 即失效)
109
+ try {
110
+ const oldKey = ring.keys.find((k) => { const b = accountFromBlob(k); return b && b.refreshToken === data.refresh_token; }) || null;
111
+ const newBlob = JSON.stringify({ device_token: access, refresh_token: refresh });
112
+ const cur = ring.keys.find((k) => accountFromBlob(k)?.accessToken === account.accessToken);
113
+ if (cur) ring.replace(cur, newBlob);
114
+ else if (oldKey) ring.replace(oldKey, newBlob);
115
+ } catch {}
116
+ return true;
117
+ } catch (e) {
118
+ cdbg(`[refresh-fail] uid=${String(account.uid).slice(-8)} ${String(e?.message || e).slice(0, 160)}`);
119
+ return false;
120
+ }
121
+ }
122
+
123
+ async function chat(body, opts) {
124
+ const stream = body?.stream !== false;
125
+ const wantModel = typeof body?.model === "string" && body.model.startsWith("qwenwork/")
126
+ ? body.model.slice("qwenwork/".length)
127
+ : (body?.model || "flash");
128
+ const modelKey = mapModel(wantModel);
129
+ const stripped = { ...body, model: wantModel };
130
+ const total = ring.keys.length;
131
+ // 构造参数无号但 auth 目录有号(如测试注入单测环境或 state 被外部改写):不视为"无号",
132
+ // 直接按 401 引导 login——调用方先 login 落盘再 chat,这与各 provider 门面语义一致
133
+ if (!total) {
134
+ return errRes(401, "qwenwork: 无可用账号 — 先跑 mslxdff -provider qwenwork login", "auth_error");
135
+ }
136
+ let lastRes = null;
137
+ const refreshed = new Set();
138
+ for (let hop = 0; hop <= total; hop++) {
139
+ const key = ring.next();
140
+ if (!key) break;
141
+ if (exhaustedByQuota.has(key)) {
142
+ if (ring.isCooling(key)) {
143
+ if (ring.available() > 0) continue;
144
+ break;
145
+ }
146
+ exhaustedByQuota.delete(key);
147
+ }
148
+ let account = accountFor(key);
149
+ if (!account) { try { ring.onError(key); } catch {} continue; }
150
+ // 身份缺失(手动配 key、未走 login)时补一次 userinfo:COSY 身份 payload 的 uid/name/email 为空
151
+ // 会被上游判 `code 101 Signature invalid`(实测:同 token 空身份 403、有身份 200)。补上后才签名。
152
+ if (!account.uid) {
153
+ try {
154
+ const info = await userInfo(account.accessToken, fetchImpl);
155
+ if (info?.id) account.uid = String(info.id);
156
+ if (info?.name) account.nickname = String(info.name);
157
+ if (info?.email) account.email = String(info.email);
158
+ if (account.uid) {
159
+ try {
160
+ const { saveQwenworkAccount } = await import("./account-store.js");
161
+ await saveQwenworkAccount({ uid: account.uid, accessToken: account.accessToken, refreshToken: account.refreshToken || "", name: account.nickname || "", email: account.email || "", file });
162
+ } catch {}
163
+ }
164
+ } catch (e) {
165
+ cdbg(`[identity-enrich-fail] ${String(e?.message || e).slice(0, 160)}`);
166
+ }
167
+ if (!account.uid) { try { ring.onError(key); } catch {} lastRes = withEcho(errRes(401, "qwenwork: 账号身份缺失且 userinfo 失败,该 key 不可用", "auth_error"), account, 401); continue; }
168
+ }
169
+ const bodyStr = buildBody(stripped, modelKey);
170
+ let upRes;
171
+ try {
172
+ upRes = await chatRequest(account, modelKey, bodyStr, timeoutSignal(connectTimeoutMs), fetchImpl);
173
+ } catch (e) {
174
+ try { ring.onError(key); } catch {}
175
+ lastRes = withEcho(errRes(502, `qwenwork: 上游连接失败 ${String(e?.message || e).slice(0, 200)}`), account, 502);
176
+ continue;
177
+ }
178
+ if (!upRes.ok) {
179
+ const text = await upRes.text().catch(() => "");
180
+ const quota = isCreditsExhausted(upRes.status, text);
181
+ if (quota) {
182
+ try { ring.onError(key, quotaCooldownMs); } catch {}
183
+ exhaustedByQuota.add(key);
184
+ lastRes = withQuota(withEcho(errRes(429, `qwenwork: 账号积分耗尽 ${text.slice(0, 200)}`, "quota_exhausted"), account, upRes.status));
185
+ if (ring.available() > 0) continue;
186
+ break;
187
+ }
188
+ if ((upRes.status === 401 || upRes.status === 403) && account.refreshToken && !refreshed.has(key)) {
189
+ refreshed.add(key);
190
+ const ok = await tryRefresh(account);
191
+ if (ok) { hop -= 1; continue; }
192
+ try { ring.onError(key); } catch {}
193
+ lastRes = withEcho(errRes(upRes.status, `qwenwork: 授权失效 ${text.slice(0, 200)}`, "auth_error"), account, upRes.status);
194
+ continue;
195
+ }
196
+ try { ring.onError(key); } catch {}
197
+ lastRes = withEcho(errRes(upRes.status >= 500 ? 502 : upRes.status, `qwenwork: 上游 ${upRes.status} ${text.slice(0, 200)}`), account, upRes.status);
198
+ if (ring.available() > 0 && (upRes.status === 429 || upRes.status >= 500)) continue;
199
+ return lastRes;
200
+ }
201
+ // 200:流内仍可能裹着业务错(信封 statusCodeValue / code),非流式聚合时由 collectSync 判决;
202
+ // 流式路径照原作者 transform 透传(错误帧由 sse.handleLine 转成流内 error 事件)。
203
+ if (stream) {
204
+ const out = new Response(transformStream(upRes.body, wantModel, () => {}), {
205
+ status: 200,
206
+ headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" },
207
+ });
208
+ return withEcho(out, account, 0);
209
+ }
210
+ const result = await collectSync(upRes.body, wantModel);
211
+ if (result.error) {
212
+ if (creditsExhaustedText(result.error)) {
213
+ try { ring.onError(key, quotaCooldownMs); } catch {}
214
+ exhaustedByQuota.add(key);
215
+ lastRes = withQuota(withEcho(errRes(429, `qwenwork: 账号积分耗尽 ${result.error}`, "quota_exhausted"), account, 429));
216
+ if (ring.available() > 0) continue;
217
+ break;
218
+ }
219
+ try { ring.onError(key); } catch {}
220
+ lastRes = withEcho(errRes(502, `qwenwork: 上游流内错误 ${result.error}`), account, 502);
221
+ continue;
222
+ }
223
+ const completion = result.completion;
224
+ completion.model = wantModel;
225
+ return withEcho(new Response(JSON.stringify(completion), { status: 200, headers: { "Content-Type": "application/json" } }), account, 0);
226
+ }
227
+ if (total > 0 && ring.keys.every((k) => exhaustedByQuota.has(k))) {
228
+ return errRes(429, "qwenwork: 所有账号积分已用完,请更换账号或等待额度恢复", "quota_exhausted", { "x-mslxdff-qwenwork-quota-exhausted": "1" });
229
+ }
230
+ if (lastRes) return lastRes;
231
+ if (!ring.available()) {
232
+ return errRes(429, "qwenwork: 账号暂不可用(上游限流/排队冷却中),请稍后重试", "all_cooling", { "x-mslxdff-qwenwork-all-cooling": "1" });
233
+ }
234
+ return errRes(401, "qwenwork: 无可用账号 — 先跑 mslxdff -provider qwenwork login", "auth_error");
235
+ }
236
+
237
+ // 全号聚合:逐号拉 qwork 切片求并集(单号 3 个,多号互相印证)
238
+ let cache = null;
239
+ let fetchedAt = 0;
240
+ function eachAccount() {
241
+ const out = [];
242
+ const seen = new Set();
243
+ const push = (key, auth) => {
244
+ const account = accountFor(key);
245
+ if (!account?.accessToken || seen.has(account.accessToken)) return;
246
+ seen.add(account.accessToken);
247
+ out.push(account);
248
+ };
249
+ for (const k of keys) {
250
+ const blob = accountFromBlob(k);
251
+ if (!blob?.accessToken) continue;
252
+ const auth = authList.find((a) => String(a?.refreshToken || "") === String(blob.refreshToken || "")) || {};
253
+ push(k, auth);
254
+ }
255
+ if (!out.length) {
256
+ try {
257
+ for (const { uid, doc } of listAccountDocs()) {
258
+ const a = doc?.auth || {};
259
+ if (!a.accessToken) continue;
260
+ const account = { id: uid, uid, nickname: doc?.account?.name || "", email: doc?.account?.email || "", accessToken: a.accessToken, refreshToken: a.refreshToken || "" };
261
+ if (seen.has(account.accessToken)) continue;
262
+ seen.add(account.accessToken);
263
+ out.push(account);
264
+ }
265
+ } catch {}
266
+ }
267
+ return out;
268
+ }
269
+
270
+ async function listModels() {
271
+ const now = Date.now();
272
+ if (cache && now - fetchedAt < MODELS_CACHE_MS) return cache;
273
+ const accounts = eachAccount();
274
+ if (!accounts.length) return [];
275
+ const seen = new Set();
276
+ const out = [];
277
+ for (const account of accounts) {
278
+ try {
279
+ const list = await modelList(account, fetchImpl);
280
+ for (const m of list) {
281
+ if (!m?.key || seen.has(m.key)) continue;
282
+ seen.add(m.key);
283
+ out.push({
284
+ id: joinModelId(id, m.key),
285
+ object: "model",
286
+ created: 1753600000,
287
+ owned_by: "qwenwork",
288
+ name: m.name || m.key,
289
+ context_length: m.maxInputTokens || 0,
290
+ price_factor: m.priceFactor || 0,
291
+ is_reasoning: !!m.isReasoning,
292
+ });
293
+ }
294
+ } catch {}
295
+ }
296
+ if (out.length) { cache = out; fetchedAt = now; }
297
+ // 取数失败时用实测快照兜底(目录恒为 3 个,不会空)
298
+ if (!out.length && !cache) {
299
+ return KNOWN_MODELS.map((m) => ({
300
+ id: joinModelId(id, m.key),
301
+ object: "model",
302
+ created: 1753600000,
303
+ owned_by: "qwenwork",
304
+ name: m.name,
305
+ context_length: 1000000,
306
+ price_factor: m.priceFactor,
307
+ is_reasoning: true,
308
+ }));
309
+ }
310
+ return out.length ? out : (cache || []);
311
+ }
312
+
313
+ async function preheat() {
314
+ try {
315
+ const list = await listModels();
316
+ return list.length ? { ok: true } : { ok: false, error: "no account" };
317
+ } catch (e) { return { ok: false, error: String(e?.message || e).slice(0, 120) }; }
318
+ }
319
+
320
+ async function close() {}
321
+ async function chatWithKeys(body, keysOverride, opts) {
322
+ const tmp = createQwenworkProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, quotaCooldownMs, connectTimeoutMs });
323
+ return tmp.chat(body, opts);
324
+ }
325
+
326
+ return { id, chat, chatWithKeys, listModels, preheat, close, keyRing: ring, baseUrl: "qwenwork://native" };
327
+ }