mslxdff 0.1.233 → 0.1.234

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 (102) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/docs/cli_help_mini.md +148 -0
  3. package/package.json +1 -1
  4. package/src/auto.js +264 -264
  5. package/src/bench/cline-bench.js +42 -42
  6. package/src/bench/probe.js +70 -70
  7. package/src/bench/report.js +162 -162
  8. package/src/bench/runner.js +77 -77
  9. package/src/bench/via-probe.js +124 -124
  10. package/src/bench/via-routes.js +87 -87
  11. package/src/bench/workbuddy-bench.js +54 -54
  12. package/src/chat/engine.js +160 -160
  13. package/src/chat/gateway.js +163 -163
  14. package/src/chat/orchestrator.js +234 -234
  15. package/src/chat/prompt.js +70 -70
  16. package/src/chat/repl.js +88 -88
  17. package/src/chat/terminal.js +135 -135
  18. package/src/chat/tools.js +306 -306
  19. package/src/chat-pipeline/index.js +155 -155
  20. package/src/chat-pipeline/policy.js +84 -84
  21. package/src/cli/commands/group.js +266 -266
  22. package/src/cli/commands/model/picks.js +50 -50
  23. package/src/cli/commands/provider/bench-via.js +247 -247
  24. package/src/cli/commands/provider/bench.js +141 -141
  25. package/src/cli/commands/provider/index.js +139 -139
  26. package/src/cli/commands/provider/models.js +149 -149
  27. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  28. package/src/cli/commands/provider/raccoon-quota.js +156 -156
  29. package/src/cli/commands/sync.js +310 -310
  30. package/src/cli/status.js +279 -279
  31. package/src/daemon.js +246 -246
  32. package/src/model-capabilities/enrich.js +86 -86
  33. package/src/model-capabilities/index.js +183 -183
  34. package/src/model-capabilities/parse.js +70 -70
  35. package/src/models.js +293 -293
  36. package/src/peers.js +345 -345
  37. package/src/providers/AGENTS.md +49 -0
  38. package/src/providers/agentrouter.js +238 -238
  39. package/src/providers/base.js +164 -164
  40. package/src/providers/cline/auth.js +228 -228
  41. package/src/providers/cline/chat.js +307 -307
  42. package/src/providers/cline.js +2 -2
  43. package/src/providers/codearts/chat.js +207 -207
  44. package/src/providers/dispatcher.js +147 -147
  45. package/src/providers/globalqwenwork/cosy.js +123 -123
  46. package/src/providers/globalqwenwork/crypto.js +218 -218
  47. package/src/providers/globalqwenwork/http.js +20 -20
  48. package/src/providers/globalqwenwork/rsa.js +54 -54
  49. package/src/providers/globalqwenwork/sse.js +268 -268
  50. package/src/providers/globalqwenwork/stream.js +130 -130
  51. package/src/providers/globalqwenwork/upstream.js +122 -122
  52. package/src/providers/keyring.js +60 -60
  53. package/src/providers/qoder/chat.js +292 -292
  54. package/src/providers/qoder/index.js +311 -311
  55. package/src/providers/qoder/sse.js +233 -233
  56. package/src/providers/qwenwork/account-store.js +133 -133
  57. package/src/providers/qwenwork/constants.js +67 -67
  58. package/src/providers/qwenwork/cosy.js +120 -120
  59. package/src/providers/qwenwork/crypto.js +218 -218
  60. package/src/providers/qwenwork/http.js +20 -20
  61. package/src/providers/qwenwork/index.js +337 -337
  62. package/src/providers/qwenwork/payload.js +144 -144
  63. package/src/providers/qwenwork/rsa.js +54 -54
  64. package/src/providers/qwenwork/sse.js +268 -268
  65. package/src/providers/qwenwork/stream.js +130 -130
  66. package/src/providers/qwenwork/upstream.js +120 -120
  67. package/src/providers/qwenwork.js +1 -1
  68. package/src/providers/raccoon/const.js +219 -219
  69. package/src/providers/raccoon/credits.js +285 -285
  70. package/src/providers/raccoon/index.js +36 -4
  71. package/src/providers/raccoon/sticky.js +46 -0
  72. package/src/providers/registry.js +89 -89
  73. package/src/providers/workbuddy/chat.js +298 -298
  74. package/src/providers/workbuddy/reshape.js +152 -152
  75. package/src/providers/workbuddy.js +2 -2
  76. package/src/reasoning.js +32 -32
  77. package/src/routes/AGENTS.md +37 -0
  78. package/src/routes/chat/broadband-handler.js +80 -80
  79. package/src/routes/chat/gateway.js +46 -46
  80. package/src/routes/chat/relay-pipeline.js +282 -282
  81. package/src/routes/chat/via-route-handler.js +156 -156
  82. package/src/routes/hedge.js +260 -260
  83. package/src/routes/models-route.js +167 -167
  84. package/src/routes/peers.js +373 -373
  85. package/src/routes/stream.js +364 -364
  86. package/src/runtime/bootstrap.js +75 -75
  87. package/src/runtime/keep-warm.js +135 -135
  88. package/src/runtime/provider-gate.js +75 -75
  89. package/src/runtime/providers-setup.js +187 -187
  90. package/src/runtime/raccoon-checkin.js +175 -175
  91. package/src/server.js +85 -85
  92. package/src/state/schemas/allowlist.js +92 -92
  93. package/src/sync-opencode.js +280 -280
  94. package/src/transport/index.js +244 -244
  95. package/src/transport/pool.js +56 -56
  96. package/src/transport/retry.js +24 -24
  97. package/src/transport/sse.js +93 -93
  98. package/src/upstream-probe/display.js +52 -52
  99. package/src/upstream-probe/probe.js +49 -49
  100. package/src/upstream-probe/rotate.js +110 -110
  101. package/src/upstream-probe/start.js +45 -45
  102. package/src/upstream.js +355 -355
@@ -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
+ }