mslxdff 0.1.170 → 0.1.171

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 (107) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/docs/cli_help_mini.md +143 -0
  3. package/package.json +1 -1
  4. package/src/anthropic/count-tokens.js +39 -0
  5. package/src/anthropic/translate.js +20 -41
  6. package/src/auto.js +254 -254
  7. package/src/bench/cline-bench.js +42 -42
  8. package/src/bench/probe.js +70 -70
  9. package/src/bench/report.js +162 -162
  10. package/src/bench/runner.js +77 -77
  11. package/src/bench/via-probe.js +124 -124
  12. package/src/bench/via-routes.js +87 -87
  13. package/src/bench/workbuddy-bench.js +54 -54
  14. package/src/chat/engine.js +160 -160
  15. package/src/chat/gateway.js +163 -163
  16. package/src/chat/orchestrator.js +234 -234
  17. package/src/chat/prompt.js +70 -70
  18. package/src/chat/repl.js +88 -88
  19. package/src/chat/terminal.js +135 -135
  20. package/src/chat/tools.js +306 -306
  21. package/src/chat-pipeline/index.js +131 -131
  22. package/src/chat-pipeline/policy.js +76 -76
  23. package/src/cli/commands/group.js +249 -249
  24. package/src/cli/commands/model/picks.js +50 -50
  25. package/src/cli/commands/provider/bench-via.js +247 -247
  26. package/src/cli/commands/provider/bench.js +141 -141
  27. package/src/cli/commands/provider/index.js +133 -133
  28. package/src/cli/commands/provider/models.js +145 -145
  29. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  30. package/src/cli/commands/sync.js +310 -310
  31. package/src/cli/status.js +279 -279
  32. package/src/daemon.js +112 -112
  33. package/src/model-capabilities/enrich.js +86 -86
  34. package/src/model-capabilities/index.js +183 -183
  35. package/src/model-capabilities/parse.js +70 -70
  36. package/src/models.js +225 -225
  37. package/src/providers/AGENTS.md +49 -0
  38. package/src/providers/cline/auth.js +228 -228
  39. package/src/providers/cline/chat.js +307 -307
  40. package/src/providers/cline.js +2 -2
  41. package/src/providers/codearts/concurrency.js +34 -0
  42. package/src/providers/codearts/index.js +11 -3
  43. package/src/providers/globalqwenwork/cosy.js +123 -123
  44. package/src/providers/globalqwenwork/crypto.js +218 -218
  45. package/src/providers/globalqwenwork/http.js +20 -20
  46. package/src/providers/globalqwenwork/payload.js +4 -2
  47. package/src/providers/globalqwenwork/rsa.js +54 -54
  48. package/src/providers/globalqwenwork/sse.js +268 -268
  49. package/src/providers/globalqwenwork/stream.js +130 -130
  50. package/src/providers/globalqwenwork/upstream.js +122 -122
  51. package/src/providers/keyring.js +60 -60
  52. package/src/providers/qoder/chat.js +203 -200
  53. package/src/providers/qoder/index.js +249 -249
  54. package/src/providers/qoder/sse.js +145 -145
  55. package/src/providers/qwenwork/account-store.js +133 -133
  56. package/src/providers/qwenwork/constants.js +67 -67
  57. package/src/providers/qwenwork/cosy.js +120 -120
  58. package/src/providers/qwenwork/crypto.js +218 -218
  59. package/src/providers/qwenwork/http.js +20 -20
  60. package/src/providers/qwenwork/index.js +327 -327
  61. package/src/providers/qwenwork/payload.js +144 -142
  62. package/src/providers/qwenwork/rsa.js +54 -54
  63. package/src/providers/qwenwork/sse.js +268 -268
  64. package/src/providers/qwenwork/stream.js +130 -130
  65. package/src/providers/qwenwork/upstream.js +120 -120
  66. package/src/providers/qwenwork.js +1 -1
  67. package/src/providers/raccoon/chat.js +10 -5
  68. package/src/providers/raccoon/const.js +4 -4
  69. package/src/providers/registry.js +79 -79
  70. package/src/providers/workbuddy/chat.js +248 -248
  71. package/src/providers/workbuddy/payload.js +16 -7
  72. package/src/providers/workbuddy/reshape.js +152 -152
  73. package/src/providers/workbuddy.js +2 -2
  74. package/src/providers/zcode/chat.js +7 -0
  75. package/src/reasoning.js +32 -32
  76. package/src/responses/translate.js +4 -0
  77. package/src/routes/AGENTS.md +37 -0
  78. package/src/routes/chat/exhausted-handler.js +5 -0
  79. package/src/routes/chat/gateway.js +46 -46
  80. package/src/routes/chat/relay-pipeline.js +294 -291
  81. package/src/routes/chat/via-route-handler.js +146 -146
  82. package/src/routes/hedge.js +255 -255
  83. package/src/routes/messages-route.js +1 -1
  84. package/src/routes/models-route.js +167 -167
  85. package/src/routes/peers.js +273 -273
  86. package/src/routes/stream-scan.js +47 -21
  87. package/src/routes/stream.js +385 -385
  88. package/src/runtime/bootstrap.js +50 -50
  89. package/src/runtime/provider-gate.js +36 -36
  90. package/src/runtime/providers-setup.js +165 -165
  91. package/src/server.js +69 -69
  92. package/src/state/schemas/allowlist.js +92 -92
  93. package/src/sync-opencode.js +280 -280
  94. package/src/talk-full.js +1 -0
  95. package/src/talk-log.js +3 -2
  96. package/src/thinking-effort.js +67 -0
  97. package/src/transport/index.js +244 -244
  98. package/src/transport/pool.js +56 -56
  99. package/src/transport/retry.js +24 -24
  100. package/src/transport/sse.js +93 -93
  101. package/src/upstream-engine/sdk/convert.js +6 -0
  102. package/src/upstream-probe/display.js +52 -52
  103. package/src/upstream-probe/probe.js +49 -49
  104. package/src/upstream-probe/rotate.js +110 -110
  105. package/src/upstream-probe/start.js +45 -45
  106. package/src/upstream-responses.js +5 -0
  107. package/src/upstream.js +289 -289
@@ -1,268 +1,268 @@
1
- // vendor 自 _shared/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-qwenwork",
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
- }
1
+ // vendor 自 _shared/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-qwenwork",
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
+ }