mslxdff 0.1.187 → 0.1.188

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 (111) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/docs/cli_help_mini.md +145 -0
  3. package/package.json +1 -1
  4. package/src/auto.js +254 -254
  5. package/src/autostart.js +5 -2
  6. package/src/bench/cline-bench.js +42 -42
  7. package/src/bench/probe.js +70 -70
  8. package/src/bench/report.js +162 -162
  9. package/src/bench/runner.js +77 -77
  10. package/src/bench/via-probe.js +124 -124
  11. package/src/bench/via-routes.js +87 -87
  12. package/src/bench/workbuddy-bench.js +54 -54
  13. package/src/chat/engine.js +160 -160
  14. package/src/chat/gateway.js +163 -163
  15. package/src/chat/orchestrator.js +234 -234
  16. package/src/chat/prompt.js +70 -70
  17. package/src/chat/repl.js +88 -88
  18. package/src/chat/terminal.js +135 -135
  19. package/src/chat/tools.js +306 -306
  20. package/src/chat-pipeline/index.js +173 -131
  21. package/src/chat-pipeline/policy.js +84 -84
  22. package/src/chat-pipeline/serial-trial.js +6 -3
  23. package/src/chat-pipeline/terminal-verdict.js +29 -0
  24. package/src/cli/commands/daemon.js +55 -18
  25. package/src/cli/commands/group.js +249 -249
  26. package/src/cli/commands/model/picks.js +50 -50
  27. package/src/cli/commands/provider/bench-via.js +247 -247
  28. package/src/cli/commands/provider/bench.js +141 -141
  29. package/src/cli/commands/provider/index.js +136 -136
  30. package/src/cli/commands/provider/models.js +145 -145
  31. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  32. package/src/cli/commands/sync.js +310 -310
  33. package/src/cli/commands/system.js +23 -7
  34. package/src/cli/join-wizard.js +8 -4
  35. package/src/cli/policy.js +14 -2
  36. package/src/cli/status.js +279 -279
  37. package/src/daemon.js +232 -195
  38. package/src/logs.js +27 -11
  39. package/src/model-capabilities/enrich.js +86 -86
  40. package/src/model-capabilities/index.js +183 -183
  41. package/src/model-capabilities/parse.js +70 -70
  42. package/src/model-trace.js +35 -4
  43. package/src/models.js +225 -225
  44. package/src/peers.js +20 -1
  45. package/src/providers/AGENTS.md +49 -0
  46. package/src/providers/cline/auth.js +228 -228
  47. package/src/providers/cline/chat.js +307 -307
  48. package/src/providers/cline.js +2 -2
  49. package/src/providers/codearts/chat.js +182 -182
  50. package/src/providers/globalqwenwork/cosy.js +123 -123
  51. package/src/providers/globalqwenwork/crypto.js +218 -218
  52. package/src/providers/globalqwenwork/http.js +20 -20
  53. package/src/providers/globalqwenwork/rsa.js +54 -54
  54. package/src/providers/globalqwenwork/sse.js +268 -268
  55. package/src/providers/globalqwenwork/stream.js +130 -130
  56. package/src/providers/globalqwenwork/upstream.js +122 -122
  57. package/src/providers/keyring.js +60 -60
  58. package/src/providers/qoder/chat.js +203 -203
  59. package/src/providers/qoder/index.js +249 -249
  60. package/src/providers/qoder/sse.js +145 -145
  61. package/src/providers/qwenwork/account-store.js +133 -133
  62. package/src/providers/qwenwork/constants.js +67 -67
  63. package/src/providers/qwenwork/cosy.js +120 -120
  64. package/src/providers/qwenwork/crypto.js +218 -218
  65. package/src/providers/qwenwork/http.js +20 -20
  66. package/src/providers/qwenwork/index.js +337 -327
  67. package/src/providers/qwenwork/payload.js +144 -144
  68. package/src/providers/qwenwork/rsa.js +54 -54
  69. package/src/providers/qwenwork/sse.js +268 -268
  70. package/src/providers/qwenwork/stream.js +130 -130
  71. package/src/providers/qwenwork/upstream.js +120 -120
  72. package/src/providers/qwenwork.js +1 -1
  73. package/src/providers/registry.js +79 -79
  74. package/src/providers/traework/chat.js +7 -1
  75. package/src/providers/workbuddy/chat.js +248 -248
  76. package/src/providers/workbuddy/reshape.js +152 -152
  77. package/src/providers/workbuddy.js +2 -2
  78. package/src/reasoning.js +32 -32
  79. package/src/routes/AGENTS.md +37 -0
  80. package/src/routes/chat/empty-turn-report.js +31 -0
  81. package/src/routes/chat/gateway.js +46 -46
  82. package/src/routes/chat/peer-handler.js +3 -2
  83. package/src/routes/chat/relay-pipeline.js +282 -294
  84. package/src/routes/chat/via-route-handler.js +146 -146
  85. package/src/routes/hedge.js +253 -255
  86. package/src/routes/index.js +14 -6
  87. package/src/routes/models-route.js +167 -167
  88. package/src/routes/peers.js +335 -273
  89. package/src/routes/responses-route.js +44 -2
  90. package/src/routes/stream-body.js +84 -0
  91. package/src/routes/stream-hold.js +152 -4
  92. package/src/routes/stream-scan.js +27 -2
  93. package/src/routes/stream.js +343 -385
  94. package/src/runtime/bootstrap.js +67 -67
  95. package/src/runtime/group-sync.js +70 -17
  96. package/src/runtime/provider-gate.js +36 -36
  97. package/src/runtime/providers-setup.js +168 -168
  98. package/src/runtime/server-lifecycle.js +1 -1
  99. package/src/server.js +78 -78
  100. package/src/state/schemas/allowlist.js +92 -92
  101. package/src/sync-opencode.js +280 -280
  102. package/src/transport/index.js +244 -244
  103. package/src/transport/pool.js +56 -56
  104. package/src/transport/retry.js +24 -24
  105. package/src/transport/sse.js +93 -93
  106. package/src/upstream-engine/sdk/attempt.js +9 -1
  107. package/src/upstream-probe/display.js +52 -52
  108. package/src/upstream-probe/probe.js +49 -49
  109. package/src/upstream-probe/rotate.js +110 -110
  110. package/src/upstream-probe/start.js +45 -45
  111. package/src/upstream.js +293 -293
