mslxdff 0.1.164 → 0.1.169

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 (56) hide show
  1. package/package.json +1 -1
  2. package/src/anthropic/translate.js +23 -5
  3. package/src/anthropic/web-search.js +361 -0
  4. package/src/api-kind.js +31 -0
  5. package/src/chat-pipeline/auto-race.js +8 -0
  6. package/src/chat-pipeline/empty-turn.js +28 -0
  7. package/src/chat-pipeline/index.js +8 -4
  8. package/src/chat-pipeline/serial-trial.js +8 -1
  9. package/src/claude-desktop/apply.js +64 -0
  10. package/src/claude-desktop/doctor.js +146 -0
  11. package/src/claude-desktop/slots.js +86 -0
  12. package/src/cli/commands/claude-desktop.js +264 -0
  13. package/src/cli/commands/model/list-providers.js +1 -1
  14. package/src/cli/commands/provider/index.js +7 -0
  15. package/src/cli/commands/provider/models.js +3 -0
  16. package/src/cli/commands/provider/raccoon-login.js +131 -0
  17. package/src/cli/commands/provider/raccoon-quota.js +109 -0
  18. package/src/cli/commands/sync.js +8 -2
  19. package/src/cli/format.js +1 -1
  20. package/src/cli/help.js +2 -0
  21. package/src/cli/index.js +2 -0
  22. package/src/cli/provider-row.js +2 -2
  23. package/src/model-capabilities/parse.js +1 -1
  24. package/src/model-trace.js +2 -1
  25. package/src/providers/classify.js +1 -1
  26. package/src/providers/dispatcher.js +2 -2
  27. package/src/providers/keyring.js +1 -1
  28. package/src/providers/model-id.js +10 -0
  29. package/src/providers/raccoon/account-store.js +216 -0
  30. package/src/providers/raccoon/auth.js +67 -0
  31. package/src/providers/raccoon/chat.js +207 -0
  32. package/src/providers/raccoon/const.js +111 -0
  33. package/src/providers/raccoon/credits.js +161 -0
  34. package/src/providers/raccoon/envelope.js +23 -0
  35. package/src/providers/raccoon/headers.js +45 -0
  36. package/src/providers/raccoon/index.js +216 -0
  37. package/src/providers/raccoon/login.js +195 -0
  38. package/src/providers/raccoon/models.js +160 -0
  39. package/src/providers/raccoon/qr-codewords.js +115 -0
  40. package/src/providers/raccoon/qr.js +236 -0
  41. package/src/providers/raccoon/sse.js +135 -0
  42. package/src/providers/registry.js +5 -0
  43. package/src/providers/share-keys.js +1 -1
  44. package/src/providers/workbuddy/models.js +29 -14
  45. package/src/providers/workbuddy/payload.js +34 -0
  46. package/src/routes/chat/exhausted-handler.js +4 -4
  47. package/src/routes/chat/relay-pipeline.js +6 -7
  48. package/src/routes/messages-route.js +114 -3
  49. package/src/runtime/bootstrap.js +5 -0
  50. package/src/runtime/broadband.js +4 -1
  51. package/src/runtime/provider-gate.js +3 -1
  52. package/src/runtime/raccoon-checkin.js +126 -0
  53. package/src/state/provider-config.js +1 -1
  54. package/src/sync-claude-desktop.js +234 -0
  55. package/src/talk-full.js +2 -2
  56. package/src/talk-log.js +9 -6
