mslxdff 0.1.197 → 0.1.199

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 (95) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/docs/cli_help_mini.md +146 -0
  3. package/package.json +1 -1
  4. package/src/auto.js +254 -254
  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 +173 -173
  20. package/src/chat-pipeline/policy.js +84 -84
  21. package/src/chat-pipeline/serial-trial.js +8 -6
  22. package/src/cli/commands/group.js +249 -249
  23. package/src/cli/commands/model/picks.js +50 -50
  24. package/src/cli/commands/provider/bench-via.js +247 -247
  25. package/src/cli/commands/provider/bench.js +141 -141
  26. package/src/cli/commands/provider/index.js +137 -136
  27. package/src/cli/commands/provider/models.js +145 -145
  28. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  29. package/src/cli/commands/provider/raccoon-login.js +29 -1
  30. package/src/cli/commands/provider/raccoon-password.js +162 -0
  31. package/src/cli/commands/sync.js +310 -310
  32. package/src/cli/status.js +279 -279
  33. package/src/daemon.js +232 -232
  34. package/src/model-capabilities/enrich.js +86 -86
  35. package/src/model-capabilities/index.js +183 -183
  36. package/src/model-capabilities/parse.js +70 -70
  37. package/src/models.js +225 -225
  38. package/src/providers/AGENTS.md +49 -0
  39. package/src/providers/cline/auth.js +228 -228
  40. package/src/providers/cline/chat.js +307 -307
  41. package/src/providers/cline.js +2 -2
  42. package/src/providers/codearts/chat.js +182 -182
  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/rsa.js +54 -54
  47. package/src/providers/globalqwenwork/sse.js +268 -268
  48. package/src/providers/globalqwenwork/stream.js +130 -130
  49. package/src/providers/globalqwenwork/upstream.js +122 -122
  50. package/src/providers/keyring.js +60 -60
  51. package/src/providers/qoder/chat.js +203 -203
  52. package/src/providers/qoder/index.js +249 -249
  53. package/src/providers/qoder/sse.js +145 -145
  54. package/src/providers/qwenwork/account-store.js +133 -133
  55. package/src/providers/qwenwork/constants.js +67 -67
  56. package/src/providers/qwenwork/cosy.js +120 -120
  57. package/src/providers/qwenwork/crypto.js +218 -218
  58. package/src/providers/qwenwork/http.js +20 -20
  59. package/src/providers/qwenwork/index.js +337 -337
  60. package/src/providers/qwenwork/payload.js +144 -144
  61. package/src/providers/qwenwork/rsa.js +54 -54
  62. package/src/providers/qwenwork/sse.js +268 -268
  63. package/src/providers/qwenwork/stream.js +130 -130
  64. package/src/providers/qwenwork/upstream.js +120 -120
  65. package/src/providers/qwenwork.js +1 -1
  66. package/src/providers/raccoon/const.js +25 -0
  67. package/src/providers/raccoon/password-login.js +87 -0
  68. package/src/providers/registry.js +79 -79
  69. package/src/providers/workbuddy/chat.js +264 -264
  70. package/src/providers/workbuddy/reshape.js +152 -152
  71. package/src/providers/workbuddy.js +2 -2
  72. package/src/reasoning.js +32 -32
  73. package/src/routes/AGENTS.md +37 -0
  74. package/src/routes/chat/gateway.js +46 -46
  75. package/src/routes/chat/relay-pipeline.js +282 -282
  76. package/src/routes/chat/via-route-handler.js +146 -146
  77. package/src/routes/hedge.js +260 -260
  78. package/src/routes/models-route.js +167 -167
  79. package/src/routes/peers.js +335 -335
  80. package/src/routes/stream.js +347 -347
  81. package/src/runtime/bootstrap.js +67 -67
  82. package/src/runtime/provider-gate.js +36 -36
  83. package/src/runtime/providers-setup.js +168 -168
  84. package/src/server.js +78 -78
  85. package/src/state/schemas/allowlist.js +92 -92
  86. package/src/sync-opencode.js +280 -280
  87. package/src/transport/index.js +244 -244
  88. package/src/transport/pool.js +56 -56
  89. package/src/transport/retry.js +24 -24
  90. package/src/transport/sse.js +93 -93
  91. package/src/upstream-probe/display.js +52 -52
  92. package/src/upstream-probe/probe.js +49 -49
  93. package/src/upstream-probe/rotate.js +110 -110
  94. package/src/upstream-probe/start.js +45 -45
  95. package/src/upstream.js +293 -293
