mslxdff 0.1.170 → 0.1.172

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 (110) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/docs/cli_help_mini.md +143 -0
  3. package/package.json +1 -1
  4. package/src/anthropic/count-tokens.js +39 -0
  5. package/src/anthropic/translate.js +20 -41
  6. package/src/auto.js +254 -254
  7. package/src/bench/cline-bench.js +42 -42
  8. package/src/bench/probe.js +70 -70
  9. package/src/bench/report.js +162 -162
  10. package/src/bench/runner.js +77 -77
  11. package/src/bench/via-probe.js +124 -124
  12. package/src/bench/via-routes.js +87 -87
  13. package/src/bench/workbuddy-bench.js +54 -54
  14. package/src/chat/engine.js +160 -160
  15. package/src/chat/gateway.js +163 -163
  16. package/src/chat/orchestrator.js +234 -234
  17. package/src/chat/prompt.js +70 -70
  18. package/src/chat/repl.js +88 -88
  19. package/src/chat/terminal.js +135 -135
  20. package/src/chat/tools.js +306 -306
  21. package/src/chat-pipeline/index.js +131 -131
  22. package/src/chat-pipeline/policy.js +76 -76
  23. package/src/cli/commands/group.js +249 -249
  24. package/src/cli/commands/model/picks.js +50 -50
  25. package/src/cli/commands/provider/bench-via.js +247 -247
  26. package/src/cli/commands/provider/bench.js +141 -141
  27. package/src/cli/commands/provider/index.js +133 -133
  28. package/src/cli/commands/provider/models.js +145 -145
  29. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  30. package/src/cli/commands/sync.js +310 -310
  31. package/src/cli/status.js +279 -279
  32. package/src/daemon.js +112 -112
  33. package/src/model-capabilities/context-lookup.js +65 -0
  34. package/src/model-capabilities/enrich.js +86 -86
  35. package/src/model-capabilities/index.js +183 -183
  36. package/src/model-capabilities/merge.js +50 -35
  37. package/src/model-capabilities/parse.js +70 -70
  38. package/src/models.js +225 -225
  39. package/src/providers/AGENTS.md +49 -0
  40. package/src/providers/cline/auth.js +228 -228
  41. package/src/providers/cline/chat.js +307 -307
  42. package/src/providers/cline.js +2 -2
  43. package/src/providers/codearts/concurrency.js +34 -0
  44. package/src/providers/codearts/index.js +11 -3
  45. package/src/providers/globalqwenwork/cosy.js +123 -123
  46. package/src/providers/globalqwenwork/crypto.js +218 -218
  47. package/src/providers/globalqwenwork/http.js +20 -20
  48. package/src/providers/globalqwenwork/payload.js +4 -2
  49. package/src/providers/globalqwenwork/rsa.js +54 -54
  50. package/src/providers/globalqwenwork/sse.js +268 -268
  51. package/src/providers/globalqwenwork/stream.js +130 -130
  52. package/src/providers/globalqwenwork/upstream.js +122 -122
  53. package/src/providers/keyring.js +60 -60
  54. package/src/providers/qoder/chat.js +203 -200
  55. package/src/providers/qoder/index.js +249 -249
  56. package/src/providers/qoder/sse.js +145 -145
  57. package/src/providers/qwenwork/account-store.js +133 -133
  58. package/src/providers/qwenwork/constants.js +67 -67
  59. package/src/providers/qwenwork/cosy.js +120 -120
  60. package/src/providers/qwenwork/crypto.js +218 -218
  61. package/src/providers/qwenwork/http.js +20 -20
  62. package/src/providers/qwenwork/index.js +327 -327
  63. package/src/providers/qwenwork/payload.js +144 -142
  64. package/src/providers/qwenwork/rsa.js +54 -54
  65. package/src/providers/qwenwork/sse.js +268 -268
  66. package/src/providers/qwenwork/stream.js +130 -130
  67. package/src/providers/qwenwork/upstream.js +120 -120
  68. package/src/providers/qwenwork.js +1 -1
  69. package/src/providers/raccoon/chat.js +10 -5
  70. package/src/providers/raccoon/const.js +4 -4
  71. package/src/providers/registry.js +79 -79
  72. package/src/providers/traework/models.js +4 -3
  73. package/src/providers/workbuddy/chat.js +248 -248
  74. package/src/providers/workbuddy/payload.js +16 -7
  75. package/src/providers/workbuddy/reshape.js +152 -152
  76. package/src/providers/workbuddy.js +2 -2
  77. package/src/providers/zcode/chat.js +7 -0
  78. package/src/reasoning.js +32 -32
  79. package/src/responses/translate.js +4 -0
  80. package/src/routes/AGENTS.md +37 -0
  81. package/src/routes/chat/exhausted-handler.js +5 -0
  82. package/src/routes/chat/gateway.js +46 -46
  83. package/src/routes/chat/relay-pipeline.js +294 -291
  84. package/src/routes/chat/via-route-handler.js +146 -146
  85. package/src/routes/hedge.js +255 -255
  86. package/src/routes/messages-route.js +1 -1
  87. package/src/routes/models-route.js +167 -167
  88. package/src/routes/peers.js +273 -273
  89. package/src/routes/stream-scan.js +47 -21
  90. package/src/routes/stream.js +385 -385
  91. package/src/runtime/bootstrap.js +50 -50
  92. package/src/runtime/provider-gate.js +36 -36
  93. package/src/runtime/providers-setup.js +165 -165
  94. package/src/server.js +69 -69
  95. package/src/state/schemas/allowlist.js +92 -92
  96. package/src/sync-opencode.js +280 -280
  97. package/src/talk-full.js +1 -0
  98. package/src/talk-log.js +3 -2
  99. package/src/thinking-effort.js +67 -0
  100. package/src/transport/index.js +244 -244
  101. package/src/transport/pool.js +56 -56
  102. package/src/transport/retry.js +24 -24
  103. package/src/transport/sse.js +93 -93
  104. package/src/upstream-engine/sdk/convert.js +6 -0
  105. package/src/upstream-probe/display.js +52 -52
  106. package/src/upstream-probe/probe.js +49 -49
  107. package/src/upstream-probe/rotate.js +110 -110
  108. package/src/upstream-probe/start.js +45 -45
  109. package/src/upstream-responses.js +5 -0
  110. package/src/upstream.js +289 -289
