mslxdff 0.1.160 → 0.1.162

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 (49) hide show
  1. package/package.json +1 -1
  2. package/src/autostart.js +3 -0
  3. package/src/chat-pipeline/empty-turn.js +119 -0
  4. package/src/chat-pipeline/index.js +4 -1
  5. package/src/chat-pipeline/serial-trial.js +53 -19
  6. package/src/cli/commands/daemon.js +4 -4
  7. package/src/cli/commands/model/list-providers.js +1 -1
  8. package/src/cli/commands/provider/globalqwenwork-login.js +126 -0
  9. package/src/cli/commands/provider/index.js +2 -0
  10. package/src/cli/commands/provider/models.js +3 -0
  11. package/src/cli/commands/system.js +2 -2
  12. package/src/cli/format.js +7 -0
  13. package/src/cli/policy.js +2 -2
  14. package/src/cli/provider-row.js +2 -2
  15. package/src/daemon.js +7 -2
  16. package/src/logs.js +14 -1
  17. package/src/model-trace.js +8 -4
  18. package/src/providers/classify.js +1 -1
  19. package/src/providers/dispatcher.js +26 -14
  20. package/src/providers/globalqwenwork/account-store.js +141 -0
  21. package/src/providers/globalqwenwork/constants.js +73 -0
  22. package/src/providers/globalqwenwork/cosy.js +123 -0
  23. package/src/providers/globalqwenwork/crypto.js +220 -0
  24. package/src/providers/globalqwenwork/http.js +22 -0
  25. package/src/providers/globalqwenwork/index.js +331 -0
  26. package/src/providers/globalqwenwork/payload.js +145 -0
  27. package/src/providers/globalqwenwork/rsa.js +56 -0
  28. package/src/providers/globalqwenwork/sse.js +270 -0
  29. package/src/providers/globalqwenwork/stream.js +132 -0
  30. package/src/providers/globalqwenwork/upstream.js +122 -0
  31. package/src/providers/globalqwenwork.js +1 -0
  32. package/src/providers/qoder/chat.js +16 -6
  33. package/src/providers/qoder/index.js +13 -4
  34. package/src/providers/qoder/sse.js +39 -1
  35. package/src/providers/registry.js +8 -0
  36. package/src/providers/zcode/sse.js +19 -2
  37. package/src/routes/chat/exhausted-handler.js +23 -8
  38. package/src/routes/chat/local-handler.js +3 -1
  39. package/src/routes/chat/relay-pipeline.js +22 -10
  40. package/src/routes/helpers.js +20 -4
  41. package/src/routes/stream-hold.js +138 -0
  42. package/src/routes/stream-scan.js +192 -0
  43. package/src/routes/stream.js +97 -104
  44. package/src/runtime/lifecycle-forensics.js +116 -0
  45. package/src/runtime/lifecycle-log.js +23 -0
  46. package/src/runtime/provider-gate.js +4 -3
  47. package/src/runtime/server-lifecycle.js +5 -6
  48. package/src/talk-log.js +226 -0
  49. package/src/timeline.js +5 -2
