mslxdff 0.1.161 → 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 (93) hide show
  1. package/bin/mslxdff.js +4 -4
  2. package/package.json +1 -1
  3. package/src/auto.js +254 -254
  4. package/src/bench/cline-bench.js +42 -42
  5. package/src/bench/probe.js +70 -70
  6. package/src/bench/report.js +162 -162
  7. package/src/bench/runner.js +77 -77
  8. package/src/bench/via-probe.js +124 -124
  9. package/src/bench/via-routes.js +87 -87
  10. package/src/bench/workbuddy-bench.js +54 -54
  11. package/src/chat/engine.js +160 -160
  12. package/src/chat/gateway.js +163 -163
  13. package/src/chat/orchestrator.js +234 -234
  14. package/src/chat/prompt.js +70 -70
  15. package/src/chat/repl.js +88 -88
  16. package/src/chat/terminal.js +135 -135
  17. package/src/chat/tools.js +306 -306
  18. package/src/chat-pipeline/index.js +126 -126
  19. package/src/chat-pipeline/policy.js +76 -76
  20. package/src/cli/commands/group.js +249 -249
  21. package/src/cli/commands/model/picks.js +50 -50
  22. package/src/cli/commands/provider/bench-via.js +247 -247
  23. package/src/cli/commands/provider/bench.js +141 -141
  24. package/src/cli/commands/provider/index.js +126 -126
  25. package/src/cli/commands/provider/models.js +142 -142
  26. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  27. package/src/cli/commands/sync.js +232 -232
  28. package/src/cli/format.js +1 -0
  29. package/src/cli/status.js +279 -279
  30. package/src/daemon.js +101 -101
  31. package/src/model-capabilities/enrich.js +86 -86
  32. package/src/model-capabilities/index.js +183 -183
  33. package/src/model-capabilities/parse.js +70 -70
  34. package/src/model-trace.js +4 -3
  35. package/src/models.js +225 -225
  36. package/src/providers/cline/auth.js +228 -228
  37. package/src/providers/cline/chat.js +307 -307
  38. package/src/providers/cline.js +2 -2
  39. package/src/providers/dispatcher.js +26 -14
  40. package/src/providers/globalqwenwork/cosy.js +123 -123
  41. package/src/providers/globalqwenwork/crypto.js +218 -218
  42. package/src/providers/globalqwenwork/http.js +20 -20
  43. package/src/providers/globalqwenwork/rsa.js +54 -54
  44. package/src/providers/globalqwenwork/sse.js +268 -268
  45. package/src/providers/globalqwenwork/stream.js +130 -130
  46. package/src/providers/globalqwenwork/upstream.js +122 -122
  47. package/src/providers/keyring.js +60 -60
  48. package/src/providers/qoder/chat.js +193 -183
  49. package/src/providers/qoder/index.js +239 -230
  50. package/src/providers/qoder/sse.js +141 -103
  51. package/src/providers/qwenwork/account-store.js +133 -133
  52. package/src/providers/qwenwork/constants.js +67 -67
  53. package/src/providers/qwenwork/cosy.js +120 -120
  54. package/src/providers/qwenwork/crypto.js +218 -218
  55. package/src/providers/qwenwork/http.js +20 -20
  56. package/src/providers/qwenwork/index.js +327 -327
  57. package/src/providers/qwenwork/payload.js +142 -142
  58. package/src/providers/qwenwork/rsa.js +54 -54
  59. package/src/providers/qwenwork/sse.js +268 -268
  60. package/src/providers/qwenwork/stream.js +130 -130
  61. package/src/providers/qwenwork/upstream.js +120 -120
  62. package/src/providers/qwenwork.js +1 -1
  63. package/src/providers/registry.js +74 -74
  64. package/src/providers/workbuddy/chat.js +248 -248
  65. package/src/providers/workbuddy/reshape.js +152 -152
  66. package/src/providers/workbuddy.js +2 -2
  67. package/src/reasoning.js +32 -32
  68. package/src/routes/chat/gateway.js +46 -46
  69. package/src/routes/chat/relay-pipeline.js +276 -276
  70. package/src/routes/chat/via-route-handler.js +146 -146
  71. package/src/routes/hedge.js +255 -255
  72. package/src/routes/models-route.js +167 -167
  73. package/src/routes/peers.js +273 -273
  74. package/src/routes/stream.js +386 -386
  75. package/src/runtime/bootstrap.js +45 -45
  76. package/src/runtime/provider-gate.js +34 -34
  77. package/src/runtime/providers-setup.js +165 -165
  78. package/src/runtime/server-lifecycle.js +5 -6
  79. package/src/server.js +64 -64
  80. package/src/state/schemas/allowlist.js +92 -92
  81. package/src/sync-opencode.js +280 -280
  82. package/src/transport/index.js +244 -244
  83. package/src/transport/pool.js +56 -56
  84. package/src/transport/retry.js +24 -24
  85. package/src/transport/sse.js +93 -93
  86. package/src/upstream-probe/display.js +52 -52
  87. package/src/upstream-probe/probe.js +49 -49
  88. package/src/upstream-probe/rotate.js +110 -110
  89. package/src/upstream-probe/start.js +45 -45
  90. package/src/upstream.js +289 -289
  91. package/docs/cli_help_mini.md +0 -135
  92. package/src/providers/AGENTS.md +0 -46
  93. package/src/routes/AGENTS.md +0 -37
