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.
Files changed (59) hide show
  1. package/docs/cli_help_mini.md +3 -1
  2. package/package.json +1 -1
  3. package/src/autostart.js +3 -0
  4. package/src/chat-pipeline/auto-race.js +1 -1
  5. package/src/chat-pipeline/empty-turn.js +119 -0
  6. package/src/chat-pipeline/index.js +4 -1
  7. package/src/chat-pipeline/serial-trial.js +244 -210
  8. package/src/cli/commands/daemon.js +4 -4
  9. package/src/cli/commands/model/list-providers.js +1 -1
  10. package/src/cli/commands/provider/globalqwenwork-login.js +126 -0
  11. package/src/cli/commands/provider/index.js +2 -0
  12. package/src/cli/commands/provider/models.js +4 -1
  13. package/src/cli/commands/stats.js +20 -5
  14. package/src/cli/commands/system.js +2 -2
  15. package/src/cli/format.js +6 -0
  16. package/src/cli/policy.js +2 -2
  17. package/src/cli/provider-row.js +2 -2
  18. package/src/daemon.js +7 -2
  19. package/src/logs.js +14 -1
  20. package/src/model-trace.js +5 -2
  21. package/src/providers/AGENTS.md +46 -0
  22. package/src/providers/classify.js +1 -1
  23. package/src/providers/globalqwenwork/account-store.js +141 -0
  24. package/src/providers/globalqwenwork/constants.js +73 -0
  25. package/src/providers/globalqwenwork/cosy.js +123 -0
  26. package/src/providers/globalqwenwork/crypto.js +220 -0
  27. package/src/providers/globalqwenwork/http.js +22 -0
  28. package/src/providers/globalqwenwork/index.js +331 -0
  29. package/src/providers/globalqwenwork/payload.js +145 -0
  30. package/src/providers/globalqwenwork/rsa.js +56 -0
  31. package/src/providers/globalqwenwork/sse.js +270 -0
  32. package/src/providers/globalqwenwork/stream.js +132 -0
  33. package/src/providers/globalqwenwork/upstream.js +122 -0
  34. package/src/providers/globalqwenwork.js +1 -0
  35. package/src/providers/registry.js +8 -0
  36. package/src/providers/zcode/chat.js +11 -10
  37. package/src/providers/zcode/const.js +1 -1
  38. package/src/providers/zcode/context-shape.js +162 -0
  39. package/src/providers/zcode/headers.js +38 -0
  40. package/src/providers/zcode/sse.js +19 -2
  41. package/src/routes/AGENTS.md +37 -0
  42. package/src/routes/chat/broadband-handler.js +3 -2
  43. package/src/routes/chat/exhausted-handler.js +23 -8
  44. package/src/routes/chat/hedge-handler.js +3 -0
  45. package/src/routes/chat/local-handler.js +5 -1
  46. package/src/routes/chat/peer-handler.js +2 -0
  47. package/src/routes/chat/relay-pipeline.js +40 -14
  48. package/src/routes/chat/via-route-handler.js +2 -0
  49. package/src/routes/helpers.js +20 -4
  50. package/src/routes/stream-hold.js +138 -0
  51. package/src/routes/stream-scan.js +278 -0
  52. package/src/routes/stream.js +106 -158
  53. package/src/runtime/lifecycle-forensics.js +116 -0
  54. package/src/runtime/lifecycle-log.js +23 -0
  55. package/src/runtime/provider-gate.js +4 -3
  56. package/src/talk-log.js +226 -0
  57. package/src/timeline.js +5 -2
  58. package/src/usage/record.js +8 -1
  59. package/src/usage/report.js +39 -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";
@@ -30,6 +30,14 @@ export const customProviders = [
30
30
  match: (id, baseUrl) => id === "qoder" || String(baseUrl).includes("qoder"),
31
31
  load: () => import("./qoder/index.js").then((m) => m.createQoderProvider),
32
32
  },