@@ -1,264 +1,264 @@
1
- import { joinUrl } from "../base.js";
2
- import { isAuthError, isInsufficientStatus, isRateLimitedStatus, parseRateLimitResetMs } from "./auth.js";
3
- import { appendRotationLog as defaultAppend } from "./rotation-log.js";
4
- import { createTransport } from "../../transport/index.js";
5
- import { dispatcherFetch } from "../../upstream-engine/sdk/attempt.js";
6
- import { reshapeWorkbuddySse } from "./reshape.js";
7
- import { attemptOnceSdk } from "./sdk-chat.js";
8
- import { sanitizeToolSequence } from "./sanitize-tools.js";
9
- import { rewriteWorkbuddyPayload } from "./payload.js";
10
- import { resolveEngineMode } from "../../upstream-engine/mode.js";
11
-
12
- function buildAuthHeaders(key, auth) {
13
- const h = {
14
- "Content-Type": "application/json",
15
- Accept: "text/event-stream",
16
- "User-Agent": "CLI/2.115.0 WorkBuddy/2.115.0",
17
- Origin: "https://www.codebuddy.cn",
18
- Referer: "https://www.codebuddy.cn/",
19
- "X-Product": "SaaS",
20
- };
21
- if (key) h["Authorization"] = `Bearer ${key}`;
22
- if (auth?.uid) h["X-User-Id"] = auth.uid;
23
- h["X-Domain"] = auth?.domain || "www.codebuddy.cn";
24
- if (auth?.enterpriseId) { h["X-Enterprise-Id"] = auth.enterpriseId; h["X-Tenant-Id"] = auth.enterpriseId; }
25
- return h;
26
- }
27
-
28
- function withUidHeader(res, uid) {
29
- try { res.headers.set("x-mslxdff-workbuddy-uid", uid); return res; }
30
- catch {
31
- try {
32
- const h = new Headers(res.headers);
33
- h.set("x-mslxdff-workbuddy-uid", uid);
34
- const c = new Response(res.body, { status: res.status, statusText: res.statusText, headers: h });
35
- c._t = res._t;
36
- return c;
37
- } catch { return res; }
38
- }
39
- }
40
-
41
- // 400 判型需读 body 文本;读过的 Response body 不可再读(下游转发报 "Body is unusable"),
42
- // 用文本重建一个等价响应(去掉 content-length 防长度不符)。
43
- function rewrapBody(res, txt) {
44
- try { console.error(`[workbuddy] upstream ${res.status} body: ${String(txt).slice(0, 300)}`); } catch {}
45
- try {
46
- const h = new Headers(res.headers);
47
- h.delete("content-length");
48
- const r = new Response(txt, { status: res.status, statusText: res.statusText, headers: h });
49
- try { r._t = res._t; } catch {}
50
- return r;
51
- } catch { return res; }
52
- }
53
-
54
- function nowMs(clock) { return typeof performance !== "undefined" && performance.now ? performance.now() : clock(); }
55
-
56
- function errRes(status, msg, reason, uid, t0, clock) {
57
- const r = new Response(JSON.stringify({ error: msg }), { status, headers: { "Content-Type": "application/json", "x-mslxdff-workbuddy-reason": reason, "x-mslxdff-workbuddy-uid": uid } });
58
- r._t = { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
59
- return r;
60
- }
61
-
62
- function failErr(msg, t0, clock, extra) {
63
- const e = new Error(msg);
64
- e._t = { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0), ...(extra || {}) };
65
- return e;
66
- }
67
-
68
- export function createChatService({
69
- id = "workbuddy",
70
- baseUrl,
71
- chatPath,
72
- keys,
73
- authList,
74
- ring,
75
- fetchImpl,
76
- dispatcher,
77
- connectTimeoutMs = 30_000,
78
- balanceCache,
79
- authService,
80
- logger,
81
- clock = Date.now,
82
- cooldownMs = 30_000,
83
- } = {}) {
84
- const getBalance = balanceCache?.getCachedBalance || (() => null);
85
- const setBalance = balanceCache?.setCachedBalance || (() => {});
86
- const doLog = (opts) => {
87
- if (logger && typeof logger.append === "function") { try { logger.append(opts); } catch {} return; }
88
- if (logger && typeof logger.log === "function") { try { logger.log(opts); } catch {} return; }
89
- try { defaultAppend(opts); } catch {}
90
- };
91
- const transport = createTransport({ fetchImpl, dispatcher, keepAlive: !!dispatcher, timeoutMs: connectTimeoutMs, retry: {} });
92
- // SDK 通道与 legacy 同享 keep-alive 连接池(dispatcher → fetch 注入);同时该 fetch 被 attempt 层
93
- // 包装用于错误路径捕获请求体(上游 4xx 时打印 tool 序列断裂诊断,见 sdk/attempt.js)。
94
- const sdkFetch = dispatcher ? dispatcherFetch(dispatcher) : fetchImpl;
95
-
96
- function authForKey(key) {
97
- const idx = keys.indexOf(key);
98
- if (idx >= 0 && authList[idx]) return authList[idx];
99
- if (authList.length) return authList[0];
100
- return { uid: "", domain: "www.codebuddy.cn", enterpriseId: "", refreshToken: "" };
101
- }
102
-
103
- // SDK 通道(缺省启用):缺省底层走 @ai-sdk/openai-compatible,`legacy`/关闭词
104
- // (局部 MSLXDFF_WORKBUDDY_SDK,未设则继承全局 MSLXDFF_UPSTREAM_ENGINE)回退原生 transport;
105
- // 不可用(未安装)自动回退并告警一次。上层轮换/刷新/reshape 全链复用。
106
- // Note: 为什么默认 SDK、翻译层代价与回退语义 — 见 .agents/notes/implemented/feature/2026-09-12-workbuddy-sdk-channel.md
107
- // 上游非标字段(thinking / reasoning_effort / reasoning_content / tool_choice 字符串)不依赖 SDK 白名单:
108
- // payload.js 前置语义改写 + AI SDK providerOptions 透传(非白名单 key 原样 spread 进 body,2.0.41 实测)。
109
- // 序列化/流式/错误映射仍全部交 AI SDK;原生 transport 仅作 SDK 不可用时的回退。v0.1.120 实测见 .scratch/probe-sdk-body.mjs。
110
- const engineMode = resolveEngineMode(process.env, "MSLXDFF_WORKBUDDY_SDK", "sdk");
111
- let sdkFallbackLogged = false;
112
- async function fetchOnce(url, body, key, auth) {
113
- const payload = rewriteWorkbuddyPayload(body);
114
- if (engineMode === "sdk") {
115
- try {
116
- return await attemptOnceSdk({ url, body: payload, key, auth, buildHeaders: buildAuthHeaders, ...(sdkFetch ? { fetchImpl: sdkFetch } : {}) });
117
- } catch (e) {
118
- if (!e || !e._sdkLoadFailed) throw e;
119
- if (!sdkFallbackLogged) {
120
- sdkFallbackLogged = true;
121
- try { console.error(`[workbuddy] ${e.message} — 回退原生通道`); } catch {}
122
- }
123
- }
124
- }
125
- return transport.request({ url, headers: buildAuthHeaders(key, auth), body: { ...payload, stream: true }, stream: true });
126
- }
127
-
128
- async function withRefresh(url, body, key, auth) {
129
- let res;
130
- try { res = await fetchOnce(url, body, key, auth); }
131
- catch (e) { throw e; }
132
- if (res.status < 400) return reshapeWorkbuddySse(res);
133
- let txt = "";
134
- try { txt = await res.text(); } catch {}
135
- if (!isAuthError(res.status, txt)) return rewrapBody(res, txt);
136
- const newKey = await authService?.refreshTokenFor?.(key, auth);
137
- if (!newKey) throw failErr(`workbuddy refresh failed for ${auth?.uid || ""}: ${txt.slice(0, 120)}`, _t0(), clock);
138
- const auth2 = authForKey(newKey);
139
- let res2;
140
- try { res2 = await fetchOnce(url, body, newKey, auth2); }
141
- catch (e2) { throw e2; }
142
- let stillTxt = "";
143
- if (res2.status >= 400) { try { stillTxt = await res2.text(); } catch {} }
144
- if (stillTxt) res2 = rewrapBody(res2, stillTxt);
145
- const stillAuth = isAuthError(res2.status, stillTxt);
146
- const uid2 = auth2.uid || auth.uid;
147
- res2 = withUidHeader(res2, uid2);
148
- res2._t = res2._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - _t0()) };
149
- if (stillAuth || res2.status === 429 || res2.status >= 500) try { ring.onError(newKey); } catch {}
150
- doLog({ uid: uid2, model: _modelForLog(), totalMs: Math.round(nowMs(clock) - _t0()), balanceHit: false, error: stillAuth ? `still auth ${res2.status}` : undefined });
151
- if (stillAuth) throw failErr(`workbuddy auth still failing after refresh for ${uid2}: ${stillTxt.slice(0, 120)}`, _t0(), clock);
152
- return reshapeWorkbuddySse(res2);
153
- }
154
-
155
- let _t0Val = 0;
156
- let _modelVal = "";
157
- function _t0() { return _t0Val; }
158
- function _modelForLog() { return _modelVal; }
159
-
160
- async function runChat(body, activeRing, opts = {}) {
161
- const url = joinUrl(baseUrl, chatPath);
162
- const t0 = nowMs(clock);
163
- const clean = sanitizeToolSequence(body?.messages);
164
- if (clean.droppedCalls || clean.droppedResults || clean.movedResults || clean.injectedHead) {
165
- try { console.error(`[workbuddy] tool-sequence sanitized: dropped ${clean.droppedCalls} call(s), ${clean.droppedResults} result(s), moved ${clean.movedResults} result(s), head+${clean.injectedHead}, model=${body?.model || ""}`); } catch {}
166
- body = { ...body, messages: clean.messages };
167
- }
168
- _t0Val = t0;
169
- _modelVal = body?.model || "";
170
- const preferredUid = opts?.workbuddyUid ? String(opts.workbuddyUid).trim() : "";
171
-
172
- if (preferredUid) {
173
- const idx = authList.findIndex((a) => a.uid === preferredUid || String(a.uid).startsWith(preferredUid));
174
- if (idx < 0) return errRes(403, `workbuddy uid not found: ${preferredUid}`, "uid-not-found", preferredUid, t0, clock);
175
- const key = keys[idx];
176
- const auth = authList[idx];
177
- authService?.maybeProactiveRefresh?.(auth, key);
178
- const cached = getBalance(auth.uid);
179
- if (cached && Number(cached.total) === 0) return errRes(403, `workbuddy uid in cooldown (balance 0): ${auth.uid}`, "uid-cooling", auth.uid, t0, clock);
180
- try {
181
- let res = await withRefresh(url, body, key, auth);
182
- res = withUidHeader(res, auth.uid);
183
- res._t = res._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
184
- if (res.status === 401 || res.status === 403 || res.status === 429 || res.status >= 500) try { activeRing.onError(key); } catch {}
185
- doLog({ uid: auth.uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: false });
186
- return res;
187
- } catch (e) {
188
- e._t = e._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
189
- if (!(e instanceof Error) || !String(e.message).includes("refresh failed")) try { activeRing.onError(key); } catch {}
190
- throw e;
191
- }
192
- }
193
-
194
- const tried = new Set();
195
- const maxTries = Math.max(1, keys.length);
196
- let lastErr = null;
197
- for (let triedCount = 0; triedCount < maxTries; triedCount++) {
198
- const key = activeRing.next();
199
- if (!key) {
200
- if (triedCount === 0) throw failErr(`${id}: all API keys are in cooldown (last error < ${cooldownMs}ms ago) — provider temporarily unavailable`, t0, clock, { cooldownMs });
201
- break;
202
- }
203
- const auth = authForKey(key);
204
- const uid = auth?.uid || "";
205
- if (tried.has(uid || key)) continue;
206
- tried.add(uid || key);
207
- const cached = uid ? getBalance(uid) : null;
208
- if (cached && Number(cached.total) === 0) {
209
- try { activeRing.onError(key); } catch {}
210
- setBalance(uid, { ...cached, total: 0 });
211
- doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: true });
212
- if (keys.length === 1 || activeRing.available() === 0) return errRes(403, `workbuddy uid in cooldown (balance 0): ${uid}`, "uid-cooling", uid, t0, clock);
213
- continue;
214
- }
215
- if (!key && activeRing.size === 0) throw failErr(`${id}: missing MSLXDFF_WORKBUDDY_KEY (chat requires a real key) — run node workbuddy-token-auto.js`, t0, clock);
216
- authService?.maybeProactiveRefresh?.(auth, key);
217
- let res;
218
- try { res = await withRefresh(url, body, key, auth); }
219
- catch (e) {
220
- e._t = e._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
221
- try { activeRing.onError(key); } catch {}
222
- lastErr = e;
223
- continue;
224
- }
225
- if (res.status === 402 || res.status === 403 || res.status === 429) {
226
- let txt = "";
227
- try { txt = await res.text(); } catch {}
228
- if (isInsufficientStatus(res.status, txt, cached)) {
229
- try { activeRing.onError(key); } catch {}
230
- if (uid) setBalance(uid, { total: 0, dailyPacks: 0, activeCount: 0, nextExpire: null, fetchedAt: clock() });
231
- doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: true, error: txt.slice(0, 120) });
232
- lastErr = failErr(`workbuddy insufficient for ${uid}: ${txt.slice(0, 120)}`, t0, clock);
233
- continue;
234
- }
235
- // 频率限制(腾讯 code 6004):这个号撞了限流,但**额度还在**(total 可能还有几千点)。
236
- // 必须换下一个号顶,且绝不能 setBalance(total:0) —— 那会把好号永久跳过,
237
- // 是「429 原样吐回客户端、从不换号」在 2026-10-17 实锤的那条老路。
238
- // Note: 6004 的判据与冷却分档 — 见 .agents/notes/implemented/bug-fix/2026-10-18-workbuddy-6004-rate-limit-rotate.md
239
- if (isRateLimitedStatus(res.status, txt)) {
240
- const resetMs = parseRateLimitResetMs(txt, clock);
241
- // 冷却时长取「上游给的重置时刻」与固定下限的较大者;解析不出就只按固定档,
242
- // 且**封顶 10 分钟**:6004 的重置时间可能远在数小时后,照抄会把号冻到下班。
243
- const coolMs = Math.min(Math.max(resetMs || 0, cooldownMs), 10 * 60_000);
244
- try { activeRing.onError(key, coolMs); } catch {}
245
- doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: false, error: `rate-limited(${coolMs}ms) ${txt.slice(0, 120)}` });
246
- lastErr = failErr(`workbuddy rate limited for ${uid}: ${txt.slice(0, 120)}`, t0, clock);
247
- if (activeRing.available() > 0) continue;
248
- res = rewrapBody(res, txt);
249
- } else {
250
- res = rewrapBody(res, txt);
251
- }
252
- }
253
- if (res.status === 401 || res.status === 403 || res.status === 429 || res.status >= 500) try { activeRing.onError(key); } catch {}
254
- res = withUidHeader(res, uid);
255
- res._t = res._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
256
- doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: false });
257
- return res;
258
- }
259
- if (lastErr) throw lastErr;
260
- throw failErr(`${id}: all workbuddy accounts exhausted or unavailable`, t0, clock);
261
- }
262
-
263
- return { runChat, authForKey, buildAuthHeaders, withUidHeader, attemptOnce: fetchOnce };
264
- }
1
+ import { joinUrl } from "../base.js";
2
+ import { isAuthError, isInsufficientStatus, isRateLimitedStatus, parseRateLimitResetMs } from "./auth.js";
3
+ import { appendRotationLog as defaultAppend } from "./rotation-log.js";
4
+ import { createTransport } from "../../transport/index.js";
5
+ import { dispatcherFetch } from "../../upstream-engine/sdk/attempt.js";
6
+ import { reshapeWorkbuddySse } from "./reshape.js";
7
+ import { attemptOnceSdk } from "./sdk-chat.js";
8
+ import { sanitizeToolSequence } from "./sanitize-tools.js";
9
+ import { rewriteWorkbuddyPayload } from "./payload.js";
10
+ import { resolveEngineMode } from "../../upstream-engine/mode.js";
11
+
12
+ function buildAuthHeaders(key, auth) {
13
+ const h = {
14
+ "Content-Type": "application/json",
15
+ Accept: "text/event-stream",
16
+ "User-Agent": "CLI/2.115.0 WorkBuddy/2.115.0",
17
+ Origin: "https://www.codebuddy.cn",
18
+ Referer: "https://www.codebuddy.cn/",
19
+ "X-Product": "SaaS",
20
+ };
21
+ if (key) h["Authorization"] = `Bearer ${key}`;
22
+ if (auth?.uid) h["X-User-Id"] = auth.uid;
23
+ h["X-Domain"] = auth?.domain || "www.codebuddy.cn";
24
+ if (auth?.enterpriseId) { h["X-Enterprise-Id"] = auth.enterpriseId; h["X-Tenant-Id"] = auth.enterpriseId; }
25
+ return h;
26
+ }
27
+
28
+ function withUidHeader(res, uid) {
29
+ try { res.headers.set("x-mslxdff-workbuddy-uid", uid); return res; }
30
+ catch {
31
+ try {
32
+ const h = new Headers(res.headers);
33
+ h.set("x-mslxdff-workbuddy-uid", uid);
34
+ const c = new Response(res.body, { status: res.status, statusText: res.statusText, headers: h });
35
+ c._t = res._t;
36
+ return c;
37
+ } catch { return res; }
38
+ }
39
+ }
40
+
41
+ // 400 判型需读 body 文本;读过的 Response body 不可再读(下游转发报 "Body is unusable"),
42
+ // 用文本重建一个等价响应(去掉 content-length 防长度不符)。
43
+ function rewrapBody(res, txt) {
44
+ try { console.error(`[workbuddy] upstream ${res.status} body: ${String(txt).slice(0, 300)}`); } catch {}
45
+ try {
46
+ const h = new Headers(res.headers);
47
+ h.delete("content-length");
48
+ const r = new Response(txt, { status: res.status, statusText: res.statusText, headers: h });
49
+ try { r._t = res._t; } catch {}
50
+ return r;
51
+ } catch { return res; }
52
+ }
53
+
54
+ function nowMs(clock) { return typeof performance !== "undefined" && performance.now ? performance.now() : clock(); }
55
+
56
+ function errRes(status, msg, reason, uid, t0, clock) {
57
+ const r = new Response(JSON.stringify({ error: msg }), { status, headers: { "Content-Type": "application/json", "x-mslxdff-workbuddy-reason": reason, "x-mslxdff-workbuddy-uid": uid } });
58
+ r._t = { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
59
+ return r;
60
+ }
61
+
62
+ function failErr(msg, t0, clock, extra) {
63
+ const e = new Error(msg);
64
+ e._t = { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0), ...(extra || {}) };
65
+ return e;
66
+ }
67
+
68
+ export function createChatService({
69
+ id = "workbuddy",
70
+ baseUrl,
71
+ chatPath,
72
+ keys,
73
+ authList,
74
+ ring,
75
+ fetchImpl,
76
+ dispatcher,
77
+ connectTimeoutMs = 30_000,
78
+ balanceCache,
79
+ authService,
80
+ logger,
81
+ clock = Date.now,
82
+ cooldownMs = 30_000,
83
+ } = {}) {
84
+ const getBalance = balanceCache?.getCachedBalance || (() => null);
85
+ const setBalance = balanceCache?.setCachedBalance || (() => {});
86
+ const doLog = (opts) => {
87
+ if (logger && typeof logger.append === "function") { try { logger.append(opts); } catch {} return; }
88
+ if (logger && typeof logger.log === "function") { try { logger.log(opts); } catch {} return; }
89
+ try { defaultAppend(opts); } catch {}
90
+ };
91
+ const transport = createTransport({ fetchImpl, dispatcher, keepAlive: !!dispatcher, timeoutMs: connectTimeoutMs, retry: {} });
92
+ // SDK 通道与 legacy 同享 keep-alive 连接池(dispatcher → fetch 注入);同时该 fetch 被 attempt 层
93
+ // 包装用于错误路径捕获请求体(上游 4xx 时打印 tool 序列断裂诊断,见 sdk/attempt.js)。
94
+ const sdkFetch = dispatcher ? dispatcherFetch(dispatcher) : fetchImpl;
95
+
96
+ function authForKey(key) {
97
+ const idx = keys.indexOf(key);
98
+ if (idx >= 0 && authList[idx]) return authList[idx];
99
+ if (authList.length) return authList[0];
100
+ return { uid: "", domain: "www.codebuddy.cn", enterpriseId: "", refreshToken: "" };
101
+ }
102
+
103
+ // SDK 通道(缺省启用):缺省底层走 @ai-sdk/openai-compatible,`legacy`/关闭词
104
+ // (局部 MSLXDFF_WORKBUDDY_SDK,未设则继承全局 MSLXDFF_UPSTREAM_ENGINE)回退原生 transport;
105
+ // 不可用(未安装)自动回退并告警一次。上层轮换/刷新/reshape 全链复用。
106
+ // Note: 为什么默认 SDK、翻译层代价与回退语义 — 见 .agents/notes/implemented/feature/2026-09-12-workbuddy-sdk-channel.md
107
+ // 上游非标字段(thinking / reasoning_effort / reasoning_content / tool_choice 字符串)不依赖 SDK 白名单:
108
+ // payload.js 前置语义改写 + AI SDK providerOptions 透传(非白名单 key 原样 spread 进 body,2.0.41 实测)。
109
+ // 序列化/流式/错误映射仍全部交 AI SDK;原生 transport 仅作 SDK 不可用时的回退。v0.1.120 实测见 .scratch/probe-sdk-body.mjs。
110
+ const engineMode = resolveEngineMode(process.env, "MSLXDFF_WORKBUDDY_SDK", "sdk");
111
+ let sdkFallbackLogged = false;
112
+ async function fetchOnce(url, body, key, auth) {
113
+ const payload = rewriteWorkbuddyPayload(body);
114
+ if (engineMode === "sdk") {
115
+ try {
116
+ return await attemptOnceSdk({ url, body: payload, key, auth, buildHeaders: buildAuthHeaders, ...(sdkFetch ? { fetchImpl: sdkFetch } : {}) });
117
+ } catch (e) {
118
+ if (!e || !e._sdkLoadFailed) throw e;
119
+ if (!sdkFallbackLogged) {
120
+ sdkFallbackLogged = true;
121
+ try { console.error(`[workbuddy] ${e.message} — 回退原生通道`); } catch {}
122
+ }
123
+ }
124
+ }
125
+ return transport.request({ url, headers: buildAuthHeaders(key, auth), body: { ...payload, stream: true }, stream: true });
126
+ }
127
+
128
+ async function withRefresh(url, body, key, auth) {
129
+ let res;
130
+ try { res = await fetchOnce(url, body, key, auth); }
131
+ catch (e) { throw e; }
132
+ if (res.status < 400) return reshapeWorkbuddySse(res);
133
+ let txt = "";
134
+ try { txt = await res.text(); } catch {}
135
+ if (!isAuthError(res.status, txt)) return rewrapBody(res, txt);
136
+ const newKey = await authService?.refreshTokenFor?.(key, auth);
137
+ if (!newKey) throw failErr(`workbuddy refresh failed for ${auth?.uid || ""}: ${txt.slice(0, 120)}`, _t0(), clock);
138
+ const auth2 = authForKey(newKey);
139
+ let res2;
140
+ try { res2 = await fetchOnce(url, body, newKey, auth2); }
141
+ catch (e2) { throw e2; }
142
+ let stillTxt = "";
143
+ if (res2.status >= 400) { try { stillTxt = await res2.text(); } catch {} }
144
+ if (stillTxt) res2 = rewrapBody(res2, stillTxt);
145
+ const stillAuth = isAuthError(res2.status, stillTxt);
146
+ const uid2 = auth2.uid || auth.uid;
147
+ res2 = withUidHeader(res2, uid2);
148
+ res2._t = res2._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - _t0()) };
149
+ if (stillAuth || res2.status === 429 || res2.status >= 500) try { ring.onError(newKey); } catch {}
150
+ doLog({ uid: uid2, model: _modelForLog(), totalMs: Math.round(nowMs(clock) - _t0()), balanceHit: false, error: stillAuth ? `still auth ${res2.status}` : undefined });
151
+ if (stillAuth) throw failErr(`workbuddy auth still failing after refresh for ${uid2}: ${stillTxt.slice(0, 120)}`, _t0(), clock);
152
+ return reshapeWorkbuddySse(res2);
153
+ }
154
+
155
+ let _t0Val = 0;
156
+ let _modelVal = "";
157
+ function _t0() { return _t0Val; }
158
+ function _modelForLog() { return _modelVal; }
159
+
160
+ async function runChat(body, activeRing, opts = {}) {
161
+ const url = joinUrl(baseUrl, chatPath);
162
+ const t0 = nowMs(clock);
163
+ const clean = sanitizeToolSequence(body?.messages);
164
+ if (clean.droppedCalls || clean.droppedResults || clean.movedResults || clean.injectedHead) {
165
+ try { console.error(`[workbuddy] tool-sequence sanitized: dropped ${clean.droppedCalls} call(s), ${clean.droppedResults} result(s), moved ${clean.movedResults} result(s), head+${clean.injectedHead}, model=${body?.model || ""}`); } catch {}
166
+ body = { ...body, messages: clean.messages };
167
+ }
168
+ _t0Val = t0;
169
+ _modelVal = body?.model || "";
170
+ const preferredUid = opts?.workbuddyUid ? String(opts.workbuddyUid).trim() : "";
171
+
172
+ if (preferredUid) {
173
+ const idx = authList.findIndex((a) => a.uid === preferredUid || String(a.uid).startsWith(preferredUid));
174
+ if (idx < 0) return errRes(403, `workbuddy uid not found: ${preferredUid}`, "uid-not-found", preferredUid, t0, clock);
175
+ const key = keys[idx];
176
+ const auth = authList[idx];
177
+ authService?.maybeProactiveRefresh?.(auth, key);
178
+ const cached = getBalance(auth.uid);
179
+ if (cached && Number(cached.total) === 0) return errRes(403, `workbuddy uid in cooldown (balance 0): ${auth.uid}`, "uid-cooling", auth.uid, t0, clock);
180
+ try {
181
+ let res = await withRefresh(url, body, key, auth);
182
+ res = withUidHeader(res, auth.uid);
183
+ res._t = res._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
184
+ if (res.status === 401 || res.status === 403 || res.status === 429 || res.status >= 500) try { activeRing.onError(key); } catch {}
185
+ doLog({ uid: auth.uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: false });
186
+ return res;
187
+ } catch (e) {
188
+ e._t = e._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
189
+ if (!(e instanceof Error) || !String(e.message).includes("refresh failed")) try { activeRing.onError(key); } catch {}
190
+ throw e;
191
+ }
192
+ }
193
+
194
+ const tried = new Set();
195
+ const maxTries = Math.max(1, keys.length);
196
+ let lastErr = null;
197
+ for (let triedCount = 0; triedCount < maxTries; triedCount++) {
198
+ const key = activeRing.next();
199
+ if (!key) {
200
+ if (triedCount === 0) throw failErr(`${id}: all API keys are in cooldown (last error < ${cooldownMs}ms ago) — provider temporarily unavailable`, t0, clock, { cooldownMs });
201
+ break;
202
+ }
203
+ const auth = authForKey(key);
204
+ const uid = auth?.uid || "";
205
+ if (tried.has(uid || key)) continue;
206
+ tried.add(uid || key);
207
+ const cached = uid ? getBalance(uid) : null;
208
+ if (cached && Number(cached.total) === 0) {
209
+ try { activeRing.onError(key); } catch {}
210
+ setBalance(uid, { ...cached, total: 0 });
211
+ doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: true });
212
+ if (keys.length === 1 || activeRing.available() === 0) return errRes(403, `workbuddy uid in cooldown (balance 0): ${uid}`, "uid-cooling", uid, t0, clock);
213
+ continue;
214
+ }
215
+ if (!key && activeRing.size === 0) throw failErr(`${id}: missing MSLXDFF_WORKBUDDY_KEY (chat requires a real key) — run node workbuddy-token-auto.js`, t0, clock);
216
+ authService?.maybeProactiveRefresh?.(auth, key);
217
+ let res;
218
+ try { res = await withRefresh(url, body, key, auth); }
219
+ catch (e) {
220
+ e._t = e._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
221
+ try { activeRing.onError(key); } catch {}
222
+ lastErr = e;
223
+ continue;
224
+ }
225
+ if (res.status === 402 || res.status === 403 || res.status === 429) {
226
+ let txt = "";
227
+ try { txt = await res.text(); } catch {}
228
+ if (isInsufficientStatus(res.status, txt, cached)) {
229
+ try { activeRing.onError(key); } catch {}
230
+ if (uid) setBalance(uid, { total: 0, dailyPacks: 0, activeCount: 0, nextExpire: null, fetchedAt: clock() });
231
+ doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: true, error: txt.slice(0, 120) });
232
+ lastErr = failErr(`workbuddy insufficient for ${uid}: ${txt.slice(0, 120)}`, t0, clock);
233
+ continue;
234
+ }
235
+ // 频率限制(腾讯 code 6004):这个号撞了限流,但**额度还在**(total 可能还有几千点)。
236
+ // 必须换下一个号顶,且绝不能 setBalance(total:0) —— 那会把好号永久跳过,
237
+ // 是「429 原样吐回客户端、从不换号」在 2026-10-17 实锤的那条老路。
238
+ // Note: 6004 的判据与冷却分档 — 见 .agents/notes/implemented/bug-fix/2026-10-18-workbuddy-6004-rate-limit-rotate.md
239
+ if (isRateLimitedStatus(res.status, txt)) {
240
+ const resetMs = parseRateLimitResetMs(txt, clock);
241
+ // 冷却时长取「上游给的重置时刻」与固定下限的较大者;解析不出就只按固定档,
242
+ // 且**封顶 10 分钟**:6004 的重置时间可能远在数小时后,照抄会把号冻到下班。
243
+ const coolMs = Math.min(Math.max(resetMs || 0, cooldownMs), 10 * 60_000);
244
+ try { activeRing.onError(key, coolMs); } catch {}
245
+ doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: false, error: `rate-limited(${coolMs}ms) ${txt.slice(0, 120)}` });
246
+ lastErr = failErr(`workbuddy rate limited for ${uid}: ${txt.slice(0, 120)}`, t0, clock);
247
+ if (activeRing.available() > 0) continue;
248
+ res = rewrapBody(res, txt);
249
+ } else {
250
+ res = rewrapBody(res, txt);
251
+ }
252
+ }
253
+ if (res.status === 401 || res.status === 403 || res.status === 429 || res.status >= 500) try { activeRing.onError(key); } catch {}
254
+ res = withUidHeader(res, uid);
255
+ res._t = res._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
256
+ doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: false });
257
+ return res;
258
+ }
259
+ if (lastErr) throw lastErr;
260
+ throw failErr(`${id}: all workbuddy accounts exhausted or unavailable`, t0, clock);
261
+ }
262
+
263
+ return { runChat, authForKey, buildAuthHeaders, withUidHeader, attemptOnce: fetchOnce };
264
+ }