@@ -1,183 +1,193 @@
1
- // qoder 对话服务:上游恒 stream:true;请求方 stream=true → 真流式转发边收边吐,
2
- // false → 聚合回 JSON。装配走 request.js,帧格式走 sse.js,两条管线共享。
3
- import { compatFetch, timeoutSignal } from "../../compat.js";
4
- import { normalizeRegion } from "./constants.js";
5
- import { buildUpstreamRequest } from "./request.js";
6
- import { reshapeQoderStream } from "./stream.js";
7
- import { aggregateQoderStream, toCompletionJson } from "./aggregate.js";
8
- import { errorStatus, extractDelta } from "./sse.js";
9
-
10
- function hostOf(url) {
11
- try { return new URL(String(url)).host; } catch { return "-"; }
12
- }
13
-
14
- function errRes(status, msg, type = "upstream_error") {
15
- return new Response(JSON.stringify({ error: { message: msg, type } }), { status, headers: { "Content-Type": "application/json" } });
16
- }
17
-
18
- function mapUpstreamError(status, detail) {
19
- return { kind: status === 401 || status === 403 ? "auth" : "upstream", status, detail: String(detail || "").slice(0, 300) };
20
- }
21
-
22
- // 预读上限:判决恒在首帧(实测 457 字节),8 帧足够覆盖"角色帧先到、判决帧随后",
23
- // 又不会把首字节延迟拖到不可控。超窗未得判决即放弃(退化为无冷却的流内 error,见 SPEC 已知上限)。
24
- const PEEK_MAX_FRAMES = 8;
25
-
26
- // 预读上游首帧只为取「流内判决」:qoder 把限流/鉴权判决裹在 HTTP 200 的 SSE 信封里
27
- //(statusCodeValue:403 + serviceAvailable:false),upRes.status 恒 200,判决只有读完帧才知道。
28
- // 不预读则状态码永远出不来流式路径 → 门面不冷却该号(ADR-0036 的粘号会把重试继续粘在它上面)。
29
- // 返回 { res, status, frames }:res 是把预读帧回灌后的等价上游响应,frames 交回灌用。
30
- // 任何异常都降级为「无判决」(status=0):排障手段不得变成故障源。
31
- async function peekEnvelopeVerdict(upRes, cdbg) {
32
- if (!upRes?.body) return { res: upRes, status: 0, quota: false, frames: [] };
33
- let reader;
34
- try { reader = upRes.body.getReader(); } catch { return { res: upRes, status: 0, quota: false, frames: [] }; }
35
- const dec = new TextDecoder();
36
- const frames = [];
37
- let text = "";
38
- let status = 0;
39
- let quota = false;
40
- let decided = false;
41
- try {
42
- for (let i = 0; i < PEEK_MAX_FRAMES && !decided; i++) {
43
- const { done, value } = await reader.read();
44
- if (done) break;
45
- if (value) { frames.push(value); text += dec.decode(value, { stream: true }); }
46
- // 逐行判定:先到判决(err)或先到有效载荷即停,避免无谓等待
47
- for (const raw of text.split("\n")) {
48
- const line = raw.trim();
49
- if (!line.startsWith("data:")) continue;
50
- const p = line.slice(5).trim();
51
- if (!p || p === "[DONE]") continue;
52
- 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.content || d.reasoning || d.toolCalls || d.usageIn || d.usageOut) { decided = true; break; }
55
- }
56
- }
57
- } catch (e) {
58
- cdbg(`[peek-throw] ${String(e?.message || e).slice(0, 160)}`);
59
- }
60
- cdbg(`[peek] frames=${frames.length} verdict=${status || "none(正常流)"}`);
61
- // 回灌:已读帧先按原样吐出,再接续同一个 reader 的剩余部分
62
- const body = new ReadableStream({
63
- start(ctrl) {
64
- for (const f of frames) { try { ctrl.enqueue(f); } catch {} }
65
- (async () => {
66
- try {
67
- for (;;) {
68
- const { done, value } = await reader.read();
69
- if (done) break;
70
- if (value) ctrl.enqueue(value);
71
- }
72
- } catch {}
73
- try { ctrl.close(); } catch {}
74
- })();
75
- },
76
- });
77
- return { res: new Response(body, { status: upRes.status, headers: upRes.headers }), status, quota, frames };
78
- }
79
- export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
80
- if (!fetchImpl) fetchImpl = compatFetch;
81
-
82
- // body: OpenAI chat 请求;sess: 已建 COSY 会话;region: 该账号所属区(每号独立选端点)。返回 Response。
83
- // 回显(可观测,不落凭据):x-mslxdff-upstream=本次请求的 host、x-mslxdff-qoder-region=cn|global;
84
- // 管线层据此把"这次谁上的、打哪个站"投进模型日志(此前 provider 内部选号/切 URL 完全静默,排障无据)。
85
- const withEcho = (res, url, region, pick) => {
86
- try {
87
- res.headers.set("x-mslxdff-upstream", hostOf(url));
88
- res.headers.set("x-mslxdff-qoder-region", normalizeRegion(region));
89
- // 账号选择决定(new/sticky/switch/forced):管线把它写进模型日志,"为什么会切号"才有据可查
90
- if (pick) res.headers.set("x-mslxdff-qoder-account", String(pick));
91
- } catch {}
92
- return res;
93
- };
94
-
95
- // 上游状态回显(内部交接用,不落日志):流式路径按对外契约把非 200 整形成 "200 + 流内 error",
96
- // 真实状态码只能靠这个头带出——否则 401/403/429/5xx 到不了 provider 门面,坏号不被冷却,
97
- // 而"同请求粘号"(ADR-0036)会把后续重试继续粘在这个坏号上。
98
- // Note: 流内判决需预读首帧才能拿到(HTTP 200 里裹 statusCodeValue)— 见 .agents/notes/implemented/bug-fix/2026-09-27-qoder-envelope-verdict-cooldown.md
99
- const withUpstreamStatus = (res, st) => {
100
- try { res.headers.set("x-mslxdff-qoder-upstream-status", String(st)); } catch {}
101
- return res;
102
- };
103
- // 额度耗尽标记(内部交接,不落日志):门面据此换号(长冷却该号)而非普通短冷却
104
- const withQuota = (res) => {
105
- try { res.headers.set("x-mslxdff-qoder-quota", "1"); } catch {}
106
- return res;
107
- };
108
-
109
- async function runChat(body, sess, region = "global", pick = "") {
110
- const stream = body?.stream !== false;
111
- const model = body?.model || "qfmodel";
112
- const chatId = "chatcmpl-qoder-" + Math.random().toString(16).slice(2, 10);
113
- const tools = Array.isArray(body?.tools) && body.tools.length ? body.tools : null;
114
- const messages = Array.isArray(body?.messages) ? body.messages : [];
115
- const maxTokens = Number(body?.max_tokens) || 0;
116
-
117
- let upRes; let reqUrl = "";
118
- const echo = (res) => withEcho(res, reqUrl, region, pick);
119
- // 排障日志(QODER_DEBUG_STREAM=1 开):记录出口/状态/耗时/响应头,便于对比"200 但空轮"
120
- const cdbg = (...a) => { if (process.env.QODER_DEBUG_STREAM === "1") console.log("[qoder-chat]", ...a); };
121
- let upMs = 0;
122
- try {
123
- const req = buildUpstreamRequest({ sess, region: normalizeRegion(region), model, messages, tools, maxTokens });
124
- reqUrl = req.url;
125
- cdbg(`[req] url=${hostOf(req.url)} region=${normalizeRegion(region)} model=${model} msgs=${messages.length} tools=${tools?.length ?? 0} maxTokens=${maxTokens} stream=${stream} bodyBytes=${req.bodyStr?.length ?? 0}`);
126
- const t0 = Date.now();
127
- upRes = await fetchImpl(req.url, {
128
- method: "POST",
129
- headers: req.headers,
130
- body: req.bodyStr,
131
- signal: timeoutSignal(timeoutMs || 120_000),
132
- });
133
- upMs = Date.now() - t0;
134
- cdbg(`[res] status=${upRes.status} ms=${upMs} ct=${upRes.headers.get("content-type")} host=${hostOf(reqUrl)}`);
135
- } catch (e) {
136
- const detail = String(e?.message || e).slice(0, 300);
137
- cdbg(`[res-throw] ms=${upMs} err=${detail}`);
138
- // 网络异常(超时/连接失败)折成 502:门面据此冷却该号(否则坏号恒在轮换池里)
139
- if (stream) return withUpstreamStatus(echo(reshapeQoderStream(new Response("data: [DONE]\n\n"), { model, chatId })), 502);
140
- return withUpstreamStatus(echo(errRes(502, detail)), 502);
141
- }
142
- if (upRes.status !== 200) {
143
- const detail = await upRes.text().catch(() => "");
144
- cdbg(`[res-non200] status=${upRes.status} body=${detail.slice(0, 300)}`);
145
- const e = mapUpstreamError(upRes.status, detail);
146
- if (stream) {
147
- // 首包错误也走流内 error 事件(与旧 reshapeStream catch 语义一致:200 + event:error + DONE)
148
- const enc = new TextEncoder();
149
- const s = new ReadableStream({
150
- start(c) {
151
- c.enqueue(enc.encode(`data: ${JSON.stringify({ id: chatId, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: {}, finish_reason: null }] })}\n\n`));
152
- c.enqueue(enc.encode(`event: error\ndata: ${JSON.stringify({ message: e.detail, type: e.kind })}\n\ndata: [DONE]\n\n`));
153
- c.close();
154
- },
155
- });
156
- // 对外仍是 200(契约不变),真实状态码经回显头交门面决定是否冷却
157
- return withUpstreamStatus(echo(new Response(s, { status: 200, headers: { "Content-Type": "text/event-stream" } })), upRes.status);
158
- }
159
- return withUpstreamStatus(echo(errRes(errorStatus(e), e.detail, e.kind)), upRes.status);
160
- }
161
- if (stream) {
162
- // 预读首帧取流内判决(qoder 把 403/429 裹在 200 的信封里),预读帧原样回灌给整形器。
163
- // 判决状态码经 withUpstreamStatus 出门面 → index.js 据此 ring.onError 冷却该号 →
164
- // 粘号选择器下次因 isCooling 为真而换号。对外仍恒 200(契约不变)。
165
- const peek = await peekEnvelopeVerdict(upRes, cdbg);
166
- let shaped = echo(reshapeQoderStream(peek.res, { model, chatId, prefetched: peek.frames }));
167
- // 只在真有判决时挂状态码:正常流不写这个头(index.js 靠它区分"要不要冷却")
168
- if (peek.status) shaped = withUpstreamStatus(shaped, peek.status);
169
- if (peek.quota) shaped = withQuota(shaped);
170
- return shaped;
171
- }
172
- try {
173
- const agg = await aggregateQoderStream(upRes);
174
- const out = toCompletionJson({ model, chatId, ...agg });
175
- return echo(new Response(JSON.stringify(out), { status: 200, headers: { "Content-Type": "application/json" } }));
176
- } catch (e) {
177
- 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;
179
- }
180
- }
181
-
182
- return { runChat };
183
- }
1
+ // qoder 对话服务:上游恒 stream:true;请求方 stream=true → 真流式转发边收边吐,
2
+ // false → 聚合回 JSON。装配走 request.js,帧格式走 sse.js,两条管线共享。
3
+ import { compatFetch, timeoutSignal } from "../../compat.js";
4
+ import { normalizeRegion } from "./constants.js";
5
+ import { buildUpstreamRequest } from "./request.js";
6
+ import { reshapeQoderStream } from "./stream.js";
7
+ import { aggregateQoderStream, toCompletionJson } from "./aggregate.js";
8
+ import { errorStatus, extractDelta } from "./sse.js";
9
+
10
+ function hostOf(url) {
11
+ try { return new URL(String(url)).host; } catch { return "-"; }
12
+ }
13
+
14
+ function errRes(status, msg, type = "upstream_error") {
15
+ return new Response(JSON.stringify({ error: { message: msg, type } }), { status, headers: { "Content-Type": "application/json" } });
16
+ }
17
+
18
+ function mapUpstreamError(status, detail) {
19
+ return { kind: status === 401 || status === 403 ? "auth" : "upstream", status, detail: String(detail || "").slice(0, 300) };
20
+ }
21
+
22
+ // 预读上限:判决恒在首帧(实测 457 字节),8 帧足够覆盖"角色帧先到、判决帧随后",
23
+ // 又不会把首字节延迟拖到不可控。超窗未得判决即放弃(退化为无冷却的流内 error,见 SPEC 已知上限)。
24
+ const PEEK_MAX_FRAMES = 8;
25
+
26
+ // 预读上游首帧只为取「流内判决」:qoder 把限流/鉴权判决裹在 HTTP 200 的 SSE 信封里
27
+ //(statusCodeValue:403 + serviceAvailable:false),upRes.status 恒 200,判决只有读完帧才知道。
28
+ // 不预读则状态码永远出不来流式路径 → 门面不冷却该号(ADR-0036 的粘号会把重试继续粘在它上面)。
29
+ // 返回 { res, status, frames }:res 是把预读帧回灌后的等价上游响应,frames 交回灌用。
30
+ // 任何异常都降级为「无判决」(status=0):排障手段不得变成故障源。
31
+ async function peekEnvelopeVerdict(upRes, cdbg) {
32
+ if (!upRes?.body) return { res: upRes, status: 0, quota: false, queued: false, frames: [] };
33
+ let reader;
34
+ try { reader = upRes.body.getReader(); } catch { return { res: upRes, status: 0, quota: false, queued: false, frames: [] }; }
35
+ const dec = new TextDecoder();
36
+ const frames = [];
37
+ let text = "";
38
+ let status = 0;
39
+ let quota = false;
40
+ let queued = false;
41
+ let decided = false;
42
+ try {
43
+ for (let i = 0; i < PEEK_MAX_FRAMES && !decided; i++) {
44
+ const { done, value } = await reader.read();
45
+ if (done) break;
46
+ if (value) { frames.push(value); text += dec.decode(value, { stream: true }); }
47
+ // 逐行判定:先到判决(err)或先到有效载荷即停,避免无谓等待
48
+ for (const raw of text.split("\n")) {
49
+ const line = raw.trim();
50
+ if (!line.startsWith("data:")) continue;
51
+ const p = line.slice(5).trim();
52
+ if (!p || p === "[DONE]") continue;
53
+ const d = extractDelta(p);
54
+ if (d.err) { status = Number(d.err.status) || 0; quota = d.err.kind === "quota"; queued = d.err.queued === true; decided = true; break; }
55
+ if (d.content || d.reasoning || d.toolCalls || d.usageIn || d.usageOut) { decided = true; break; }
56
+ }
57
+ }
58
+ } catch (e) {
59
+ cdbg(`[peek-throw] ${String(e?.message || e).slice(0, 160)}`);
60
+ }
61
+ cdbg(`[peek] frames=${frames.length} verdict=${status || "none(正常流)"} quota=${quota} queued=${queued}`);
62
+ // 回灌:已读帧先按原样吐出,再接续同一个 reader 的剩余部分
63
+ const body = new ReadableStream({
64
+ start(ctrl) {
65
+ for (const f of frames) { try { ctrl.enqueue(f); } catch {} }
66
+ (async () => {
67
+ try {
68
+ for (;;) {
69
+ const { done, value } = await reader.read();
70
+ if (done) break;
71
+ if (value) ctrl.enqueue(value);
72
+ }
73
+ } catch {}
74
+ try { ctrl.close(); } catch {}
75
+ })();
76
+ },
77
+ });
78
+ return { res: new Response(body, { status: upRes.status, headers: upRes.headers }), status, quota, queued, frames };
79
+ }
80
+ export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
81
+ if (!fetchImpl) fetchImpl = compatFetch;
82
+
83
+ // body: OpenAI chat 请求;sess: 已建 COSY 会话;region: 该账号所属区(每号独立选端点)。返回 Response。
84
+ // 回显(可观测,不落凭据):x-mslxdff-upstream=本次请求的 host、x-mslxdff-qoder-region=cn|global;
85
+ // 管线层据此把"这次谁上的、打哪个站"投进模型日志(此前 provider 内部选号/切 URL 完全静默,排障无据)。
86
+ const withEcho = (res, url, region, pick) => {
87
+ try {
88
+ res.headers.set("x-mslxdff-upstream", hostOf(url));
89
+ res.headers.set("x-mslxdff-qoder-region", normalizeRegion(region));
90
+ // 账号选择决定(new/sticky/switch/forced):管线把它写进模型日志,"为什么会切号"才有据可查
91
+ if (pick) res.headers.set("x-mslxdff-qoder-account", String(pick));
92
+ } catch {}
93
+ return res;
94
+ };
95
+
96
+ // 上游状态回显(内部交接用,不落日志):流式路径按对外契约把非 200 整形成 "200 + 流内 error",
97
+ // 真实状态码只能靠这个头带出——否则 401/403/429/5xx 到不了 provider 门面,坏号不被冷却,
98
+ // 而"同请求粘号"(ADR-0036)会把后续重试继续粘在这个坏号上。
99
+ // Note: 流内判决需预读首帧才能拿到(HTTP 200 里裹 statusCodeValue)— 见 .agents/notes/implemented/bug-fix/2026-09-27-qoder-envelope-verdict-cooldown.md
100
+ const withUpstreamStatus = (res, st) => {
101
+ try { res.headers.set("x-mslxdff-qoder-upstream-status", String(st)); } catch {}
102
+ return res;
103
+ };
104
+ // 额度耗尽标记(内部交接,不落日志):门面据此换号(长冷却该号)而非普通短冷却
105
+ const withQuota = (res) => {
106
+ try { res.headers.set("x-mslxdff-qoder-quota", "1"); } catch {}
107
+ return res;
108
+ };
109
+ // 排队标记(内部交接,不落日志):与额度同为「换号」信号但冷却档不同——
110
+ // 排队是「稍后再来」,长冷却到点自动回池;额度是「今天没了」,按天重置才回。
111
+ const withQueued = (res) => {
112
+ try { res.headers.set("x-mslxdff-qoder-queued", "1"); } catch {}
113
+ return res;
114
+ };
115
+
116
+ async function runChat(body, sess, region = "global", pick = "") {
117
+ const stream = body?.stream !== false;
118
+ const model = body?.model || "qfmodel";
119
+ const chatId = "chatcmpl-qoder-" + Math.random().toString(16).slice(2, 10);
120
+ const tools = Array.isArray(body?.tools) && body.tools.length ? body.tools : null;
121
+ const messages = Array.isArray(body?.messages) ? body.messages : [];
122
+ const maxTokens = Number(body?.max_tokens) || 0;
123
+
124
+ let upRes; let reqUrl = "";
125
+ const echo = (res) => withEcho(res, reqUrl, region, pick);
126
+ // 排障日志(QODER_DEBUG_STREAM=1 开):记录出口/状态/耗时/响应头,便于对比"200 但空轮"
127
+ const cdbg = (...a) => { if (process.env.QODER_DEBUG_STREAM === "1") console.log("[qoder-chat]", ...a); };
128
+ let upMs = 0;
129
+ try {
130
+ const req = buildUpstreamRequest({ sess, region: normalizeRegion(region), model, messages, tools, maxTokens });
131
+ reqUrl = req.url;
132
+ cdbg(`[req] url=${hostOf(req.url)} region=${normalizeRegion(region)} model=${model} msgs=${messages.length} tools=${tools?.length ?? 0} maxTokens=${maxTokens} stream=${stream} bodyBytes=${req.bodyStr?.length ?? 0}`);
133
+ const t0 = Date.now();
134
+ upRes = await fetchImpl(req.url, {
135
+ method: "POST",
136
+ headers: req.headers,
137
+ body: req.bodyStr,
138
+ signal: timeoutSignal(timeoutMs || 120_000),
139
+ });
140
+ upMs = Date.now() - t0;
141
+ cdbg(`[res] status=${upRes.status} ms=${upMs} ct=${upRes.headers.get("content-type")} host=${hostOf(reqUrl)}`);
142
+ } catch (e) {
143
+ const detail = String(e?.message || e).slice(0, 300);
144
+ cdbg(`[res-throw] ms=${upMs} err=${detail}`);
145
+ // 网络异常(超时/连接失败)折成 502:门面据此冷却该号(否则坏号恒在轮换池里)
146
+ if (stream) return withUpstreamStatus(echo(reshapeQoderStream(new Response("data: [DONE]\n\n"), { model, chatId })), 502);
147
+ return withUpstreamStatus(echo(errRes(502, detail)), 502);
148
+ }
149
+ if (upRes.status !== 200) {
150
+ const detail = await upRes.text().catch(() => "");
151
+ cdbg(`[res-non200] status=${upRes.status} body=${detail.slice(0, 300)}`);
152
+ const e = mapUpstreamError(upRes.status, detail);
153
+ if (stream) {
154
+ // 首包错误也走流内 error 事件(与旧 reshapeStream catch 语义一致:200 + event:error + DONE)
155
+ const enc = new TextEncoder();
156
+ const s = new ReadableStream({
157
+ start(c) {
158
+ c.enqueue(enc.encode(`data: ${JSON.stringify({ id: chatId, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: {}, finish_reason: null }] })}\n\n`));
159
+ c.enqueue(enc.encode(`event: error\ndata: ${JSON.stringify({ message: e.detail, type: e.kind })}\n\ndata: [DONE]\n\n`));
160
+ c.close();
161
+ },
162
+ });
163
+ // 对外仍是 200(契约不变),真实状态码经回显头交门面决定是否冷却
164
+ return withUpstreamStatus(echo(new Response(s, { status: 200, headers: { "Content-Type": "text/event-stream" } })), upRes.status);
165
+ }
166
+ return withUpstreamStatus(echo(errRes(errorStatus(e), e.detail, e.kind)), upRes.status);
167
+ }
168
+ if (stream) {
169
+ // 预读首帧取流内判决(qoder 把 403/429 裹在 200 的信封里),预读帧原样回灌给整形器。
170
+ // 判决状态码经 withUpstreamStatus 出门面 → index.js 据此 ring.onError 冷却该号 →
171
+ // 粘号选择器下次因 isCooling 为真而换号。对外仍恒 200(契约不变)。
172
+ const peek = await peekEnvelopeVerdict(upRes, cdbg);
173
+ let shaped = echo(reshapeQoderStream(peek.res, { model, chatId, prefetched: peek.frames }));
174
+ // 只在真有判决时挂状态码:正常流不写这个头(index.js 靠它区分"要不要冷却")
175
+ if (peek.status) shaped = withUpstreamStatus(shaped, peek.status);
176
+ if (peek.quota) shaped = withQuota(shaped);
177
+ // 排队旗标(内部交接):门面据此走队列档冷却并在同一请求内换号,别把排队号送回客户端
178
+ if (peek.queued) shaped = withQueued(shaped);
179
+ return shaped;
180
+ }
181
+ try {
182
+ const agg = await aggregateQoderStream(upRes);
183
+ const out = toCompletionJson({ model, chatId, ...agg });
184
+ return echo(new Response(JSON.stringify(out), { status: 200, headers: { "Content-Type": "application/json" } }));
185
+ } catch (e) {
186
+ const out = echo(errRes(errorStatus(e), String(e?.detail || e?.message || e).slice(0, 300), e?.kind || "upstream_error"));
187
+ const marked = e?.kind === "quota" ? withQuota(out) : out;
188
+ return e?.queued ? withQueued(marked) : marked;
189
+ }
190
+ }
191
+
192
+ return { runChat };
193
+ }