33
+ {
34
+ // ⚠ 必须排在 qwenwork 之前:qwenwork 的 match 用 `includes("qwenwork")`,
35
+ // 而 "globalqwenwork" 与 "gateway.qwenwork.ai"/"globalqwenwork://native" 都含该子串,
36
+ // 若后置会被 cn 条目抢先命中(first-match-wins),把国际站 token 打到 cn 网关。
37
+ id: "globalqwenwork",
38
+ match: (id, baseUrl) => id === "globalqwenwork" || String(baseUrl).includes("qwenwork.ai"),
39
+ load: () => import("./globalqwenwork/index.js").then((m) => m.createGlobalQwenworkProvider),
40
+ },
33
41
  {
34
42
  id: "qwenwork",
35
43
  match: (id, baseUrl) => id === "qwenwork" || String(baseUrl).includes("qwenwork"),
@@ -2,7 +2,8 @@
2
2
  // 失败响应带 x-mslxdff-zcode-kind 标记,供 provider 工厂决定冷却策略。
3
3
  import { timeoutSignal } from "../../compat.js";
4
4
  import { ZCODE_MESSAGES_URL, canonicalZcodeModel, zcodeErrorKind } from "./const.js";
5
- import { buildZcodeHeaders } from "./headers.js";
5
+ import { shapeZcodeWireRequest } from "./context-shape.js";
6
+ import { buildZcodeModelHeaders } from "./headers.js";
6
7
  import { aggregateAnthropicToOpenAi, anthropicToOpenAiStream } from "./sse.js";
7
8
 
8
9
  const DEFAULT_MAX_TOKENS = 4096;
@@ -97,7 +98,7 @@ const ERROR_MAP = {
97
98
  auth: { status: 401, type: "auth_error", text: (f) => `zcode: 登录已失效(code ${f.code || 1006})。请运行 mslxdff -provider zcode login 重新登录` },
98
99
  quota: { status: 429, type: "quota_exhausted", text: () => "zcode: 免费额度已用完(按日重置),请明日再试或添加账号" },
99
100
  rate_limit: { status: 429, type: "all_cooling", text: () => "zcode: 上游限流(账号冷却中),请稍后重试" },
100
- security: { status: 403, type: "security_reject", text: (f) => `zcode: 安全校验拒绝(code ${f.code || 3007})${f.message ? `:${f.message}` : ""} · 该额度走 Start Plan 验证码通道(每条请求需一次性 x-aliyun-captcha-verify-param;未启用验证码农场时必现),见 docs/adr/0038` },
101
+ security: { status: 403, type: "security_reject", text: (f) => `zcode: 安全校验拒绝(code ${f.code || 3007})${f.message ? `:${f.message}` : ""} · v3.14.4 起模型请求已免验证码(仅 claim 通道仍需要),偶发请重试,见 docs/adr/0038` },
101
102
  param: { status: 400, type: "invalid_request", text: (f) => `zcode: 请求参数被上游拒绝(code ${f.code})${f.message ? `:${f.message}` : ""}` },
102
103
  server: { status: 502, type: "upstream_error", text: (f) => `zcode: 上游服务异常${f.code ? `(code ${f.code})` : ""}${f.message ? `:${f.message}` : ""}` },
103
104
  network: { status: 502, type: "upstream_error", text: (f) => `zcode: 网络错误 ${f.message || ""}`.trim() },
@@ -115,21 +116,21 @@ export function zcodeErrorResponse(fail = {}) {
115
116
  });
116
117
  }
117
118
 
118
- export async function forwardZcodeChat({ body, token, deviceMid, fetchImpl, version, timeoutMs = 120_000 } = {}) {
119
+ export async function forwardZcodeChat({ body, token, deviceMid, fetchImpl, version, timeoutMs = 120_000, provider = "zai" } = {}) {
119
120
  const anthropicBody = toAnthropicRequest(body);
120
- const modelId = anthropicBody.model;
121
- const headers = {
122
- ...buildZcodeHeaders({ token, deviceMid, version }),
123
- "Content-Type": "application/json",
124
- Accept: "text/event-stream",
125
- };
121
+ const modelId = anthropicBody.model; // 响应回显用 canonical id;出站另行归一
122
+ // 官方线形:小写模型 + system 身份块 + currentDate 前缀(缺任一 → 上游 3012)。
123
+ // deviceMid 入参保留签名兼容,但模型请求出站不带(官方 CLI 模型请求不带该头,实测)。
124
+ const wireBody = shapeZcodeWireRequest(anthropicBody, { provider });
125
+ const headers = { "content-type": "application/json", ...buildZcodeModelHeaders({ token, version }) };
126
+ void deviceMid;
126
127
 
127
128
  let res;
128
129
  try {
129
130
  res = await fetchImpl(ZCODE_MESSAGES_URL, {
130
131
  method: "POST",
131
132
  headers,
132
- body: JSON.stringify(anthropicBody),
133
+ body: JSON.stringify(wireBody),
133
134
  signal: timeoutSignal(timeoutMs),
134
135
  });
135
136
  } catch (e) {
@@ -8,7 +8,7 @@ export const ZCODE_MESSAGES_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/anthropic/v
8
8
  export const zcodeBalanceUrl = (appVersion) =>
9
9
  `${ZCODE_ORIGIN}/api/v1/zcode-plan/billing/balance?app_version=${encodeURIComponent(String(appVersion || ""))}`;
10
10
 
11
- export const ZCODE_DEFAULT_APP_VERSION = "3.11.2";
11
+ export const ZCODE_DEFAULT_APP_VERSION = "3.14.4";
12
12
  export const ZCODE_RELEASE_CHANNEL = "stable";
13
13
 
14
14
  export function zcodeAppVersion(env = process.env) {