mslxdff 0.1.162 → 0.1.164
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.
- package/package.json +1 -1
- package/src/anthropic/translate.js +379 -0
- package/src/chat-pipeline/index.js +3 -2
- package/src/cli/commands/stats.js +21 -9
- package/src/cli/commands/sync.js +74 -2
- package/src/cli/help.js +2 -1
- package/src/providers/globalworkbuddy/account-store.js +198 -0
- package/src/providers/globalworkbuddy/auth.js +97 -0
- package/src/providers/globalworkbuddy/catalog.js +138 -0
- package/src/providers/globalworkbuddy/constants.js +73 -0
- package/src/providers/globalworkbuddy/device-auth.js +120 -0
- package/src/providers/globalworkbuddy/errors.js +98 -0
- package/src/providers/globalworkbuddy/headers.js +89 -0
- package/src/providers/globalworkbuddy/models.js +96 -0
- package/src/providers/globalworkbuddy/payload.js +80 -0
- package/src/providers/qoder/aggregate.js +12 -3
- package/src/providers/qoder/chat.js +9 -2
- package/src/providers/qoder/index.js +13 -3
- package/src/providers/qoder/models.js +7 -3
- package/src/providers/qoder/payload.js +7 -1
- package/src/providers/qoder/request.js +2 -1
- package/src/providers/qoder/sse.js +5 -1
- package/src/providers/qoder/stream.js +16 -4
- package/src/routes/chat/exhausted-handler.js +13 -2
- package/src/routes/chat/relay-pipeline.js +18 -2
- package/src/routes/index.js +13 -0
- package/src/routes/messages-route.js +290 -0
- package/src/routes/responses-route.js +2 -2
- package/src/routes/stream-scan.js +22 -5
- package/src/routes/stream.js +2 -3
- package/src/server.js +5 -0
- package/src/sync-claude.js +152 -0
- package/src/talk-full-redact.js +129 -0
- package/src/talk-full.js +130 -0
- package/src/talk-log.js +42 -15
- package/src/upstream-engine/sdk/responses.js +5 -0
- package/src/usage/report.js +14 -8
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// 上游错误分型:决定一次失败该「刷新」「换号」「原地重试」还是「直接报错」。
|
|
2
|
+
// 与国内版 `workbuddy/auth.js:20` 的关键区别:**403 不再一律当鉴权失败**。
|
|
3
|
+
// 国际版实测:11140(安全审核)、11128、11133、11101、11102 全是 403/400,refresh 对它们完全无用
|
|
4
|
+
// —— 而 CN 版把 403 当鉴权,等于每命中一次就白烧一次 token 刷新(`global-hi.js:221` 早已发现却从未回流 provider)。
|
|
5
|
+
// Note: 同一个业务码在两区含义不同(11128 在 CN=developer role 被拒、在国际版=缺首条 system),
|
|
6
|
+
// 所以判型只能「码 + 文案」一起看,且**绝不按码单独分支**。
|
|
7
|
+
|
|
8
|
+
/** 积分不足标记:英文小写形 + 中文原文(词表照参考仓库 upstream.ts:184-189)。 */
|
|
9
|
+
const HARD_CREDIT_MARKERS = [
|
|
10
|
+
"insufficient credit", "no credit", "credit exhausted", "credits exhausted", "out of credit",
|
|
11
|
+
"quota exceeded", "quota exhaust", "payment required", "credit not enough", "not enough credit",
|
|
12
|
+
"积分不足", "额度不足", "余额不足", "积分用完", "额度用尽", "没有积分",
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
/** 会话失效措辞(403 时用于区分「真鉴权」与「业务拒绝」)。 */
|
|
16
|
+
const SESSION_MARKERS = [
|
|
17
|
+
"unauthorized", "authenticate", "invalid token", "token expired", "token invalid",
|
|
18
|
+
"access token", "login expired", "need login", "session expired", "未登录", "登录过期", "会话过期",
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
/** 安全审核类:11140 是伞形码(实测 displayMsg 既见「内容未通过安全审核」也见「访问受限」)。 */
|
|
22
|
+
const SAFETY_MARKERS = ["request illegal", "safety", "安全审核", "內容未通過", "访问受限"];
|
|
23
|
+
|
|
24
|
+
/** 参数类业务码(实测:11101 tool_choice 反序列化、11102 模型不存在、11128 首条/角色、11133 参数被模型拒)。 */
|
|
25
|
+
const PARAM_CODES = new Set(["11101", "11102", "11128", "11133"]);
|
|
26
|
+
|
|
27
|
+
function pickBusinessCode(text) {
|
|
28
|
+
const m = String(text || "").match(/"code"\s*:\s*"?(\d{4,6})"?/);
|
|
29
|
+
return m ? m[1] : "";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 提取 `displayMsg.zh` → `displayMsg.en` → `msg`(参考仓库 issue #58 的教训:别把整串 JSON 甩给用户)。 */
|
|
33
|
+
export function extractDisplayMessage(text) {
|
|
34
|
+
let obj;
|
|
35
|
+
try { obj = JSON.parse(String(text || "")); } catch { return ""; }
|
|
36
|
+
if (!obj || typeof obj !== "object") return "";
|
|
37
|
+
const dm = obj.displayMsg;
|
|
38
|
+
if (dm && typeof dm === "object") {
|
|
39
|
+
for (const key of ["zh", "en", "zh-hant"]) {
|
|
40
|
+
if (typeof dm[key] === "string" && dm[key].trim()) return dm[key].trim();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return typeof obj.msg === "string" ? obj.msg.trim() : "";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function extErrorCode(text) {
|
|
47
|
+
try {
|
|
48
|
+
const obj = JSON.parse(String(text || ""));
|
|
49
|
+
const code = obj?.extError?.code;
|
|
50
|
+
return typeof code === "string" ? code : "";
|
|
51
|
+
} catch { return ""; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 分型入口。返回 `{ kind, code, extCode, displayMsg, detail }`。
|
|
56
|
+
* kind ∈ session_dead | hard_credit | safety | param | rate_limit | server | client | unknown
|
|
57
|
+
*/
|
|
58
|
+
export function classifyUpstreamError(status, bodyText) {
|
|
59
|
+
const text = String(bodyText || "");
|
|
60
|
+
const lower = text.toLowerCase();
|
|
61
|
+
const code = pickBusinessCode(text);
|
|
62
|
+
const extCode = extErrorCode(text);
|
|
63
|
+
const out = { kind: "unknown", code, extCode, displayMsg: extractDisplayMessage(text), detail: text.slice(0, 200) };
|
|
64
|
+
|
|
65
|
+
if (status === 401) { out.kind = "session_dead"; return out; }
|
|
66
|
+
if (status === 402) { out.kind = "hard_credit"; return out; }
|
|
67
|
+
if (status === 429) { out.kind = "rate_limit"; return out; }
|
|
68
|
+
if (status >= 500) { out.kind = "server"; return out; }
|
|
69
|
+
|
|
70
|
+
// 顺序即优先级:先排掉「刷了也没用」的三类,再谈鉴权。
|
|
71
|
+
if (SAFETY_MARKERS.some((m) => lower.includes(m.toLowerCase()) || text.includes(m))) { out.kind = "safety"; return out; }
|
|
72
|
+
if (HARD_CREDIT_MARKERS.some((m) => lower.includes(m.toLowerCase()) || text.includes(m))) { out.kind = "hard_credit"; return out; }
|
|
73
|
+
if (PARAM_CODES.has(code) || (status === 400 && code && code !== "11140")) { out.kind = "param"; return out; }
|
|
74
|
+
if (status === 403 && SESSION_MARKERS.some((m) => lower.includes(m))) { out.kind = "session_dead"; return out; }
|
|
75
|
+
if (status === 400 && lower.includes("token")) { out.kind = "session_dead"; return out; }
|
|
76
|
+
if (status >= 400 && status < 500) { out.kind = "client"; return out; }
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 只有这类才值得去刷 token。 */
|
|
81
|
+
export function isSessionDead(kind) { return kind === "session_dead"; }
|
|
82
|
+
/** 只有这类才该把该号冷却并换下一个号(刷 token 与重试都无救)。 */
|
|
83
|
+
export function isCreditExhausted(kind) { return kind === "hard_credit"; }
|
|
84
|
+
/** 这类是「随机拦截」,同请求体原地重试可救(`global-hi.js:229` 实测 11140 按 ~10-25% 概率出现)。 */
|
|
85
|
+
export function isRetryableSafety(kind) { return kind === "safety"; }
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 给人看的错误文案。
|
|
89
|
+
* ⚠ 非鉴权类刻意**不写裸 `401`/`403` 数字**:下游宿主/适配器常按 `/\b(401|403)\b/` 直接判成
|
|
90
|
+
* "API Key 无效",会把真实业务错误覆盖掉(参考仓库 issue #58 原封不动踩过这个坑)。
|
|
91
|
+
*/
|
|
92
|
+
export function friendlyMessage(kind, bodyText, providerId = "globalworkbuddy") {
|
|
93
|
+
const display = extractDisplayMessage(bodyText);
|
|
94
|
+
const code = pickBusinessCode(bodyText);
|
|
95
|
+
const label = display || (code ? `code ${code}` : String(bodyText || "").slice(0, 160)) || "上游拒绝";
|
|
96
|
+
const prefix = kind === "session_dead" ? `${providerId} 会话已失效` : `${providerId} 上游拒绝`;
|
|
97
|
+
return code ? `${prefix}(${code}):${label}` : `${prefix}:${label}`;
|
|
98
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// 三条通道的请求头装配。与国内版(`workbuddy/chat.js:12` 的 buildAuthHeaders)有三处**有意的**不同,
|
|
2
|
+
// 全部来自 2026-10-05 取证与参考仓库 upstream.ts:374-421 的通道隔离纪律:
|
|
3
|
+
// ① Origin/Referer 与 host 同源 —— 国内版对 `.ai` token 发 `www.codebuddy.cn` 的 Origin 属跨产品指纹错配;
|
|
4
|
+
// ② chat 通道**绝不**携带 refreshToken(参考仓库注释称「安全红线」,我们国内版没这条约束但同样该守);
|
|
5
|
+
// ③ refresh 通道**不带** `Authorization: Bearer`(`global-hi.js:143` 现在带着可能已过期的 token,属错误做法)。
|
|
6
|
+
// 缺值一律走 `X-No-*` 占位:上游区分「字段缺失」与「字段为空」(参考仓库同款处理)。
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
ORIGIN, DOMAIN, CHAT_UA, CATALOG_UA, REFRESH_UA, APP_VERSION,
|
|
10
|
+
} from "./constants.js";
|
|
11
|
+
|
|
12
|
+
function common(ua) {
|
|
13
|
+
return {
|
|
14
|
+
Accept: "application/json, text/plain, */*",
|
|
15
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
16
|
+
Origin: ORIGIN,
|
|
17
|
+
Referer: `${ORIGIN}/`,
|
|
18
|
+
"User-Agent": ua,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 身份类头:uid/enterpriseId/domain 缺值走 X-No-* 占位。 */
|
|
23
|
+
function identityHeaders(cred) {
|
|
24
|
+
const uid = String(cred?.uid || "");
|
|
25
|
+
const ent = String(cred?.enterpriseId || "");
|
|
26
|
+
const domain = String(cred?.domain || "") || DOMAIN;
|
|
27
|
+
return {
|
|
28
|
+
...(uid ? { "X-User-Id": uid } : { "X-No-User-Id": "1" }),
|
|
29
|
+
...(ent ? { "X-Enterprise-Id": ent, "X-Tenant-Id": ent } : { "X-No-Enterprise-Id": "1" }),
|
|
30
|
+
...(cred?.domain ? { "X-Domain": domain } : { "X-No-Department-Info": "1" }),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** chat:只带 Bearer,永不含 refreshToken。Accept 用「全量族」写法(实测穿得过参数校验)。 */
|
|
35
|
+
export function chatHeaders(cred) {
|
|
36
|
+
return {
|
|
37
|
+
...common(CHAT_UA),
|
|
38
|
+
"Content-Type": "application/json",
|
|
39
|
+
"Accept-Language": "en-US",
|
|
40
|
+
"X-IDE-Name": "WorkBuddy",
|
|
41
|
+
"X-IDE-Type": "WorkBuddy",
|
|
42
|
+
"X-IDE-Version": APP_VERSION,
|
|
43
|
+
"X-Product": "SaaS",
|
|
44
|
+
...identityHeaders(cred),
|
|
45
|
+
Authorization: `Bearer ${cred?.accessToken || ""}`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 目录(/v3/config):Bearer + 同源 Origin;UA 独立可覆盖(结论 B 证明上游不据此分流,但留排障口子)。 */
|
|
50
|
+
export function catalogHeaders(cred) {
|
|
51
|
+
return {
|
|
52
|
+
Accept: "application/json",
|
|
53
|
+
Origin: ORIGIN,
|
|
54
|
+
Referer: `${ORIGIN}/`,
|
|
55
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
56
|
+
"X-Product": "SaaS",
|
|
57
|
+
"User-Agent": CATALOG_UA,
|
|
58
|
+
Authorization: `Bearer ${cred?.accessToken || ""}`,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** refresh:`X-Refresh-Token` 只出现在这里;**不带 Authorization**。 */
|
|
63
|
+
export function refreshHeaders(cred) {
|
|
64
|
+
return {
|
|
65
|
+
...common(REFRESH_UA),
|
|
66
|
+
"Content-Type": "application/json",
|
|
67
|
+
"X-Refresh-Token": String(cred?.refreshToken || ""),
|
|
68
|
+
"X-Auth-Refresh-Source": "workbuddy",
|
|
69
|
+
...identityHeaders(cred),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 计费(余额):Bearer + 身份头,无 IDE 指纹。 */
|
|
74
|
+
export function billingHeaders(cred) {
|
|
75
|
+
return {
|
|
76
|
+
Accept: "application/json",
|
|
77
|
+
"Content-Type": "application/json",
|
|
78
|
+
Origin: ORIGIN,
|
|
79
|
+
Referer: `${ORIGIN}/`,
|
|
80
|
+
"User-Agent": CHAT_UA,
|
|
81
|
+
...identityHeaders(cred),
|
|
82
|
+
Authorization: `Bearer ${cred?.accessToken || ""}`,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 设备授权流(登录时手里还没有凭据):UA/Origin 齐,但既无 Bearer 也无 X-User-Id。 */
|
|
87
|
+
export function deviceHeaders() {
|
|
88
|
+
return { ...common(REFRESH_UA), "Content-Type": "application/json" };
|
|
89
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// 目录服务:`GET /v3/config` → 带 `globalworkbuddy/` 前缀的模型表,10 分钟缓存。
|
|
2
|
+
// 三条取证结论落在这里:① 国内版的 console 目录在国际版恒 500,**不留那条兜底路径**;
|
|
3
|
+
// ② 目录不随 UA 变(结论 B),所以 UA 只是排障变量;③ 取数失败要**标来源**回落,
|
|
4
|
+
// 让上层能分清「真目录」与「兜底表」—— 拿兜底表冒充上游目录去烧积分是最坏情况。
|
|
5
|
+
import { compatFetch, timeoutSignal } from "../../compat.js";
|
|
6
|
+
import { joinUrl } from "../base.js";
|
|
7
|
+
import { joinModelId } from "../model-id.js";
|
|
8
|
+
import { BASE, MODELS_PATH, MODELS_CACHE_MS, JSON_TIMEOUT_MS } from "./constants.js";
|
|
9
|
+
import { catalogHeaders } from "./headers.js";
|
|
10
|
+
import { unwrapConfigDocument, parseModelCatalog, fallbackCatalog } from "./catalog.js";
|
|
11
|
+
import { classifyUpstreamError } from "./errors.js";
|
|
12
|
+
|
|
13
|
+
export function createModelsService({
|
|
14
|
+
id = "globalworkbuddy",
|
|
15
|
+
baseUrl = BASE,
|
|
16
|
+
fetchImpl,
|
|
17
|
+
dispatcher,
|
|
18
|
+
getCred, // async () => cred | null(第一个可用国际号)
|
|
19
|
+
authService,
|
|
20
|
+
clock = Date.now,
|
|
21
|
+
} = {}) {
|
|
22
|
+
if (!fetchImpl) fetchImpl = compatFetch;
|
|
23
|
+
const resolvedBase = String(baseUrl || BASE).trim().replace(/\/+$/, "");
|
|
24
|
+
let cache = null; // { rows, source, fetchedAt }
|
|
25
|
+
let refreshInFlight = null;
|
|
26
|
+
|
|
27
|
+
async function exec(cred) {
|
|
28
|
+
const opts = { headers: catalogHeaders(cred), signal: timeoutSignal(JSON_TIMEOUT_MS) };
|
|
29
|
+
if (dispatcher) opts.dispatcher = dispatcher;
|
|
30
|
+
return fetchImpl(joinUrl(resolvedBase, MODELS_PATH), opts);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function readOnce(cred) {
|
|
34
|
+
const res = await exec(cred);
|
|
35
|
+
if (!res.ok) {
|
|
36
|
+
let text = "";
|
|
37
|
+
try { text = await res.clone().text(); } catch {}
|
|
38
|
+
return { ok: false, kind: classifyUpstreamError(res.status, text).kind, status: res.status };
|
|
39
|
+
}
|
|
40
|
+
const json = await res.json().catch(() => ({}));
|
|
41
|
+
const rows = parseModelCatalog(unwrapConfigDocument(json));
|
|
42
|
+
if (!rows.length) return { ok: false, kind: "empty", status: res.status };
|
|
43
|
+
return { ok: true, rows, status: res.status };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 真正打上游:401/会话失效时刷一次再来;失败回落兜底表(并保留上次成功结果优先)。 */
|
|
47
|
+
async function fetchLive() {
|
|
48
|
+
const cred = typeof getCred === "function" ? await getCred() : null;
|
|
49
|
+
if (!cred?.accessToken) return { rows: fallbackCatalog(), source: "fallback", reason: "no-credential" };
|
|
50
|
+
let r = await readOnce(cred);
|
|
51
|
+
if (!r.ok && r.kind === "session_dead" && authService && !refreshInFlight) {
|
|
52
|
+
refreshInFlight = (async () => {
|
|
53
|
+
const nk = await authService.refreshTokenFor?.(cred);
|
|
54
|
+
return nk ? { ...cred, accessToken: nk } : null;
|
|
55
|
+
})();
|
|
56
|
+
try {
|
|
57
|
+
const cred2 = await refreshInFlight;
|
|
58
|
+
if (cred2) r = await readOnce(cred2);
|
|
59
|
+
} finally { refreshInFlight = null; }
|
|
60
|
+
}
|
|
61
|
+
if (r.ok) return { rows: r.rows, source: "upstream", status: r.status };
|
|
62
|
+
// 上游失败:先吃旧缓存(哪怕过期),再退兜底表 —— 目录列表空掉比目录旧更伤体验
|
|
63
|
+
if (cache?.rows?.length) return { rows: cache.rows, source: cache.source, stale: true, reason: r.kind };
|
|
64
|
+
return { rows: fallbackCatalog(), source: "fallback", reason: r.kind };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function listModels() {
|
|
68
|
+
const now = clock();
|
|
69
|
+
if (cache && cache.source === "upstream" && now - cache.fetchedAt < MODELS_CACHE_MS) {
|
|
70
|
+
return cache.rows.map((m) => ({ ...m, id: joinModelId(id, m.id) }));
|
|
71
|
+
}
|
|
72
|
+
const out = await fetchLive();
|
|
73
|
+
cache = { rows: out.rows, source: out.source, fetchedAt: now, reason: out.reason || "" };
|
|
74
|
+
return cache.rows.map((m) => ({ ...m, id: joinModelId(id, m.id) }));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 预热:只探连通与鉴权,不解析结果;失败也回结构,供启动日志一行诊断。 */
|
|
78
|
+
async function preheat() {
|
|
79
|
+
const t0 = clock();
|
|
80
|
+
try {
|
|
81
|
+
const cred = typeof getCred === "function" ? await getCred() : null;
|
|
82
|
+
if (!cred?.accessToken) return { ok: false, error: "no-credential", ms: 0 };
|
|
83
|
+
const res = await exec(cred);
|
|
84
|
+
try { if (res.body) await res.text().catch(() => {}); } catch {}
|
|
85
|
+
return { ok: res.ok, status: res.status, ms: Math.round(clock() - t0) };
|
|
86
|
+
} catch (err) {
|
|
87
|
+
return { ok: false, error: String(err?.message || err), ms: Math.round(clock() - t0) };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function clearCache() { cache = null; }
|
|
92
|
+
/** 给状态卡/诊断用:当前列表来自上游还是兜底。 */
|
|
93
|
+
function catalogSource() { return cache ? { source: cache.source, fetchedAt: cache.fetchedAt, reason: cache.reason } : null; }
|
|
94
|
+
|
|
95
|
+
return { listModels, preheat, clearCache, catalogSource, _getCache: () => cache };
|
|
96
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// 国际版出站 chat body 改写。四条规则**全部是本 provider 现网实测**(2026-10-05,见 FINDINGS 结论 C/C 表),
|
|
2
|
+
// 不是从国内版 `workbuddy/payload.js` 搬来的经验值。
|
|
3
|
+
//
|
|
4
|
+
// 规则 实测响应
|
|
5
|
+
// 缺首条 system → 400/11128 "first message is not system prompt"
|
|
6
|
+
// role:"developer" → 400/11128 "Illegal API invocation from an unapproved channel"
|
|
7
|
+
// tool_choice 传对象 → 400/11101 "cannot unmarshal object into ... Request.tool_choice of type string"
|
|
8
|
+
// reasoning_effort:"off" → 国际版 GPT 系 400/11133(参考仓库 issue #49/#50 同款;本区只删这一个字面量)
|
|
9
|
+
//
|
|
10
|
+
// ⚠ **刻意不做**的两件事(国内版 payload.js 里有,国际版未取证,凭经验加等于猜上游):
|
|
11
|
+
// · DeepSeek `thinking.type=enabled` 注入 —— 国际版是否需要/是否接受该非标字段,未测;
|
|
12
|
+
// · assistant `reasoning_content` 回填 —— 同上。要加先跑探针(`.scratch/globalworkbuddy/probe*.mjs` 有现成骨架)。
|
|
13
|
+
export const INTERNATIONAL_SYSTEM_PROMPT = "You are a helpful assistant.";
|
|
14
|
+
|
|
15
|
+
/** role 归一:上游白名单不含 developer。就地改,返回改动计数供日志。 */
|
|
16
|
+
export function normalizeRoles(obj) {
|
|
17
|
+
const msgs = obj?.messages;
|
|
18
|
+
if (!Array.isArray(msgs)) return obj;
|
|
19
|
+
for (const m of msgs) {
|
|
20
|
+
if (m && typeof m === "object" && typeof m.role === "string" && m.role.trim().toLowerCase() === "developer") {
|
|
21
|
+
m.role = "system";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return obj;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** tool_choice 必须是 string;`none` 连带删掉 tools/functions(上游会拒「说不调工具又给工具」)。 */
|
|
28
|
+
export function normalizeToolChoice(obj) {
|
|
29
|
+
const tc = obj?.tool_choice;
|
|
30
|
+
if (tc === undefined || tc === null) return obj;
|
|
31
|
+
const dropTools = () => { delete obj.tools; delete obj.functions; };
|
|
32
|
+
if (typeof tc === "string") {
|
|
33
|
+
if (tc.trim().toLowerCase() === "none") { delete obj.tool_choice; dropTools(); }
|
|
34
|
+
return obj;
|
|
35
|
+
}
|
|
36
|
+
if (typeof tc === "object") {
|
|
37
|
+
const type = String(tc.type || "").trim().toLowerCase();
|
|
38
|
+
if (type === "none") { delete obj.tool_choice; dropTools(); }
|
|
39
|
+
else if (type === "auto" || type === "required") obj.tool_choice = type;
|
|
40
|
+
else if (type === "function") {
|
|
41
|
+
const name = String(tc?.function?.name || tc?.name || "").trim();
|
|
42
|
+
obj.tool_choice = name || "auto";
|
|
43
|
+
} else delete obj.tool_choice;
|
|
44
|
+
return obj;
|
|
45
|
+
}
|
|
46
|
+
delete obj.tool_choice;
|
|
47
|
+
return obj;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 只删适配器自造的 `off`;`low/medium/high/xhigh/max` 与显式 `none` 原样透传。 */
|
|
51
|
+
export function dropUnsupportedEffort(obj) {
|
|
52
|
+
if (obj?.reasoning_effort === "off") delete obj.reasoning_effort;
|
|
53
|
+
return obj;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 首条必须 system:缺了就**前插**一条中性提示,绝不合并/改写用户已有消息。 */
|
|
57
|
+
export function ensureLeadingSystem(obj) {
|
|
58
|
+
if (!Array.isArray(obj?.messages)) return obj;
|
|
59
|
+
const first = obj.messages[0];
|
|
60
|
+
if (first && typeof first === "object" && first.role === "system") return obj;
|
|
61
|
+
obj.messages.unshift({ role: "system", content: INTERNATIONAL_SYSTEM_PROMPT });
|
|
62
|
+
return obj;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 入口:吃 OpenAI 形状 body,返回**新对象**(messages 浅拷贝,不污染调用方)。
|
|
67
|
+
* 上游拒绝非流式,故强制 `stream: true`。
|
|
68
|
+
*/
|
|
69
|
+
export function rewriteGlobalworkbuddyPayload(body) {
|
|
70
|
+
if (!body || typeof body !== "object") return body;
|
|
71
|
+
const obj = { ...body, stream: true };
|
|
72
|
+
obj.messages = Array.isArray(body.messages)
|
|
73
|
+
? body.messages.map((m) => (m && typeof m === "object" ? { ...m } : m))
|
|
74
|
+
: body.messages;
|
|
75
|
+
normalizeRoles(obj);
|
|
76
|
+
normalizeToolChoice(obj);
|
|
77
|
+
dropUnsupportedEffort(obj);
|
|
78
|
+
ensureLeadingSystem(obj);
|
|
79
|
+
return obj;
|
|
80
|
+
}
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
// 真流式走 stream.js;本模块只服务 stream:false(行为与旧 callQoder 聚合同)。
|
|
3
3
|
import { extractDelta } from "./sse.js";
|
|
4
4
|
|
|
5
|
+
// 与 stream.js 同限:未完结行超 2MiB 即中断(内存保护)。
|
|
6
|
+
const MAX_BUFFER_CHARS = 2 * 1024 * 1024;
|
|
7
|
+
|
|
5
8
|
export async function aggregateQoderStream(upstreamRes) {
|
|
6
9
|
const reader = upstreamRes.body.getReader();
|
|
7
10
|
const dec = new TextDecoder();
|
|
@@ -10,6 +13,7 @@ export async function aggregateQoderStream(upstreamRes) {
|
|
|
10
13
|
let content = "";
|
|
11
14
|
let reasoning = "";
|
|
12
15
|
const toolCalls = [];
|
|
16
|
+
let finishReason = "";
|
|
13
17
|
let sawContent = false;
|
|
14
18
|
for (;;) {
|
|
15
19
|
const { done, value } = await reader.read();
|
|
@@ -23,6 +27,7 @@ export async function aggregateQoderStream(upstreamRes) {
|
|
|
23
27
|
if (!payload || payload === "[DONE]") continue;
|
|
24
28
|
const d = extractDelta(payload);
|
|
25
29
|
if (d.err) throw d.err;
|
|
30
|
+
if (d.finishReason) finishReason = d.finishReason;
|
|
26
31
|
if (d.usageIn > 0 || d.usageOut > 0) {
|
|
27
32
|
usage = { prompt_tokens: d.usageIn, completion_tokens: d.usageOut, total_tokens: d.usageIn + d.usageOut };
|
|
28
33
|
}
|
|
@@ -30,13 +35,17 @@ export async function aggregateQoderStream(upstreamRes) {
|
|
|
30
35
|
if (d.reasoning) { reasoning += d.reasoning; sawContent = true; }
|
|
31
36
|
if (d.toolCalls) { toolCalls.push(...d.toolCalls); sawContent = true; }
|
|
32
37
|
}
|
|
38
|
+
// 完整行消费完毕后再判越限:leftover 超大不得把同 chunk 里的合法帧连坐丢弃(评审路1 P1#4)
|
|
39
|
+
if (buf.length > MAX_BUFFER_CHARS) {
|
|
40
|
+
throw { kind: "upstream", status: 502, detail: "qoder SSE buffer exceeded 2MiB limit" };
|
|
41
|
+
}
|
|
33
42
|
if (done) break;
|
|
34
43
|
}
|
|
35
44
|
if (!sawContent && !usage) throw { kind: "upstream", status: 502, detail: "empty upstream stream" };
|
|
36
|
-
return { usage, content, reasoning, toolCalls };
|
|
45
|
+
return { usage, content, reasoning, toolCalls, finishReason };
|
|
37
46
|
}
|
|
38
47
|
|
|
39
|
-
export function toCompletionJson({ model, chatId, content, reasoning, toolCalls, usage }) {
|
|
48
|
+
export function toCompletionJson({ model, chatId, content, reasoning, toolCalls, usage, finishReason }) {
|
|
40
49
|
const msg = { role: "assistant", content: content || (toolCalls.length ? null : "") };
|
|
41
50
|
if (reasoning) msg.reasoning_content = reasoning;
|
|
42
51
|
if (toolCalls.length) msg.tool_calls = toolCalls;
|
|
@@ -45,7 +54,7 @@ export function toCompletionJson({ model, chatId, content, reasoning, toolCalls,
|
|
|
45
54
|
object: "chat.completion",
|
|
46
55
|
created: Math.floor(Date.now() / 1000),
|
|
47
56
|
model,
|
|
48
|
-
choices: [{ index: 0, message: msg, finish_reason: toolCalls.length ? "tool_calls" : "stop" }],
|
|
57
|
+
choices: [{ index: 0, message: msg, finish_reason: finishReason || (toolCalls.length ? "tool_calls" : "stop") }],
|
|
49
58
|
usage: usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
|
|
50
59
|
};
|
|
51
60
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// qoder 对话服务:上游恒 stream:true;请求方 stream=true → 真流式转发边收边吐,
|
|
2
2
|
// false → 聚合回 JSON。装配走 request.js,帧格式走 sse.js,两条管线共享。
|
|
3
3
|
import { compatFetch, timeoutSignal } from "../../compat.js";
|
|
4
|
+
import { mapModel } from "./payload.js";
|
|
4
5
|
import { normalizeRegion } from "./constants.js";
|
|
5
6
|
import { buildUpstreamRequest } from "./request.js";
|
|
6
7
|
import { reshapeQoderStream } from "./stream.js";
|
|
@@ -77,7 +78,7 @@ async function peekEnvelopeVerdict(upRes, cdbg) {
|
|
|
77
78
|
});
|
|
78
79
|
return { res: new Response(body, { status: upRes.status, headers: upRes.headers }), status, quota, queued, frames };
|
|
79
80
|
}
|
|
80
|
-
export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
|
|
81
|
+
export function createChatService({ id = "qoder", fetchImpl, timeoutMs, getModelMeta } = {}) {
|
|
81
82
|
if (!fetchImpl) fetchImpl = compatFetch;
|
|
82
83
|
|
|
83
84
|
// body: OpenAI chat 请求;sess: 已建 COSY 会话;region: 该账号所属区(每号独立选端点)。返回 Response。
|
|
@@ -120,6 +121,12 @@ export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
|
|
|
120
121
|
const tools = Array.isArray(body?.tools) && body.tools.length ? body.tools : null;
|
|
121
122
|
const messages = Array.isArray(body?.messages) ? body.messages : [];
|
|
122
123
|
const maxTokens = Number(body?.max_tokens) || 0;
|
|
124
|
+
// is_reasoning 由模型目录供数(index 注入 getModelMeta,只读 peekModels 快照缓存,chat 路径恒 0 上游调用);
|
|
125
|
+
// 冷缓存/缺失一律降级 false(= 旧行为,不阻断对话)—— P0:推理标志此前从未出门。
|
|
126
|
+
let isReasoning = false;
|
|
127
|
+
try {
|
|
128
|
+
if (getModelMeta) isReasoning = (await getModelMeta(sess, normalizeRegion(region), mapModel(model)))?.is_reasoning === true;
|
|
129
|
+
} catch {}
|
|
123
130
|
|
|
124
131
|
let upRes; let reqUrl = "";
|
|
125
132
|
const echo = (res) => withEcho(res, reqUrl, region, pick);
|
|
@@ -127,7 +134,7 @@ export function createChatService({ id = "qoder", fetchImpl, timeoutMs } = {}) {
|
|
|
127
134
|
const cdbg = (...a) => { if (process.env.QODER_DEBUG_STREAM === "1") console.log("[qoder-chat]", ...a); };
|
|
128
135
|
let upMs = 0;
|
|
129
136
|
try {
|
|
130
|
-
const req = buildUpstreamRequest({ sess, region: normalizeRegion(region), model, messages, tools, maxTokens });
|
|
137
|
+
const req = buildUpstreamRequest({ sess, region: normalizeRegion(region), model, messages, tools, maxTokens, isReasoning });
|
|
131
138
|
reqUrl = req.url;
|
|
132
139
|
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
140
|
const t0 = Date.now();
|
|
@@ -34,6 +34,7 @@ export function createQoderProvider({
|
|
|
34
34
|
file,
|
|
35
35
|
region,
|
|
36
36
|
fetchImpl,
|
|
37
|
+
sharedModelsSvc, // chatWithKeys 等临时门面复用主实例目录快照(评审路1 P1#3:冷缓存否则恒 false)
|
|
37
38
|
cooldownMs = envInt("MSLXDFF_QODER_COOLDOWN_MS", 30_000),
|
|
38
39
|
// 额度耗尽(code 110)按天重置:短冷却等于反复撞死号,故单独配长冷却(默认 1h)
|
|
39
40
|
quotaCooldownMs = envInt("MSLXDFF_QODER_QUOTA_COOLDOWN_MS", 3600_000),
|
|
@@ -88,9 +89,18 @@ export function createQoderProvider({
|
|
|
88
89
|
}
|
|
89
90
|
const region0 = region; // 构造参数优先
|
|
90
91
|
|
|
91
|
-
const chatSvc = createChatService({
|
|
92
|
+
const chatSvc = createChatService({
|
|
93
|
+
id,
|
|
94
|
+
fetchImpl,
|
|
95
|
+
// 目录驱动请求(只读 peekModels 缓存,chat 路径恒 0 额外上游调用;preheat 负责灌缓存)
|
|
96
|
+
getModelMeta: (sess2, reg, key) => {
|
|
97
|
+
const list = modelsSvc.peekModels(reg);
|
|
98
|
+
return list ? list.find((m) => m.id === `${id}/${key}` || m.id === key) || null : null;
|
|
99
|
+
},
|
|
100
|
+
timeoutMs: connectTimeoutMs,
|
|
101
|
+
});
|
|
92
102
|
// models 服务按号选区:构造时无固定 region,listModels(sess, region) 动态传
|
|
93
|
-
const modelsSvc = createModelsService({ id, fetchImpl });
|
|
103
|
+
const modelsSvc = sharedModelsSvc || createModelsService({ id, fetchImpl });
|
|
94
104
|
|
|
95
105
|
// 失败冷却:401/403/429/5xx 冷却当前号(cooldownMs,默认 30s),坏号不再参与轮换。
|
|
96
106
|
// 额度耗尽(quota)走长冷却(quotaCooldownMs,默认 1h)——额度按天重置,短冷却等于反复撞死号。
|
|
@@ -232,7 +242,7 @@ export function createQoderProvider({
|
|
|
232
242
|
|
|
233
243
|
async function close() {}
|
|
234
244
|
async function chatWithKeys(body, keysOverride, opts) {
|
|
235
|
-
const tmp = createQoderProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, queueCooldownMs, connectTimeoutMs });
|
|
245
|
+
const tmp = createQoderProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, queueCooldownMs, connectTimeoutMs, sharedModelsSvc: modelsSvc });
|
|
236
246
|
return tmp.chat(body, opts);
|
|
237
247
|
}
|
|
238
248
|
|
|
@@ -67,7 +67,11 @@ export function createModelsService({ id = "qoder", fetchImpl, clock = Date.now
|
|
|
67
67
|
return list;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
70
|
+
function clearCache() { cache = null; fetchedAt = 0; cacheByRegion.clear(); }
|
|
71
|
+
// 快照语义(评审路2 P0:不吃 TTL):daemon 稳态里 chat 不再回源,能力标记「过期」也比「丢失」强——
|
|
72
|
+
// is_reasoning 启动预热后持续有效;刷新走 listModels(preheat/CLI/聚合路由),chat 路径恒 0 额外上游调用。
|
|
73
|
+
function peekModels(region = "global") {
|
|
74
|
+
return cacheByRegion.get(normalizeRegion(region))?.list ?? null;
|
|
75
|
+
}
|
|
76
|
+
return { listModels, peekModels, clearCache, _getCache: () => cache ?? cacheByRegion.get("global")?.list ?? null };
|
|
73
77
|
}
|
|
@@ -119,6 +119,11 @@ export function buildQoderBody({ template, userType, model, messages, tools, max
|
|
|
119
119
|
body.model_config.key = model;
|
|
120
120
|
if (isReasoning) body.model_config.is_reasoning = true;
|
|
121
121
|
}
|
|
122
|
+
// 推理标志两处镜像写(对齐官方 CLI 请求形状),只写 model_config 上游不吐 reasoning_content
|
|
123
|
+
if (isReasoning && body.chat_context?.extra?.modelConfig) {
|
|
124
|
+
body.chat_context.extra.modelConfig.is_reasoning = true;
|
|
125
|
+
body.chat_context.extra.modelConfig.key = model; // 与 model_config.key 同步,不留模板 "auto"(评审路1 P1#5)
|
|
126
|
+
}
|
|
122
127
|
if (maxTokens > 0 && body.parameters) body.parameters.max_tokens = maxTokens;
|
|
123
128
|
const prompt = extractLatestUserPrompt(messages);
|
|
124
129
|
if (body.business) {
|
|
@@ -131,7 +136,8 @@ export function buildQoderBody({ template, userType, model, messages, tools, max
|
|
|
131
136
|
if (body.chat_context.extra?.originalContent) body.chat_context.extra.originalContent.text = prompt;
|
|
132
137
|
}
|
|
133
138
|
body.messages = messages;
|
|
134
|
-
|
|
139
|
+
// tools 空数组契约:模板内嵌的 14 个 Qoder CLI 工具永不出门;无工具时上游官方亦发 []
|
|
140
|
+
body.tools = Array.isArray(tools) && tools.length ? tools : [];
|
|
135
141
|
return { body, prompt, mcSource: body.model_config?.source || "system" };
|
|
136
142
|
}
|
|
137
143
|
|
|
@@ -5,7 +5,7 @@ import { buildCosyHeaders, pathSigFrom } from "./session.js";
|
|
|
5
5
|
import { cosyEncode } from "./encode.js";
|
|
6
6
|
import { buildQoderBody, mapModel } from "./payload.js";
|
|
7
7
|
|
|
8
|
-
export function buildUpstreamRequest({ sess, region, model, messages, tools, maxTokens }) {
|
|
8
|
+
export function buildUpstreamRequest({ sess, region, model, messages, tools, maxTokens, isReasoning }) {
|
|
9
9
|
const upstreamModel = mapModel(model);
|
|
10
10
|
const { body, mcSource } = buildQoderBody({
|
|
11
11
|
template: undefined,
|
|
@@ -14,6 +14,7 @@ export function buildUpstreamRequest({ sess, region, model, messages, tools, max
|
|
|
14
14
|
messages,
|
|
15
15
|
tools,
|
|
16
16
|
maxTokens,
|
|
17
|
+
isReasoning,
|
|
17
18
|
});
|
|
18
19
|
const ep = getEndpoints(normalizeRegion(region));
|
|
19
20
|
const url = ep.chatStreamURL;
|
|
@@ -40,7 +40,10 @@ export function extractDelta(dataLine) {
|
|
|
40
40
|
usageOut = Math.trunc(Number(j.usage.completion_tokens) || 0);
|
|
41
41
|
}
|
|
42
42
|
const choices = Array.isArray(j.choices) ? j.choices : [];
|
|
43
|
+
let finishReason = "";
|
|
43
44
|
for (const ch of choices) {
|
|
45
|
+
const fr = ch?.finish_reason;
|
|
46
|
+
if (typeof fr === "string" && fr) finishReason = fr;
|
|
44
47
|
const delta = ch?.delta;
|
|
45
48
|
if (!delta) continue;
|
|
46
49
|
const role = typeof delta.role === "string" ? delta.role : "";
|
|
@@ -48,7 +51,7 @@ export function extractDelta(dataLine) {
|
|
|
48
51
|
const reasoning = typeof delta.reasoning_content === "string" ? delta.reasoning_content : "";
|
|
49
52
|
const toolCalls = Array.isArray(delta.tool_calls) && delta.tool_calls.length ? delta.tool_calls : null;
|
|
50
53
|
if (role || content || reasoning || toolCalls) {
|
|
51
|
-
return { role, content, reasoning, toolCalls, usageIn, usageOut };
|
|
54
|
+
return { role, content, reasoning, toolCalls, usageIn, usageOut, ...(finishReason ? { finishReason } : {}) };
|
|
52
55
|
}
|
|
53
56
|
}
|
|
54
57
|
if (typeof j.code === "string" && j.code && j.code !== "0") {
|
|
@@ -58,6 +61,7 @@ export function extractDelta(dataLine) {
|
|
|
58
61
|
if (isQuotaError(j.code, msg)) return { err: { kind: "quota", status: 429, code: j.code, detail: msg || `code=${j.code}` } };
|
|
59
62
|
return { err: { kind: /inappropriate|DataInspection|Sensitive|ContentFilter/i.test(msg) ? "content_policy" : "business", code: j.code, detail: msg } };
|
|
60
63
|
}
|
|
64
|
+
if (finishReason) return { finishReason, usageIn, usageOut };
|
|
61
65
|
if (usageIn > 0 || usageOut > 0) return { usageIn, usageOut };
|
|
62
66
|
// 走到这里 = 帧既无 content/tool_calls、也无业务错、也无 usage。空轮排查的关键取证点:
|
|
63
67
|
// 把内层 JSON 的顶层键与 choices 原样打出来,一眼看出上游改了什么字段名。
|
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
// usage 只在尾帧出现:收到即记,附在 finish chunk 上一次发出(与旧回放语义一致)。
|
|
4
4
|
import { extractDelta } from "./sse.js";
|
|
5
5
|
|
|
6
|
+
// SSE 缓冲上限:未完结行超 2MiB 立即中断(内存保护,对齐外部参照实现 defaultMaxSseBufferChars)
|
|
7
|
+
const MAX_BUFFER_CHARS = 2 * 1024 * 1024;
|
|
8
|
+
|
|
6
9
|
// 空轮排障用的临时日志开关:QODER_DEBUG_STREAM=1 才输出,默认静默(问题定位后可摘)
|
|
7
10
|
const DBG_STREAM = () => process.env.QODER_DEBUG_STREAM === "1";
|
|
8
11
|
const sdbg = (...a) => { if (DBG_STREAM()) console.log("[qoder-stream]", ...a); };
|
|
@@ -30,7 +33,9 @@ export function reshapeQoderStream(upstreamRes, { model, chatId, prefetched = []
|
|
|
30
33
|
// 判决帧会在这里被正常解析并抛错,同时 chat.js 已用同一批帧定出状态码挂上门面。
|
|
31
34
|
let buf = prefetched.map((b) => dec.decode(b, { stream: true })).join("");
|
|
32
35
|
let usage = null;
|
|
33
|
-
|
|
36
|
+
// 收尾判定与 aggregate 同构:上游给过 finish_reason 一律优先,全程没给才兜底(tool_calls > stop)
|
|
37
|
+
let upstreamFinish = "";
|
|
38
|
+
let sawToolCalls = false;
|
|
34
39
|
let sawContent = false;
|
|
35
40
|
let finishSent = false;
|
|
36
41
|
const stream = new ReadableStream({
|
|
@@ -67,21 +72,28 @@ export function reshapeQoderStream(upstreamRes, { model, chatId, prefetched = []
|
|
|
67
72
|
usage = { prompt_tokens: d.usageIn, completion_tokens: d.usageOut, total_tokens: d.usageIn + d.usageOut };
|
|
68
73
|
sdbg(`[usage] ${JSON.stringify(usage)}`);
|
|
69
74
|
}
|
|
75
|
+
if (d.finishReason) upstreamFinish = d.finishReason;
|
|
70
76
|
const delta = {};
|
|
71
77
|
if (!sawContent) delta.role = "assistant";
|
|
72
78
|
if (d.content) { delta.content = d.content; contentLen += d.content.length; sawContent = true; }
|
|
73
79
|
if (d.reasoning) { delta.reasoning_content = d.reasoning; sawContent = true; }
|
|
74
|
-
if (d.toolCalls) { delta.tool_calls = d.toolCalls;
|
|
80
|
+
if (d.toolCalls) { delta.tool_calls = d.toolCalls; sawToolCalls = true; sawContent = true; }
|
|
75
81
|
if (Object.keys(delta).length) send(openaiChunk({ model, chatId, delta }));
|
|
76
|
-
sdbg(`[acc] line#=${lineIdx} sawContent=${sawContent} contentLen=${contentLen}
|
|
82
|
+
sdbg(`[acc] line#=${lineIdx} sawContent=${sawContent} contentLen=${contentLen} upstreamFinish=${upstreamFinish} usage=${JSON.stringify(usage)}`);
|
|
83
|
+
}
|
|
84
|
+
// 完整行消费完毕后再判越限:leftover 超大不得把同 chunk 里的合法帧连坐丢弃(评审路1 P1#4)
|
|
85
|
+
if (buf.length > MAX_BUFFER_CHARS) {
|
|
86
|
+
sdbg(`[buffer-limit] leftover=${buf.length} chars → abort stream`);
|
|
87
|
+
throw { kind: "upstream", status: 502, detail: "qoder SSE buffer exceeded 2MiB limit" };
|
|
77
88
|
}
|
|
78
89
|
if (done) break;
|
|
79
90
|
}
|
|
80
|
-
sdbg(`[end] totalChunks=${chunkIdx} totalLines=${lineIdx} sawContent=${sawContent} contentLen=${contentLen}
|
|
91
|
+
sdbg(`[end] totalChunks=${chunkIdx} totalLines=${lineIdx} sawContent=${sawContent} contentLen=${contentLen} upstreamFinish=${upstreamFinish} usage=${JSON.stringify(usage)}`);
|
|
81
92
|
if (!sawContent && !usage) {
|
|
82
93
|
sdbg(`[empty-stream] sawContent=false usage=null → throw 502 empty upstream stream`);
|
|
83
94
|
throw { kind: "upstream", status: 502, detail: "empty upstream stream" };
|
|
84
95
|
}
|
|
96
|
+
const finish = upstreamFinish || (sawToolCalls ? "tool_calls" : "stop");
|
|
85
97
|
send(openaiChunk({ model, chatId, delta: {}, finish, usage }));
|
|
86
98
|
send("data: [DONE]\n\n");
|
|
87
99
|
finishSent = true;
|