mslxdff 0.1.161 → 0.1.162

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/bin/mslxdff.js +4 -4
  2. package/package.json +1 -1
  3. package/src/auto.js +254 -254
  4. package/src/bench/cline-bench.js +42 -42
  5. package/src/bench/probe.js +70 -70
  6. package/src/bench/report.js +162 -162
  7. package/src/bench/runner.js +77 -77
  8. package/src/bench/via-probe.js +124 -124
  9. package/src/bench/via-routes.js +87 -87
  10. package/src/bench/workbuddy-bench.js +54 -54
  11. package/src/chat/engine.js +160 -160
  12. package/src/chat/gateway.js +163 -163
  13. package/src/chat/orchestrator.js +234 -234
  14. package/src/chat/prompt.js +70 -70
  15. package/src/chat/repl.js +88 -88
  16. package/src/chat/terminal.js +135 -135
  17. package/src/chat/tools.js +306 -306
  18. package/src/chat-pipeline/index.js +126 -126
  19. package/src/chat-pipeline/policy.js +76 -76
  20. package/src/cli/commands/group.js +249 -249
  21. package/src/cli/commands/model/picks.js +50 -50
  22. package/src/cli/commands/provider/bench-via.js +247 -247
  23. package/src/cli/commands/provider/bench.js +141 -141
  24. package/src/cli/commands/provider/index.js +126 -126
  25. package/src/cli/commands/provider/models.js +142 -142
  26. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  27. package/src/cli/commands/sync.js +232 -232
  28. package/src/cli/format.js +1 -0
  29. package/src/cli/status.js +279 -279
  30. package/src/daemon.js +101 -101
  31. package/src/model-capabilities/enrich.js +86 -86
  32. package/src/model-capabilities/index.js +183 -183
  33. package/src/model-capabilities/parse.js +70 -70
  34. package/src/model-trace.js +4 -3
  35. package/src/models.js +225 -225
  36. package/src/providers/cline/auth.js +228 -228
  37. package/src/providers/cline/chat.js +307 -307
  38. package/src/providers/cline.js +2 -2
  39. package/src/providers/dispatcher.js +26 -14
  40. package/src/providers/globalqwenwork/cosy.js +123 -123
  41. package/src/providers/globalqwenwork/crypto.js +218 -218
  42. package/src/providers/globalqwenwork/http.js +20 -20
  43. package/src/providers/globalqwenwork/rsa.js +54 -54
  44. package/src/providers/globalqwenwork/sse.js +268 -268
  45. package/src/providers/globalqwenwork/stream.js +130 -130
  46. package/src/providers/globalqwenwork/upstream.js +122 -122
  47. package/src/providers/keyring.js +60 -60
  48. package/src/providers/qoder/chat.js +193 -183
  49. package/src/providers/qoder/index.js +239 -230
  50. package/src/providers/qoder/sse.js +141 -103
  51. package/src/providers/qwenwork/account-store.js +133 -133
  52. package/src/providers/qwenwork/constants.js +67 -67
  53. package/src/providers/qwenwork/cosy.js +120 -120
  54. package/src/providers/qwenwork/crypto.js +218 -218
  55. package/src/providers/qwenwork/http.js +20 -20
  56. package/src/providers/qwenwork/index.js +327 -327
  57. package/src/providers/qwenwork/payload.js +142 -142
  58. package/src/providers/qwenwork/rsa.js +54 -54
  59. package/src/providers/qwenwork/sse.js +268 -268
  60. package/src/providers/qwenwork/stream.js +130 -130
  61. package/src/providers/qwenwork/upstream.js +120 -120
  62. package/src/providers/qwenwork.js +1 -1
  63. package/src/providers/registry.js +74 -74
  64. package/src/providers/workbuddy/chat.js +248 -248
  65. package/src/providers/workbuddy/reshape.js +152 -152
  66. package/src/providers/workbuddy.js +2 -2
  67. package/src/reasoning.js +32 -32
  68. package/src/routes/chat/gateway.js +46 -46
  69. package/src/routes/chat/relay-pipeline.js +276 -276
  70. package/src/routes/chat/via-route-handler.js +146 -146
  71. package/src/routes/hedge.js +255 -255
  72. package/src/routes/models-route.js +167 -167
  73. package/src/routes/peers.js +273 -273
  74. package/src/routes/stream.js +386 -386
  75. package/src/runtime/bootstrap.js +45 -45
  76. package/src/runtime/provider-gate.js +34 -34
  77. package/src/runtime/providers-setup.js +165 -165
  78. package/src/runtime/server-lifecycle.js +5 -6
  79. package/src/server.js +64 -64
  80. package/src/state/schemas/allowlist.js +92 -92
  81. package/src/sync-opencode.js +280 -280
  82. package/src/transport/index.js +244 -244
  83. package/src/transport/pool.js +56 -56
  84. package/src/transport/retry.js +24 -24
  85. package/src/transport/sse.js +93 -93
  86. package/src/upstream-probe/display.js +52 -52
  87. package/src/upstream-probe/probe.js +49 -49
  88. package/src/upstream-probe/rotate.js +110 -110
  89. package/src/upstream-probe/start.js +45 -45
  90. package/src/upstream.js +289 -289
  91. package/docs/cli_help_mini.md +0 -135
  92. package/src/providers/AGENTS.md +0 -46
  93. package/src/routes/AGENTS.md +0 -37
@@ -1,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
+ }