@@ -156,7 +156,13 @@ export function createChatService({
156
156
  if (tried.has(uid || key)) continue;
157
157
  tried.add(uid || key);
158
158
  await maybeRefresh(auth, key);
159
- const curKey = keys.includes(key) ? key : (keys[keys.indexOf(key)] || key);
159
+ // 刷新后用**新** accessToken 发请求:maybeRefresh → applyTokenRefresh 会把 keys[keyIdx] 就地换成 newToken
160
+ //(`account-store.js` 的 `keys[idx] = newToken`),而局部变量 key 仍是旧值。
161
+ // 旧写法 `keys.includes(key) ? key : (keys[keyIdx] || key)` 两个分支恒等于 key(命中取 key;未命中的
162
+ // indexOf 为 -1 ⇒ keys[-1] undefined ⇒ `|| key` 又取 key)⇒ 整行是恒等 no-op,刷新后照样拿旧 token 打上游。
163
+ // 取 keys[keyIdx]:未刷新时它就是 key(无行为变化),刷新后即新 token。
164
+ const keyIdx = keys.indexOf(key);
165
+ const curKey = keyIdx >= 0 ? keys[keyIdx] : key;
160
166
  let res;
161
167
  try { res = await postOnce(curKey, authForKey(curKey), payload); }
162
168
  catch (e) { try { activeRing?.onError(key); } catch {} lastErr = e; continue; }
@@ -1,248 +1,248 @@
1
- import { joinUrl } from "../base.js";
2
- import { isAuthError, isInsufficientStatus } 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
- res = rewrapBody(res, txt);
236
- }
237
- if (res.status === 401 || res.status === 403 || res.status === 429 || res.status >= 500) try { activeRing.onError(key); } catch {}
238
- res = withUidHeader(res, uid);
239
- res._t = res._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
240
- doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: false });
241
- return res;
242
- }
243
- if (lastErr) throw lastErr;
244
- throw failErr(`${id}: all workbuddy accounts exhausted or unavailable`, t0, clock);
245
- }
246
-
247
- return { runChat, authForKey, buildAuthHeaders, withUidHeader, attemptOnce: fetchOnce };
248
- }
1
+ import { joinUrl } from "../base.js";
2
+ import { isAuthError, isInsufficientStatus } 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
+ res = rewrapBody(res, txt);
236
+ }
237
+ if (res.status === 401 || res.status === 403 || res.status === 429 || res.status >= 500) try { activeRing.onError(key); } catch {}
238
+ res = withUidHeader(res, uid);
239
+ res._t = res._t || { attempts: [], waitMs: 0, totalMs: Math.round(nowMs(clock) - t0) };
240
+ doLog({ uid, model: _modelVal, totalMs: Math.round(nowMs(clock) - t0), balanceHit: false });
241
+ return res;
242
+ }
243
+ if (lastErr) throw lastErr;
244
+ throw failErr(`${id}: all workbuddy accounts exhausted or unavailable`, t0, clock);
245
+ }
246
+
247
+ return { runChat, authForKey, buildAuthHeaders, withUidHeader, attemptOnce: fetchOnce };
248
+ }