@@ -0,0 +1,236 @@
1
+ // raccoon 扫码登录用的最小二维码「矩阵层」+ 终端渲染(零依赖,不引入 npm 包)。
2
+ // 码字计算在 qr-codewords.js;本文件只负责功能图案、码字摆放、掩码择优与字符画输出。
3
+ // 参考:dsh-our-free-model 的 vendor/channel-pack/src/raccoon-qr.ts(同为无依赖自写)。
4
+ //
5
+ // 与渲染分离:encodeQr() 出矩阵,renderTerminal() 出字符串;任何一步失败都返回 undefined,
6
+ // 由调用方退回「只打印 URL」——用户拿不到字符画也必须能登录。
7
+ import { buildQrCodewords, pickQrVersion } from "./qr-codewords.js";
8
+
9
+ /** 掩码条件(QR 规范 8 条),索引即掩码号。 */
10
+ function maskBit(mask, x, y) {
11
+ switch (mask) {
12
+ case 0: return (x + y) % 2 === 0;
13
+ case 1: return y % 2 === 0;
14
+ case 2: return x % 3 === 0;
15
+ case 3: return (x + y) % 3 === 0;
16
+ case 4: return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
17
+ case 5: return ((x * y) % 2) + ((x * y) % 3) === 0;
18
+ case 6: return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;
19
+ default: return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;
20
+ }
21
+ }
22
+
23
+ /** 校正图案中心坐标(规范表算法,与参考实现一致)。 */
24
+ function alignmentPositions(version, size) {
25
+ if (version === 1) return [];
26
+ const numAlign = Math.floor(version / 7) + 2;
27
+ const step = Math.ceil((version * 4 + 4) / (numAlign * 2 - 2)) * 2;
28
+ const result = [6];
29
+ for (let pos = size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);
30
+ return result;
31
+ }
32
+
33
+ class Matrix {
34
+ constructor(size) {
35
+ this.size = size;
36
+ this.modules = Array.from({ length: size }, () => new Array(size).fill(false));
37
+ this.isFunction = Array.from({ length: size }, () => new Array(size).fill(false));
38
+ }
39
+
40
+ set(x, y, dark) {
41
+ this.modules[y][x] = dark;
42
+ this.isFunction[y][x] = true;
43
+ }
44
+
45
+ drawFunctionPatterns(version) {
46
+ const { size } = this;
47
+ for (let i = 0; i < size; i++) {
48
+ this.set(6, i, i % 2 === 0); // 竖向定时
49
+ this.set(i, 6, i % 2 === 0); // 横向定时
50
+ }
51
+ for (const [x, y] of [[3, 3], [size - 4, 3], [3, size - 4]]) this.drawFinder(x, y);
52
+ const positions = alignmentPositions(version, size);
53
+ const n = positions.length;
54
+ for (let i = 0; i < n; i++) {
55
+ for (let j = 0; j < n; j++) {
56
+ const isCorner = (i === 0 && j === 0) || (i === 0 && j === n - 1) || (i === n - 1 && j === 0);
57
+ if (!isCorner) this.drawAlignment(positions[i], positions[j]);
58
+ }
59
+ }
60
+ this.drawFormatBits(0); // 占位;掩码定下后重画
61
+ if (version >= 7) this.drawVersionBits(version);
62
+ }
63
+
64
+ /** 定位图案含分隔带:切比雪夫距离 2 与 4 处为白,其余为黑(参考实现同款判据)。 */
65
+ drawFinder(cx, cy) {
66
+ for (let dy = -4; dy <= 4; dy++) {
67
+ for (let dx = -4; dx <= 4; dx++) {
68
+ const x = cx + dx;
69
+ const y = cy + dy;
70
+ if (x < 0 || x >= this.size || y < 0 || y >= this.size) continue;
71
+ const dist = Math.max(Math.abs(dx), Math.abs(dy));
72
+ this.set(x, y, dist !== 2 && dist !== 4);
73
+ }
74
+ }
75
+ }
76
+
77
+ drawAlignment(cx, cy) {
78
+ for (let dy = -2; dy <= 2; dy++) {
79
+ for (let dx = -2; dx <= 2; dx++) this.set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
80
+ }
81
+ }
82
+
83
+ /** 格式信息:纠错级 M 的格式位 = 00,BCH(15,5) 校验 + 固定掩码 0x5412,两处各写一份。 */
84
+ drawFormatBits(mask) {
85
+ const data = (0 << 3) | mask;
86
+ let rem = data;
87
+ for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
88
+ const bits = ((data << 10) | rem) ^ 0x5412;
89
+ const bit = (i) => ((bits >> i) & 1) === 1;
90
+ for (let i = 0; i <= 5; i++) this.set(8, i, bit(i));
91
+ this.set(8, 7, bit(6));
92
+ this.set(8, 8, bit(7));
93
+ this.set(7, 8, bit(8));
94
+ for (let i = 9; i < 15; i++) this.set(14 - i, 8, bit(i));
95
+ for (let i = 0; i < 8; i++) this.set(this.size - 1 - i, 8, bit(i));
96
+ for (let i = 8; i < 15; i++) this.set(8, this.size - 15 + i, bit(i));
97
+ this.set(8, this.size - 8, true); // 固定黑模块
98
+ }
99
+
100
+ drawVersionBits(version) {
101
+ let rem = version;
102
+ for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
103
+ const bits = (version << 12) | rem;
104
+ for (let i = 0; i < 18; i++) {
105
+ const dark = ((bits >> i) & 1) === 1;
106
+ const a = this.size - 11 + (i % 3);
107
+ const b = Math.floor(i / 3);
108
+ this.set(a, b, dark);
109
+ this.set(b, a, dark);
110
+ }
111
+ }
112
+
113
+ /** 码字按「自右向左、上下往复」的之字形填入非功能模块(跳过第 6 列定时线)。 */
114
+ drawCodewords(codewords) {
115
+ let i = 0;
116
+ for (let right = this.size - 1; right >= 1; right -= 2) {
117
+ if (right === 6) right = 5;
118
+ for (let vert = 0; vert < this.size; vert++) {
119
+ for (let j = 0; j < 2; j++) {
120
+ const x = right - j;
121
+ const upward = ((right + 1) & 2) === 0;
122
+ const y = upward ? this.size - 1 - vert : vert;
123
+ if (!this.isFunction[y][x] && i < codewords.length * 8) {
124
+ this.modules[y][x] = ((codewords[i >>> 3] >> (7 - (i & 7))) & 1) === 1;
125
+ i++;
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+
132
+ applyMask(mask) {
133
+ for (let y = 0; y < this.size; y++) {
134
+ for (let x = 0; x < this.size; x++) {
135
+ if (!this.isFunction[y][x] && maskBit(mask, x, y)) this.modules[y][x] = !this.modules[y][x];
136
+ }
137
+ }
138
+ }
139
+
140
+ clone() {
141
+ const m = new Matrix(this.size);
142
+ for (let y = 0; y < this.size; y++) {
143
+ m.modules[y] = [...this.modules[y]];
144
+ m.isFunction[y] = [...this.isFunction[y]];
145
+ }
146
+ return m;
147
+ }
148
+
149
+ /**
150
+ * 掩码惩罚分(N1 同色连跑 / N2 2×2 同色块 / N4 黑白失衡)。
151
+ * 规范里的 N3(类定位图案)未实现:它只影响选掩码的偏好、不影响码的正确性,
152
+ * 省下的复杂度换更小的文件体积;本用途(终端展示的短 URL)实测不影响识别。
153
+ */
154
+ penalty() {
155
+ let score = 0;
156
+ const { size } = this;
157
+ for (let y = 0; y < size; y++) {
158
+ let run = 1;
159
+ for (let x = 1; x < size; x++) {
160
+ if (this.modules[y][x] === this.modules[y][x - 1]) run++;
161
+ else { if (run >= 5) score += 3 + (run - 5); run = 1; }
162
+ }
163
+ if (run >= 5) score += 3 + (run - 5);
164
+ }
165
+ for (let x = 0; x < size; x++) {
166
+ let run = 1;
167
+ for (let y = 1; y < size; y++) {
168
+ if (this.modules[y][x] === this.modules[y - 1][x]) run++;
169
+ else { if (run >= 5) score += 3 + (run - 5); run = 1; }
170
+ }
171
+ if (run >= 5) score += 3 + (run - 5);
172
+ }
173
+ for (let y = 0; y < size - 1; y++) {
174
+ for (let x = 0; x < size - 1; x++) {
175
+ const c = this.modules[y][x];
176
+ if (c === this.modules[y][x + 1] && c === this.modules[y + 1][x] && c === this.modules[y + 1][x + 1]) score += 3;
177
+ }
178
+ }
179
+ let dark = 0;
180
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) if (this.modules[y][x]) dark++;
181
+ const total = size * size;
182
+ score += (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10;
183
+ return score;
184
+ }
185
+ }
186
+
187
+ /** 文本 → 二维码矩阵;过长或任何异常返回 undefined(调用方退回打印 URL)。 */
188
+ export function encodeQr(text) {
189
+ try {
190
+ const bytes = [...Buffer.from(String(text), "utf8")];
191
+ const version = pickQrVersion(bytes.length);
192
+ if (version === undefined) return undefined;
193
+ const codewords = buildQrCodewords(bytes, version);
194
+ const base = new Matrix(version * 4 + 17);
195
+ base.drawFunctionPatterns(version);
196
+ base.drawCodewords(codewords);
197
+ let best;
198
+ let bestScore = Infinity;
199
+ for (let mask = 0; mask < 8; mask++) {
200
+ const candidate = base.clone();
201
+ candidate.applyMask(mask);
202
+ candidate.drawFormatBits(mask);
203
+ const score = candidate.penalty();
204
+ if (score < bestScore) { bestScore = score; best = candidate; }
205
+ }
206
+ return best;
207
+ } catch {
208
+ return undefined;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * 矩阵 → 终端字符画(半块字符,1 字符宽 / 2 模块高),含 2 模块静区。
214
+ * 用 ▀▄█ 而非双宽全块:同样的可扫性下把宽度砍半,窄终端也放得下。
215
+ */
216
+ export function renderTerminal(matrix, { quiet = 2 } = {}) {
217
+ if (!matrix?.modules?.length) return undefined;
218
+ const size = matrix.size;
219
+ const n = size + quiet * 2;
220
+ const dark = (x, y) => {
221
+ const mx = x - quiet;
222
+ const my = y - quiet;
223
+ return mx >= 0 && mx < size && my >= 0 && my < size ? Boolean(matrix.modules[my][mx]) : false;
224
+ };
225
+ const lines = [];
226
+ for (let y = 0; y < n; y += 2) {
227
+ let line = "";
228
+ for (let x = 0; x < n; x++) {
229
+ const top = dark(x, y);
230
+ const bottom = y + 1 < n ? dark(x, y + 1) : false;
231
+ line += top && bottom ? "█" : top ? "▀" : bottom ? "▄" : " ";
232
+ }
233
+ lines.push(line);
234
+ }
235
+ return lines.join("\n");
236
+ }
@@ -0,0 +1,135 @@
1
+ // raccoon 流处理:上游就是 OpenAI 形(`/api/web/llm/v2/chat/completions`),
2
+ // 因此**不做协议转换**——本文件只做三件事:形状判定、错误信封分类、非流式聚合。
3
+ // 流式路径直接把上游 body 透传(逐字节),避免任何整形引入的失真。
4
+ import { createSseParser } from "../../transport/sse.js";
5
+ import { isRaccoonAuthFailure, parseRaccoonEnvelope, raccoonEnvelopeText } from "./envelope.js";
6
+
7
+ /**
8
+ * 额度类措辞(业务码未取证,见 ADR-0050 决策 8):**宁可漏判也不误报**。
9
+ * 刻意不收裸 `insufficient`/`balance`/`points` —— 那些词会命中「权限不足」这类非额度错,
10
+ * 一旦误判成 quota 就会长冷 1h 并回 429 `quota_exhausted`,违反 ADR-0044 的「非额度原因不得谎报」。
11
+ */
12
+ const QUOTA_HINTS = /(积分|额度|quota|欠费)/i;
13
+
14
+ export function isRaccoonSseContentType(value) {
15
+ return String(value || "").includes("text/event-stream");
16
+ }
17
+
18
+ function isQuotaLike(envelope) {
19
+ const text = `${envelope?.message ?? ""} ${envelope?.details ?? ""}`;
20
+ if (QUOTA_HINTS.test(text)) return true;
21
+ return envelope?.status === 402;
22
+ }
23
+
24
+ /**
25
+ * 失败分类 → `{ kind, code, status, message }`。
26
+ * kind 取值:auth(重登)/ quota(长冷却)/ rate_limit(短冷却)/ server(上游 5xx,短冷却)/ unknown(4xx 如实透出)。
27
+ */
28
+ export function classifyRaccoonFailure(status, payload) {
29
+ const envelope = parseRaccoonEnvelope(payload, status);
30
+ let kind = "unknown";
31
+ if (isRaccoonAuthFailure(envelope, status)) kind = "auth";
32
+ else if (isQuotaLike(envelope)) kind = "quota";
33
+ else if (status === 429) kind = "rate_limit";
34
+ else if (status >= 500) kind = "server";
35
+ return { kind, code: envelope.code, status, message: raccoonEnvelopeText(envelope, `HTTP ${status}`) };
36
+ }
37
+
38
+ const ERROR_MAP = {
39
+ auth: { status: 401, type: "auth_error", text: (f) => `raccoon: 登录态已失效${f.code ? `(code ${f.code})` : ""}。请运行 mslxdff -provider raccoon login 重新登录` },
40
+ quota: { status: 429, type: "quota_exhausted", text: (f) => `raccoon: 积分不足${f.message ? `(${f.message})` : ""}。请运行 mslxdff -provider raccoon checkin 领取每日积分,或更换账号` },
41
+ rate_limit: { status: 429, type: "rate_limited", text: () => "raccoon: 上游限流(账号冷却中),请稍后重试" },
42
+ server: { status: 502, type: "upstream_error", text: (f) => `raccoon: 上游服务异常${f.code ? `(code ${f.code})` : ""}${f.message ? `:${f.message}` : ""}` },
43
+ // unknown 只覆盖 4xx(5xx 已被上面分流成 server):按请求缺陷如实回 400,不谎报成网关故障
44
+ unknown: { status: 400, type: "invalid_request", text: (f) => `raccoon: 上游拒绝请求(HTTP ${f.status || "?"}${f.code ? ` code ${f.code}` : ""})${f.message ? `:${f.message}` : ""}` },
45
+ };
46
+
47
+ /** 失败 → Response(带 `x-mslxdff-raccoon-kind`,供工厂决定冷却档位)。 */
48
+ export function raccoonErrorResponse(fail = {}) {
49
+ const kind = ERROR_MAP[fail.kind] ? fail.kind : "unknown";
50
+ const entry = ERROR_MAP[kind];
51
+ const headers = { "Content-Type": "application/json" };
52
+ if (fail.kind) headers["x-mslxdff-raccoon-kind"] = fail.kind;
53
+ return new Response(JSON.stringify({ error: { message: entry.text(fail), type: entry.type, code: fail.code || 0 } }), {
54
+ status: entry.status,
55
+ headers,
56
+ });
57
+ }
58
+
59
+ /** 工具调用增量合并(对齐 `qwenwork/sse.js` 的 mergeToolCallDelta:id/type 取一次,name/arguments 追加)。 */
60
+ function mergeRaccoonToolCallDelta(merged, delta) {
61
+ for (const key of ["id", "type"]) {
62
+ if (merged[key] === undefined && typeof delta[key] === "string" && delta[key] !== "") merged[key] = delta[key];
63
+ }
64
+ const dfn = delta.function;
65
+ if (!dfn || typeof dfn !== "object") return;
66
+ if (!merged.function || typeof merged.function !== "object") merged.function = {};
67
+ if (typeof dfn.name === "string" && dfn.name !== "") merged.function.name = (merged.function.name || "") + dfn.name;
68
+ if (typeof dfn.arguments === "string" && dfn.arguments !== "") {
69
+ merged.function.arguments = (merged.function.arguments || "") + dfn.arguments;
70
+ }
71
+ }
72
+
73
+ /** 把 SSE 文本聚合成一条 OpenAI chat completion(非流式请求、以及「header 说是 JSON 但体是 SSE」时走这里)。 */
74
+ export async function aggregateRaccoonSse(text, { model } = {}) {
75
+ const parser = createSseParser();
76
+ // 聚合拿到的是**完整 body**(不是分片):补一个定界符,否则末尾缺 `\n\n` 的最后一帧会被当半包丢掉
77
+ const events = parser.push(`${String(text || "")}\n\n`);
78
+ const content = [];
79
+ const reasoning = [];
80
+ const toolCalls = new Map();
81
+ const toolOrder = [];
82
+ let finishReason = "stop";
83
+ let usage;
84
+ let id = "";
85
+ let created = 0;
86
+ for (const raw of events) {
87
+ if (raw === "[DONE]" || !raw) continue;
88
+ let payload;
89
+ try {
90
+ payload = JSON.parse(raw);
91
+ } catch {
92
+ continue;
93
+ }
94
+ // 流内错误信封:优先按失败分类返回,不要静默当成空回复
95
+ if (payload?.code !== undefined && Number(payload.code) !== 0) {
96
+ return { error: classifyRaccoonFailure(200, payload) };
97
+ }
98
+ if (payload?.error) {
99
+ return { error: classifyRaccoonFailure(200, payload) };
100
+ }
101
+ if (!id && typeof payload?.id === "string") id = payload.id;
102
+ if (!created && Number.isFinite(payload?.created)) created = Number(payload.created);
103
+ if (payload?.usage) usage = payload.usage;
104
+ const choice = Array.isArray(payload?.choices) ? payload.choices[0] : undefined;
105
+ const delta = choice?.delta ?? choice?.message;
106
+ if (typeof delta?.content === "string" && delta.content.length > 0) content.push(delta.content);
107
+ if (typeof delta?.reasoning_content === "string" && delta.reasoning_content.length > 0) reasoning.push(delta.reasoning_content);
108
+ for (const call of Array.isArray(delta?.tool_calls) ? delta.tool_calls : []) {
109
+ if (!call || typeof call !== "object") continue;
110
+ const idx = typeof call.index === "number" ? call.index : 0;
111
+ if (!toolCalls.has(idx)) {
112
+ toolCalls.set(idx, { index: idx });
113
+ toolOrder.push(idx);
114
+ }
115
+ mergeRaccoonToolCallDelta(toolCalls.get(idx), call);
116
+ }
117
+ if (typeof choice?.finish_reason === "string" && choice.finish_reason.length > 0) finishReason = choice.finish_reason;
118
+ }
119
+ const message = { role: "assistant", content: content.join("") || null };
120
+ if (reasoning.length > 0) message.reasoning_content = reasoning.join("");
121
+ if (toolOrder.length > 0) {
122
+ toolOrder.sort((a, b) => a - b);
123
+ message.tool_calls = toolOrder.map((idx) => toolCalls.get(idx));
124
+ }
125
+ return {
126
+ openAi: {
127
+ id: id || `chatcmpl-raccoon-${Date.now()}`,
128
+ object: "chat.completion",
129
+ created: created || Math.floor(Date.now() / 1000),
130
+ model: model || "",
131
+ choices: [{ index: 0, message, finish_reason: finishReason }],
132
+ ...(usage ? { usage } : {}),
133
+ },
134
+ };
135
+ }
@@ -48,6 +48,11 @@ export const customProviders = [
48
48
  match: (id, baseUrl) => id === "zcode" || String(baseUrl).includes("zcode.z.ai"),
49
49
  load: () => import("./zcode/index.js").then((m) => m.createZcodeProvider),
50
50
  },
51
+ {
52
+ id: "raccoon",
53
+ match: (id, baseUrl) => id === "raccoon" || String(baseUrl).includes("xiaohuanxiong.com"),
54
+ load: () => import("./raccoon/index.js").then((m) => m.createRaccoonProvider),
55
+ },
51
56
  ];
52
57
 
53
58
  // 供 bench/probe 等需要定制化解析模型列表的场景
@@ -10,7 +10,7 @@ export const SHARE_KEYS_HEADER = "x-mslxdff-share-keys";
10
10
  // 硬排除:refresh-token 型凭据(对端刷新会轮换 token,与本机互相踢下线)——正确性问题。
11
11
  // 二层保护:① 按 id 硬排除(cline 恒 local-only);② 按凭据形状兜底(见 shareableProviderIds)。
12
12
  // traework/workbuddy/zcode 同为本机账号绑定型(auths/*.json + uid;zcode 还带 per-account deviceMid),恒不借出。
13
- const NEVER_SHARE_IDS = new Set(["cline", "codearts", "traework", "qoder", "zcode"]);
13
+ const NEVER_SHARE_IDS = new Set(["cline", "codearts", "traework", "qoder", "zcode", "raccoon"]);
14
14
  // 本节点应 cast key 到出站转发的供应商 id 集合 = 所有「本机有 key」的供应商,
15
15
  // 减去:opencode(无 key 且恒排除)、local-only(workbuddy/cline系,本就不走组员)、刷新型凭据。
16
16
  export function shareableProviderIds({ file } = {}) {
@@ -49,25 +49,40 @@ export function createModelsService({
49
49
  async function listModels() {
50
50
  const now = clock();
51
51
  if (cache && now - fetchedAt < CACHE_TTL_MS) return cache;
52
+ // 逐 key 试到成功:单个 token 被上游撤销时整个目录不该空掉。2026-10-10 实测 4 个 token 里 3 个
53
+ // 已失效,旧逻辑取 ring.next() 首个 key 401 即 return [],CLI 端表现为 `workbuddy models (0 total)`
54
+ // → aggLoad 判 `!allowed.length` 把整家 workbuddy 跳过,用户侧就是「模型全没了」。
55
+ const tried = new Set();
56
+ let res = null;
52
57
  try {
53
- const key = getKey ? getKey() : "";
54
- const auth = getAuth ? getAuth(key) : null;
55
- if (auth && key) maybeProactiveRefresh?.(auth, key);
56
- let res = await execList(key, auth);
57
- if (!res.ok) {
58
- let t = "";
59
- try { t = await res.clone().text(); } catch {}
60
- if (isAuthError?.(res.status, t)) {
61
- const newKey = await refreshTokenFor?.(key, auth);
62
- if (newKey) {
63
- const auth2 = getAuth ? getAuth(newKey) : auth;
64
- res = await execList(newKey, auth2);
58
+ for (let i = 0; i < 8; i++) {
59
+ const key = getKey ? getKey() : "";
60
+ if (tried.has(key)) break; // ring 绕回已试过的号 = 没有新号了
61
+ tried.add(key);
62
+ const auth = getAuth ? getAuth(key) : null;
63
+ if (auth && key) maybeProactiveRefresh?.(auth, key);
64
+ let r = await execList(key, auth);
65
+ if (!r.ok) {
66
+ let t = "";
67
+ try { t = await r.clone().text(); } catch {}
68
+ if (isAuthError?.(r.status, t)) {
69
+ const newKey = await refreshTokenFor?.(key, auth);
70
+ if (newKey && !tried.has(newKey)) {
71
+ tried.add(newKey);
72
+ r = await execList(newKey, getAuth ? getAuth(newKey) : auth);
73
+ }
65
74
  }
66
75
  }
76
+ if (r.ok) { res = r; break; }
67
77
  }
68
- if (!res.ok) return [];
78
+ if (!res) return [];
69
79
  const json = await res.json().catch(() => ({}));
70
- const models = json?.data?.models;
80
+ // `/v3/config` 两种形状都出现过:`{code,msg,data}` 信封 / 产品文档裸放顶层
81
+ const doc = json && typeof json === "object"
82
+ ? (json.data && typeof json.data === "object" && !Array.isArray(json.data) ? json.data
83
+ : (Array.isArray(json.models) || Array.isArray(json.agents) ? json : null))
84
+ : null;
85
+ const models = doc?.models;
71
86
  if (!Array.isArray(models)) return [];
72
87
  const sorted = [...models].sort((a, b) => creditsValue(a.credits) - creditsValue(b.credits));
73
88
  cache = sorted.filter((m) => m && typeof m.id === "string").map((m) => ({ ...m, id: joinModelId(id, m.id) }));
@@ -5,8 +5,23 @@
5
5
  // 显式 disabled 尊重并删 effort;缺档补默认 "high"
6
6
  // 4. DeepSeek reasoning_content 回填:会话内任一 assistant 带 reasoning 痕迹时,
7
7
  // 所有 assistant 必须带 reasoning_content(string,可空串)——requiresReasoningContentOnAssistantMessages
8
+ // 5. Claude Code 指纹剥离:上游扫 system/assistant 文本,命中官方固定串即 400 code=11128
9
+ // "Illegal API invocation from an unapproved channel"(拒当 Claude Code 的免费通道)。
10
+ // 实测 2026-10-10(拿真 Claude Code 27KB prompt 二分定位):触发形态共三种——行首 `x-anthropic-billing-header:` 整行 +
11
+ // 两句官方固定整句("You are Claude Code, Anthropic's official CLI for Claude." 与
12
+ // "To give feedback, users should report the issue at https://github.com/anthropics/claude-code/issues");
13
+ // 整句为**纯子串匹配**(去掉行首 `- ` 照拦),user/tool 文本不扫、换说法/中间片段/普通长文全放行
14
+ // → 只剥官方注入物不动用户内容;日后撞见新拦句,加进 CC_SENTENCES 即可
8
15
  const DEEPSEEK_PREFIX = "deepseek";
9
16
  const DEFAULT_DEEPSEEK_EFFORT = "high";
17
+ const CC_BILLING_LINE = /^x-anthropic-billing-header:.*\r?\n?/gim;
18
+ // 整句指纹清单:官方固定整句(实测为纯子串匹配,与行首前缀无关;新拦句直接往这里追加整句)
19
+ const CC_SENTENCES = [
20
+ "You are Claude Code, Anthropic's official CLI for Claude.",
21
+ "To give feedback, users should report the issue at https://github.com/anthropics/claude-code/issues",
22
+ ];
23
+ // 廉价预检:上面三种形态的大小写不敏感超集——只多放行进剥离流程,绝不漏剥
24
+ const CC_MAYBE = /x-anthropic-billing-header|Claude Code|anthropics\/claude-code/i;
10
25
 
11
26
  export function isDeepSeekModel(model) {
12
27
  return String(model || "").trim().toLowerCase().startsWith(DEEPSEEK_PREFIX);
@@ -81,6 +96,24 @@ export function backfillReasoningContent(obj) {
81
96
  return obj;
82
97
  }
83
98
 
99
+ export function stripClaudeFingerprints(obj) {
100
+ const msgs = obj?.messages;
101
+ if (!Array.isArray(msgs)) return obj;
102
+ const clean = (text) => {
103
+ if (typeof text !== "string" || !CC_MAYBE.test(text)) return text;
104
+ let out = text.replace(CC_BILLING_LINE, "");
105
+ for (const s of CC_SENTENCES) out = out.split(s).join("");
106
+ return out;
107
+ };
108
+ for (const m of msgs) {
109
+ if (!m || typeof m !== "object") continue;
110
+ if (m.role !== "system" && m.role !== "assistant") continue; // 上游不扫 user/tool,不碰用户内容
111
+ if (typeof m.content === "string") m.content = clean(m.content);
112
+ else if (Array.isArray(m.content)) m.content = m.content.map((p) => (p && typeof p === "object" && typeof p.text === "string" ? { ...p, text: clean(p.text) } : p));
113
+ }
114
+ return obj;
115
+ }
116
+
84
117
  // 入口:输入 chat body(OpenAI 格式),返回改写后的新对象(messages 浅拷贝,避免污染调用方)。
85
118
  export function rewriteWorkbuddyPayload(body) {
86
119
  if (!body || typeof body !== "object") return body;
@@ -89,6 +122,7 @@ export function rewriteWorkbuddyPayload(body) {
89
122
  ? body.messages.map((m) => (m && typeof m === "object" ? { ...m } : m))
90
123
  : body.messages;
91
124
  normalizeRoles(obj);
125
+ stripClaudeFingerprints(obj); // 11128:官方客户端指纹必须出网前剥掉(实测命中即秒拒,不进模型)
92
126
  normalizeToolChoice(obj);
93
127
  if (isDeepSeekModel(obj.model)) {
94
128
  injectThinking(obj);
@@ -28,11 +28,11 @@ export async function handleExhaustedLocal({ res, body, lastErr, order, handlerC
28
28
  // 绕过 relay-pipeline 的最后一站:对话日志照常落盘(正文只进 talk/*.log,不进 events.log)
29
29
  // 本收尾点没有 attemptStartMs 可取(绕过 relay-pipeline 直连 relay)→ 不传 attemptMs,按回退路径走:
30
30
  // elapsed=relay 内部计时(与 relayMs 同值,spec 降级 scenario);finishReason 传 out.detail.sawFinishReason 与 3.3 同源。
31
- try { recordRelayTalk({ reqId: handlerCtx.reqId, model: lastErr.model, via: "local-exhausted", body, out, finishReason: out.detail?.sawFinishReason }); } catch {}
31
+ try { recordRelayTalk({ reqId: handlerCtx.reqId, api: handlerCtx?.api, model: lastErr.model, via: "local-exhausted", body, out, finishReason: out.detail?.sawFinishReason }); } catch {}
32
32
  // 回路语料另起一条独立 try:talk.log 是人读环形稿、capture 是机读全量语料,两者生死独立。
33
33
  // hops 走 handlerCtx.hops(serial-trial 以 {...handlerCtx} 展开传进来,与 reqId 同源);缺值时不兜 0 ——
34
34
  // 交给 talk-full 落 null(「hops 未知」在语料里看得见,比伪造成 0 诚实),组员流量拦截靠真值。
35
- try { recordAgentLoop({ reqId: handlerCtx.reqId, model: lastErr.model, via: "local-exhausted", hops: handlerCtx?.hops, body, out, sessionKey: handlerCtx?.sessionId, clientIp: handlerCtx?.clientIp }); } catch {} // attemptMs 缺省 → 回退 out.totalMs;缺 echo 的既有形状本期不补(tasks 3.4)
35
+ try { recordAgentLoop({ reqId: handlerCtx.reqId, api: handlerCtx?.api, model: lastErr.model, via: "local-exhausted", hops: handlerCtx?.hops, body, out, sessionKey: handlerCtx?.sessionId, clientIp: handlerCtx?.clientIp }); } catch {} // attemptMs 缺省 → 回退 out.totalMs;缺 echo 的既有形状本期不补(tasks 3.4)
36
36
  evt("result", { reqId: handlerCtx.reqId, model: lastErr.model, status: out.status, via: "local", timing: lastErr.upstream._t ?? null, ttfMs: out.ttfMs, totalMs: out.totalMs, detail: out.detail ?? null });
37
37
  evt("client-response", { requested, actual: lastErr.model, via: "local", fallback: false, status: out.status, reqId: handlerCtx.reqId });
38
38
  // 最后一站:relay 超时/空轮留口路径都不写响应,这里没有上层,必须自己收尾
@@ -64,9 +64,9 @@ export async function handleExhaustedAll({ res, body, lastErr, order, requested,
64
64
  // 同上:全链耗尽的最终转发也要留下问答原文
65
65
  // 同上:本收尾点没有 attemptStartMs 可取(relay 直连、无尝试起点)→ 不传 attemptMs,
66
66
  // recordRelayTalk/recordAgentLoop 内部按回退路径走 elapsed=relay 计时(与 relayMs 同值,spec 降级 scenario);finishReason 同源传 out.detail.sawFinishReason。
67
- try { recordRelayTalk({ reqId: handlerCtx.reqId, model: lastErr.model, via: "local-final", body, out, finishReason: out.detail?.sawFinishReason }); } catch {}
67
+ try { recordRelayTalk({ reqId: handlerCtx.reqId, api: handlerCtx?.api, model: lastErr.model, via: "local-final", body, out, finishReason: out.detail?.sawFinishReason }); } catch {}
68
68
  // 同上:全链耗尽的最终转发也要进语料(这条往往是「客户端只看到 502」时唯一的现场材料)
69
- try { recordAgentLoop({ reqId: handlerCtx.reqId, model: lastErr.model, via: "local-final", hops: handlerCtx?.hops, body, out, sessionKey: handlerCtx?.sessionId, clientIp: handlerCtx?.clientIp }); } catch {} // attemptMs 缺省 → 回退 out.totalMs(见上行注释;缺 echo 的形状本期不补)
69
+ try { recordAgentLoop({ reqId: handlerCtx.reqId, api: handlerCtx?.api, model: lastErr.model, via: "local-final", hops: handlerCtx?.hops, body, out, sessionKey: handlerCtx?.sessionId, clientIp: handlerCtx?.clientIp }); } catch {} // attemptMs 缺省 → 回退 out.totalMs(见上行注释;缺 echo 的形状本期不补)
70
70
  evt("result", { reqId: handlerCtx.reqId, model: lastErr.model, status: out.status, via: "local", timing: lastErr.upstream._t ?? null, ttfMs: out.ttfMs, totalMs: out.totalMs, detail: out.detail ?? null });
71
71
  evt("client-response", { requested, actual: lastErr.model, via: "local", fallback: false, status: out.status, reqId: handlerCtx.reqId });
72
72
  // 最后一站:relay 超时/空轮留口路径不写响应,这里没有上层 failover,必须自己收尾
@@ -81,8 +81,7 @@ export function createRelayPipeline({
81
81
  const markFn = m2 || _mark;
82
82
  const curStartedAt = sa2 ?? defaultStartedAt ?? Date.now();
83
83
  const curStages = s2 ?? defaultStages ?? [];
84
- const reqId = handlerCtx?.reqId;
85
- const hops = handlerCtx?.hops;
84
+ const { reqId, api, hops } = handlerCtx || {};
86
85
 
87
86
  // 1. logCall(pre) — 保持原 handler 的 logCall→fallback→relay-start 时序
88
87
  try { _logCall(actual, upRes?.status); } catch {}
@@ -141,13 +140,16 @@ export function createRelayPipeline({
141
140
  //(P0 回归实锤:落盘 elapsedMs=1791249258686;测试喂了同钟 perfNow 桩才把混钟掩盖住 —— 防回归见 test/agent-loop-wiring.test.js 真时钟两例)。
142
141
  // attemptStartMs 非有限(调用方未给该 ctx,如管线直调)→ 回退 out.totalMs,此时 elapsed 与 relayMs 同值(spec 降级 scenario),不伪造。
143
142
  const attemptMs = Number.isFinite(attemptStartMs) ? Math.round(performance.now() - attemptStartMs) : out.totalMs;
143
+ // ttft = relay 入口前消耗的等待(anchorMs) + relay 内首块;与 usage 行 rowTtfb 同源。anchorMs 只加给上报时长,闸门计时与 recordModelStats 不碰(design D2)。
144
+ const anchorMs = Number.isFinite(out?.preflightMs) && out.preflightMs > 0 ? out.preflightMs : 0;
145
+ const ttftMs = Number.isFinite(out?.ttfMs) && out.ttfMs >= 0 ? out.ttfMs + anchorMs : null;
144
146
  // 环形对话日志:只记有真实输出的轮次(空轮交给下面的空转判定另行报错)。
145
147
  // 纯旁路:不改闸门、不改计时、不改返回体;任何异常都吞掉,绝不影响转发。
146
- try { recordRelayTalk({ reqId, model: actual, via, hops, body, out, echo: upstreamEcho(upRes), attemptMs, finishReason: out.detail?.sawFinishReason }); } catch {}
148
+ try { recordRelayTalk({ reqId, api, model: actual, via, hops, body, out, echo: upstreamEcho(upRes), attemptMs, ttftMs, finishReason: out.detail?.sawFinishReason }); } catch {}
147
149
  // 回路语料(talk/full)另起一条独立 try,不与上面合并:talk.log 是人读环形稿、capture 是机读全量语料,
148
150
  // 两者生死独立 —— 一边不落另一边照落,判据也不同(capture 只认 hops=0,且要带 sessionKey/clientIp 供分组与来源核对)。
149
151
  // 纯旁路同上:不改闸门、不改计时、不改返回体;out.detail.talk 是原桶(logs.js 的 dropTalk 剥的是副本),这里不再剥。
150
- try { recordAgentLoop({ reqId, model: actual, via, hops, body, out, sessionKey: handlerCtx?.sessionId, clientIp: handlerCtx?.clientIp, echo: upstreamEcho(upRes), attemptMs, relayMs: out.totalMs }); } catch {}
152
+ try { recordAgentLoop({ reqId, api, model: actual, via, hops, body, out, sessionKey: handlerCtx?.sessionId, clientIp: handlerCtx?.clientIp, echo: upstreamEcho(upRes), attemptMs, relayMs: out.totalMs }); } catch {}
151
153
 
152
154
  // 5a0. 空转 200:流正常结束但零正文零工具调用 → 客户端会报 EMPTY_MODEL_RESPONSE
153
155
  // ("The model ended its turn without producing any output");转 failover 而不是
@@ -181,9 +183,6 @@ export function createRelayPipeline({
181
183
  return { handled: false, upRes: null, lastErr: { model: actual, upstream: null, status: 502, message: _errMsg, emptyTurn: true, heldOpen: out.heldOpen === true } };
182
184
  }
183
185
 
184
- // 上报锚点偏移:relay 入口之前消耗掉的等待(上游排队、建连、provider 为取判决预读的首帧)。
185
- // 只加给 usage 行的时长;闸门计时与 recordModelStats 一律不碰 —— 见 design D2 与 Non-Goals。
186
- const anchorMs = Number.isFinite(out?.preflightMs) && out.preflightMs > 0 ? out.preflightMs : 0;
187
186
  // 5a. 首块超时未写字节 → 回退(显式 timedOut 字段,status 只是 HTTP 语义展示)
188
187
  if (out.timedOut === true) {
189
188
  const why = out.detail?.upstreamError ? ` (upstream read error: ${out.detail.upstreamError})` : "";