mslxdff 0.1.197 → 0.1.199
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/docs/cli_help_mini.md +146 -0
- package/package.json +1 -1
- package/src/auto.js +254 -254
- 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 +173 -173
- package/src/chat-pipeline/policy.js +84 -84
- package/src/chat-pipeline/serial-trial.js +8 -6
- package/src/cli/commands/group.js +249 -249
- 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 +137 -136
- package/src/cli/commands/provider/models.js +145 -145
- package/src/cli/commands/provider/qwenwork-login.js +119 -119
- package/src/cli/commands/provider/raccoon-login.js +29 -1
- package/src/cli/commands/provider/raccoon-password.js +162 -0
- package/src/cli/commands/sync.js +310 -310
- package/src/cli/status.js +279 -279
- package/src/daemon.js +232 -232
- 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 +225 -225
- package/src/providers/AGENTS.md +49 -0
- 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 +182 -182
- 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 +203 -203
- package/src/providers/qoder/index.js +249 -249
- package/src/providers/qoder/sse.js +145 -145
- 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 +25 -0
- package/src/providers/raccoon/password-login.js +87 -0
- package/src/providers/registry.js +79 -79
- package/src/providers/workbuddy/chat.js +264 -264
- package/src/providers/workbuddy/reshape.js +152 -152
- package/src/providers/workbuddy.js +2 -2
- package/src/reasoning.js +32 -32
- package/src/routes/AGENTS.md +37 -0
- 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 +146 -146
- package/src/routes/hedge.js +260 -260
- package/src/routes/models-route.js +167 -167
- package/src/routes/peers.js +335 -335
- package/src/routes/stream.js +347 -347
- package/src/runtime/bootstrap.js +67 -67
- package/src/runtime/provider-gate.js +36 -36
- package/src/runtime/providers-setup.js +168 -168
- package/src/server.js +78 -78
- 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 +293 -293
|
@@ -1,182 +1,182 @@
|
|
|
1
|
-
// CodeArts 聊天服务:上游 body/头组装 + SDK-HMAC-SHA256 签名 + 401 刷新重试 + 环形切号。
|
|
2
|
-
// 上游恒 stream:true(chatBodyV2 契约);流式客户端转 OpenAI SSE,非流式聚合回 JSON。
|
|
3
|
-
import crypto from "node:crypto";
|
|
4
|
-
import { joinUrl } from "../base.js";
|
|
5
|
-
import { createTransport } from "../../transport/index.js";
|
|
6
|
-
import { SNAP_BASE, EP_CHAT_V2, chatBaseHeaders, MAAS_TYPE_HEADER, MAAS_BENEFIT, MAX_TOKENS_CEILING } from "./const.js";
|
|
7
|
-
import { signRequest } from "./sign.js";
|
|
8
|
-
import { newChatId, preflightResponse, sseToOpenAIResponse, aggregateToCompletion, UpstreamEventError } from "./stream.js";
|
|
9
|
-
|
|
10
|
-
const MODEL_RULES = [
|
|
11
|
-
{ match: (m) => String(m || "").toLowerCase().includes("deepseek"), scope: "all" },
|
|
12
|
-
{ match: (m) => /(^kimi-|kimi)/i.test(String(m || "")), scope: "toolCalls" },
|
|
13
|
-
];
|
|
14
|
-
|
|
15
|
-
// DeepSeek 系思考模式要求 assistant 消息回传 reasoning_content,缺失补 " " 占位(ADR-0001 同款)。
|
|
16
|
-
export function injectReasoningPlaceholder(messages, model) {
|
|
17
|
-
const rule = MODEL_RULES.find((r) => r.match(model));
|
|
18
|
-
if (!rule || !Array.isArray(messages)) return messages;
|
|
19
|
-
return messages.map((m) => {
|
|
20
|
-
if (m?.role !== "assistant") return m;
|
|
21
|
-
if (typeof m.reasoning_content === "string" && m.reasoning_content.length) return m;
|
|
22
|
-
if (rule.scope === "toolCalls" && !(Array.isArray(m.tool_calls) && m.tool_calls.length)) return m;
|
|
23
|
-
return { ...m, reasoning_content: " " };
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const PASSTHROUGH_KEYS = ["temperature", "top_p", "max_tokens", "max_completion_tokens", "reasoning_effort", "tools", "tool_choice", "stop", "presence_penalty", "frequency_penalty", "response_format", "user", "n", "seed"];
|
|
28
|
-
|
|
29
|
-
export function buildUpstreamBody(body, { chatId, upstreamModel }) {
|
|
30
|
-
const out = {
|
|
31
|
-
model: upstreamModel,
|
|
32
|
-
stream: true, // v2 端点契约:恒流式,非流式由本层聚合
|
|
33
|
-
messages: injectReasoningPlaceholder(body?.messages || [], upstreamModel),
|
|
34
|
-
prompt_cache_key: chatId,
|
|
35
|
-
tool_stream: true,
|
|
36
|
-
chat_id: chatId,
|
|
37
|
-
};
|
|
38
|
-
for (const k of PASSTHROUGH_KEYS) {
|
|
39
|
-
if (k === "max_completion_tokens") continue; // v2 端点不认这个名字(透传 → InferHub.001001005.400,2026-10-16 现网 A/B 复现)
|
|
40
|
-
if (body?.[k] !== undefined && body?.[k] !== null) out[k] = body[k];
|
|
41
|
-
}
|
|
42
|
-
// Responses 风格客户端只发 max_completion_tokens:映射成 v2 认的 max_tokens(显式 max_tokens 优先)
|
|
43
|
-
if (out.max_tokens === undefined && body?.max_completion_tokens != null) out.max_tokens = body.max_completion_tokens;
|
|
44
|
-
// 超上限的 max_tokens 上游一律回 InferHub.001001005.400(参数非法),在这里夹住(env 可放宽)
|
|
45
|
-
const ceiling = Number.parseInt(process.env.MSLXDFF_CODEARTS_MAX_TOKENS_CEILING ?? "", 10) || MAX_TOKENS_CEILING;
|
|
46
|
-
if (typeof out.max_tokens === "number" && out.max_tokens > ceiling) out.max_tokens = ceiling;
|
|
47
|
-
return out;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Session-Id:由 chatId 派生的稳定会话标识(prompt cache 亲和,对齐 Go sessionIDFor)。
|
|
51
|
-
function sessionIdFor(chatId) {
|
|
52
|
-
return crypto.createHash("sha256").update(`codearts-session:${chatId}`, "utf8").digest("hex").slice(0, 32);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function stripOwnPrefix(model, providerId) {
|
|
56
|
-
const s = String(model || "");
|
|
57
|
-
const i = s.indexOf("/");
|
|
58
|
-
if (i <= 0) return s;
|
|
59
|
-
return s.slice(0, i).toLowerCase() === String(providerId || "").toLowerCase() ? s.slice(i + 1) : s;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export function createChatService({
|
|
63
|
-
id = "codearts",
|
|
64
|
-
baseUrl = SNAP_BASE,
|
|
65
|
-
chatPath = EP_CHAT_V2,
|
|
66
|
-
fetchImpl,
|
|
67
|
-
dispatcher,
|
|
68
|
-
authPool,
|
|
69
|
-
catalog,
|
|
70
|
-
connectTimeoutMs = 30_000,
|
|
71
|
-
clock = Date.now,
|
|
72
|
-
} = {}) {
|
|
73
|
-
const resolvedBase = String(baseUrl).trim().replace(/\/+$/, "") || SNAP_BASE;
|
|
74
|
-
const transport = createTransport({ fetchImpl, dispatcher, keepAlive: !!dispatcher, timeoutMs: connectTimeoutMs, retry: {} });
|
|
75
|
-
|
|
76
|
-
async function sendOnce({ bodyStr, account, benefit, chatId, sessionId, traceId }) {
|
|
77
|
-
const url = joinUrl(resolvedBase, chatPath);
|
|
78
|
-
const h = chatBaseHeaders(account.securityToken, traceId);
|
|
79
|
-
if (benefit) h[MAAS_TYPE_HEADER] = MAAS_BENEFIT;
|
|
80
|
-
const { headers } = signRequest({ method: "POST", url, headers: h, body: bodyStr, cred: account });
|
|
81
|
-
// Chat-Id / Session-Id 在签名之后追加(对齐官方客户端:不进 SignedHeaders)。
|
|
82
|
-
headers["chat-id"] = chatId;
|
|
83
|
-
headers["session-id"] = sessionId;
|
|
84
|
-
return transport.request({ url, method: "POST", headers, body: bodyStr, stream: true, timeoutMs: connectTimeoutMs });
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function errRes(status, msg, code) {
|
|
88
|
-
return new Response(JSON.stringify({ error: { message: msg, type: "upstream_error", ...(code ? { code } : {}) } }), {
|
|
89
|
-
status,
|
|
90
|
-
headers: { "Content-Type": "application/json" },
|
|
91
|
-
});
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function withTiming(res, t0) {
|
|
95
|
-
try { res._t = { attempts: [], waitMs: 0, totalMs: Math.round(clock() - t0) }; } catch {}
|
|
96
|
-
return res;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* 跑一次对话。body.model 已由 dispatcher 剥前缀(容忍自带前缀)。
|
|
101
|
-
* @returns {Promise<Response>} 流式 → OpenAI SSE;非流式 → chat.completion JSON
|
|
102
|
-
*/
|
|
103
|
-
async function runChat(body, activeRing, opts = {}) {
|
|
104
|
-
const t0 = clock();
|
|
105
|
-
const requestedModel = String(body?.model || "");
|
|
106
|
-
const rawModel = stripOwnPrefix(requestedModel, id);
|
|
107
|
-
const upstreamModel = catalog?.canonical(rawModel) || rawModel;
|
|
108
|
-
const chatId = newChatId(body, opts);
|
|
109
|
-
const sessionId = sessionIdFor(chatId);
|
|
110
|
-
const upstreamBody = buildUpstreamBody(body, { chatId, upstreamModel });
|
|
111
|
-
const bodyStr = JSON.stringify(upstreamBody);
|
|
112
|
-
const isStream = body?.stream === true;
|
|
113
|
-
let lastErr = null;
|
|
114
|
-
|
|
115
|
-
const maxTries = Math.max(1, activeRing.size || 1);
|
|
116
|
-
for (let attempt = 0; attempt < maxTries; attempt++) {
|
|
117
|
-
const blob = activeRing.next();
|
|
118
|
-
if (!blob) break;
|
|
119
|
-
let account;
|
|
120
|
-
try {
|
|
121
|
-
account = await authPool.getCredential(blob);
|
|
122
|
-
} catch (err) {
|
|
123
|
-
try { activeRing.onError(blob); } catch {}
|
|
124
|
-
lastErr = err;
|
|
125
|
-
continue; // 死号/不在池:换下一个账号
|
|
126
|
-
}
|
|
127
|
-
const benefit = catalog?.isBenefit ? catalog.isBenefit(account.userId, upstreamModel) : false;
|
|
128
|
-
const traceId = crypto.randomBytes(8).toString("hex") + String(clock());
|
|
129
|
-
let res;
|
|
130
|
-
try {
|
|
131
|
-
res = await sendOnce({ bodyStr, account, benefit, chatId, sessionId, traceId });
|
|
132
|
-
} catch (err) {
|
|
133
|
-
try { activeRing.onError(blob); } catch {}
|
|
134
|
-
lastErr = err;
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
if (res.status === 401 || res.status === 403) {
|
|
138
|
-
// STS 临时凭证失效:强制刷新重试一次,仍 401/403 换号
|
|
139
|
-
authPool.invalidate(blob);
|
|
140
|
-
let account2 = null;
|
|
141
|
-
try { account2 = await authPool.getCredential(blob); } catch { /* 死号 → 换号 */ }
|
|
142
|
-
if (account2) {
|
|
143
|
-
const traceId2 = crypto.randomBytes(8).toString("hex") + String(clock());
|
|
144
|
-
try { res = await sendOnce({ bodyStr, account: account2, benefit, chatId, sessionId, traceId: traceId2 }); } catch (err2) { lastErr = err2; try { activeRing.onError(blob); } catch {} continue; }
|
|
145
|
-
if (res.status === 401 || res.status === 403) {
|
|
146
|
-
try { await res.text(); } catch {}
|
|
147
|
-
try { activeRing.onError(blob); } catch {}
|
|
148
|
-
lastErr = new Error(`codearts auth still failing after refresh (http ${res.status})`);
|
|
149
|
-
continue;
|
|
150
|
-
}
|
|
151
|
-
} else {
|
|
152
|
-
try { activeRing.onError(blob); } catch {}
|
|
153
|
-
continue;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
if (res.status >= 400) {
|
|
157
|
-
const txt = await res.text().catch(() => "");
|
|
158
|
-
if (res.status === 429 || res.status >= 500) try { activeRing.onError(blob); } catch {}
|
|
159
|
-
return withTiming(errRes(res.status, `codearts upstream http ${res.status}: ${String(txt).slice(0, 300)}`), t0);
|
|
160
|
-
}
|
|
161
|
-
try {
|
|
162
|
-
const pre = await preflightResponse(res); // HTTP 200 内嵌错误(排队/未注册/福利未领)→ 抛 UpstreamEventError
|
|
163
|
-
if (isStream) return withTiming(sseToOpenAIResponse(pre, { model: requestedModel || upstreamModel, id: `chatcmpl-${chatId.slice(0, 12)}` }), t0);
|
|
164
|
-
const data = await aggregateToCompletion(pre, { model: requestedModel || upstreamModel, id: `chatcmpl-${chatId.slice(0, 12)}` });
|
|
165
|
-
return withTiming(new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" } }), t0);
|
|
166
|
-
} catch (err) {
|
|
167
|
-
if (err instanceof UpstreamEventError) {
|
|
168
|
-
if (err.status === 429 || err.status >= 500) try { activeRing.onError(blob); } catch {}
|
|
169
|
-
return withTiming(errRes(err.status, `codearts upstream: ${err.message}`, err.code), t0);
|
|
170
|
-
}
|
|
171
|
-
try { activeRing.onError(blob); } catch {}
|
|
172
|
-
lastErr = err;
|
|
173
|
-
continue;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
throw Object.assign(lastErr || new Error("codearts: all accounts unavailable"), {
|
|
177
|
-
_t: { attempts: [], waitMs: 0, totalMs: Math.round(clock() - t0) },
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
return { runChat, buildUpstreamBody, injectReasoningPlaceholder, _sendOnce: sendOnce };
|
|
182
|
-
}
|
|
1
|
+
// CodeArts 聊天服务:上游 body/头组装 + SDK-HMAC-SHA256 签名 + 401 刷新重试 + 环形切号。
|
|
2
|
+
// 上游恒 stream:true(chatBodyV2 契约);流式客户端转 OpenAI SSE,非流式聚合回 JSON。
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import { joinUrl } from "../base.js";
|
|
5
|
+
import { createTransport } from "../../transport/index.js";
|
|
6
|
+
import { SNAP_BASE, EP_CHAT_V2, chatBaseHeaders, MAAS_TYPE_HEADER, MAAS_BENEFIT, MAX_TOKENS_CEILING } from "./const.js";
|
|
7
|
+
import { signRequest } from "./sign.js";
|
|
8
|
+
import { newChatId, preflightResponse, sseToOpenAIResponse, aggregateToCompletion, UpstreamEventError } from "./stream.js";
|
|
9
|
+
|
|
10
|
+
const MODEL_RULES = [
|
|
11
|
+
{ match: (m) => String(m || "").toLowerCase().includes("deepseek"), scope: "all" },
|
|
12
|
+
{ match: (m) => /(^kimi-|kimi)/i.test(String(m || "")), scope: "toolCalls" },
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
// DeepSeek 系思考模式要求 assistant 消息回传 reasoning_content,缺失补 " " 占位(ADR-0001 同款)。
|
|
16
|
+
export function injectReasoningPlaceholder(messages, model) {
|
|
17
|
+
const rule = MODEL_RULES.find((r) => r.match(model));
|
|
18
|
+
if (!rule || !Array.isArray(messages)) return messages;
|
|
19
|
+
return messages.map((m) => {
|
|
20
|
+
if (m?.role !== "assistant") return m;
|
|
21
|
+
if (typeof m.reasoning_content === "string" && m.reasoning_content.length) return m;
|
|
22
|
+
if (rule.scope === "toolCalls" && !(Array.isArray(m.tool_calls) && m.tool_calls.length)) return m;
|
|
23
|
+
return { ...m, reasoning_content: " " };
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const PASSTHROUGH_KEYS = ["temperature", "top_p", "max_tokens", "max_completion_tokens", "reasoning_effort", "tools", "tool_choice", "stop", "presence_penalty", "frequency_penalty", "response_format", "user", "n", "seed"];
|
|
28
|
+
|
|
29
|
+
export function buildUpstreamBody(body, { chatId, upstreamModel }) {
|
|
30
|
+
const out = {
|
|
31
|
+
model: upstreamModel,
|
|
32
|
+
stream: true, // v2 端点契约:恒流式,非流式由本层聚合
|
|
33
|
+
messages: injectReasoningPlaceholder(body?.messages || [], upstreamModel),
|
|
34
|
+
prompt_cache_key: chatId,
|
|
35
|
+
tool_stream: true,
|
|
36
|
+
chat_id: chatId,
|
|
37
|
+
};
|
|
38
|
+
for (const k of PASSTHROUGH_KEYS) {
|
|
39
|
+
if (k === "max_completion_tokens") continue; // v2 端点不认这个名字(透传 → InferHub.001001005.400,2026-10-16 现网 A/B 复现)
|
|
40
|
+
if (body?.[k] !== undefined && body?.[k] !== null) out[k] = body[k];
|
|
41
|
+
}
|
|
42
|
+
// Responses 风格客户端只发 max_completion_tokens:映射成 v2 认的 max_tokens(显式 max_tokens 优先)
|
|
43
|
+
if (out.max_tokens === undefined && body?.max_completion_tokens != null) out.max_tokens = body.max_completion_tokens;
|
|
44
|
+
// 超上限的 max_tokens 上游一律回 InferHub.001001005.400(参数非法),在这里夹住(env 可放宽)
|
|
45
|
+
const ceiling = Number.parseInt(process.env.MSLXDFF_CODEARTS_MAX_TOKENS_CEILING ?? "", 10) || MAX_TOKENS_CEILING;
|
|
46
|
+
if (typeof out.max_tokens === "number" && out.max_tokens > ceiling) out.max_tokens = ceiling;
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Session-Id:由 chatId 派生的稳定会话标识(prompt cache 亲和,对齐 Go sessionIDFor)。
|
|
51
|
+
function sessionIdFor(chatId) {
|
|
52
|
+
return crypto.createHash("sha256").update(`codearts-session:${chatId}`, "utf8").digest("hex").slice(0, 32);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function stripOwnPrefix(model, providerId) {
|
|
56
|
+
const s = String(model || "");
|
|
57
|
+
const i = s.indexOf("/");
|
|
58
|
+
if (i <= 0) return s;
|
|
59
|
+
return s.slice(0, i).toLowerCase() === String(providerId || "").toLowerCase() ? s.slice(i + 1) : s;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function createChatService({
|
|
63
|
+
id = "codearts",
|
|
64
|
+
baseUrl = SNAP_BASE,
|
|
65
|
+
chatPath = EP_CHAT_V2,
|
|
66
|
+
fetchImpl,
|
|
67
|
+
dispatcher,
|
|
68
|
+
authPool,
|
|
69
|
+
catalog,
|
|
70
|
+
connectTimeoutMs = 30_000,
|
|
71
|
+
clock = Date.now,
|
|
72
|
+
} = {}) {
|
|
73
|
+
const resolvedBase = String(baseUrl).trim().replace(/\/+$/, "") || SNAP_BASE;
|
|
74
|
+
const transport = createTransport({ fetchImpl, dispatcher, keepAlive: !!dispatcher, timeoutMs: connectTimeoutMs, retry: {} });
|
|
75
|
+
|
|
76
|
+
async function sendOnce({ bodyStr, account, benefit, chatId, sessionId, traceId }) {
|
|
77
|
+
const url = joinUrl(resolvedBase, chatPath);
|
|
78
|
+
const h = chatBaseHeaders(account.securityToken, traceId);
|
|
79
|
+
if (benefit) h[MAAS_TYPE_HEADER] = MAAS_BENEFIT;
|
|
80
|
+
const { headers } = signRequest({ method: "POST", url, headers: h, body: bodyStr, cred: account });
|
|
81
|
+
// Chat-Id / Session-Id 在签名之后追加(对齐官方客户端:不进 SignedHeaders)。
|
|
82
|
+
headers["chat-id"] = chatId;
|
|
83
|
+
headers["session-id"] = sessionId;
|
|
84
|
+
return transport.request({ url, method: "POST", headers, body: bodyStr, stream: true, timeoutMs: connectTimeoutMs });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function errRes(status, msg, code) {
|
|
88
|
+
return new Response(JSON.stringify({ error: { message: msg, type: "upstream_error", ...(code ? { code } : {}) } }), {
|
|
89
|
+
status,
|
|
90
|
+
headers: { "Content-Type": "application/json" },
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function withTiming(res, t0) {
|
|
95
|
+
try { res._t = { attempts: [], waitMs: 0, totalMs: Math.round(clock() - t0) }; } catch {}
|
|
96
|
+
return res;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 跑一次对话。body.model 已由 dispatcher 剥前缀(容忍自带前缀)。
|
|
101
|
+
* @returns {Promise<Response>} 流式 → OpenAI SSE;非流式 → chat.completion JSON
|
|
102
|
+
*/
|
|
103
|
+
async function runChat(body, activeRing, opts = {}) {
|
|
104
|
+
const t0 = clock();
|
|
105
|
+
const requestedModel = String(body?.model || "");
|
|
106
|
+
const rawModel = stripOwnPrefix(requestedModel, id);
|
|
107
|
+
const upstreamModel = catalog?.canonical(rawModel) || rawModel;
|
|
108
|
+
const chatId = newChatId(body, opts);
|
|
109
|
+
const sessionId = sessionIdFor(chatId);
|
|
110
|
+
const upstreamBody = buildUpstreamBody(body, { chatId, upstreamModel });
|
|
111
|
+
const bodyStr = JSON.stringify(upstreamBody);
|
|
112
|
+
const isStream = body?.stream === true;
|
|
113
|
+
let lastErr = null;
|
|
114
|
+
|
|
115
|
+
const maxTries = Math.max(1, activeRing.size || 1);
|
|
116
|
+
for (let attempt = 0; attempt < maxTries; attempt++) {
|
|
117
|
+
const blob = activeRing.next();
|
|
118
|
+
if (!blob) break;
|
|
119
|
+
let account;
|
|
120
|
+
try {
|
|
121
|
+
account = await authPool.getCredential(blob);
|
|
122
|
+
} catch (err) {
|
|
123
|
+
try { activeRing.onError(blob); } catch {}
|
|
124
|
+
lastErr = err;
|
|
125
|
+
continue; // 死号/不在池:换下一个账号
|
|
126
|
+
}
|
|
127
|
+
const benefit = catalog?.isBenefit ? catalog.isBenefit(account.userId, upstreamModel) : false;
|
|
128
|
+
const traceId = crypto.randomBytes(8).toString("hex") + String(clock());
|
|
129
|
+
let res;
|
|
130
|
+
try {
|
|
131
|
+
res = await sendOnce({ bodyStr, account, benefit, chatId, sessionId, traceId });
|
|
132
|
+
} catch (err) {
|
|
133
|
+
try { activeRing.onError(blob); } catch {}
|
|
134
|
+
lastErr = err;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (res.status === 401 || res.status === 403) {
|
|
138
|
+
// STS 临时凭证失效:强制刷新重试一次,仍 401/403 换号
|
|
139
|
+
authPool.invalidate(blob);
|
|
140
|
+
let account2 = null;
|
|
141
|
+
try { account2 = await authPool.getCredential(blob); } catch { /* 死号 → 换号 */ }
|
|
142
|
+
if (account2) {
|
|
143
|
+
const traceId2 = crypto.randomBytes(8).toString("hex") + String(clock());
|
|
144
|
+
try { res = await sendOnce({ bodyStr, account: account2, benefit, chatId, sessionId, traceId: traceId2 }); } catch (err2) { lastErr = err2; try { activeRing.onError(blob); } catch {} continue; }
|
|
145
|
+
if (res.status === 401 || res.status === 403) {
|
|
146
|
+
try { await res.text(); } catch {}
|
|
147
|
+
try { activeRing.onError(blob); } catch {}
|
|
148
|
+
lastErr = new Error(`codearts auth still failing after refresh (http ${res.status})`);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
} else {
|
|
152
|
+
try { activeRing.onError(blob); } catch {}
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (res.status >= 400) {
|
|
157
|
+
const txt = await res.text().catch(() => "");
|
|
158
|
+
if (res.status === 429 || res.status >= 500) try { activeRing.onError(blob); } catch {}
|
|
159
|
+
return withTiming(errRes(res.status, `codearts upstream http ${res.status}: ${String(txt).slice(0, 300)}`), t0);
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
const pre = await preflightResponse(res); // HTTP 200 内嵌错误(排队/未注册/福利未领)→ 抛 UpstreamEventError
|
|
163
|
+
if (isStream) return withTiming(sseToOpenAIResponse(pre, { model: requestedModel || upstreamModel, id: `chatcmpl-${chatId.slice(0, 12)}` }), t0);
|
|
164
|
+
const data = await aggregateToCompletion(pre, { model: requestedModel || upstreamModel, id: `chatcmpl-${chatId.slice(0, 12)}` });
|
|
165
|
+
return withTiming(new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" } }), t0);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
if (err instanceof UpstreamEventError) {
|
|
168
|
+
if (err.status === 429 || err.status >= 500) try { activeRing.onError(blob); } catch {}
|
|
169
|
+
return withTiming(errRes(err.status, `codearts upstream: ${err.message}`, err.code), t0);
|
|
170
|
+
}
|
|
171
|
+
try { activeRing.onError(blob); } catch {}
|
|
172
|
+
lastErr = err;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
throw Object.assign(lastErr || new Error("codearts: all accounts unavailable"), {
|
|
177
|
+
_t: { attempts: [], waitMs: 0, totalMs: Math.round(clock() - t0) },
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return { runChat, buildUpstreamBody, injectReasoningPlaceholder, _sendOnce: sendOnce };
|
|
182
|
+
}
|
|
@@ -1,123 +1,123 @@
|
|
|
1
|
-
// cosy.js(COSY 会话 + 签名头)— vendor 自 src/providers/qwenwork/cosy.js 逐字搬;
|
|
2
|
-
// 本目录 import 全为相对路径,自动绑定本目录 constants/crypto/rsa。线上头 x-qwenwork-* 与 cn 同名,**禁止改名**(实测 .ai 接受)。
|
|
3
|
-
// 关键不变式(改动即 403):
|
|
4
|
-
// · identity/payload 都必须 key 升序紧凑 JSON(sortedCompact)
|
|
5
|
-
// · 签名 = md5(payloadB64 \n cosyKey \n date \n body \n pathSig),pathSig 去 /algo 前缀、不含 query
|
|
6
|
-
// · authorization = `Bearer COSY.${payloadB64}.${sig}`;payloadB64 是**标准 base64(带 padding)**
|
|
7
|
-
// · 同一 requestId 重放会被上游判 `code 103 Duplicate request`
|
|
8
|
-
import { uuid, b64, b64url, utf8, aesCbcEncrypt, md5 } from "./crypto.js";
|
|
9
|
-
import { rsaPkcs1Encrypt } from "./rsa.js";
|
|
10
|
-
import {
|
|
11
|
-
COSY_VERSION, IDE_VERSION, RELEASE_VERSION, BUILD, CLIENT_TYPE,
|
|
12
|
-
BUSINESS_PRODUCT, BUSINESS_TYPE, SCENE, MACHINE_OS, UA,
|
|
13
|
-
} from "./constants.js";
|
|
14
|
-
|
|
15
|
-
const cache = new Map();
|
|
16
|
-
|
|
17
|
-
function sortedCompact(obj) {
|
|
18
|
-
const keys = Object.keys(obj).sort();
|
|
19
|
-
let out = "{";
|
|
20
|
-
for (let i = 0; i < keys.length; i++) {
|
|
21
|
-
if (i > 0) out += ",";
|
|
22
|
-
out += JSON.stringify(keys[i]) + ":" + JSON.stringify(obj[keys[i]]);
|
|
23
|
-
}
|
|
24
|
-
return out + "}";
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function newSession(account) {
|
|
28
|
-
const machineID = uuid();
|
|
29
|
-
const seed = (uuid() + uuid()).slice(0, 50);
|
|
30
|
-
const machineToken = b64url(utf8(seed));
|
|
31
|
-
const machineType = uuid().replace(/-/g, "").slice(0, 18);
|
|
32
|
-
const tempKey = uuid().replace(/-/g, "").slice(0, 16);
|
|
33
|
-
|
|
34
|
-
const identity = sortedCompact({
|
|
35
|
-
uid: account.uid || "",
|
|
36
|
-
aid: account.uid || "",
|
|
37
|
-
name: account.nickname || "",
|
|
38
|
-
email: account.email || "",
|
|
39
|
-
security_oauth_token: account.accessToken,
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
return {
|
|
43
|
-
machineID,
|
|
44
|
-
machineToken,
|
|
45
|
-
machineType,
|
|
46
|
-
tempKey,
|
|
47
|
-
cosyKey: rsaPkcs1Encrypt(utf8(tempKey)),
|
|
48
|
-
info: b64(aesCbcEncrypt(utf8(identity), utf8(tempKey))),
|
|
49
|
-
accessToken: account.accessToken,
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export function sessionFor(account) {
|
|
54
|
-
if (!account || !account.accessToken) throw new Error("cosy: empty access token");
|
|
55
|
-
const key = account.id || account.uid || account.accessToken.slice(0, 16);
|
|
56
|
-
const hit = cache.get(key);
|
|
57
|
-
if (hit && hit.accessToken === account.accessToken) return hit;
|
|
58
|
-
if (cache.size > 128) cache.clear();
|
|
59
|
-
const sess = newSession(account);
|
|
60
|
-
cache.set(key, sess);
|
|
61
|
-
return sess;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export function invalidateSession(account) {
|
|
65
|
-
const key = account && (account.id || account.uid);
|
|
66
|
-
if (key) cache.delete(key);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function pathSig(rawURL) {
|
|
70
|
-
const u = new URL(rawURL);
|
|
71
|
-
let p = u.pathname;
|
|
72
|
-
if (p.startsWith("/algo")) p = p.slice("/algo".length);
|
|
73
|
-
return p;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export function signHeaders(account, body, rawURL, modelKey, accept) {
|
|
77
|
-
const sess = sessionFor(account);
|
|
78
|
-
const payload = sortedCompact({
|
|
79
|
-
cosyVersion: COSY_VERSION,
|
|
80
|
-
ideVersion: IDE_VERSION,
|
|
81
|
-
info: sess.info,
|
|
82
|
-
requestId: uuid(),
|
|
83
|
-
version: "v1",
|
|
84
|
-
});
|
|
85
|
-
const payloadB64 = b64(utf8(payload));
|
|
86
|
-
const date = Math.floor(Date.now() / 1000).toString();
|
|
87
|
-
const sig = md5(`${payloadB64}\n${sess.cosyKey}\n${date}\n${body}\n${pathSig(rawURL)}`);
|
|
88
|
-
|
|
89
|
-
const headers = {
|
|
90
|
-
accept: accept || "text/event-stream",
|
|
91
|
-
"content-type": "application/json",
|
|
92
|
-
"user-agent": UA,
|
|
93
|
-
"x-request-id": uuid(),
|
|
94
|
-
"x-qwenwork-version": IDE_VERSION,
|
|
95
|
-
"x-qwenwork-release-version": RELEASE_VERSION,
|
|
96
|
-
"x-qwenwork-build": BUILD,
|
|
97
|
-
"x-qwenwork-platform": "win32",
|
|
98
|
-
"x-qwenwork-arch": "x64",
|
|
99
|
-
"x-qwenwork-channel": "stable",
|
|
100
|
-
"cosy-version": COSY_VERSION,
|
|
101
|
-
"cosy-clienttype": CLIENT_TYPE,
|
|
102
|
-
"cosy-business-product": BUSINESS_PRODUCT,
|
|
103
|
-
"cosy-business-type": BUSINESS_TYPE,
|
|
104
|
-
"cosy-scene": SCENE,
|
|
105
|
-
"cosy-machineos": MACHINE_OS,
|
|
106
|
-
"login-version": "v2",
|
|
107
|
-
authorization: `Bearer COSY.${payloadB64}.${sig}`,
|
|
108
|
-
"cosy-key": sess.cosyKey,
|
|
109
|
-
"cosy-user": account.uid || "",
|
|
110
|
-
"cosy-date": date,
|
|
111
|
-
"cosy-machineid": sess.machineID,
|
|
112
|
-
"accept-encoding": "identity",
|
|
113
|
-
connection: "keep-alive",
|
|
114
|
-
"cache-control": "no-cache",
|
|
115
|
-
};
|
|
116
|
-
if (modelKey) {
|
|
117
|
-
headers["x-model-key"] = modelKey;
|
|
118
|
-
headers["x-model-source"] = "system";
|
|
119
|
-
}
|
|
120
|
-
return headers;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// globalqwenwork 变体(国际站 gateway.qwenwork.ai):协议与 cn 逐字同构,2026-10-01 现网实测签名/请求 200 — 见 docs/adr/0041-globalqwenwork-international-provider.md
|
|
1
|
+
// cosy.js(COSY 会话 + 签名头)— vendor 自 src/providers/qwenwork/cosy.js 逐字搬;
|
|
2
|
+
// 本目录 import 全为相对路径,自动绑定本目录 constants/crypto/rsa。线上头 x-qwenwork-* 与 cn 同名,**禁止改名**(实测 .ai 接受)。
|
|
3
|
+
// 关键不变式(改动即 403):
|
|
4
|
+
// · identity/payload 都必须 key 升序紧凑 JSON(sortedCompact)
|
|
5
|
+
// · 签名 = md5(payloadB64 \n cosyKey \n date \n body \n pathSig),pathSig 去 /algo 前缀、不含 query
|
|
6
|
+
// · authorization = `Bearer COSY.${payloadB64}.${sig}`;payloadB64 是**标准 base64(带 padding)**
|
|
7
|
+
// · 同一 requestId 重放会被上游判 `code 103 Duplicate request`
|
|
8
|
+
import { uuid, b64, b64url, utf8, aesCbcEncrypt, md5 } from "./crypto.js";
|
|
9
|
+
import { rsaPkcs1Encrypt } from "./rsa.js";
|
|
10
|
+
import {
|
|
11
|
+
COSY_VERSION, IDE_VERSION, RELEASE_VERSION, BUILD, CLIENT_TYPE,
|
|
12
|
+
BUSINESS_PRODUCT, BUSINESS_TYPE, SCENE, MACHINE_OS, UA,
|
|
13
|
+
} from "./constants.js";
|
|
14
|
+
|
|
15
|
+
const cache = new Map();
|
|
16
|
+
|
|
17
|
+
function sortedCompact(obj) {
|
|
18
|
+
const keys = Object.keys(obj).sort();
|
|
19
|
+
let out = "{";
|
|
20
|
+
for (let i = 0; i < keys.length; i++) {
|
|
21
|
+
if (i > 0) out += ",";
|
|
22
|
+
out += JSON.stringify(keys[i]) + ":" + JSON.stringify(obj[keys[i]]);
|
|
23
|
+
}
|
|
24
|
+
return out + "}";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function newSession(account) {
|
|
28
|
+
const machineID = uuid();
|
|
29
|
+
const seed = (uuid() + uuid()).slice(0, 50);
|
|
30
|
+
const machineToken = b64url(utf8(seed));
|
|
31
|
+
const machineType = uuid().replace(/-/g, "").slice(0, 18);
|
|
32
|
+
const tempKey = uuid().replace(/-/g, "").slice(0, 16);
|
|
33
|
+
|
|
34
|
+
const identity = sortedCompact({
|
|
35
|
+
uid: account.uid || "",
|
|
36
|
+
aid: account.uid || "",
|
|
37
|
+
name: account.nickname || "",
|
|
38
|
+
email: account.email || "",
|
|
39
|
+
security_oauth_token: account.accessToken,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
machineID,
|
|
44
|
+
machineToken,
|
|
45
|
+
machineType,
|
|
46
|
+
tempKey,
|
|
47
|
+
cosyKey: rsaPkcs1Encrypt(utf8(tempKey)),
|
|
48
|
+
info: b64(aesCbcEncrypt(utf8(identity), utf8(tempKey))),
|
|
49
|
+
accessToken: account.accessToken,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function sessionFor(account) {
|
|
54
|
+
if (!account || !account.accessToken) throw new Error("cosy: empty access token");
|
|
55
|
+
const key = account.id || account.uid || account.accessToken.slice(0, 16);
|
|
56
|
+
const hit = cache.get(key);
|
|
57
|
+
if (hit && hit.accessToken === account.accessToken) return hit;
|
|
58
|
+
if (cache.size > 128) cache.clear();
|
|
59
|
+
const sess = newSession(account);
|
|
60
|
+
cache.set(key, sess);
|
|
61
|
+
return sess;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function invalidateSession(account) {
|
|
65
|
+
const key = account && (account.id || account.uid);
|
|
66
|
+
if (key) cache.delete(key);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function pathSig(rawURL) {
|
|
70
|
+
const u = new URL(rawURL);
|
|
71
|
+
let p = u.pathname;
|
|
72
|
+
if (p.startsWith("/algo")) p = p.slice("/algo".length);
|
|
73
|
+
return p;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function signHeaders(account, body, rawURL, modelKey, accept) {
|
|
77
|
+
const sess = sessionFor(account);
|
|
78
|
+
const payload = sortedCompact({
|
|
79
|
+
cosyVersion: COSY_VERSION,
|
|
80
|
+
ideVersion: IDE_VERSION,
|
|
81
|
+
info: sess.info,
|
|
82
|
+
requestId: uuid(),
|
|
83
|
+
version: "v1",
|
|
84
|
+
});
|
|
85
|
+
const payloadB64 = b64(utf8(payload));
|
|
86
|
+
const date = Math.floor(Date.now() / 1000).toString();
|
|
87
|
+
const sig = md5(`${payloadB64}\n${sess.cosyKey}\n${date}\n${body}\n${pathSig(rawURL)}`);
|
|
88
|
+
|
|
89
|
+
const headers = {
|
|
90
|
+
accept: accept || "text/event-stream",
|
|
91
|
+
"content-type": "application/json",
|
|
92
|
+
"user-agent": UA,
|
|
93
|
+
"x-request-id": uuid(),
|
|
94
|
+
"x-qwenwork-version": IDE_VERSION,
|
|
95
|
+
"x-qwenwork-release-version": RELEASE_VERSION,
|
|
96
|
+
"x-qwenwork-build": BUILD,
|
|
97
|
+
"x-qwenwork-platform": "win32",
|
|
98
|
+
"x-qwenwork-arch": "x64",
|
|
99
|
+
"x-qwenwork-channel": "stable",
|
|
100
|
+
"cosy-version": COSY_VERSION,
|
|
101
|
+
"cosy-clienttype": CLIENT_TYPE,
|
|
102
|
+
"cosy-business-product": BUSINESS_PRODUCT,
|
|
103
|
+
"cosy-business-type": BUSINESS_TYPE,
|
|
104
|
+
"cosy-scene": SCENE,
|
|
105
|
+
"cosy-machineos": MACHINE_OS,
|
|
106
|
+
"login-version": "v2",
|
|
107
|
+
authorization: `Bearer COSY.${payloadB64}.${sig}`,
|
|
108
|
+
"cosy-key": sess.cosyKey,
|
|
109
|
+
"cosy-user": account.uid || "",
|
|
110
|
+
"cosy-date": date,
|
|
111
|
+
"cosy-machineid": sess.machineID,
|
|
112
|
+
"accept-encoding": "identity",
|
|
113
|
+
connection: "keep-alive",
|
|
114
|
+
"cache-control": "no-cache",
|
|
115
|
+
};
|
|
116
|
+
if (modelKey) {
|
|
117
|
+
headers["x-model-key"] = modelKey;
|
|
118
|
+
headers["x-model-source"] = "system";
|
|
119
|
+
}
|
|
120
|
+
return headers;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// globalqwenwork 变体(国际站 gateway.qwenwork.ai):协议与 cn 逐字同构,2026-10-01 现网实测签名/请求 200 — 见 docs/adr/0041-globalqwenwork-international-provider.md
|