@@ -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
+ }
@@ -12,6 +12,8 @@
12
12
  // "To give feedback, users should report the issue at https://github.com/anthropics/claude-code/issues");
13
13
  // 整句为**纯子串匹配**(去掉行首 `- ` 照拦),user/tool 文本不扫、换说法/中间片段/普通长文全放行
14
14
  // → 只剥官方注入物不动用户内容;日后撞见新拦句,加进 CC_SENTENCES 即可
15
+ import { effortFromBody, effortLevelFromBody, isEffortOff } from "../../thinking-effort.js";
16
+
15
17
  const DEEPSEEK_PREFIX = "deepseek";
16
18
  const DEFAULT_DEEPSEEK_EFFORT = "high";
17
19
  const CC_BILLING_LINE = /^x-anthropic-billing-header:.*\r?\n?/gim;
@@ -62,18 +64,25 @@ export function normalizeToolChoice(obj) {
62
64
 
63
65
  export function injectThinking(obj) {
64
66
  if (!isDeepSeekModel(obj?.model)) return obj;
67
+ // 档位词表与关断判定统一走 src/thinking-effort.js:客户端**任一**载体声明 off/none/disabled 都算关思考
68
+ //(旧版只认 thinking.type,会把新透传进来的 reasoning_effort:"off" 反转为开——change fix-thinking-effort-passthrough)。
65
69
  const th = obj.thinking && typeof obj.thinking === "object" ? obj.thinking : null;
66
- const type = th ? String(th.type || "").trim() : "";
67
- if (type && type.toLowerCase() === "disabled") {
70
+ const declared = effortFromBody(obj);
71
+ if (declared && isEffortOff(declared)) {
68
72
  delete obj.reasoning_effort;
69
73
  delete obj.reasoningEffort;
74
+ delete obj.effort;
75
+ if (th) th.type = "disabled";
76
+ else obj.thinking = { type: "disabled" };
70
77
  return obj;
71
78
  }
72
- if (!type) {
73
- if (th) th.type = "enabled";
74
- else obj.thinking = { type: "enabled" };
75
- }
76
- if (!("reasoning_effort" in obj) && !("reasoningEffort" in obj)) obj.reasoning_effort = DEFAULT_DEEPSEEK_EFFORT;
79
+ if (!th) obj.thinking = { type: "enabled" };
80
+ else if (!String(th.type || "").trim()) th.type = "enabled";
81
+ // 归一档位载体:上游只认 reasoning_effort,故 camel 与 effort 都折成 snake 再删掉(免得未知字段裸奔)。
82
+ const level = effortLevelFromBody(obj);
83
+ if (!("reasoning_effort" in obj)) obj.reasoning_effort = level || DEFAULT_DEEPSEEK_EFFORT;
84
+ delete obj.reasoningEffort;
85
+ delete obj.effort;
77
86
  return obj;
78
87
  }
79
88