mslxdff 0.1.159 → 0.1.161
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/docs/cli_help_mini.md +3 -1
- package/package.json +1 -1
- package/src/autostart.js +3 -0
- package/src/chat-pipeline/auto-race.js +1 -1
- package/src/chat-pipeline/empty-turn.js +119 -0
- package/src/chat-pipeline/index.js +4 -1
- package/src/chat-pipeline/serial-trial.js +244 -210
- package/src/cli/commands/daemon.js +4 -4
- package/src/cli/commands/model/list-providers.js +1 -1
- package/src/cli/commands/provider/globalqwenwork-login.js +126 -0
- package/src/cli/commands/provider/index.js +2 -0
- package/src/cli/commands/provider/models.js +4 -1
- package/src/cli/commands/stats.js +20 -5
- package/src/cli/commands/system.js +2 -2
- package/src/cli/format.js +6 -0
- package/src/cli/policy.js +2 -2
- package/src/cli/provider-row.js +2 -2
- package/src/daemon.js +7 -2
- package/src/logs.js +14 -1
- package/src/model-trace.js +5 -2
- package/src/providers/AGENTS.md +46 -0
- package/src/providers/classify.js +1 -1
- package/src/providers/globalqwenwork/account-store.js +141 -0
- package/src/providers/globalqwenwork/constants.js +73 -0
- package/src/providers/globalqwenwork/cosy.js +123 -0
- package/src/providers/globalqwenwork/crypto.js +220 -0
- package/src/providers/globalqwenwork/http.js +22 -0
- package/src/providers/globalqwenwork/index.js +331 -0
- package/src/providers/globalqwenwork/payload.js +145 -0
- package/src/providers/globalqwenwork/rsa.js +56 -0
- package/src/providers/globalqwenwork/sse.js +270 -0
- package/src/providers/globalqwenwork/stream.js +132 -0
- package/src/providers/globalqwenwork/upstream.js +122 -0
- package/src/providers/globalqwenwork.js +1 -0
- package/src/providers/registry.js +8 -0
- package/src/providers/zcode/chat.js +11 -10
- package/src/providers/zcode/const.js +1 -1
- package/src/providers/zcode/context-shape.js +162 -0
- package/src/providers/zcode/headers.js +38 -0
- package/src/providers/zcode/sse.js +19 -2
- package/src/routes/AGENTS.md +37 -0
- package/src/routes/chat/broadband-handler.js +3 -2
- package/src/routes/chat/exhausted-handler.js +23 -8
- package/src/routes/chat/hedge-handler.js +3 -0
- package/src/routes/chat/local-handler.js +5 -1
- package/src/routes/chat/peer-handler.js +2 -0
- package/src/routes/chat/relay-pipeline.js +40 -14
- package/src/routes/chat/via-route-handler.js +2 -0
- package/src/routes/helpers.js +20 -4
- package/src/routes/stream-hold.js +138 -0
- package/src/routes/stream-scan.js +278 -0
- package/src/routes/stream.js +106 -158
- package/src/runtime/lifecycle-forensics.js +116 -0
- package/src/runtime/lifecycle-log.js +23 -0
- package/src/runtime/provider-gate.js +4 -3
- package/src/talk-log.js +226 -0
- package/src/timeline.js +5 -2
- package/src/usage/record.js +8 -1
- package/src/usage/report.js +39 -2
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
// globalqwenwork provider 门面:多号 keyring 轮转 + 401/403 refresh 重试 + 额度长冷却换号。
|
|
2
|
+
// 协议细节全部下沉到 cosy/upstream/payload/sse/stream;这里只做编排(对齐 qwenwork/index.js 形状)。
|
|
3
|
+
// vendor 自 src/providers/qwenwork/index.js,改动面 = 命名空间(id/env/响应头/提示语)+ 默认模型名,
|
|
4
|
+
// 中继逻辑逐字同构:实测国际站接受 cn 同款 COSY 签名与 chat body(2026-10-01 现网 200 出词)。
|
|
5
|
+
// Note: 为何独立 provider 而非 qwenwork 的新 region — 见 docs/adr/0041-globalqwenwork-international-provider.md
|
|
6
|
+
import { loadProviderKeys, loadProviderConfig } from "../../state.js";
|
|
7
|
+
import { listAccountDocs, accountFromBlob, updateGlobalQwenworkTokens } from "./account-store.js";
|
|
8
|
+
import { createKeyRing } from "../keyring.js";
|
|
9
|
+
import { envInt } from "../base.js";
|
|
10
|
+
import { compatFetch, timeoutSignal } from "../../compat.js";
|
|
11
|
+
import { joinModelId } from "../model-id.js";
|
|
12
|
+
import { buildBody, mapModel } from "./payload.js";
|
|
13
|
+
import { chatRequest, modelList, refreshDeviceToken, expiryUnix, userInfo } from "./upstream.js";
|
|
14
|
+
import { invalidateSession } from "./cosy.js";
|
|
15
|
+
import { collectSync, isCreditsExhausted, creditsExhaustedText } from "./sse.js";
|
|
16
|
+
import { transformStream } from "./stream.js";
|
|
17
|
+
import { KNOWN_MODELS, MODELS_CACHE_MS, CHAT_URL, CONTEXT_LENGTH, DEFAULT_MODEL } from "./constants.js";
|
|
18
|
+
|
|
19
|
+
const ID_PREFIX = "globalqwenwork/";
|
|
20
|
+
|
|
21
|
+
function hostOf(url) {
|
|
22
|
+
try { return new URL(String(url)).host; } catch { return "-"; }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function errRes(status, msg, type = "upstream_error", extra = {}) {
|
|
26
|
+
return new Response(JSON.stringify({ error: { message: msg, type } }), {
|
|
27
|
+
status,
|
|
28
|
+
headers: { "Content-Type": "application/json", ...extra },
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function createGlobalQwenworkProvider({
|
|
33
|
+
id = "globalqwenwork",
|
|
34
|
+
apiKeys,
|
|
35
|
+
file,
|
|
36
|
+
fetchImpl,
|
|
37
|
+
cooldownMs = envInt("MSLXDFF_GLOBALQWENWORK_COOLDOWN_MS", 30_000),
|
|
38
|
+
quotaCooldownMs = envInt("MSLXDFF_GLOBALQWENWORK_QUOTA_COOLDOWN_MS", 3600_000),
|
|
39
|
+
connectTimeoutMs = Number(process.env.MSLXDFF_GLOBALQWENWORK_TIMEOUT_MS) || 120_000,
|
|
40
|
+
} = {}) {
|
|
41
|
+
// 单测隔离(MSLXDFF_TEST=1 / NODE_ENV=test / --test 进程):state 与 auth 目录走测试替身,
|
|
42
|
+
// 与你个人真实账号完全隔离(防止单测把真号读进来、把真 refreshToken 写回去)。
|
|
43
|
+
// 教训继承自 qwenwork:构造传了 `apiKeys: []`,门面却从 state.json 读出真号 → 无号测试打了现网。
|
|
44
|
+
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"));
|
|
45
|
+
const keys = (() => {
|
|
46
|
+
if (testIsolated && file === undefined && apiKeys !== undefined) {
|
|
47
|
+
return [...new Set((Array.isArray(apiKeys) ? apiKeys : []).map((k) => String(k).trim()).filter(Boolean))];
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(apiKeys) && apiKeys.length) return [...new Set(apiKeys.map((k) => String(k).trim()).filter(Boolean))];
|
|
50
|
+
try { return loadProviderKeys(id, file ? { file } : {}); } catch { return []; }
|
|
51
|
+
})();
|
|
52
|
+
let authList = [];
|
|
53
|
+
if (!testIsolated) {
|
|
54
|
+
try { authList = loadProviderConfig(id, file ? { file } : {})?.auths || []; } catch {}
|
|
55
|
+
try {
|
|
56
|
+
const docs = listAccountDocs();
|
|
57
|
+
for (const d of docs) {
|
|
58
|
+
const row = authList.find((a) => String(a?.uid) === String(d.uid));
|
|
59
|
+
if (!row) authList.push({ uid: d.uid, refreshToken: d.doc?.auth?.refreshToken || "", name: d.doc?.account?.name || "" });
|
|
60
|
+
}
|
|
61
|
+
} catch {}
|
|
62
|
+
}
|
|
63
|
+
const ring = createKeyRing(keys, { cooldownMs });
|
|
64
|
+
const exhaustedByQuota = new Set();
|
|
65
|
+
if (!fetchImpl) fetchImpl = compatFetch;
|
|
66
|
+
const cdbg = (...a) => { if (process.env.GLOBALQWENWORK_DEBUG === "1") console.log("[globalqwenwork-chat]", ...a); };
|
|
67
|
+
|
|
68
|
+
// blob → 上游 account(含 uid/nickname/email,供 COSY 身份 payload 用)
|
|
69
|
+
function accountFor(key) {
|
|
70
|
+
const blob = accountFromBlob(key);
|
|
71
|
+
if (!blob?.accessToken) return null;
|
|
72
|
+
const auth = authList.find((a) => String(a?.refreshToken || "") === String(blob.refreshToken || "")) || {};
|
|
73
|
+
let doc = null;
|
|
74
|
+
try {
|
|
75
|
+
const docs = listAccountDocs();
|
|
76
|
+
doc = docs.find((d) => String(d.uid) === String(auth.uid)) || docs.find((d) => d.doc?.auth?.refreshToken === blob.refreshToken) || null;
|
|
77
|
+
} catch {}
|
|
78
|
+
return {
|
|
79
|
+
id: auth.uid || doc?.uid || "",
|
|
80
|
+
uid: auth.uid || doc?.uid || "",
|
|
81
|
+
nickname: auth.name || doc?.doc?.account?.name || "",
|
|
82
|
+
email: doc?.doc?.account?.email || "",
|
|
83
|
+
accessToken: blob.accessToken,
|
|
84
|
+
refreshToken: blob.refreshToken || auth.refreshToken || doc?.doc?.auth?.refreshToken || "",
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function withEcho(res, account, upstreamStatus) {
|
|
89
|
+
try {
|
|
90
|
+
res.headers.set("x-mslxdff-upstream", hostOf(CHAT_URL));
|
|
91
|
+
if (account?.uid) res.headers.set("x-mslxdff-globalqwenwork-account", String(account.uid).slice(-8));
|
|
92
|
+
if (upstreamStatus) res.headers.set("x-mslxdff-globalqwenwork-upstream-status", String(upstreamStatus));
|
|
93
|
+
} catch {}
|
|
94
|
+
return res;
|
|
95
|
+
}
|
|
96
|
+
function withQuota(res) {
|
|
97
|
+
try { res.headers.set("x-mslxdff-globalqwenwork-quota", "1"); } catch {}
|
|
98
|
+
return res;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function tryRefresh(account) {
|
|
102
|
+
if (!account?.refreshToken) return false;
|
|
103
|
+
try {
|
|
104
|
+
// 实测 .ai 的 /api/v1/deviceToken/refresh 接受 cn 原形状 {refresh_token}(200,且轮换 refresh_token)
|
|
105
|
+
const data = await refreshDeviceToken(account.refreshToken, fetchImpl);
|
|
106
|
+
const access = data.token || data.device_token;
|
|
107
|
+
const refresh = data.refresh_token || account.refreshToken;
|
|
108
|
+
const expiresAt = expiryUnix(data);
|
|
109
|
+
account.accessToken = access;
|
|
110
|
+
account.refreshToken = refresh;
|
|
111
|
+
try { await updateGlobalQwenworkTokens({ uid: account.uid, accessToken: access, refreshToken: refresh, expiresAt, file }); }
|
|
112
|
+
catch { invalidateSession(account); }
|
|
113
|
+
// 同步 ring 里的 blob(token 轮换后旧 blob 即失效)
|
|
114
|
+
try {
|
|
115
|
+
const oldKey = ring.keys.find((k) => { const b = accountFromBlob(k); return b && b.refreshToken === data.refresh_token; }) || null;
|
|
116
|
+
const newBlob = JSON.stringify({ device_token: access, refresh_token: refresh });
|
|
117
|
+
const cur = ring.keys.find((k) => accountFromBlob(k)?.accessToken === account.accessToken);
|
|
118
|
+
if (cur) ring.replace(cur, newBlob);
|
|
119
|
+
else if (oldKey) ring.replace(oldKey, newBlob);
|
|
120
|
+
} catch {}
|
|
121
|
+
return true;
|
|
122
|
+
} catch (e) {
|
|
123
|
+
cdbg(`[refresh-fail] uid=${String(account.uid).slice(-8)} ${String(e?.message || e).slice(0, 160)}`);
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function chat(body, opts) {
|
|
129
|
+
const stream = body?.stream !== false;
|
|
130
|
+
const wantModel = typeof body?.model === "string" && body.model.startsWith(ID_PREFIX)
|
|
131
|
+
? body.model.slice(ID_PREFIX.length)
|
|
132
|
+
: (body?.model || DEFAULT_MODEL);
|
|
133
|
+
const modelKey = mapModel(wantModel);
|
|
134
|
+
const stripped = { ...body, model: wantModel };
|
|
135
|
+
const total = ring.keys.length;
|
|
136
|
+
// 构造参数无号但 auth 目录有号:不视为"无号",直接按 401 引导 login——调用方先 login 落盘再 chat
|
|
137
|
+
if (!total) {
|
|
138
|
+
return errRes(401, "globalqwenwork: 无可用账号 — 先跑 mslxdff -provider globalqwenwork login", "auth_error");
|
|
139
|
+
}
|
|
140
|
+
let lastRes = null;
|
|
141
|
+
const refreshed = new Set();
|
|
142
|
+
for (let hop = 0; hop <= total; hop++) {
|
|
143
|
+
const key = ring.next();
|
|
144
|
+
if (!key) break;
|
|
145
|
+
if (exhaustedByQuota.has(key)) {
|
|
146
|
+
if (ring.isCooling(key)) {
|
|
147
|
+
if (ring.available() > 0) continue;
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
exhaustedByQuota.delete(key);
|
|
151
|
+
}
|
|
152
|
+
let account = accountFor(key);
|
|
153
|
+
if (!account) { try { ring.onError(key); } catch {} continue; }
|
|
154
|
+
// 身份缺失(手动配 key、未走 login)时补一次 userinfo:COSY 身份 payload 的 uid/name/email 为空
|
|
155
|
+
// 会被上游判 `code 101 Signature invalid`(cn 实测同 token 空身份 403、有身份 200;.ai 同构)。
|
|
156
|
+
if (!account.uid) {
|
|
157
|
+
try {
|
|
158
|
+
const info = await userInfo(account.accessToken, fetchImpl);
|
|
159
|
+
if (info?.id) account.uid = String(info.id);
|
|
160
|
+
if (info?.name) account.nickname = String(info.name);
|
|
161
|
+
if (info?.email) account.email = String(info.email);
|
|
162
|
+
if (account.uid) {
|
|
163
|
+
try {
|
|
164
|
+
const { saveGlobalQwenworkAccount } = await import("./account-store.js");
|
|
165
|
+
await saveGlobalQwenworkAccount({ uid: account.uid, accessToken: account.accessToken, refreshToken: account.refreshToken || "", name: account.nickname || "", email: account.email || "", file });
|
|
166
|
+
} catch {}
|
|
167
|
+
}
|
|
168
|
+
} catch (e) {
|
|
169
|
+
cdbg(`[identity-enrich-fail] ${String(e?.message || e).slice(0, 160)}`);
|
|
170
|
+
}
|
|
171
|
+
if (!account.uid) { try { ring.onError(key); } catch {} lastRes = withEcho(errRes(401, "globalqwenwork: 账号身份缺失且 userinfo 失败,该 key 不可用", "auth_error"), account, 401); continue; }
|
|
172
|
+
}
|
|
173
|
+
const bodyStr = buildBody(stripped, modelKey);
|
|
174
|
+
let upRes;
|
|
175
|
+
try {
|
|
176
|
+
upRes = await chatRequest(account, modelKey, bodyStr, timeoutSignal(connectTimeoutMs), fetchImpl);
|
|
177
|
+
} catch (e) {
|
|
178
|
+
try { ring.onError(key); } catch {}
|
|
179
|
+
lastRes = withEcho(errRes(502, `globalqwenwork: 上游连接失败 ${String(e?.message || e).slice(0, 200)}`), account, 502);
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (!upRes.ok) {
|
|
183
|
+
const text = await upRes.text().catch(() => "");
|
|
184
|
+
const quota = isCreditsExhausted(upRes.status, text);
|
|
185
|
+
if (quota) {
|
|
186
|
+
try { ring.onError(key, quotaCooldownMs); } catch {}
|
|
187
|
+
exhaustedByQuota.add(key);
|
|
188
|
+
lastRes = withQuota(withEcho(errRes(429, `globalqwenwork: 账号积分耗尽 ${text.slice(0, 200)}`, "quota_exhausted"), account, upRes.status));
|
|
189
|
+
if (ring.available() > 0) continue;
|
|
190
|
+
break;
|
|
191
|
+
}
|
|
192
|
+
if ((upRes.status === 401 || upRes.status === 403) && account.refreshToken && !refreshed.has(key)) {
|
|
193
|
+
refreshed.add(key);
|
|
194
|
+
const ok = await tryRefresh(account);
|
|
195
|
+
if (ok) { hop -= 1; continue; }
|
|
196
|
+
try { ring.onError(key); } catch {}
|
|
197
|
+
lastRes = withEcho(errRes(upRes.status, `globalqwenwork: 授权失效 ${text.slice(0, 200)}`, "auth_error"), account, upRes.status);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
try { ring.onError(key); } catch {}
|
|
201
|
+
lastRes = withEcho(errRes(upRes.status >= 500 ? 502 : upRes.status, `globalqwenwork: 上游 ${upRes.status} ${text.slice(0, 200)}`), account, upRes.status);
|
|
202
|
+
if (ring.available() > 0 && (upRes.status === 429 || upRes.status >= 500)) continue;
|
|
203
|
+
return lastRes;
|
|
204
|
+
}
|
|
205
|
+
// 200:流内仍可能裹着业务错(信封 statusCodeValue / code),非流式聚合时由 collectSync 判决;
|
|
206
|
+
// 流式路径照 transform 透传(错误帧由 sse.handleLine 转成流内 error 事件)。
|
|
207
|
+
if (stream) {
|
|
208
|
+
const out = new Response(transformStream(upRes.body, wantModel, () => {}), {
|
|
209
|
+
status: 200,
|
|
210
|
+
headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" },
|
|
211
|
+
});
|
|
212
|
+
return withEcho(out, account, 0);
|
|
213
|
+
}
|
|
214
|
+
const result = await collectSync(upRes.body, wantModel);
|
|
215
|
+
if (result.error) {
|
|
216
|
+
if (creditsExhaustedText(result.error)) {
|
|
217
|
+
try { ring.onError(key, quotaCooldownMs); } catch {}
|
|
218
|
+
exhaustedByQuota.add(key);
|
|
219
|
+
lastRes = withQuota(withEcho(errRes(429, `globalqwenwork: 账号积分耗尽 ${result.error}`, "quota_exhausted"), account, 429));
|
|
220
|
+
if (ring.available() > 0) continue;
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
try { ring.onError(key); } catch {}
|
|
224
|
+
lastRes = withEcho(errRes(502, `globalqwenwork: 上游流内错误 ${result.error}`), account, 502);
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
const completion = result.completion;
|
|
228
|
+
completion.model = wantModel;
|
|
229
|
+
return withEcho(new Response(JSON.stringify(completion), { status: 200, headers: { "Content-Type": "application/json" } }), account, 0);
|
|
230
|
+
}
|
|
231
|
+
if (total > 0 && ring.keys.every((k) => exhaustedByQuota.has(k))) {
|
|
232
|
+
return errRes(429, "globalqwenwork: 所有账号积分已用完,请更换账号或等待额度恢复", "quota_exhausted", { "x-mslxdff-globalqwenwork-quota-exhausted": "1" });
|
|
233
|
+
}
|
|
234
|
+
if (lastRes) return lastRes;
|
|
235
|
+
if (!ring.available()) {
|
|
236
|
+
return errRes(429, "globalqwenwork: 账号暂不可用(上游限流/排队冷却中),请稍后重试", "all_cooling", { "x-mslxdff-globalqwenwork-all-cooling": "1" });
|
|
237
|
+
}
|
|
238
|
+
return errRes(401, "globalqwenwork: 无可用账号 — 先跑 mslxdff -provider globalqwenwork login", "auth_error");
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// 全号聚合:逐号拉 qwork 切片求并集(国际站实测该切片 2 个模型,多号互相印证)
|
|
242
|
+
let cache = null;
|
|
243
|
+
let fetchedAt = 0;
|
|
244
|
+
function eachAccount() {
|
|
245
|
+
const out = [];
|
|
246
|
+
const seen = new Set();
|
|
247
|
+
const push = (key, auth) => {
|
|
248
|
+
const account = accountFor(key);
|
|
249
|
+
if (!account?.accessToken || seen.has(account.accessToken)) return;
|
|
250
|
+
seen.add(account.accessToken);
|
|
251
|
+
out.push(account);
|
|
252
|
+
};
|
|
253
|
+
for (const k of keys) {
|
|
254
|
+
const blob = accountFromBlob(k);
|
|
255
|
+
if (!blob?.accessToken) continue;
|
|
256
|
+
const auth = authList.find((a) => String(a?.refreshToken || "") === String(blob.refreshToken || "")) || {};
|
|
257
|
+
push(k, auth);
|
|
258
|
+
}
|
|
259
|
+
if (!out.length) {
|
|
260
|
+
try {
|
|
261
|
+
for (const { uid, doc } of listAccountDocs()) {
|
|
262
|
+
const a = doc?.auth || {};
|
|
263
|
+
if (!a.accessToken) continue;
|
|
264
|
+
const account = { id: uid, uid, nickname: doc?.account?.name || "", email: doc?.account?.email || "", accessToken: a.accessToken, refreshToken: a.refreshToken || "" };
|
|
265
|
+
if (seen.has(account.accessToken)) continue;
|
|
266
|
+
seen.add(account.accessToken);
|
|
267
|
+
out.push(account);
|
|
268
|
+
}
|
|
269
|
+
} catch {}
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function listModels() {
|
|
275
|
+
const now = Date.now();
|
|
276
|
+
if (cache && now - fetchedAt < MODELS_CACHE_MS) return cache;
|
|
277
|
+
const accounts = eachAccount();
|
|
278
|
+
if (!accounts.length) return [];
|
|
279
|
+
const seen = new Set();
|
|
280
|
+
const out = [];
|
|
281
|
+
for (const account of accounts) {
|
|
282
|
+
try {
|
|
283
|
+
const list = await modelList(account, fetchImpl);
|
|
284
|
+
for (const m of list) {
|
|
285
|
+
if (!m?.key || seen.has(m.key)) continue;
|
|
286
|
+
seen.add(m.key);
|
|
287
|
+
out.push({
|
|
288
|
+
id: joinModelId(id, m.key),
|
|
289
|
+
object: "model",
|
|
290
|
+
created: 1790000000,
|
|
291
|
+
owned_by: "globalqwenwork",
|
|
292
|
+
name: m.name || m.key,
|
|
293
|
+
context_length: m.maxInputTokens || CONTEXT_LENGTH,
|
|
294
|
+
price_factor: m.priceFactor || 0,
|
|
295
|
+
is_reasoning: !!m.isReasoning,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
} catch {}
|
|
299
|
+
}
|
|
300
|
+
if (out.length) { cache = out; fetchedAt = now; }
|
|
301
|
+
// 取数失败时用实测快照兜底(国际站 qwork 切片恒为 2 个,不会空)
|
|
302
|
+
if (!out.length && !cache) {
|
|
303
|
+
return KNOWN_MODELS.map((m) => ({
|
|
304
|
+
id: joinModelId(id, m.key),
|
|
305
|
+
object: "model",
|
|
306
|
+
created: 1790000000,
|
|
307
|
+
owned_by: "globalqwenwork",
|
|
308
|
+
name: m.name,
|
|
309
|
+
context_length: CONTEXT_LENGTH,
|
|
310
|
+
price_factor: m.priceFactor,
|
|
311
|
+
is_reasoning: false,
|
|
312
|
+
}));
|
|
313
|
+
}
|
|
314
|
+
return out.length ? out : (cache || []);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async function preheat() {
|
|
318
|
+
try {
|
|
319
|
+
const list = await listModels();
|
|
320
|
+
return list.length ? { ok: true } : { ok: false, error: "no account" };
|
|
321
|
+
} catch (e) { return { ok: false, error: String(e?.message || e).slice(0, 120) }; }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function close() {}
|
|
325
|
+
async function chatWithKeys(body, keysOverride, opts) {
|
|
326
|
+
const tmp = createGlobalQwenworkProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, quotaCooldownMs, connectTimeoutMs });
|
|
327
|
+
return tmp.chat(body, opts);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
return { id, chat, chatWithKeys, listModels, preheat, close, keyRing: ring, baseUrl: "globalqwenwork://native" };
|
|
331
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// vendor 自 src/providers/qwenwork/payload.js(OpenAI body → agent_chat 请求体)逐字搬;
|
|
2
|
+
// **唯一实质改动 = mapModel 的模型名表**:国际站 qwork 切片是 qwork-auto/qwork-advanced,
|
|
3
|
+
// 与 cn 站的 flash/pro/qwen3.8-max-preview 完全不同池(2026-10-01 现网取证)。
|
|
4
|
+
// 实测通过的字段形状(.ai 真号 200 出词):request_id==request_set_id==chat_record_id、
|
|
5
|
+
// stream 恒 true、system 抽到顶层且不出现在 messages、parameters.max_tokens 默认 32000。
|
|
6
|
+
import { uuid } from "./crypto.js";
|
|
7
|
+
import { DEFAULT_MODEL, BUSINESS_PRODUCT, BUSINESS_TYPE, CONTEXT_LENGTH } from "./constants.js";
|
|
8
|
+
|
|
9
|
+
export function mapModel(name) {
|
|
10
|
+
const m = String(name || "").trim();
|
|
11
|
+
switch (m) {
|
|
12
|
+
case "":
|
|
13
|
+
case "auto":
|
|
14
|
+
case "standard":
|
|
15
|
+
case "lite":
|
|
16
|
+
case "flash":
|
|
17
|
+
case "qwork-auto":
|
|
18
|
+
return "qwork-auto";
|
|
19
|
+
case "advanced":
|
|
20
|
+
case "pro":
|
|
21
|
+
case "max":
|
|
22
|
+
case "qwork-advanced":
|
|
23
|
+
return "qwork-advanced";
|
|
24
|
+
default:
|
|
25
|
+
return m;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function contentText(value) {
|
|
30
|
+
if (typeof value === "string") return value;
|
|
31
|
+
if (Array.isArray(value)) {
|
|
32
|
+
let out = "";
|
|
33
|
+
for (const part of value) {
|
|
34
|
+
if (part && typeof part === "object" && typeof part.text === "string") out += part.text;
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
if (value === null || value === undefined) return "";
|
|
39
|
+
return JSON.stringify(value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function splitMessages(payload) {
|
|
43
|
+
const raw = Array.isArray(payload.messages) ? payload.messages : [];
|
|
44
|
+
const sysParts = [];
|
|
45
|
+
const messages = [];
|
|
46
|
+
let lastUser = "";
|
|
47
|
+
for (const item of raw) {
|
|
48
|
+
if (!item || typeof item !== "object") continue;
|
|
49
|
+
if (item.role === "system") {
|
|
50
|
+
const text = contentText(item.content);
|
|
51
|
+
if (text) sysParts.push(text);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
messages.push(item);
|
|
55
|
+
}
|
|
56
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
57
|
+
const m = messages[i];
|
|
58
|
+
if (m && m.role === "user") {
|
|
59
|
+
lastUser = contentText(m.content);
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return { system: sysParts.join("\n\n"), messages, lastUser };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function buildBody(payload, modelKey) {
|
|
67
|
+
const key = modelKey || DEFAULT_MODEL;
|
|
68
|
+
const requestID = uuid();
|
|
69
|
+
const { system, messages, lastUser: first } = splitMessages(payload);
|
|
70
|
+
let lastUser = first;
|
|
71
|
+
if (!lastUser) {
|
|
72
|
+
for (const m of messages) {
|
|
73
|
+
if (m && m.role === "user") {
|
|
74
|
+
lastUser = contentText(m.content);
|
|
75
|
+
if (lastUser) break;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (!lastUser) lastUser = "ping";
|
|
80
|
+
|
|
81
|
+
const tokenCap = payload.max_completion_tokens !== undefined ? payload.max_completion_tokens : payload.max_tokens;
|
|
82
|
+
const parameters = {};
|
|
83
|
+
for (const k of ["temperature", "top_p", "presence_penalty", "frequency_penalty"]) {
|
|
84
|
+
if (payload[k] !== undefined && payload[k] !== null) parameters[k] = payload[k];
|
|
85
|
+
}
|
|
86
|
+
if (tokenCap !== undefined && tokenCap !== null) {
|
|
87
|
+
const n = Number(tokenCap);
|
|
88
|
+
if (Number.isFinite(n) && n > 0) parameters.max_tokens = Math.floor(n);
|
|
89
|
+
}
|
|
90
|
+
if (parameters.max_tokens === undefined) parameters.max_tokens = 32000;
|
|
91
|
+
|
|
92
|
+
const tools = !(payload.tool_choice === "none") && Array.isArray(payload.tools) ? payload.tools : [];
|
|
93
|
+
// 国际站 qwork 切片两模型均 is_reasoning=false(cn 站为 true),故保持 false 与上游目录一致。
|
|
94
|
+
const isReasoning = false;
|
|
95
|
+
|
|
96
|
+
return JSON.stringify({
|
|
97
|
+
request_id: requestID,
|
|
98
|
+
request_set_id: requestID,
|
|
99
|
+
chat_record_id: requestID,
|
|
100
|
+
session_id: uuid(),
|
|
101
|
+
stream: true,
|
|
102
|
+
chat_task: "FREE_INPUT",
|
|
103
|
+
chat_context: {
|
|
104
|
+
text: lastUser,
|
|
105
|
+
features: [],
|
|
106
|
+
extra: {
|
|
107
|
+
context: [],
|
|
108
|
+
modelConfig: { key, is_reasoning: isReasoning },
|
|
109
|
+
originalContent: lastUser,
|
|
110
|
+
},
|
|
111
|
+
chatPrompt: "",
|
|
112
|
+
imageUrls: null,
|
|
113
|
+
},
|
|
114
|
+
is_reply: true,
|
|
115
|
+
is_retry: false,
|
|
116
|
+
source: 1,
|
|
117
|
+
version: "3",
|
|
118
|
+
agent_id: "agent_common",
|
|
119
|
+
task_id: "common",
|
|
120
|
+
session_type: "qoder_work",
|
|
121
|
+
aliyun_user_type: "",
|
|
122
|
+
model_config: {
|
|
123
|
+
key,
|
|
124
|
+
display_name: key,
|
|
125
|
+
model: "",
|
|
126
|
+
format: "openai",
|
|
127
|
+
is_vl: true,
|
|
128
|
+
is_reasoning: isReasoning,
|
|
129
|
+
api_key: "",
|
|
130
|
+
url: "",
|
|
131
|
+
source: "system",
|
|
132
|
+
max_input_tokens: CONTEXT_LENGTH,
|
|
133
|
+
},
|
|
134
|
+
system,
|
|
135
|
+
messages,
|
|
136
|
+
tools,
|
|
137
|
+
parameters,
|
|
138
|
+
business: {
|
|
139
|
+
product: BUSINESS_PRODUCT,
|
|
140
|
+
type: BUSINESS_TYPE,
|
|
141
|
+
version: "1",
|
|
142
|
+
feature_switches: {},
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// vendor 自 src/providers/qwenwork/crypto.js 的 RSA 段(BigInt modPow + PKCS#1 v1.5 type-2),逐字搬。
|
|
2
|
+
// 模数取 constants.js 的 RSA_MODULUS_HEX(与上游一致,勿改)。
|
|
3
|
+
import { b64, utf8 } from "./crypto.js";
|
|
4
|
+
import { RSA_MODULUS_HEX, RSA_EXPONENT } from "./constants.js";
|
|
5
|
+
|
|
6
|
+
export const RSA_N = BigInt("0x" + RSA_MODULUS_HEX);
|
|
7
|
+
export const RSA_E = BigInt(RSA_EXPONENT);
|
|
8
|
+
|
|
9
|
+
function modPow(base, exp, mod) {
|
|
10
|
+
let result = 1n;
|
|
11
|
+
let b = base % mod;
|
|
12
|
+
let e = exp;
|
|
13
|
+
while (e > 0n) {
|
|
14
|
+
if (e & 1n) result = (result * b) % mod;
|
|
15
|
+
b = (b * b) % mod;
|
|
16
|
+
e >>= 1n;
|
|
17
|
+
}
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function rsaPkcs1Encrypt(data, n = RSA_N, e = RSA_E, k = 128) {
|
|
22
|
+
const psLen = k - data.length - 3;
|
|
23
|
+
if (psLen < 8) throw new Error("rsa: message too long");
|
|
24
|
+
const ps = new Uint8Array(psLen);
|
|
25
|
+
for (;;) {
|
|
26
|
+
crypto.getRandomValues(ps);
|
|
27
|
+
let ok = true;
|
|
28
|
+
for (let i = 0; i < psLen; i++) {
|
|
29
|
+
if (ps[i] === 0) {
|
|
30
|
+
ok = false;
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (ok) break;
|
|
35
|
+
}
|
|
36
|
+
const em = new Uint8Array(k);
|
|
37
|
+
em[0] = 0x00;
|
|
38
|
+
em[1] = 0x02;
|
|
39
|
+
em.set(ps, 2);
|
|
40
|
+
em[2 + psLen] = 0x00;
|
|
41
|
+
em.set(data, 3 + psLen);
|
|
42
|
+
let m = 0n;
|
|
43
|
+
for (let i = 0; i < k; i++) m = (m << 8n) | BigInt(em[i]);
|
|
44
|
+
const c = modPow(m, e, n);
|
|
45
|
+
const out = new Uint8Array(k);
|
|
46
|
+
let v = c;
|
|
47
|
+
for (let i = k - 1; i >= 0; i--) {
|
|
48
|
+
out[i] = Number(v & 0xffn);
|
|
49
|
+
v >>= 8n;
|
|
50
|
+
}
|
|
51
|
+
return b64(out);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export { b64, utf8 };
|
|
55
|
+
|
|
56
|
+
// globalqwenwork 变体:国际站 gateway.qwenwork.ai,协议与 cn 逐字同构(2026-10-01 现网取证),仅命名空间与常量不同 — 见 docs/adr/0041-globalqwenwork-international-provider.md
|