@@ -0,0 +1,270 @@
1
+ // vendor 自 src/providers/qwenwork/sse.js 的解帧/清洗/聚合段(逐字搬),另并入上游 completions.js 的额度措辞判定。
2
+ // 关键:qwenwork 上游的内层 body **本身就是 OpenAI chunk**(不像 qoder 需要转译),
3
+ // 外层是 `{"headers":{},"body":"<内层JSON字符串>","statusCodeValue":200}` 的信封。
4
+ import { cleanErrorText } from "./http.js";
5
+
6
+ function fmtBodyText(value) {
7
+ if (typeof value === "string") return value;
8
+ if (value && typeof value === "object") return JSON.stringify(value);
9
+ return "";
10
+ }
11
+
12
+ function bodyCodeMessage(raw, status) {
13
+ let inner;
14
+ try {
15
+ inner = JSON.parse(raw);
16
+ } catch {
17
+ return status >= 400 ? `upstream ${status}: ${String(raw).slice(0, 200)}` : "";
18
+ }
19
+ if (!inner || typeof inner !== "object") return "";
20
+ const code = inner.code;
21
+ if (code === "400" || code === "401" || code === "403") {
22
+ return inner.message ? String(inner.message) : `upstream ${code}`;
23
+ }
24
+ if (status >= 400) {
25
+ return inner.message ? String(inner.message) : `upstream ${status}: ${String(raw).slice(0, 200)}`;
26
+ }
27
+ return "";
28
+ }
29
+
30
+ export function unwrapFrame(payload) {
31
+ if (typeof payload !== "string") return { ok: false };
32
+ const text = String(payload).trim();
33
+ if (!text || text === "[DONE]" || text === "{}") return { ok: false };
34
+ let outer;
35
+ try {
36
+ outer = JSON.parse(text);
37
+ } catch {
38
+ return { ok: true, body: text };
39
+ }
40
+ if (!outer || typeof outer !== "object") return { ok: false };
41
+ if (Object.prototype.hasOwnProperty.call(outer, "choices")) return { ok: true, body: text };
42
+ if (outer.object === "chat.completion.chunk" || outer.object === "chat.completion") return { ok: true, body: text };
43
+ if (typeof outer.statusCodeValue === "number" && outer.statusCodeValue >= 400) {
44
+ return { ok: false, error: bodyCodeMessage(fmtBodyText(outer.body), outer.statusCodeValue) };
45
+ }
46
+ if (!Object.prototype.hasOwnProperty.call(outer, "body")) return { ok: false };
47
+ const inner = outer.body;
48
+ if (typeof inner === "string") {
49
+ if (!inner || inner === "[DONE]" || inner === "{}" || inner === "null") return { ok: false };
50
+ const msg = bodyCodeMessage(inner, 0);
51
+ if (msg) return { ok: false, error: msg };
52
+ return { ok: true, body: inner };
53
+ }
54
+ if (inner && typeof inner === "object") {
55
+ const s = JSON.stringify(inner);
56
+ if (s === "{}" || s === "[]") return { ok: false };
57
+ return { ok: true, body: s };
58
+ }
59
+ return { ok: false };
60
+ }
61
+
62
+ function isEmptyValue(v) {
63
+ if (v === null || v === undefined) return true;
64
+ if (typeof v === "string") return v === "";
65
+ if (Array.isArray(v)) return v.length === 0;
66
+ if (typeof v === "object") {
67
+ for (const key of Object.keys(v)) {
68
+ if (!isEmptyValue(v[key])) return false;
69
+ }
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+
75
+ export function cleanChunk(text) {
76
+ let obj;
77
+ try {
78
+ obj = JSON.parse(text);
79
+ } catch {
80
+ return text;
81
+ }
82
+ if (!obj || typeof obj !== "object") return text;
83
+
84
+ if (obj.usage && typeof obj.usage === "object") {
85
+ let changed = false;
86
+ for (const noise of ["raw_usage", "sub_usages"]) {
87
+ if (Object.prototype.hasOwnProperty.call(obj.usage, noise)) {
88
+ delete obj.usage[noise];
89
+ changed = true;
90
+ }
91
+ if (Object.prototype.hasOwnProperty.call(obj, noise)) {
92
+ delete obj[noise];
93
+ changed = true;
94
+ }
95
+ }
96
+ return changed ? JSON.stringify(obj) : text;
97
+ }
98
+
99
+ let changed = false;
100
+ if (Array.isArray(obj.choices)) {
101
+ for (const choice of obj.choices) {
102
+ if (!choice || typeof choice !== "object") continue;
103
+ const delta = choice.delta;
104
+ if (!delta || typeof delta !== "object") continue;
105
+ if (Array.isArray(delta.tool_calls) && delta.tool_calls.length === 0) {
106
+ delete delta.tool_calls;
107
+ changed = true;
108
+ }
109
+ for (const noise of ["content", "reasoning_content", "function_call", "refusal", "extra_fields"]) {
110
+ if (Object.prototype.hasOwnProperty.call(delta, noise) && isEmptyValue(delta[noise])) {
111
+ delete delta[noise];
112
+ changed = true;
113
+ }
114
+ }
115
+ if (Object.keys(delta).length === 0 && !choice.finish_reason) return "";
116
+ }
117
+ }
118
+ return changed ? JSON.stringify(obj) : text;
119
+ }
120
+
121
+ function mergeToolCallDelta(merged, delta) {
122
+ for (const key of ["id", "type"]) {
123
+ if (merged[key] === undefined && typeof delta[key] === "string" && delta[key] !== "") merged[key] = delta[key];
124
+ }
125
+ const dfn = delta.function;
126
+ if (!dfn || typeof dfn !== "object") return;
127
+ if (!merged.function || typeof merged.function !== "object") merged.function = {};
128
+ if (typeof dfn.name === "string" && dfn.name !== "") merged.function.name = (merged.function.name || "") + dfn.name;
129
+ if (typeof dfn.arguments === "string" && dfn.arguments !== "") {
130
+ merged.function.arguments = (merged.function.arguments || "") + dfn.arguments;
131
+ }
132
+ }
133
+
134
+ export function aggregate(chunks, model) {
135
+ let content = "";
136
+ let reasoning = "";
137
+ let role = "";
138
+ let respModel = "";
139
+ let respID = "";
140
+ let finish = "";
141
+ let created = 0;
142
+ let usage = null;
143
+ const toolCalls = new Map();
144
+ const toolOrder = [];
145
+
146
+ for (const text of chunks) {
147
+ let chunk;
148
+ try {
149
+ chunk = JSON.parse(text);
150
+ } catch {
151
+ continue;
152
+ }
153
+ if (!chunk || typeof chunk !== "object") continue;
154
+ if (typeof chunk.id === "string" && chunk.id !== "") respID = chunk.id;
155
+ if (typeof chunk.model === "string" && chunk.model !== "") respModel = chunk.model;
156
+ if (typeof chunk.created === "number") created = chunk.created;
157
+ if (chunk.usage && typeof chunk.usage === "object") usage = chunk.usage;
158
+ if (!Array.isArray(chunk.choices)) continue;
159
+ for (const choice of chunk.choices) {
160
+ if (!choice || typeof choice !== "object") continue;
161
+ const delta = choice.delta;
162
+ if (delta && typeof delta === "object") {
163
+ if (typeof delta.role === "string" && delta.role !== "") role = delta.role;
164
+ if (typeof delta.content === "string") content += delta.content;
165
+ if (typeof delta.reasoning_content === "string") reasoning += delta.reasoning_content;
166
+ if (Array.isArray(delta.tool_calls)) {
167
+ for (const call of delta.tool_calls) {
168
+ if (!call || typeof call !== "object") continue;
169
+ const idx = typeof call.index === "number" ? call.index : 0;
170
+ if (!toolCalls.has(idx)) {
171
+ toolCalls.set(idx, { index: idx });
172
+ toolOrder.push(idx);
173
+ }
174
+ mergeToolCallDelta(toolCalls.get(idx), call);
175
+ }
176
+ }
177
+ }
178
+ if (typeof choice.finish_reason === "string" && choice.finish_reason !== "") finish = choice.finish_reason;
179
+ }
180
+ }
181
+
182
+ const message = { role: role || "assistant", content };
183
+ if (reasoning !== "") message.reasoning_content = reasoning;
184
+ if (toolOrder.length > 0) {
185
+ toolOrder.sort((a, b) => a - b);
186
+ message.tool_calls = toolOrder.map((idx) => toolCalls.get(idx));
187
+ }
188
+ const result = {
189
+ id: respID || "chatcmpl-globalqwenwork",
190
+ object: "chat.completion",
191
+ created: created || Math.floor(Date.now() / 1000),
192
+ model: respModel || model,
193
+ choices: [{ index: 0, message, finish_reason: finish || "stop" }],
194
+ };
195
+ if (usage) result.usage = usage;
196
+ return result;
197
+ }
198
+
199
+ /** 单行 SSE → OpenAI chunk 文本(null = 跳过);错误写进 state.error。 */
200
+ export function handleLine(line, state) {
201
+ if (!line.startsWith("data:")) return null;
202
+ const frame = unwrapFrame(line.slice(5));
203
+ if (frame.error) {
204
+ state.error = frame.error;
205
+ return null;
206
+ }
207
+ if (!frame.ok) return null;
208
+ try {
209
+ const parsed = JSON.parse(frame.body);
210
+ if (parsed && typeof parsed === "object" && parsed.usage && typeof parsed.usage === "object") state.usage = parsed.usage;
211
+ } catch {
212
+ /* keep raw chunk */
213
+ }
214
+ const cleaned = cleanChunk(frame.body);
215
+ if (!cleaned) return null;
216
+ return `data: ${cleaned}\n\n`;
217
+ }
218
+
219
+ export async function collectSync(upstreamBody, model) {
220
+ const reader = upstreamBody.getReader();
221
+ const decoder = new TextDecoder();
222
+ let buffer = "";
223
+ const chunks = [];
224
+ const state = { usage: null, error: null };
225
+
226
+ try {
227
+ for (;;) {
228
+ const { done, value } = await reader.read();
229
+ if (done) break;
230
+ buffer += decoder.decode(value, { stream: true });
231
+ const lines = buffer.split("\n");
232
+ buffer = lines.pop() || "";
233
+ for (const line of lines) {
234
+ const out = handleLine(line, state);
235
+ if (out) chunks.push(out.slice(6).trim());
236
+ }
237
+ }
238
+ if (buffer) {
239
+ const out = handleLine(buffer, state);
240
+ if (out) chunks.push(out.slice(6).trim());
241
+ }
242
+ } catch (err) {
243
+ state.error = `upstream stream read error: ${err && err.message ? err.message : err}`;
244
+ }
245
+
246
+ if (state.error) return { error: cleanErrorText(state.error) };
247
+ return { completion: aggregate(chunks, model), usage: state.usage };
248
+ }
249
+
250
+ // ---- 额度耗尽识别(上游措辞表逐字搬自原作者 completions.js,含 code 14018)----
251
+ const CREDIT_EXHAUSTED_MARKERS = [
252
+ "credits exhausted", "insufficient credit", "no credit", "credit exhausted", "out of credit",
253
+ "quota exceeded", "quota exhaust", "credit not enough", "not enough credit", "payment required",
254
+ "积分不足", "额度不足", "余额不足", "积分用完", "额度用尽", "没有积分",
255
+ ];
256
+
257
+ export function creditsExhaustedText(value) {
258
+ const s = String(value === undefined || value === null ? "" : value);
259
+ if (/\bcode["'\s:=]*14018\b/.test(s)) return true;
260
+ const lower = s.toLowerCase();
261
+ return CREDIT_EXHAUSTED_MARKERS.some((m) => lower.includes(m.toLowerCase()));
262
+ }
263
+
264
+ export function isCreditsExhausted(status, text) {
265
+ if (status !== 429 && status !== 402) return false;
266
+ if (status === 402) return true;
267
+ return creditsExhaustedText(text);
268
+ }
269
+
270
+ // globalqwenwork 变体:国际站 gateway.qwenwork.ai,协议与 cn 逐字同构(2026-10-01 现网取证),仅命名空间与常量不同 — 见 docs/adr/0041-globalqwenwork-international-provider.md
@@ -0,0 +1,132 @@
1
+ // vendor 自 src/providers/qwenwork/sse.js 的 transform(真流式:上游 SSE → OpenAI chunk,边收边吐)。
2
+ // 唯一一处**有意偏离**原作者实现:把 chunk 里的 `model` 回写成客户端请求的模型名。
3
+ // 上游实际返回的是池名(实测 `qwork-openai-chat-mode-pool`),直接透传会让客户端按模型名匹配失败,
4
+ // 违反本仓契约 1「model 原样透传」。原作者的非流式路径同样做了 `completion.model = wantModel`。
5
+ import { handleLine } from "./sse.js";
6
+
7
+ function rewriteModel(frameText, model) {
8
+ if (!model) return frameText;
9
+ const body = frameText.slice(6, -2);
10
+ let obj;
11
+ try {
12
+ obj = JSON.parse(body);
13
+ } catch {
14
+ return frameText;
15
+ }
16
+ if (!obj || typeof obj !== "object") return frameText;
17
+ obj.model = model;
18
+ return `data: ${JSON.stringify(obj)}\n\n`;
19
+ }
20
+
21
+ export function transformStream(upstreamBody, model, onUsage, { heartbeatMs = 15000 } = {}) {
22
+ const reader = upstreamBody.getReader();
23
+ const decoder = new TextDecoder();
24
+ const encoder = new TextEncoder();
25
+ let buffer = "";
26
+ let notified = false;
27
+ let heartbeat = null;
28
+ const state = { usage: null, error: null };
29
+
30
+ const notify = () => {
31
+ if (notified) return;
32
+ notified = true;
33
+ if (onUsage) onUsage(state.usage);
34
+ };
35
+
36
+ const emitError = (controller, message) => {
37
+ try {
38
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify({ error: { message, type: "upstream_error" } })}\n\n`));
39
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
40
+ controller.close();
41
+ } catch {
42
+ /* 客户端已断开 */
43
+ }
44
+ };
45
+
46
+ const stopHeartbeat = () => {
47
+ if (heartbeat) {
48
+ clearInterval(heartbeat);
49
+ heartbeat = null;
50
+ }
51
+ };
52
+
53
+ const finish = () => {
54
+ stopHeartbeat();
55
+ notify();
56
+ };
57
+
58
+ return new ReadableStream({
59
+ start(controller) {
60
+ if (heartbeatMs > 0) {
61
+ heartbeat = setInterval(() => {
62
+ try {
63
+ controller.enqueue(encoder.encode(": ping\n\n"));
64
+ } catch {
65
+ /* 已关闭 */
66
+ }
67
+ }, heartbeatMs);
68
+ if (heartbeat.unref) heartbeat.unref();
69
+ }
70
+ },
71
+ async pull(controller) {
72
+ try {
73
+ for (;;) {
74
+ let read;
75
+ try {
76
+ read = await reader.read();
77
+ } catch (err) {
78
+ const message = `upstream stream read error: ${err && err.message ? err.message : err}`;
79
+ stopHeartbeat();
80
+ emitError(controller, message);
81
+ notify();
82
+ return;
83
+ }
84
+ if (read.done) {
85
+ stopHeartbeat();
86
+ if (buffer) {
87
+ const out = handleLine(buffer, state);
88
+ if (out) controller.enqueue(encoder.encode(rewriteModel(out, model)));
89
+ buffer = "";
90
+ }
91
+ if (state.error) emitError(controller, state.error);
92
+ else {
93
+ try {
94
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
95
+ controller.close();
96
+ } catch {
97
+ /* 客户端已断开 */
98
+ }
99
+ }
100
+ finish();
101
+ return;
102
+ }
103
+ buffer += decoder.decode(read.value, { stream: true });
104
+ const lines = buffer.split("\n");
105
+ buffer = lines.pop() || "";
106
+ let out = "";
107
+ for (const line of lines) {
108
+ const frame = handleLine(line, state);
109
+ if (frame) out += rewriteModel(frame, model);
110
+ }
111
+ if (out) {
112
+ controller.enqueue(encoder.encode(out));
113
+ return;
114
+ }
115
+ }
116
+ } catch (err) {
117
+ finish();
118
+ try {
119
+ emitError(controller, `stream error: ${err && err.message ? err.message : err}`);
120
+ } catch {
121
+ /* 已关闭 */
122
+ }
123
+ }
124
+ },
125
+ cancel(reason) {
126
+ finish();
127
+ if (reader.cancel) reader.cancel(reason);
128
+ },
129
+ });
130
+ }
131
+
132
+ // globalqwenwork 变体:国际站 gateway.qwenwork.ai,协议与 cn 逐字同构(2026-10-01 现网取证),仅命名空间与常量不同 — 见 docs/adr/0041-globalqwenwork-international-provider.md
@@ -0,0 +1,122 @@
1
+ // upstream.js(签名请求装配 + OAuth 设备流)— vendor 自 src/providers/qwenwork/upstream.js 逐字搬;
2
+ // URL 全部来自本目录 constants.js(BASE=.ai),client_id/redirect_uri 自动取国际站值。
3
+ import { compatFetch } from "../../compat.js";
4
+ import { uuid, b64url, utf8 } from "./crypto.js";
5
+ import { signHeaders } from "./cosy.js";
6
+ import {
7
+ UA, CLIENT_ID, REDIRECT_URI, DEVICE_AUTH_URL, CHAT_URL, MODELS_URL,
8
+ USERINFO_URL, ACCOUNT_CONTEXT_URL, POLL_URL, REFRESH_URL, MODEL_SLICE,
9
+ } from "./constants.js";
10
+
11
+ function plainHeaders() {
12
+ return {
13
+ accept: "application/json, text/plain, */*",
14
+ "content-type": "application/json",
15
+ "user-agent": UA,
16
+ };
17
+ }
18
+
19
+ export function chatRequest(account, modelKey, bodyStr, signal, fetchImpl = compatFetch) {
20
+ const headers = signHeaders(account, bodyStr, CHAT_URL, modelKey, "text/event-stream");
21
+ return fetchImpl(CHAT_URL, { method: "POST", headers, body: bodyStr, signal });
22
+ }
23
+
24
+ export async function modelList(account, fetchImpl = compatFetch) {
25
+ const headers = signHeaders(account, "", MODELS_URL, "", "application/json");
26
+ const res = await fetchImpl(MODELS_URL, { headers });
27
+ if (!res.ok) throw new Error(`models http ${res.status}`);
28
+ const data = await res.json();
29
+ // 实测 11 个根切片只有 `qwork` 非空(其余 n=0);切片名见 constants.MODEL_SLICE
30
+ const list = Array.isArray(data && data[MODEL_SLICE]) ? data[MODEL_SLICE] : [];
31
+ return list
32
+ .filter((m) => m && m.enable !== false && m.key)
33
+ .map((m) => ({
34
+ key: m.key,
35
+ name: m.display_name || m.key,
36
+ isReasoning: !!m.is_reasoning,
37
+ isVL: !!m.is_vl,
38
+ maxInputTokens: m.max_input_tokens || 0,
39
+ maxOutputTokens: m.max_output_tokens || 0,
40
+ priceFactor: typeof m.price_factor === "number" ? m.price_factor : 0,
41
+ description: typeof m.description === "string" ? m.description : "",
42
+ }));
43
+ }
44
+
45
+ export async function userInfo(accessToken, fetchImpl = compatFetch) {
46
+ const res = await fetchImpl(USERINFO_URL, {
47
+ headers: { ...plainHeaders(), authorization: `Bearer ${accessToken}` },
48
+ });
49
+ if (!res.ok) throw new Error(`userinfo http ${res.status}`);
50
+ return res.json();
51
+ }
52
+
53
+ /** 额度/套餐:data.{user,plan,quota};quota.remaining 即积分余量。 */
54
+ export async function accountContext(accessToken, fetchImpl = compatFetch) {
55
+ const res = await fetchImpl(ACCOUNT_CONTEXT_URL, {
56
+ headers: { ...plainHeaders(), authorization: `Bearer ${accessToken}` },
57
+ });
58
+ if (!res.ok) throw new Error(`account-context http ${res.status}`);
59
+ const body = await res.json();
60
+ if (!body || (body.code && body.code !== "ok")) throw new Error(`account-context code=${body && body.code}`);
61
+ return (body && body.data) || {};
62
+ }
63
+
64
+ export async function refreshDeviceToken(refreshToken, fetchImpl = compatFetch) {
65
+ const res = await fetchImpl(REFRESH_URL, {
66
+ method: "POST",
67
+ headers: plainHeaders(),
68
+ body: JSON.stringify({ refresh_token: refreshToken }),
69
+ });
70
+ if (!res.ok) throw new Error(`refresh http ${res.status}`);
71
+ const data = await res.json();
72
+ const access = data && (data.token || data.device_token);
73
+ if (!access || !data.refresh_token) throw new Error("refresh: incomplete token pair");
74
+ return data;
75
+ }
76
+
77
+ export async function pollGrant(nonce, verifier, fetchImpl = compatFetch) {
78
+ const q = new URLSearchParams({ nonce, verifier, challenge_method: "S256" });
79
+ const res = await fetchImpl(`${POLL_URL}?${q.toString()}`, {
80
+ headers: { accept: "application/json", "user-agent": UA },
81
+ });
82
+ if (res.status === 404 || res.status === 202) return { pending: true };
83
+ if (!res.ok) throw new Error(`poll http ${res.status}`);
84
+ const data = await res.json();
85
+ if (!data || !(data.token || data.device_token)) return { pending: true };
86
+ return { pending: false, grant: data };
87
+ }
88
+
89
+ export async function newDeviceFlow() {
90
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
91
+ const raw = new Uint8Array(64);
92
+ crypto.getRandomValues(raw);
93
+ let verifier = "";
94
+ for (let i = 0; i < raw.length; i++) verifier += alphabet[raw[i] % alphabet.length];
95
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8(verifier)));
96
+ const challenge = b64url(digest);
97
+ const nonce = uuid();
98
+ const machineID = uuid();
99
+ const q = new URLSearchParams({
100
+ challenge,
101
+ challenge_method: "S256",
102
+ nonce,
103
+ machine_id: machineID,
104
+ client_id: CLIENT_ID,
105
+ redirect_uri: REDIRECT_URI,
106
+ });
107
+ return { verifier, nonce, url: `${DEVICE_AUTH_URL}?${q.toString()}` };
108
+ }
109
+
110
+ export function expiryUnix(grant) {
111
+ if (grant && grant.expires_at) {
112
+ const t = Date.parse(grant.expires_at);
113
+ if (!Number.isNaN(t)) return Math.floor(t / 1000);
114
+ }
115
+ if (grant && grant.expires_in > 0) {
116
+ const ms = grant.expires_in > 10000000 ? grant.expires_in : grant.expires_in * 1000;
117
+ return Math.floor((Date.now() + ms) / 1000);
118
+ }
119
+ return Math.floor((Date.now() + 30 * 24 * 3600 * 1000) / 1000);
120
+ }
121
+
122
+ // globalqwenwork 变体(国际站 gateway.qwenwork.ai):协议与 cn 逐字同构,2026-10-01 现网实测签名/请求 200 — 见 docs/adr/0041-globalqwenwork-international-provider.md
@@ -0,0 +1 @@
1
+ export * from "./globalqwenwork/index.js";
@@ -29,14 +29,15 @@ const PEEK_MAX_FRAMES = 8;
29
29
  // 返回 { res, status, frames }:res 是把预读帧回灌后的等价上游响应,frames 交回灌用。
30
30
  // 任何异常都降级为「无判决」(status=0):排障手段不得变成故障源。
31
31
  async function peekEnvelopeVerdict(upRes, cdbg) {
32
- if (!upRes?.body) return { res: upRes, status: 0, quota: false, frames: [] };
32
+ if (!upRes?.body) return { res: upRes, status: 0, quota: false, queued: false, frames: [] };
33
33
  let reader;
34
- try { reader = upRes.body.getReader(); } catch { return { res: upRes, status: 0, quota: false, frames: [] }; }
34
+ try { reader = upRes.body.getReader(); } catch { return { res: upRes, status: 0, quota: false, queued: false, frames: [] }; }
35
35
  const dec = new TextDecoder();
36
36
  const frames = [];
37
37
  let text = "";
38
38
  let status = 0;
39
39
  let quota = false;
40
+ let queued = false;
40
41
  let decided = false;
41
42
  try {
42
43
  for (let i = 0; i < PEEK_MAX_FRAMES && !decided; i++) {
@@ -50,14 +51,14 @@ async function peekEnvelopeVerdict(upRes, cdbg) {
50
51
  const p = line.slice(5).trim();
51
52
  if (!p || p === "[DONE]") continue;
52
53
  const d = extractDelta(p);
53
- if (d.err) { status = Number(d.err.status) || 0; quota = d.err.kind === "quota"; decided = true; break; }
54
+ if (d.err) { status = Number(d.err.status) || 0; quota = d.err.kind === "quota"; queued = d.err.queued === true; decided = true; break; }
54
55
  if (d.content || d.reasoning || d.toolCalls || d.usageIn || d.usageOut) { decided = true; break; }
55
56
  }
56
57
  }
57
58
  } catch (e) {
58
59
  cdbg(`[peek-throw] ${String(e?.message || e).slice(0, 160)}`);
59
60
  }
60
- cdbg(`[peek] frames=${frames.length} verdict=${status || "none(正常流)"}`);
61
+ cdbg(`[peek] frames=${frames.length} verdict=${status || "none(正常流)"} quota=${quota} queued=${queued}`);
61
62
  // 回灌:已读帧先按原样吐出,再接续同一个 reader 的剩余部分
62
63
  const body = new ReadableStream({
63
64
  start(ctrl) {
@@ -74,7 +75,7 @@ async function peekEnvelopeVerdict(upRes, cdbg) {
74
75
  })();
75
76
  },
76
77
  });
77
- return { res: new Response(body, { status: upRes.status, headers: upRes.headers }), status, quota, frames };
78
+ return { res: new Response(body, { status: upRes.status, headers: upRes.headers }), status, quota, queued, frames };
78
79
  }
79
80
  export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
80
81
  if (!fetchImpl) fetchImpl = compatFetch;
@@ -105,6 +106,12 @@ export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
105
106
  try { res.headers.set("x-mslxdff-qoder-quota", "1"); } catch {}
106
107
  return res;
107
108
  };
109
+ // 排队标记(内部交接,不落日志):与额度同为「换号」信号但冷却档不同——
110
+ // 排队是「稍后再来」,长冷却到点自动回池;额度是「今天没了」,按天重置才回。
111
+ const withQueued = (res) => {
112
+ try { res.headers.set("x-mslxdff-qoder-queued", "1"); } catch {}
113
+ return res;
114
+ };
108
115
 
109
116
  async function runChat(body, sess, region = "global", pick = "") {
110
117
  const stream = body?.stream !== false;
@@ -167,6 +174,8 @@ export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
167
174
  // 只在真有判决时挂状态码:正常流不写这个头(index.js 靠它区分"要不要冷却")
168
175
  if (peek.status) shaped = withUpstreamStatus(shaped, peek.status);
169
176
  if (peek.quota) shaped = withQuota(shaped);
177
+ // 排队旗标(内部交接):门面据此走队列档冷却并在同一请求内换号,别把排队号送回客户端
178
+ if (peek.queued) shaped = withQueued(shaped);
170
179
  return shaped;
171
180
  }
172
181
  try {
@@ -175,7 +184,8 @@ export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
175
184
  return echo(new Response(JSON.stringify(out), { status: 200, headers: { "Content-Type": "application/json" } }));
176
185
  } catch (e) {
177
186
  const out = echo(errRes(errorStatus(e), String(e?.detail || e?.message || e).slice(0, 300), e?.kind || "upstream_error"));
178
- return e?.kind === "quota" ? withQuota(out) : out;
187
+ const marked = e?.kind === "quota" ? withQuota(out) : out;
188
+ return e?.queued ? withQueued(marked) : marked;
179
189
  }
180
190
  }
181
191
 
@@ -37,6 +37,9 @@ export function createQoderProvider({
37
37
  cooldownMs = envInt("MSLXDFF_QODER_COOLDOWN_MS", 30_000),
38
38
  // 额度耗尽(code 110)按天重置:短冷却等于反复撞死号,故单独配长冷却(默认 1h)
39
39
  quotaCooldownMs = envInt("MSLXDFF_QODER_QUOTA_COOLDOWN_MS", 3600_000),
40
+ // 排队(10605/isQueued)单独一档:队列没放行前反复送回就是白烧(实测跨小时不恢复),默认 5min。
41
+ // 上游口播的 retryAfterSeconds=30 只当参考值,不当本档上限——按 30s 回池等于回到旧行为。
42
+ queueCooldownMs = envInt("MSLXDFF_QODER_QUEUE_COOLDOWN_MS", 300_000),
40
43
  connectTimeoutMs = Number(process.env.MSLXDFF_QODER_TIMEOUT_MS) || 120_000,
41
44
  } = {}) {
42
45
  const keys = (() => {
@@ -127,15 +130,21 @@ export function createQoderProvider({
127
130
  // 否则坏号(401/403/429/5xx)永不冷却,粘号还会把重试继续粘在这个坏号上。
128
131
  const ust = Number(res?.headers?.get?.("x-mslxdff-qoder-upstream-status")) || 0;
129
132
  const isQuota = res?.headers?.get?.("x-mslxdff-qoder-quota") === "1";
133
+ const isQueued = res?.headers?.get?.("x-mslxdff-qoder-queued") === "1";
130
134
  const bad = badAuth(st) ? st : (badAuth(ust) ? ust : 0);
135
+ // 冷却三档:额度(按天重置,最长)> 排队(队列没放行前别再送回,默认 5min)> 其它(普通短冷却)。
136
+ // 排队单独成档的依据:现网 31h 窗口 global 区 176 发被判决 129 发且跨小时不复现恢复,
137
+ // 30s 短冷却等于每 30s 白烧一发;但它不是「今天没了」,到点必须自动回池,故不得并入额度档。
131
138
  if (bad) {
132
- try { ring.onError(pickedKey, isQuota ? quotaCooldownMs : cooldownMs); } catch {}
139
+ const coolMs = isQuota ? quotaCooldownMs : (isQueued ? queueCooldownMs : cooldownMs);
140
+ try { ring.onError(pickedKey, coolMs); } catch {}
133
141
  if (isQuota) exhaustedByQuota.add(pickedKey);
134
142
  // 冷却是个决定:钉在响应上,管线写进模型日志(cooled=<status>)
135
143
  try { res.headers?.set?.("x-mslxdff-qoder-cooldown", String(bad)); } catch {}
136
144
  }
137
- // 额度耗尽:本号已废(长冷却),若还有别的号就立刻换号重发,别把空流递给客户端
138
- if (isQuota) {
145
+ // 额度耗尽 / 排队:本号这一发已废,只要还有别的号就当场换号重发,别把空流或排队判决递给客户端。
146
+ // (跨请求那侧不用改:长冷却让 sticky 下次因 isCooling 自动 switch。)
147
+ if (isQuota || isQueued) {
139
148
  lastRes = res;
140
149
  if (ring.available() > 0) continue;
141
150
  break;
@@ -223,7 +232,7 @@ export function createQoderProvider({
223
232
 
224
233
  async function close() {}
225
234
  async function chatWithKeys(body, keysOverride, opts) {
226
- const tmp = createQoderProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, connectTimeoutMs });
235
+ const tmp = createQoderProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, queueCooldownMs, connectTimeoutMs });
227
236
  return tmp.chat(body, opts);
228
237
  }
229
238