mslxdff 0.1.163 → 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.
- package/package.json +1 -1
- package/src/anthropic/translate.js +397 -0
- package/src/anthropic/web-search.js +361 -0
- package/src/api-kind.js +31 -0
- package/src/chat-pipeline/auto-race.js +8 -0
- package/src/chat-pipeline/empty-turn.js +28 -0
- package/src/chat-pipeline/index.js +8 -4
- package/src/chat-pipeline/serial-trial.js +8 -1
- package/src/claude-desktop/apply.js +64 -0
- package/src/claude-desktop/doctor.js +146 -0
- package/src/claude-desktop/slots.js +86 -0
- package/src/cli/commands/claude-desktop.js +264 -0
- package/src/cli/commands/model/list-providers.js +1 -1
- package/src/cli/commands/provider/index.js +7 -0
- package/src/cli/commands/provider/models.js +3 -0
- package/src/cli/commands/provider/raccoon-login.js +131 -0
- package/src/cli/commands/provider/raccoon-quota.js +109 -0
- package/src/cli/commands/sync.js +80 -2
- package/src/cli/format.js +1 -1
- package/src/cli/help.js +3 -0
- package/src/cli/index.js +2 -0
- package/src/cli/provider-row.js +2 -2
- package/src/model-capabilities/parse.js +1 -1
- package/src/model-trace.js +2 -1
- package/src/providers/classify.js +1 -1
- package/src/providers/dispatcher.js +2 -2
- package/src/providers/keyring.js +1 -1
- package/src/providers/model-id.js +10 -0
- package/src/providers/raccoon/account-store.js +216 -0
- package/src/providers/raccoon/auth.js +67 -0
- package/src/providers/raccoon/chat.js +207 -0
- package/src/providers/raccoon/const.js +111 -0
- package/src/providers/raccoon/credits.js +161 -0
- package/src/providers/raccoon/envelope.js +23 -0
- package/src/providers/raccoon/headers.js +45 -0
- package/src/providers/raccoon/index.js +216 -0
- package/src/providers/raccoon/login.js +195 -0
- package/src/providers/raccoon/models.js +160 -0
- package/src/providers/raccoon/qr-codewords.js +115 -0
- package/src/providers/raccoon/qr.js +236 -0
- package/src/providers/raccoon/sse.js +135 -0
- package/src/providers/registry.js +5 -0
- package/src/providers/share-keys.js +1 -1
- package/src/providers/workbuddy/models.js +29 -14
- package/src/providers/workbuddy/payload.js +34 -0
- package/src/routes/chat/exhausted-handler.js +4 -4
- package/src/routes/chat/relay-pipeline.js +6 -7
- package/src/routes/index.js +13 -0
- package/src/routes/messages-route.js +401 -0
- package/src/routes/responses-route.js +2 -2
- package/src/runtime/bootstrap.js +5 -0
- package/src/runtime/broadband.js +4 -1
- package/src/runtime/provider-gate.js +3 -1
- package/src/runtime/raccoon-checkin.js +126 -0
- package/src/state/provider-config.js +1 -1
- package/src/sync-claude-desktop.js +234 -0
- package/src/sync-claude.js +152 -0
- package/src/talk-full.js +2 -2
- package/src/talk-log.js +9 -6
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// raccoon 账号落盘单一源:auths/raccoon-<uid>.json(0600 tmp+rename)+ state.json providerConfigs.raccoon.keys 同步。
|
|
2
|
+
// office_identity 与 device_id(per-account 持久 UUID)随账号文档走,**不进 providerConfigs**——
|
|
3
|
+
// 规避 providerConfig 重建路径(allowlist/baseUrl 写回)静默丢字段的既有故障类(与 zcode 同款理由)。
|
|
4
|
+
import { writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync, readdirSync, readFileSync, chmodSync } from "node:fs";
|
|
5
|
+
import { join, dirname } from "node:path";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { uuid } from "../../compat.js";
|
|
8
|
+
import { isTestEnv, defaultStateFile } from "../../state/store.js";
|
|
9
|
+
|
|
10
|
+
export function raccoonAuthDir({ explicit = "", testEnv = false, stateFile } = {}) {
|
|
11
|
+
if (explicit) return explicit;
|
|
12
|
+
if (testEnv) return join(tmpdir(), "mslxdff-test-auths");
|
|
13
|
+
return join(dirname(stateFile), "auths");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function resolveRaccoonAuthDir() {
|
|
17
|
+
return raccoonAuthDir({
|
|
18
|
+
explicit: process.env.MSLXDFF_RACCOON_AUTH_DIR || "",
|
|
19
|
+
testEnv: isTestEnv(),
|
|
20
|
+
stateFile: defaultStateFile(),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 主目录 + 历史遗留 cwd/auths(只读兜底,防旧副本「复活」)。 */
|
|
25
|
+
export function resolveRaccoonAuthDirs() {
|
|
26
|
+
const primary = resolveRaccoonAuthDir();
|
|
27
|
+
const cwdDir = join(process.cwd(), "auths");
|
|
28
|
+
return primary === cwdDir ? [primary] : [primary, cwdDir];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 列出全部落盘账号(同 uid 主位置优先),跳过无 access_token 的残档。 */
|
|
32
|
+
export function listRaccoonAccountDocs({ dirs } = {}) {
|
|
33
|
+
const out = [];
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
for (const dir of dirs || resolveRaccoonAuthDirs()) {
|
|
36
|
+
let files = [];
|
|
37
|
+
try {
|
|
38
|
+
if (!existsSync(dir)) continue;
|
|
39
|
+
files = readdirSync(dir).filter((f) => f.startsWith("raccoon-") && f.endsWith(".json"));
|
|
40
|
+
} catch {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
for (const f of files) {
|
|
44
|
+
try {
|
|
45
|
+
const doc = JSON.parse(readFileSync(join(dir, f), "utf8"));
|
|
46
|
+
const uid = doc?.account?.uid;
|
|
47
|
+
const token = doc?.auth?.access_token;
|
|
48
|
+
if (!uid || !token) continue;
|
|
49
|
+
if (seen.has(String(uid))) continue;
|
|
50
|
+
seen.add(String(uid));
|
|
51
|
+
out.push({
|
|
52
|
+
uid: String(uid),
|
|
53
|
+
accessToken: String(token),
|
|
54
|
+
refreshToken: String(doc.auth.refresh_token || ""),
|
|
55
|
+
expiresAt: String(doc.auth.expires_at || ""),
|
|
56
|
+
officeIdentity: String(doc.auth.office_identity || ""),
|
|
57
|
+
deviceId: String(doc.auth.device_id || ""),
|
|
58
|
+
name: String(doc.account.name || ""),
|
|
59
|
+
phone: String(doc.account.phone || ""),
|
|
60
|
+
file: join(dir, f),
|
|
61
|
+
dir,
|
|
62
|
+
doc,
|
|
63
|
+
});
|
|
64
|
+
} catch {}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function accountFilePath(uid, dir) {
|
|
71
|
+
return join(dir, `raccoon-${uid}.json`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function writeRaccoonAccountFile(
|
|
75
|
+
{ uid, accessToken, refreshToken = "", expiresAt = "", officeIdentity = "", deviceId = "", name = "", phone = "" },
|
|
76
|
+
{ dir = resolveRaccoonAuthDir() } = {},
|
|
77
|
+
) {
|
|
78
|
+
mkdirSync(dir, { recursive: true });
|
|
79
|
+
const doc = {
|
|
80
|
+
account: { uid, name, phone },
|
|
81
|
+
auth: {
|
|
82
|
+
access_token: accessToken,
|
|
83
|
+
refresh_token: refreshToken,
|
|
84
|
+
expires_at: expiresAt,
|
|
85
|
+
office_identity: officeIdentity,
|
|
86
|
+
device_id: deviceId,
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
const fp = accountFilePath(uid, dir);
|
|
90
|
+
const tmp = `${fp}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`; // 唯一名:防并发写(daemon 续期 vs CLI login)互相踩
|
|
91
|
+
writeFileSync(tmp, JSON.stringify(doc, null, 2), { mode: 0o600 });
|
|
92
|
+
try {
|
|
93
|
+
if (existsSync(fp)) {
|
|
94
|
+
try { chmodSync(fp, 0o600); } catch {}
|
|
95
|
+
unlinkSync(fp);
|
|
96
|
+
}
|
|
97
|
+
renameSync(tmp, fp);
|
|
98
|
+
} catch {
|
|
99
|
+
// 兜底也走「唯一 tmp + rename」,绝不直写正式文件(直写非原子,并发读者会读到半截 JSON → 该号静默消失)
|
|
100
|
+
try { const t2 = `${fp}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`; writeFileSync(t2, JSON.stringify(doc, null, 2), { mode: 0o600 }); if (existsSync(fp)) unlinkSync(fp); renameSync(t2, fp); } catch {}
|
|
101
|
+
try { unlinkSync(tmp); } catch {}
|
|
102
|
+
}
|
|
103
|
+
try { chmodSync(fp, 0o600); } catch {} // mode 只在新建成时生效,存量必须补 chmod
|
|
104
|
+
return fp;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function readRaccoonAccountDoc(uid, { dir = resolveRaccoonAuthDir() } = {}) {
|
|
108
|
+
try {
|
|
109
|
+
return JSON.parse(readFileSync(accountFilePath(uid, dir), "utf8"));
|
|
110
|
+
} catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 落盘账号文档并同步 state 的 keys;已有 device_id 时复用,不覆盖。 */
|
|
116
|
+
export async function saveRaccoonAccount({
|
|
117
|
+
uid,
|
|
118
|
+
accessToken,
|
|
119
|
+
refreshToken = "",
|
|
120
|
+
expiresAt = "",
|
|
121
|
+
officeIdentity = "",
|
|
122
|
+
deviceId = "",
|
|
123
|
+
name = "",
|
|
124
|
+
phone = "",
|
|
125
|
+
dir,
|
|
126
|
+
file,
|
|
127
|
+
} = {}) {
|
|
128
|
+
if (!uid || !accessToken) throw new Error("saveRaccoonAccount: 缺少 uid/accessToken");
|
|
129
|
+
const targetDir = dir || resolveRaccoonAuthDir();
|
|
130
|
+
const existing = readRaccoonAccountDoc(uid, { dir: targetDir });
|
|
131
|
+
const device = deviceId || existing?.auth?.device_id || uuid();
|
|
132
|
+
const fp = writeRaccoonAccountFile(
|
|
133
|
+
{ uid, accessToken, refreshToken, expiresAt, officeIdentity, deviceId: device, name, phone },
|
|
134
|
+
{ dir: targetDir },
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
// keys 一律以账号文档为准(覆盖式,见 syncRaccoonKeys 的说明)
|
|
138
|
+
const sync = await syncRaccoonKeys({ dirs: [targetDir], ...(file ? { file } : {}) });
|
|
139
|
+
return { file: fp, keys: sync.keys.length, updated: Boolean(existing) };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** device_id:账号文档内持久复用;缺失且已有 token 时生成并写回。 */
|
|
143
|
+
export function ensureRaccoonDeviceId({ uid, dir } = {}) {
|
|
144
|
+
if (!uid) return "";
|
|
145
|
+
const targetDir = dir || resolveRaccoonAuthDir();
|
|
146
|
+
const doc = readRaccoonAccountDoc(uid, { dir: targetDir });
|
|
147
|
+
const cur = String(doc?.auth?.device_id || "").trim();
|
|
148
|
+
if (cur) return cur;
|
|
149
|
+
const device = uuid();
|
|
150
|
+
if (doc?.auth?.access_token) {
|
|
151
|
+
writeRaccoonAccountFile(
|
|
152
|
+
{
|
|
153
|
+
uid,
|
|
154
|
+
accessToken: doc.auth.access_token,
|
|
155
|
+
refreshToken: doc.auth?.refresh_token || "",
|
|
156
|
+
expiresAt: doc.auth?.expires_at || "",
|
|
157
|
+
officeIdentity: doc.auth?.office_identity || "",
|
|
158
|
+
deviceId: device,
|
|
159
|
+
name: doc.account?.name || "",
|
|
160
|
+
phone: doc.account?.phone || "",
|
|
161
|
+
},
|
|
162
|
+
{ dir: targetDir },
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
return device;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** 续期结果回写(refresh 可能不返回新 refresh_token,不能覆盖成空串)。 */
|
|
169
|
+
export function applyRaccoonRefresh(existing, { accessToken, refreshToken, expiresAt }) {
|
|
170
|
+
return {
|
|
171
|
+
...existing,
|
|
172
|
+
access_token: accessToken,
|
|
173
|
+
refresh_token: refreshToken && refreshToken.length > 0 ? refreshToken : existing.refresh_token,
|
|
174
|
+
expires_at: expiresAt || existing.expires_at || "",
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 账号文档 → provider/credits 认的 credential 形状。**单一源**:此前 index.js 的 credentialFor、
|
|
180
|
+
* runtime/raccoon-checkin.js 与 CLI 各自内联一份,漏一个 `expires_at` 就会让过期/临期判定静默失效。
|
|
181
|
+
* 输入是 listRaccoonAccountDocs() 的 camelCase 条目,输出是上游口径的 snake_case credential。
|
|
182
|
+
*/
|
|
183
|
+
export function raccoonCredentialFromDoc(doc) {
|
|
184
|
+
return {
|
|
185
|
+
access_token: doc?.accessToken || "",
|
|
186
|
+
refresh_token: doc?.refreshToken || "",
|
|
187
|
+
expires_at: doc?.expiresAt || "",
|
|
188
|
+
office_identity: doc?.officeIdentity || "",
|
|
189
|
+
device_id: doc?.deviceId || "",
|
|
190
|
+
uid: doc?.uid || "",
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* providerConfigs.raccoon.keys ← auths/ 各号文档里的当前 access_token(**覆盖式**,不是追加)。
|
|
196
|
+
* 为什么必须覆盖(两个都是踩过的坑):
|
|
197
|
+
* 1) access_token 约 3 小时一换,追加会让 keys 越攒越多已作废 token,ring 反复选中它们去撞 401;
|
|
198
|
+
* 2) 续期回写只改账号文档(writeRaccoonAccountFile 从不碰 keys),两者一分叉,daemon 重启后拿到的
|
|
199
|
+
* 就是过期 token —— 症状是「明明登录过、积分还在,却恒 401 / 429 全号冷却」,只能重扫码。
|
|
200
|
+
* 账号文档是身份的唯一可信源(refresh_token / office_identity / device_id 只在文档里),
|
|
201
|
+
* 所以 keys 以它为准;不在任何文档里的 token 一律剔除。
|
|
202
|
+
*/
|
|
203
|
+
export async function syncRaccoonKeys({ dirs, file } = {}) {
|
|
204
|
+
const { loadProviderConfig, saveProviderConfig } = await import("../../state.js");
|
|
205
|
+
const tokens = [...new Set(
|
|
206
|
+
listRaccoonAccountDocs(dirs ? { dirs } : {})
|
|
207
|
+
.map((d) => String(d?.accessToken || "").trim())
|
|
208
|
+
.filter(Boolean),
|
|
209
|
+
)];
|
|
210
|
+
const cfg = loadProviderConfig("raccoon", file ? { file } : {}) || {};
|
|
211
|
+
const prev = Array.isArray(cfg.keys) ? cfg.keys : [];
|
|
212
|
+
const identical = prev.length === tokens.length && prev.every((k) => tokens.includes(k));
|
|
213
|
+
if (identical) return { keys: tokens, changed: false, dropped: 0 };
|
|
214
|
+
saveProviderConfig("raccoon", { ...cfg, keys: tokens }, file ? { file } : {});
|
|
215
|
+
return { keys: tokens, changed: true, dropped: prev.filter((k) => !tokens.includes(k)).length };
|
|
216
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// raccoon 鉴权材料工具:JWT 过期判断、token 指纹、uid 归一。
|
|
2
|
+
// 指纹用于 CLI 脱敏回执与日志——**token 原文绝不出现在输出里**。
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
/** 解析 JWT payload 的 `exp`(秒 → 毫秒);坏格式/缺字段返回 undefined。 */
|
|
6
|
+
export function decodeJwtExpMs(token) {
|
|
7
|
+
if (typeof token !== "string" || token.length === 0) return undefined;
|
|
8
|
+
const parts = token.split(".");
|
|
9
|
+
if (parts.length < 2) return undefined;
|
|
10
|
+
try {
|
|
11
|
+
const payload = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
|
|
12
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return undefined;
|
|
13
|
+
const exp = payload.exp;
|
|
14
|
+
if (typeof exp !== "number" || !Number.isFinite(exp) || exp <= 0) return undefined;
|
|
15
|
+
return exp * 1000;
|
|
16
|
+
} catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 凭据到期时刻(毫秒):优先账号文档里的 `expires_at`(字符串,支持秒或毫秒),
|
|
23
|
+
* 缺失时回落 JWT 自身的 `exp`。两者都拿不到 → undefined(视为「不知何时过期」,不主动判过期)。
|
|
24
|
+
*/
|
|
25
|
+
export function raccoonCredentialExpiresAtMs(credential) {
|
|
26
|
+
const raw = credential?.expires_at;
|
|
27
|
+
if (typeof raw === "string" && raw.trim().length > 0) {
|
|
28
|
+
const n = Number(raw);
|
|
29
|
+
if (Number.isFinite(n) && n > 0) return n > 1e12 ? n : n * 1000;
|
|
30
|
+
}
|
|
31
|
+
if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) return raw > 1e12 ? raw : raw * 1000;
|
|
32
|
+
return decodeJwtExpMs(credential?.access_token);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 是否已过期(拿不到到期时刻时保守返回 false,交给上游 401 判)。 */
|
|
36
|
+
export function isRaccoonExpired(credential, now = Date.now()) {
|
|
37
|
+
const exp = raccoonCredentialExpiresAtMs(credential);
|
|
38
|
+
return exp === undefined ? false : now >= exp;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 到期前提前量(默认 60s):临期即刷新,避免请求正好撞在过期瞬间。 */
|
|
42
|
+
export const RACCOON_REFRESH_SKEW_MS = 60_000;
|
|
43
|
+
|
|
44
|
+
export function isRaccoonExpiringSoon(credential, now = Date.now(), skewMs = RACCOON_REFRESH_SKEW_MS) {
|
|
45
|
+
const exp = raccoonCredentialExpiresAtMs(credential);
|
|
46
|
+
return exp === undefined ? false : now + skewMs >= exp;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** token 指纹:sha256 前 8 位十六进制。**唯一允许出现在日志/CLI 里的 token 表示**。 */
|
|
50
|
+
export function raccoonTokenFingerprint(token) {
|
|
51
|
+
const s = String(token || "");
|
|
52
|
+
if (!s) return "";
|
|
53
|
+
try {
|
|
54
|
+
return createHash("sha256").update(s).digest("hex").slice(0, 8);
|
|
55
|
+
} catch {
|
|
56
|
+
return "";
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** uid 归一:优先 user_info 的 id,其次 office/userId,最后回退 token 指纹(保证非空且稳定)。 */
|
|
61
|
+
export function resolveRaccoonUid({ userId = "", officeIdentity = "", token = "" } = {}) {
|
|
62
|
+
for (const candidate of [userId, officeIdentity]) {
|
|
63
|
+
const s = String(candidate || "").trim();
|
|
64
|
+
if (s) return s;
|
|
65
|
+
}
|
|
66
|
+
return raccoonTokenFingerprint(token);
|
|
67
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// raccoon 模型转发:OpenAI 形进、OpenAI 形出(上游同形,**不做协议转换**)。
|
|
2
|
+
// 失败响应带 `x-mslxdff-raccoon-kind` 标记,供 provider 工厂决定冷却策略。
|
|
3
|
+
import { timeoutSignal } from "../../compat.js";
|
|
4
|
+
import {
|
|
5
|
+
RACCOON_DEFAULT_EFFORT,
|
|
6
|
+
RACCOON_REQUEST_TIMEOUT_MS,
|
|
7
|
+
canonicalRaccoonModel,
|
|
8
|
+
raccoonChatUrl,
|
|
9
|
+
raccoonEffortFromEnv,
|
|
10
|
+
raccoonThinkingType,
|
|
11
|
+
} from "./const.js";
|
|
12
|
+
import { RACCOON_CHAT_ACCEPT, raccoonAuthHeaders } from "./headers.js";
|
|
13
|
+
import {
|
|
14
|
+
aggregateRaccoonSse,
|
|
15
|
+
classifyRaccoonFailure,
|
|
16
|
+
isRaccoonSseContentType,
|
|
17
|
+
raccoonErrorResponse,
|
|
18
|
+
} from "./sse.js";
|
|
19
|
+
|
|
20
|
+
/** 首帧窥探上限:超过这个字节数还没形成完整 SSE 帧就不再等(避免慢首包把请求卡住)。 */
|
|
21
|
+
const PEEK_MAX_BYTES = 8192;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 出站请求体:剥 `raccoon/` 前缀 + 注入 `extra_body.thinking`。
|
|
25
|
+
* 思考取值优先级:**请求体自带的 `extra_body.thinking.type`**(客户端显式声明)> 构造/调用方 `effort`
|
|
26
|
+
* > env `MSLXDFF_RACCOON_THINKING` > 默认「开」。
|
|
27
|
+
* **绝不发 `reasoning_effort`**:上游不认该参数(实测传与不传无可测差异),发了只会多一处形态差异。
|
|
28
|
+
*/
|
|
29
|
+
export function buildRaccoonWireBody(body = {}, { effort, env = process.env } = {}) {
|
|
30
|
+
const wire = { ...body };
|
|
31
|
+
wire.model = canonicalRaccoonModel(body?.model);
|
|
32
|
+
delete wire.reasoning_effort;
|
|
33
|
+
const extra = typeof body?.extra_body === "object" && body.extra_body !== null ? { ...body.extra_body } : {};
|
|
34
|
+
const declared = extra?.thinking?.type;
|
|
35
|
+
const type = declared === "enabled" || declared === "disabled"
|
|
36
|
+
? declared
|
|
37
|
+
: raccoonThinkingType(effort ?? raccoonEffortFromEnv(env) ?? RACCOON_DEFAULT_EFFORT);
|
|
38
|
+
extra.thinking = { type };
|
|
39
|
+
wire.extra_body = extra;
|
|
40
|
+
return wire;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 上游用 `application/json` 回完整 SSE 帧序列(高负载下的已知行为)时,按**体形状**判定。 */
|
|
44
|
+
function looksLikeSse(text) {
|
|
45
|
+
return /^\s*(data:|:)/m.test(String(text || ""));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 从一段 SSE 文本里取首个 `data:` 载荷(可能还没凑成完整帧)。 */
|
|
49
|
+
function firstDataPayload(text) {
|
|
50
|
+
const line = String(text || "")
|
|
51
|
+
.split(/\r?\n/)
|
|
52
|
+
.find((l) => l.startsWith("data:"));
|
|
53
|
+
return line ? line.slice(5).trim() : "";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 预读上游首帧取判决(对齐 qoder 的 `peekEnvelopeVerdict` 思路)。
|
|
58
|
+
* 流式请求若把 `{"code":200003}` 这种**流内错误信封**原样透给客户端,既不返 401 也不冷却该号,
|
|
59
|
+
* 下次还会继续撞同一面墙 —— 所以返回 Response 前先看一眼。
|
|
60
|
+
* 首个完整帧不是错误时立刻停止窥探,并把已读字节原样回灌(`chunks`),不丢一个字节。
|
|
61
|
+
*/
|
|
62
|
+
async function peekStreamVerdict(res) {
|
|
63
|
+
const reader = res.body?.getReader?.();
|
|
64
|
+
if (!reader) return { chunks: [] };
|
|
65
|
+
const decoder = new TextDecoder();
|
|
66
|
+
const chunks = [];
|
|
67
|
+
let buf = "";
|
|
68
|
+
try {
|
|
69
|
+
for (;;) {
|
|
70
|
+
const { done, value } = await reader.read();
|
|
71
|
+
if (done) break;
|
|
72
|
+
chunks.push(value);
|
|
73
|
+
buf += decoder.decode(value, { stream: true });
|
|
74
|
+
const end = buf.indexOf("\n\n");
|
|
75
|
+
if (end >= 0) {
|
|
76
|
+
const payload = firstDataPayload(buf.slice(0, end));
|
|
77
|
+
if (payload && payload !== "[DONE]") {
|
|
78
|
+
let parsed;
|
|
79
|
+
try {
|
|
80
|
+
parsed = JSON.parse(payload);
|
|
81
|
+
} catch {
|
|
82
|
+
parsed = null;
|
|
83
|
+
}
|
|
84
|
+
if (parsed && ((parsed.code !== undefined && Number(parsed.code) !== 0) || parsed.error)) {
|
|
85
|
+
await reader.cancel().catch(() => {});
|
|
86
|
+
return { error: classifyRaccoonFailure(200, parsed) };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
break; // 首个完整帧不是错误 → 停止窥探
|
|
90
|
+
}
|
|
91
|
+
if (buf.length >= PEEK_MAX_BYTES) break; // 还没形成完整帧就别再等
|
|
92
|
+
}
|
|
93
|
+
} catch {
|
|
94
|
+
// 窥探本身失败不算错误:把已读字节回灌,后续由正常流路径暴露
|
|
95
|
+
}
|
|
96
|
+
return { chunks, reader };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 把「已预读的字节 + 剩余 reader」拼回一条流。 */
|
|
100
|
+
function rebuildStream(chunks, reader) {
|
|
101
|
+
if (!reader) {
|
|
102
|
+
return new ReadableStream({
|
|
103
|
+
start(controller) {
|
|
104
|
+
for (const c of chunks) controller.enqueue(c);
|
|
105
|
+
controller.close();
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return new ReadableStream({
|
|
110
|
+
start(controller) {
|
|
111
|
+
for (const c of chunks) controller.enqueue(c);
|
|
112
|
+
},
|
|
113
|
+
async pull(controller) {
|
|
114
|
+
try {
|
|
115
|
+
const { done, value } = await reader.read();
|
|
116
|
+
if (done) {
|
|
117
|
+
controller.close();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
controller.enqueue(value);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
controller.error(error);
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
cancel(reason) {
|
|
126
|
+
return reader.cancel(reason).catch(() => {});
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function forwardRaccoonChat({
|
|
132
|
+
body,
|
|
133
|
+
credential,
|
|
134
|
+
fetchImpl,
|
|
135
|
+
timeoutMs = RACCOON_REQUEST_TIMEOUT_MS,
|
|
136
|
+
effort,
|
|
137
|
+
env = process.env,
|
|
138
|
+
} = {}) {
|
|
139
|
+
const wireBody = buildRaccoonWireBody(body, { effort, env });
|
|
140
|
+
const modelId = wireBody.model;
|
|
141
|
+
|
|
142
|
+
let res;
|
|
143
|
+
try {
|
|
144
|
+
res = await fetchImpl(raccoonChatUrl(), {
|
|
145
|
+
method: "POST",
|
|
146
|
+
headers: raccoonAuthHeaders(credential, { accept: RACCOON_CHAT_ACCEPT, env }),
|
|
147
|
+
body: JSON.stringify(wireBody),
|
|
148
|
+
signal: timeoutSignal(timeoutMs),
|
|
149
|
+
});
|
|
150
|
+
} catch (e) {
|
|
151
|
+
return raccoonErrorResponse({ kind: "server", message: String(e?.message || e).slice(0, 160) });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (!res.ok) {
|
|
155
|
+
const payload = await res.json().catch(() => null);
|
|
156
|
+
return raccoonErrorResponse({ ...classifyRaccoonFailure(res.status, payload), model: modelId });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 业务错误惯例:HTTP 200 + JSON 信封(code 非 0)→ 同样按错误分类,不谎报成功
|
|
160
|
+
if (!isRaccoonSseContentType(res.headers.get("content-type"))) {
|
|
161
|
+
const text = await res.text().catch(() => "");
|
|
162
|
+
let payload = null;
|
|
163
|
+
try {
|
|
164
|
+
payload = JSON.parse(text);
|
|
165
|
+
} catch {
|
|
166
|
+
payload = null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (!payload && looksLikeSse(text)) {
|
|
170
|
+
// 形状是 SSE 而 header 不是 —— 信形状(参考实现踩过这个坑:按 header 判会把可用模型判成不可用)
|
|
171
|
+
if (body?.stream === false) {
|
|
172
|
+
const agg = await aggregateRaccoonSse(text, { model: modelId });
|
|
173
|
+
if (agg.error) return raccoonErrorResponse({ ...agg.error, model: modelId });
|
|
174
|
+
return new Response(JSON.stringify(agg.openAi), { status: 200, headers: { "Content-Type": "application/json" } });
|
|
175
|
+
}
|
|
176
|
+
const peeked = await peekStreamVerdict(new Response(text, { headers: { "Content-Type": "text/event-stream" } }));
|
|
177
|
+
if (peeked.error) return raccoonErrorResponse({ ...peeked.error, model: modelId });
|
|
178
|
+
return new Response(text, {
|
|
179
|
+
status: 200,
|
|
180
|
+
headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache" },
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (payload && ((payload.code !== undefined && Number(payload.code) !== 0) || payload.error)) {
|
|
185
|
+
return raccoonErrorResponse({ ...classifyRaccoonFailure(res.status, payload), model: modelId });
|
|
186
|
+
}
|
|
187
|
+
if (payload) {
|
|
188
|
+
return new Response(JSON.stringify(payload), { status: 200, headers: { "Content-Type": "application/json" } });
|
|
189
|
+
}
|
|
190
|
+
return raccoonErrorResponse({ kind: "server", status: 200, message: "上游返回了既非 JSON 也非 SSE 的响应" });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (body?.stream !== false) {
|
|
194
|
+
// 上游已是 OpenAI 形 SSE:先窥探首帧取流内判决,再把字节原样回灌(逐字节透传,不整形)
|
|
195
|
+
const peeked = await peekStreamVerdict(res);
|
|
196
|
+
if (peeked.error) return raccoonErrorResponse({ ...peeked.error, model: modelId });
|
|
197
|
+
return new Response(rebuildStream(peeked.chunks, peeked.reader), {
|
|
198
|
+
status: 200,
|
|
199
|
+
headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache" },
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const text = await res.text();
|
|
204
|
+
const out = await aggregateRaccoonSse(text, { model: modelId });
|
|
205
|
+
if (out.error) return raccoonErrorResponse({ ...out.error, model: modelId });
|
|
206
|
+
return new Response(JSON.stringify(out.openAi), { status: 200, headers: { "Content-Type": "application/json" } });
|
|
207
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// raccoon(商汤小浣熊)供应商常量单一源:网关地址、客户端版本与 UA、两档思考、业务码表、兜底模型目录。
|
|
2
|
+
// 端点契约调研自 Ebony-Vinyl/dsh-our-free-model 的 vendor/channel-pack/src/raccoon*.ts
|
|
3
|
+
// (打包产物 pack.js 原文)并逐条本机实测:站点根 200、model_catalog 匿名 401、
|
|
4
|
+
// chat/completions 匿名 401、login_with_qrcode_code 匿名 200 {"code":0,"data":{"status":"pending"}}。
|
|
5
|
+
export const RACCOON_ORIGIN = "https://xiaohuanxiong.com";
|
|
6
|
+
|
|
7
|
+
export const RACCOON_LLM_PREFIX = "/api/web/llm/v2";
|
|
8
|
+
export const RACCOON_AUTH_PREFIX = "/api/web/auth/v1";
|
|
9
|
+
export const RACCOON_POINTS_PREFIX = "/api/web/points/v1";
|
|
10
|
+
export const RACCOON_DESKTOP_PREFIX = "/api/web/desktop/v1";
|
|
11
|
+
|
|
12
|
+
export const raccoonModelCatalogUrl = () => `${RACCOON_ORIGIN}${RACCOON_LLM_PREFIX}/model_catalog`;
|
|
13
|
+
export const raccoonChatUrl = () => `${RACCOON_ORIGIN}${RACCOON_LLM_PREFIX}/chat/completions`;
|
|
14
|
+
export const raccoonQrLoginUrl = () => `${RACCOON_ORIGIN}${RACCOON_AUTH_PREFIX}/login_with_qrcode_code`;
|
|
15
|
+
export const raccoonRefreshUrl = () => `${RACCOON_ORIGIN}${RACCOON_AUTH_PREFIX}/refresh`;
|
|
16
|
+
export const raccoonUserInfoUrl = () => `${RACCOON_ORIGIN}${RACCOON_AUTH_PREFIX}/user_info`;
|
|
17
|
+
export const raccoonBalanceUrl = () => `${RACCOON_ORIGIN}${RACCOON_POINTS_PREFIX}/balance`;
|
|
18
|
+
export const raccoonBillsUrl = (limit = 50) =>
|
|
19
|
+
`${RACCOON_ORIGIN}${RACCOON_POINTS_PREFIX}/bills?paging.limit=${Number(limit) || 50}&paging.offset=0`;
|
|
20
|
+
export const raccoonLoginGrantUrl = () => `${RACCOON_ORIGIN}${RACCOON_DESKTOP_PREFIX}/login/points/grant`;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 扫码登录深链接:终端编成二维码,**必须用微信「扫一扫」**打开确认(浏览器直接打开会 404)。
|
|
24
|
+
* 形如 `https://xiaohuanxiong.com/login/mp?code=<hex>&appname=商汤小浣熊官网`。
|
|
25
|
+
* 实测:服务器对任意路径都回同一份 SPA 外壳(HTTP 200),但 SPA 路由表里没有 `login/mp`(只有 `login` + 兜底 `*`)→ 浏览器必 404,属正常而非链接失效。
|
|
26
|
+
*/
|
|
27
|
+
export const raccoonQrPageUrl = (code) =>
|
|
28
|
+
`${RACCOON_ORIGIN}/login/mp?code=${encodeURIComponent(String(code || ""))}&appname=${encodeURIComponent("商汤小浣熊官网")}`;
|
|
29
|
+
|
|
30
|
+
export const RACCOON_DEFAULT_CLIENT_VERSION = "v1.0.35";
|
|
31
|
+
export const RACCOON_CLIENT_PLATFORM = "desktop-windows";
|
|
32
|
+
export const RACCOON_CLIENT_LANGUAGE = "zh";
|
|
33
|
+
export const RACCOON_LOGIN_REWARD_POINTS = 3000;
|
|
34
|
+
export const RACCOON_LOGIN_REWARD_EVENT_NAME = "桌面端登录奖励";
|
|
35
|
+
|
|
36
|
+
export const RACCOON_REQUEST_TIMEOUT_MS = 60_000;
|
|
37
|
+
export const RACCOON_LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
38
|
+
export const RACCOON_LOGIN_POLL_INTERVAL_MS = 2000;
|
|
39
|
+
|
|
40
|
+
/** 客户端版本号(env 可覆盖:上游按版本做风控判断,硬编码会随官方发版失效)。 */
|
|
41
|
+
export function raccoonClientVersion(env = process.env) {
|
|
42
|
+
const v = typeof env?.MSLXDFF_RACCOON_CLIENT_VERSION === "string" ? env.MSLXDFF_RACCOON_CLIENT_VERSION.trim() : "";
|
|
43
|
+
return v || RACCOON_DEFAULT_CLIENT_VERSION;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** UA 形如 `Raccoon Work/1.0.35 (Windows)` —— 版本段不带 `v` 前缀(对齐官方客户端字面量)。 */
|
|
47
|
+
export function raccoonUserAgent(env = process.env) {
|
|
48
|
+
const ver = raccoonClientVersion(env).replace(/^v/i, "");
|
|
49
|
+
return `Raccoon Work/${ver} (Windows)`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 思考只有两档(上游不认 reasoning_effort,实测传该参数无可测差异):
|
|
53
|
+
// 出站经 extra_body.thinking.type = "enabled" | "disabled"。
|
|
54
|
+
export const RACCOON_EFFORT_ON = "on";
|
|
55
|
+
export const RACCOON_EFFORT_OFF = "off";
|
|
56
|
+
export const RACCOON_EFFORTS = [RACCOON_EFFORT_ON, RACCOON_EFFORT_OFF];
|
|
57
|
+
export const RACCOON_DEFAULT_EFFORT = RACCOON_EFFORT_ON;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 思考档位 → 出站 `thinking.type`。
|
|
61
|
+
* 上层档位词表跨供应商共用,收到非本家档位(high/xhigh/max/…)时归一为「开」而非报错。
|
|
62
|
+
*/
|
|
63
|
+
export function raccoonThinkingType(effort) {
|
|
64
|
+
const raw = String(effort ?? "").trim().toLowerCase();
|
|
65
|
+
if (raw === RACCOON_EFFORT_OFF || raw === "none" || raw === "off") return "disabled";
|
|
66
|
+
return "enabled";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 思考开关的环境默认:`MSLXDFF_RACCOON_THINKING=off|0|false|no|disabled` 关,其余(含未设)=开。
|
|
71
|
+
* 优先级见 `chat.js` 的 `buildRaccoonWireBody`(请求体显式声明 > effort 参数 > 本 env > 默认开)。
|
|
72
|
+
*/
|
|
73
|
+
export function raccoonEffortFromEnv(env = process.env) {
|
|
74
|
+
const raw = typeof env?.MSLXDFF_RACCOON_THINKING === "string" ? env.MSLXDFF_RACCOON_THINKING.trim().toLowerCase() : "";
|
|
75
|
+
return raw === "off" || raw === "0" || raw === "false" || raw === "no" || raw === "disabled" ? RACCOON_EFFORT_OFF : RACCOON_EFFORT_ON;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 冷却档位(对齐 qoder/zcode 先例:限流短冷、额度长冷)。 */
|
|
79
|
+
export const RACCOON_DEFAULT_COOLDOWN_MS = 30_000;
|
|
80
|
+
export const RACCOON_DEFAULT_QUOTA_COOLDOWN_MS = 60 * 60 * 1000;
|
|
81
|
+
|
|
82
|
+
// 业务码表(pack.js 实证):200001 未带 token,200003 登录态过期,100006 图形验证码失败(仅短信链路)。
|
|
83
|
+
export const RACCOON_ERROR_KINDS = {
|
|
84
|
+
200001: "auth",
|
|
85
|
+
200003: "auth",
|
|
86
|
+
100006: "captcha",
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export function raccoonErrorKind(code) {
|
|
90
|
+
return RACCOON_ERROR_KINDS[Number(code)] || "unknown";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 兜底模型目录(pack.js `RACCOON_FALLBACK_MODELS` 原文,全部支持读图)。
|
|
95
|
+
* `multiplier` = 每次调用扣分倍率:0 免费、1 基准、0.25 四分之一;`baseMultiplier` 存在即促销(显示 x基→x实)。
|
|
96
|
+
* 上游 `model_catalog` 不可达时用本表,保证「未登录也能看见这家有什么」。
|
|
97
|
+
*/
|
|
98
|
+
export const RACCOON_FALLBACK_MODELS = [
|
|
99
|
+
{ id: "sn-sensenova-6-8-flash", contextWindow: 256_000, maxTokens: 63_999, supportsImage: true, multiplier: 0 },
|
|
100
|
+
{ id: "sn-sensenova-6-8-flash-lite", contextWindow: 256_000, maxTokens: 63_999, supportsImage: true, multiplier: 0 },
|
|
101
|
+
{ id: "sn-kimi-k3", contextWindow: 1_000_000, maxTokens: 100_000, supportsImage: true, multiplier: 1 },
|
|
102
|
+
{ id: "sn-deepseek-v4-1-flash", contextWindow: 1_000_000, maxTokens: 100_000, supportsImage: true, multiplier: 0.25 },
|
|
103
|
+
{ id: "sn-glm-5-3", contextWindow: 1_000_000, maxTokens: 100_000, supportsImage: true, multiplier: 0.75 },
|
|
104
|
+
{ id: "sn-glm-5-3-flash", contextWindow: 1_000_000, maxTokens: 100_000, supportsImage: true, multiplier: 0.1, baseMultiplier: 0.2 },
|
|
105
|
+
];
|
|
106
|
+
|
|
107
|
+
/** 入站 `raccoon/<model>` → 裸 id(allowlist 与出站都用裸 id)。 */
|
|
108
|
+
export function canonicalRaccoonModel(id) {
|
|
109
|
+
const raw = String(id || "").trim();
|
|
110
|
+
return raw.startsWith("raccoon/") ? raw.slice("raccoon/".length) : raw;
|
|
111
|
+
}
|