mslxdff 0.1.164 → 0.1.170
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 +23 -5
- 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 +8 -2
- package/src/cli/format.js +1 -1
- package/src/cli/help.js +2 -0
- package/src/cli/index.js +2 -0
- package/src/cli/provider-row.js +2 -2
- package/src/daemon.js +13 -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/messages-route.js +114 -3
- 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/talk-full.js +2 -2
- package/src/talk-log.js +9 -6
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// raccoon 供应商工厂:keyring 多号轮换 + 差异化冷却(quota 长冷、auth/限流/服务端短冷)+ 临期自动续期。
|
|
2
|
+
// 冷却档位与话术对齐 qoder/zcode 先例(ADR-0044 同款口径):限流绝不谎报成积分不足。
|
|
3
|
+
import { compatFetch } from "../../compat.js";
|
|
4
|
+
import { envInt } from "../base.js";
|
|
5
|
+
import { createKeyRing } from "../keyring.js";
|
|
6
|
+
import { loadProviderKeys } from "../../state.js";
|
|
7
|
+
import { forwardRaccoonChat } from "./chat.js";
|
|
8
|
+
import { buildRaccoonModelList, listRaccoonModels } from "./models.js";
|
|
9
|
+
import { applyRaccoonRefresh, listRaccoonAccountDocs, raccoonCredentialFromDoc, readRaccoonAccountDoc, syncRaccoonKeys, writeRaccoonAccountFile } from "./account-store.js";
|
|
10
|
+
import { refreshRaccoonCredential } from "./login.js";
|
|
11
|
+
import { isRaccoonExpiringSoon, raccoonTokenFingerprint } from "./auth.js";
|
|
12
|
+
import { RACCOON_DEFAULT_COOLDOWN_MS, RACCOON_DEFAULT_QUOTA_COOLDOWN_MS } from "./const.js";
|
|
13
|
+
|
|
14
|
+
/** kind → 冷却档位。auth 走短冷(重登指引已由响应体给出);quota 走长冷(按天回血)。 */
|
|
15
|
+
const COOLDOWN_BY_KIND = { auth: "short", rate_limit: "short", server: "short", quota: "long" };
|
|
16
|
+
|
|
17
|
+
function notLoggedInResponse() {
|
|
18
|
+
return new Response(
|
|
19
|
+
JSON.stringify({ error: { message: "raccoon: 无可用账号 —— 先运行 mslxdff -provider raccoon login", type: "auth_error" } }),
|
|
20
|
+
{ status: 401, headers: { "Content-Type": "application/json" } },
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function allCoolingResponse() {
|
|
25
|
+
return new Response(
|
|
26
|
+
JSON.stringify({ error: { message: "raccoon: 账号暂不可用(冷却中,可能积分不足或限流),请稍后重试", type: "all_cooling" } }),
|
|
27
|
+
{ status: 429, headers: { "Content-Type": "application/json", "x-mslxdff-raccoon-all-cooling": "1" } },
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createRaccoonProvider({
|
|
32
|
+
id = "raccoon",
|
|
33
|
+
apiKeys,
|
|
34
|
+
file,
|
|
35
|
+
fetchImpl,
|
|
36
|
+
cooldownMs = envInt("MSLXDFF_RACCOON_COOLDOWN_MS", RACCOON_DEFAULT_COOLDOWN_MS),
|
|
37
|
+
quotaCooldownMs = envInt("MSLXDFF_RACCOON_QUOTA_COOLDOWN_MS", RACCOON_DEFAULT_QUOTA_COOLDOWN_MS),
|
|
38
|
+
timeoutMs = Number(process.env.MSLXDFF_RACCOON_TIMEOUT_MS) || 300_000,
|
|
39
|
+
effort,
|
|
40
|
+
} = {}) {
|
|
41
|
+
if (!fetchImpl) fetchImpl = compatFetch;
|
|
42
|
+
const explicitKeys = Array.isArray(apiKeys) && apiKeys.length;
|
|
43
|
+
let keys = explicitKeys
|
|
44
|
+
? [...new Set(apiKeys.map((k) => String(k).trim()).filter(Boolean))]
|
|
45
|
+
: (() => {
|
|
46
|
+
try {
|
|
47
|
+
return loadProviderKeys(id, file ? { file } : {});
|
|
48
|
+
} catch {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
})();
|
|
52
|
+
if (!explicitKeys) {
|
|
53
|
+
// ⚠ 自愈:keys 一律以 auths/ 文档为准。续期只回写文档,两者一旦分叉,重启后 ring 拿的就是已过期
|
|
54
|
+
// token,症状是「明明登录过、积分还在,却恒 401 / 429 全号冷却」,只能重扫码。显式传 apiKeys 的
|
|
55
|
+
// 调用方(chatWithKeys、单测)尊重入参,不覆盖。
|
|
56
|
+
try {
|
|
57
|
+
const fromDocs = [...new Set(listRaccoonAccountDocs().map((d) => String(d.accessToken || "").trim()).filter(Boolean))];
|
|
58
|
+
if (fromDocs.length && fromDocs.join("\n") !== keys.join("\n")) {
|
|
59
|
+
keys = fromDocs;
|
|
60
|
+
syncRaccoonKeys({}).catch(() => {});
|
|
61
|
+
}
|
|
62
|
+
} catch {}
|
|
63
|
+
}
|
|
64
|
+
const ring = createKeyRing(keys, { cooldownMs });
|
|
65
|
+
|
|
66
|
+
// access_token → 账号文档(office_identity / device_id / refresh_token 跟号走,取自 auths/raccoon-<uid>.json)
|
|
67
|
+
// 缓存**可失效**:重登与续期都会换盘上的 token,只建一次会让本进程永远停在旧号(见 healKeyFromDocs)
|
|
68
|
+
let docCache = null;
|
|
69
|
+
function reloadDocs() {
|
|
70
|
+
try {
|
|
71
|
+
docCache = new Map(listRaccoonAccountDocs().map((d) => [d.accessToken, d]));
|
|
72
|
+
} catch {
|
|
73
|
+
docCache = new Map();
|
|
74
|
+
}
|
|
75
|
+
return docCache;
|
|
76
|
+
}
|
|
77
|
+
function accountFor(token) {
|
|
78
|
+
if (docCache === null) reloadDocs();
|
|
79
|
+
return docCache.get(token);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 「内存号 ↔ 账号文档」对齐。daemon 只在启动时读一次 keys(providers-setup 显式传 apiKeys),重登换了盘上
|
|
84
|
+
* token 后内存那份已被上游作废(code 200003)——用户重登也没用、只能重启,这里以文档为准当场换回来。
|
|
85
|
+
* 返回换上的新 token;文档无可用新号(或候选号都在冷却)返回 null,交回既有失败路径。取舍见 ADR-0050。
|
|
86
|
+
*/
|
|
87
|
+
async function healKeyFromDocs(staleToken) {
|
|
88
|
+
const fresh = [...reloadDocs().values()].find((d) => d.accessToken && d.accessToken !== staleToken && !ring.isCooling(d.accessToken));
|
|
89
|
+
if (!fresh) return null;
|
|
90
|
+
ring.replace(staleToken, fresh.accessToken);
|
|
91
|
+
console.error(`[raccoon] 内存 token(${raccoonTokenFingerprint(staleToken)}) 已不在账号文档里 → 换用文档号(${raccoonTokenFingerprint(fresh.accessToken)}) 并同步 keys`);
|
|
92
|
+
try { await syncRaccoonKeys(file ? { file } : {}); } catch {}
|
|
93
|
+
return fresh.accessToken;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function credentialFor(token) {
|
|
97
|
+
// 映射的单一源在 account-store.raccoonCredentialFromDoc(曾各自内联,漏 expires_at 会让续期判定静默失效)
|
|
98
|
+
return raccoonCredentialFromDoc(accountFor(token) || { accessToken: token });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 同一 token 的并发续期必须合并成一次请求 —— refresh_token 是一次性轮换的(2026-10-10 实测:
|
|
102
|
+
// 续期成功后旧值立刻失效),并发各刷各的等于自己把号烧了。姿势对齐 workbuddy/auth.js 的 inflightRefresh。
|
|
103
|
+
const inflightRefresh = new Map();
|
|
104
|
+
|
|
105
|
+
/** 临期即续期;续期成功把新 token 回写账号文档并替换 keyring 里的旧键。失败不阻断(让上游如实报)。 */
|
|
106
|
+
async function ensureFresh(token) {
|
|
107
|
+
const credential = credentialFor(token);
|
|
108
|
+
if (!credential.refresh_token || !isRaccoonExpiringSoon(credential)) return credential;
|
|
109
|
+
const pending = inflightRefresh.get(token);
|
|
110
|
+
if (pending) return pending;
|
|
111
|
+
const p = (async () => {
|
|
112
|
+
try {
|
|
113
|
+
const next = await refreshRaccoonCredential(credential, { fetchImpl });
|
|
114
|
+
if (next.access_token !== token) {
|
|
115
|
+
ring.replace(token, next.access_token);
|
|
116
|
+
docCache?.delete(token);
|
|
117
|
+
}
|
|
118
|
+
// ⚠ 同 token 也必须刷新到期时间:否则 docCache 永远停在旧 expires_at,每个请求都会重复调一次 refresh
|
|
119
|
+
docCache?.set(next.access_token, { ...credential, accessToken: next.access_token, refreshToken: next.refresh_token, expiresAt: next.expires_at || "" });
|
|
120
|
+
try {
|
|
121
|
+
if (credential.uid) {
|
|
122
|
+
const existing = readRaccoonAccountDoc(credential.uid) || {}; const merged = applyRaccoonRefresh(existing.auth || {}, { accessToken: next.access_token, refreshToken: next.refresh_token, expiresAt: next.expires_at });
|
|
123
|
+
writeRaccoonAccountFile({
|
|
124
|
+
uid: credential.uid,
|
|
125
|
+
accessToken: merged.access_token,
|
|
126
|
+
refreshToken: merged.refresh_token,
|
|
127
|
+
expiresAt: merged.expires_at || "",
|
|
128
|
+
officeIdentity: credential.office_identity,
|
|
129
|
+
deviceId: credential.device_id,
|
|
130
|
+
name: existing.account?.name || "",
|
|
131
|
+
phone: existing.account?.phone || "",
|
|
132
|
+
});
|
|
133
|
+
syncRaccoonKeys({}).catch(() => {}); // 文档里 token 换了,keys 必须跟上,否则重启即拿旧值撞 401
|
|
134
|
+
}
|
|
135
|
+
} catch (e) {
|
|
136
|
+
// 绝不静默:内存里还能用,但进程一重启、盘上那份已作废的 refresh_token 就成了废号。
|
|
137
|
+
console.error(`[raccoon] token 落盘失败(刷新已成功,重启将丢失): ${String(e?.message || e).slice(0, 200)}`);
|
|
138
|
+
}
|
|
139
|
+
return next;
|
|
140
|
+
} catch (e) {
|
|
141
|
+
// 不静默:续期失败会让该号在内存与盘上同时变旧,症状必须能在 daemon.log 里看见(只允许指纹)
|
|
142
|
+
console.error(`[raccoon] 续期失败(继续用旧 token,过期即 401)token(${raccoonTokenFingerprint(token)}): ${String(e?.message || e).slice(0, 160)}`);
|
|
143
|
+
if (e?.authExpired) ring.onError(token, cooldownMs);
|
|
144
|
+
return credential;
|
|
145
|
+
} finally {
|
|
146
|
+
inflightRefresh.delete(token);
|
|
147
|
+
}
|
|
148
|
+
})();
|
|
149
|
+
inflightRefresh.set(token, p);
|
|
150
|
+
return p;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function chat(body, opts = {}) {
|
|
154
|
+
const total = ring.keys.length;
|
|
155
|
+
if (!total) return notLoggedInResponse();
|
|
156
|
+
let lastRes = null;
|
|
157
|
+
let healed = false; // 一次请求内只自愈一次:防重试风暴,也防「文档里那份同样不可用」时打旋
|
|
158
|
+
for (let hop = 0; hop <= total + 1; hop++) {
|
|
159
|
+
const key = ring.next();
|
|
160
|
+
if (!key) break;
|
|
161
|
+
const credential = await ensureFresh(key);
|
|
162
|
+
const res = await forwardRaccoonChat({ body, credential, fetchImpl, timeoutMs, effort: opts?.effort ?? effort });
|
|
163
|
+
const kind = res.headers.get("x-mslxdff-raccoon-kind");
|
|
164
|
+
if (!kind) return res; // 成功或未分类:直接交出去
|
|
165
|
+
lastRes = res;
|
|
166
|
+
if (kind === "auth" && !healed) {
|
|
167
|
+
healed = true;
|
|
168
|
+
// 自愈成功就换号重试;不给失效号记冷却(ring.replace 也不把冷却带给新号)
|
|
169
|
+
if (await healKeyFromDocs(key)) continue;
|
|
170
|
+
}
|
|
171
|
+
const mode = COOLDOWN_BY_KIND[kind] || "none";
|
|
172
|
+
if (mode === "long") ring.onError(key, quotaCooldownMs);
|
|
173
|
+
else if (mode === "short") ring.onError(key, cooldownMs);
|
|
174
|
+
if (mode === "none") break; // 换号无意义,如实透出
|
|
175
|
+
if (ring.available() === 0) break; // 没有别的可用号
|
|
176
|
+
}
|
|
177
|
+
if (lastRes) return lastRes;
|
|
178
|
+
return allCoolingResponse();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function listModels() {
|
|
182
|
+
let token = ring.keys[0];
|
|
183
|
+
// 内存号已不在文档里(重登换号)时先对齐,否则目录撞 401 后静默回落内置表,表现为「列表不是最新的」
|
|
184
|
+
if (token && !accountFor(token)) token = (await healKeyFromDocs(token)) || token;
|
|
185
|
+
if (!token) return [];
|
|
186
|
+
const { models } = await listRaccoonModels({ credential: credentialFor(token), fetchImpl });
|
|
187
|
+
return buildRaccoonModelList({ id, models });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function preheat() {
|
|
191
|
+
try {
|
|
192
|
+
const list = await listModels();
|
|
193
|
+
return list.length ? { ok: true } : { ok: false, error: "no catalog" };
|
|
194
|
+
} catch (e) {
|
|
195
|
+
return { ok: false, error: String(e?.message || e).slice(0, 120) };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function close() {}
|
|
200
|
+
|
|
201
|
+
async function chatWithKeys(body, keysOverride, opts) {
|
|
202
|
+
const tmp = createRaccoonProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, quotaCooldownMs, timeoutMs, effort });
|
|
203
|
+
return tmp.chat(body, opts);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
id,
|
|
208
|
+
chat,
|
|
209
|
+
chatWithKeys,
|
|
210
|
+
listModels,
|
|
211
|
+
preheat,
|
|
212
|
+
close,
|
|
213
|
+
keyRing: ring,
|
|
214
|
+
baseUrl: "raccoon://native",
|
|
215
|
+
};
|
|
216
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// raccoon 扫码登录状态机与会话续期。
|
|
2
|
+
// 实测依据:`POST /api/web/auth/v1/login_with_qrcode_code` **匿名可达**(HTTP 200 {"code":0,"data":{"status":"pending"}}),
|
|
3
|
+
// 故整条登录链路不需要验证码、不需要浏览器组件(短信登录才要阿里云滑块,本期不做)。
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import {
|
|
6
|
+
RACCOON_LOGIN_POLL_INTERVAL_MS,
|
|
7
|
+
RACCOON_LOGIN_TIMEOUT_MS,
|
|
8
|
+
RACCOON_REQUEST_TIMEOUT_MS,
|
|
9
|
+
raccoonQrLoginUrl,
|
|
10
|
+
raccoonQrPageUrl,
|
|
11
|
+
raccoonRefreshUrl,
|
|
12
|
+
raccoonUserInfoUrl,
|
|
13
|
+
} from "./const.js";
|
|
14
|
+
import { raccoonAnonymousHeaders, raccoonAuthHeaders } from "./headers.js";
|
|
15
|
+
import { decodeJwtExpMs } from "./auth.js";
|
|
16
|
+
import { parseRaccoonEnvelope, raccoonEnvelopeText } from "./envelope.js";
|
|
17
|
+
|
|
18
|
+
/** 上游 `data.status` 四态(pack.js RACCOON_QR_STATUS 同形)。 */
|
|
19
|
+
export const RACCOON_QR_STATUS = Object.freeze({
|
|
20
|
+
pending: "pending",
|
|
21
|
+
logging: "logging",
|
|
22
|
+
canceled: "canceled",
|
|
23
|
+
success: "success",
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** 一次性登录码:16 字节 hex(32 字符),既是二维码内容参数也是轮询凭据。 */
|
|
27
|
+
export function createQrCode() {
|
|
28
|
+
return randomBytes(16).toString("hex");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 二维码/链接内容:用户用手机扫码或直接打开它完成确认。 */
|
|
32
|
+
export function buildQrUrl(code) {
|
|
33
|
+
return raccoonQrPageUrl(code);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
37
|
+
|
|
38
|
+
async function postJson(url, body, { fetchImpl = fetch, env = process.env, timeoutMs = RACCOON_REQUEST_TIMEOUT_MS } = {}) {
|
|
39
|
+
let res;
|
|
40
|
+
try {
|
|
41
|
+
res = await fetchImpl(url, {
|
|
42
|
+
method: "POST",
|
|
43
|
+
headers: raccoonAnonymousHeaders({ env }),
|
|
44
|
+
body: JSON.stringify(body),
|
|
45
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
46
|
+
});
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw new Error(`raccoon: 请求失败:${error?.message ?? error}`);
|
|
49
|
+
}
|
|
50
|
+
let parsed;
|
|
51
|
+
try {
|
|
52
|
+
parsed = await res.json();
|
|
53
|
+
} catch {
|
|
54
|
+
throw new Error(`raccoon: 响应不是 JSON(HTTP ${res.status})`);
|
|
55
|
+
}
|
|
56
|
+
return parseRaccoonEnvelope(parsed, res.status);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 从登录成功信封里取凭据;缺 access_token 视为失败(不写半截凭据)。 */
|
|
60
|
+
export function raccoonCredentialFromEnvelope(envelope) {
|
|
61
|
+
const data = envelope?.data ?? {};
|
|
62
|
+
const accessToken = typeof data.access_token === "string" ? data.access_token : "";
|
|
63
|
+
if (!accessToken) throw new Error("raccoon: 登录响应缺少 access_token");
|
|
64
|
+
const refreshToken = typeof data.refresh_token === "string" ? data.refresh_token : "";
|
|
65
|
+
const officeIdentity = typeof data.office_identity === "string" ? data.office_identity : "";
|
|
66
|
+
const expMs = decodeJwtExpMs(accessToken);
|
|
67
|
+
return {
|
|
68
|
+
access_token: accessToken,
|
|
69
|
+
refresh_token: refreshToken,
|
|
70
|
+
...(expMs === undefined ? {} : { expires_at: String(expMs) }),
|
|
71
|
+
...(officeIdentity ? { office_identity: officeIdentity } : {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 轮询一轮。网络抖动一律折成 `pending`(用户还在扫码,不该因为一次超时把整轮打断);
|
|
77
|
+
* `canceled` / `success` 是终态。
|
|
78
|
+
*/
|
|
79
|
+
export async function pollQrLoginOnce(code, opts = {}) {
|
|
80
|
+
let envelope;
|
|
81
|
+
try {
|
|
82
|
+
envelope = await postJson(raccoonQrLoginUrl(), { qrcode_code: String(code || "") }, opts);
|
|
83
|
+
} catch {
|
|
84
|
+
return { status: RACCOON_QR_STATUS.pending };
|
|
85
|
+
}
|
|
86
|
+
if (envelope.code !== 0 || envelope.data === undefined) return { status: RACCOON_QR_STATUS.pending };
|
|
87
|
+
const status = typeof envelope.data.status === "string" ? envelope.data.status : "";
|
|
88
|
+
const expiredAt = typeof envelope.data.expired_at === "string" ? envelope.data.expired_at : undefined;
|
|
89
|
+
if (status === RACCOON_QR_STATUS.canceled) return { status: RACCOON_QR_STATUS.canceled };
|
|
90
|
+
if (status === RACCOON_QR_STATUS.logging) return { status: RACCOON_QR_STATUS.logging, ...(expiredAt ? { expiredAt } : {}) };
|
|
91
|
+
if (status === RACCOON_QR_STATUS.success) {
|
|
92
|
+
try {
|
|
93
|
+
return { status: RACCOON_QR_STATUS.success, credential: raccoonCredentialFromEnvelope(envelope) };
|
|
94
|
+
} catch {
|
|
95
|
+
return { status: RACCOON_QR_STATUS.pending };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return { status: RACCOON_QR_STATUS.pending };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 轮询直到终态。返回 `{ status, credential? }`;
|
|
103
|
+
* 超时返回 `{ status: "timeout" }`(调用方据此输出人话并非零退出)。
|
|
104
|
+
*/
|
|
105
|
+
export async function pollQrLogin(code, {
|
|
106
|
+
fetchImpl = fetch,
|
|
107
|
+
env = process.env,
|
|
108
|
+
intervalMs = RACCOON_LOGIN_POLL_INTERVAL_MS,
|
|
109
|
+
timeoutMs = RACCOON_LOGIN_TIMEOUT_MS,
|
|
110
|
+
onTick,
|
|
111
|
+
sleepFn = defaultSleep,
|
|
112
|
+
now = Date.now,
|
|
113
|
+
} = {}) {
|
|
114
|
+
const deadline = now() + timeoutMs;
|
|
115
|
+
let ticks = 0;
|
|
116
|
+
for (;;) {
|
|
117
|
+
const result = await pollQrLoginOnce(code, { fetchImpl, env });
|
|
118
|
+
ticks += 1;
|
|
119
|
+
if (typeof onTick === "function") {
|
|
120
|
+
try { onTick(result, ticks); } catch {}
|
|
121
|
+
}
|
|
122
|
+
if (result.status === RACCOON_QR_STATUS.success) return result;
|
|
123
|
+
if (result.status === RACCOON_QR_STATUS.canceled) return { status: RACCOON_QR_STATUS.canceled };
|
|
124
|
+
if (now() >= deadline) return { status: "timeout" };
|
|
125
|
+
await sleepFn(intervalMs);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 用 refresh_token 续期。上游不返回新 refresh_token 时沿用旧的(不能覆盖成空串)。
|
|
131
|
+
* 登录态失效(HTTP 401 / code 200003)抛带 `authExpired` 标记的错误,交由调用方转成重登指引。
|
|
132
|
+
*/
|
|
133
|
+
export async function refreshRaccoonCredential(credential, opts = {}) {
|
|
134
|
+
const { fetchImpl = fetch, env = process.env, timeoutMs = RACCOON_REQUEST_TIMEOUT_MS } = opts;
|
|
135
|
+
let res;
|
|
136
|
+
try {
|
|
137
|
+
res = await fetchImpl(raccoonRefreshUrl(), {
|
|
138
|
+
method: "POST",
|
|
139
|
+
headers: raccoonAnonymousHeaders({ env }),
|
|
140
|
+
body: JSON.stringify({ refresh_token: String(credential?.refresh_token ?? "") }),
|
|
141
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
142
|
+
});
|
|
143
|
+
} catch (error) {
|
|
144
|
+
throw new Error(`raccoon: 续期请求失败:${error?.message ?? error}`);
|
|
145
|
+
}
|
|
146
|
+
let parsed;
|
|
147
|
+
try {
|
|
148
|
+
parsed = await res.json();
|
|
149
|
+
} catch {
|
|
150
|
+
throw new Error(`raccoon: 续期响应不是 JSON(HTTP ${res.status})`);
|
|
151
|
+
}
|
|
152
|
+
const envelope = parseRaccoonEnvelope(parsed, res.status);
|
|
153
|
+
if (res.status === 401 || envelope.code === 200003) {
|
|
154
|
+
const err = new Error("raccoon: 登录态已过期,请重新登录");
|
|
155
|
+
err.authExpired = true;
|
|
156
|
+
throw err;
|
|
157
|
+
}
|
|
158
|
+
if (envelope.code !== 0) throw new Error(`raccoon: 续期失败:${raccoonEnvelopeText(envelope)}`);
|
|
159
|
+
const accessToken = typeof envelope.data?.access_token === "string" ? envelope.data.access_token : "";
|
|
160
|
+
if (!accessToken) throw new Error("raccoon: 续期响应缺少 access_token");
|
|
161
|
+
const nextRefresh = typeof envelope.data.refresh_token === "string" && envelope.data.refresh_token.length > 0
|
|
162
|
+
? envelope.data.refresh_token
|
|
163
|
+
: String(credential?.refresh_token ?? "");
|
|
164
|
+
const expMs = decodeJwtExpMs(accessToken);
|
|
165
|
+
return {
|
|
166
|
+
...credential,
|
|
167
|
+
access_token: accessToken,
|
|
168
|
+
refresh_token: nextRefresh,
|
|
169
|
+
...(expMs === undefined ? {} : { expires_at: String(expMs) }),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** 取用户信息(uid/昵称/手机号/office_identity);任何失败都返回空对象,不阻断登录。 */
|
|
174
|
+
export async function fetchRaccoonUserInfo(credential, opts = {}) {
|
|
175
|
+
const { fetchImpl = fetch, env = process.env, timeoutMs = RACCOON_REQUEST_TIMEOUT_MS } = opts;
|
|
176
|
+
try {
|
|
177
|
+
const res = await fetchImpl(raccoonUserInfoUrl(), {
|
|
178
|
+
method: "GET",
|
|
179
|
+
headers: raccoonAuthHeaders(credential, { env }),
|
|
180
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
181
|
+
});
|
|
182
|
+
if (!res.ok) return {};
|
|
183
|
+
const envelope = parseRaccoonEnvelope(await res.json(), res.status);
|
|
184
|
+
if (envelope.code !== 0 || envelope.data === undefined) return {};
|
|
185
|
+
const pick = (k) => (typeof envelope.data[k] === "string" ? envelope.data[k] : "");
|
|
186
|
+
return {
|
|
187
|
+
userId: pick("id"),
|
|
188
|
+
name: pick("name"),
|
|
189
|
+
phone: pick("phone"),
|
|
190
|
+
officeIdentity: pick("office_identity"),
|
|
191
|
+
};
|
|
192
|
+
} catch {
|
|
193
|
+
return {};
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// raccoon 模型目录:上游 `model_catalog` 解析 + 兜底目录 + 积分倍率展示名 + allowlist 补齐。
|
|
2
|
+
// 倍率是这家供应商的**成本唯一载体**(积分制,不是免费额度),所以它在模型名与列表里都必须出现:
|
|
3
|
+
// 0 → 「免费」;1 → 也显示 `x1`(省略会让用户以为「没倍率=不扣分」);促销 → `x0.2→x0.1`。
|
|
4
|
+
import {
|
|
5
|
+
RACCOON_FALLBACK_MODELS,
|
|
6
|
+
RACCOON_REQUEST_TIMEOUT_MS,
|
|
7
|
+
raccoonModelCatalogUrl,
|
|
8
|
+
} from "./const.js";
|
|
9
|
+
import { raccoonAuthHeaders } from "./headers.js";
|
|
10
|
+
import { parseRaccoonEnvelope } from "./envelope.js";
|
|
11
|
+
import { loadProviderAllowedModels, saveProviderAllowedModels } from "../../state/schemas/allowlist.js";
|
|
12
|
+
import { joinModelId } from "../model-id.js";
|
|
13
|
+
|
|
14
|
+
const pickString = (src, keys) => {
|
|
15
|
+
for (const k of keys) {
|
|
16
|
+
const v = src?.[k];
|
|
17
|
+
if (typeof v === "string" && v.trim().length > 0) return v.trim();
|
|
18
|
+
}
|
|
19
|
+
return "";
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const pickNumber = (src, keys) => {
|
|
23
|
+
for (const k of keys) {
|
|
24
|
+
const v = src?.[k];
|
|
25
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
26
|
+
if (typeof v === "string" && /^-?\d+(\.\d+)?$/.test(v.trim())) return Number(v.trim());
|
|
27
|
+
}
|
|
28
|
+
return undefined;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const pickBool = (src, keys) => {
|
|
32
|
+
for (const k of keys) {
|
|
33
|
+
const v = src?.[k];
|
|
34
|
+
if (typeof v === "boolean") return v;
|
|
35
|
+
}
|
|
36
|
+
return undefined;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** 兜底目录(const.js 的静态表,字段名已归一)。 */
|
|
40
|
+
export function raccoonFallbackModels() {
|
|
41
|
+
return RACCOON_FALLBACK_MODELS.map((m) => ({ ...m }));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 单条目录条目:字段名容错(缺字段即省略,不猜、不填假值)。 */
|
|
45
|
+
function parseRaccoonModelEntry(raw) {
|
|
46
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
|
|
47
|
+
const id = pickString(raw, ["id", "modelId", "model_id", "modelName", "name"]);
|
|
48
|
+
if (!id) return null;
|
|
49
|
+
const model = { id };
|
|
50
|
+
const name = pickString(raw, ["modelName", "name", "displayName", "description"]);
|
|
51
|
+
if (name) model.name = name;
|
|
52
|
+
const ctx = pickNumber(raw, ["contextWindow", "context_window", "contextLength", "context_length"]);
|
|
53
|
+
if (ctx !== undefined && ctx > 0) model.contextWindow = ctx;
|
|
54
|
+
const maxTokens = pickNumber(raw, ["maxTokens", "max_tokens", "maxCompletionTokens"]);
|
|
55
|
+
if (maxTokens !== undefined && maxTokens > 0) model.maxTokens = maxTokens;
|
|
56
|
+
const img = pickBool(raw, ["supportsImage", "supports_image", "supportsVision"]);
|
|
57
|
+
if (img !== undefined) model.supportsImage = img;
|
|
58
|
+
const eff = pickNumber(raw, ["effectiveMultiplier", "effective_multiplier", "multiplier", "costMultiplier"]);
|
|
59
|
+
if (eff !== undefined && eff >= 0) model.multiplier = eff;
|
|
60
|
+
const base = pickNumber(raw, ["baseMultiplier", "base_multiplier"]);
|
|
61
|
+
if (base !== undefined && base > 0) model.baseMultiplier = base;
|
|
62
|
+
return model;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 目录信封 → 条目数组。兼容 `data` 为数组、`data.models`、`data.list`、`data.items` 四种形状。 */
|
|
66
|
+
export function parseRaccoonCatalog(data) {
|
|
67
|
+
const list = Array.isArray(data)
|
|
68
|
+
? data
|
|
69
|
+
: Array.isArray(data?.models)
|
|
70
|
+
? data.models
|
|
71
|
+
: Array.isArray(data?.list)
|
|
72
|
+
? data.list
|
|
73
|
+
: Array.isArray(data?.items)
|
|
74
|
+
? data.items
|
|
75
|
+
: [];
|
|
76
|
+
const out = [];
|
|
77
|
+
const seen = new Set();
|
|
78
|
+
for (const raw of list) {
|
|
79
|
+
const m = parseRaccoonModelEntry(raw);
|
|
80
|
+
if (!m || seen.has(m.id)) continue;
|
|
81
|
+
seen.add(m.id);
|
|
82
|
+
out.push(m);
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 倍率文案:0 → 免费;促销 → `x基→x实`;其余 → `x实`(含 x1)。 */
|
|
88
|
+
export function raccoonMultiplierLabel(model) {
|
|
89
|
+
const eff = typeof model?.multiplier === "number" ? model.multiplier : undefined;
|
|
90
|
+
if (eff === undefined) return "";
|
|
91
|
+
if (eff === 0) return "免费";
|
|
92
|
+
const fmt = (v) => String(Number(v.toFixed(4)));
|
|
93
|
+
const base = typeof model?.baseMultiplier === "number" ? model.baseMultiplier : undefined;
|
|
94
|
+
if (base !== undefined && base > eff) return `x${fmt(base)}→x${fmt(eff)}`;
|
|
95
|
+
return `x${fmt(eff)}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 列表/模型卡展示名:`<名字或 id> · <倍率>`(无倍率时省略后缀)。 */
|
|
99
|
+
export function raccoonDisplayName(model) {
|
|
100
|
+
const base = model?.name || model?.id || "";
|
|
101
|
+
const label = raccoonMultiplierLabel(model);
|
|
102
|
+
return label ? `${base} · ${label}` : base;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 拉上游目录;失败/空目录返回 null(调用方回落兜底表)。 */
|
|
106
|
+
export async function fetchRaccoonModelCatalog({
|
|
107
|
+
credential,
|
|
108
|
+
fetchImpl = fetch,
|
|
109
|
+
env = process.env,
|
|
110
|
+
timeoutMs = RACCOON_REQUEST_TIMEOUT_MS,
|
|
111
|
+
} = {}) {
|
|
112
|
+
if (!credential?.access_token) return null;
|
|
113
|
+
try {
|
|
114
|
+
const res = await fetchImpl(raccoonModelCatalogUrl(), {
|
|
115
|
+
method: "GET",
|
|
116
|
+
headers: raccoonAuthHeaders(credential, { env }),
|
|
117
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
118
|
+
});
|
|
119
|
+
if (!res.ok) return null;
|
|
120
|
+
const envelope = parseRaccoonEnvelope(await res.json(), res.status);
|
|
121
|
+
if (envelope.code !== 0) return null;
|
|
122
|
+
const models = parseRaccoonCatalog(envelope.data);
|
|
123
|
+
return models.length > 0 ? models : null;
|
|
124
|
+
} catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** 上游优先、兜底次之。返回 `{ models, source }`,source ∈ upstream|fallback。 */
|
|
130
|
+
export async function listRaccoonModels({ credential, fetchImpl, env } = {}) {
|
|
131
|
+
const upstream = await fetchRaccoonModelCatalog({ credential, fetchImpl, env });
|
|
132
|
+
if (upstream) return { models: upstream, source: "upstream" };
|
|
133
|
+
return { models: raccoonFallbackModels(), source: "fallback" };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 登录后把兜底目录 id 只增不减并入 allowlist(避免「登录成功却处处 403」)。 */
|
|
137
|
+
export function seedRaccoonAllowlist({ ids, file } = {}) {
|
|
138
|
+
const opts = file ? { file } : {};
|
|
139
|
+
const target = ids || RACCOON_FALLBACK_MODELS.map((m) => m.id);
|
|
140
|
+
const cur = loadProviderAllowedModels("raccoon", opts);
|
|
141
|
+
const added = target.filter((m) => !cur.includes(m));
|
|
142
|
+
if (added.length) saveProviderAllowedModels("raccoon", [...cur, ...added], opts);
|
|
143
|
+
return { allowed: [...cur, ...added], added };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 对外目录条目(`/v1/models` 与 CLI models 共用形状)。 */
|
|
147
|
+
export function buildRaccoonModelList({ id = "raccoon", models } = {}) {
|
|
148
|
+
const list = models || raccoonFallbackModels();
|
|
149
|
+
return list.map((m) => ({
|
|
150
|
+
id: joinModelId(id, m.id),
|
|
151
|
+
object: "model",
|
|
152
|
+
owned_by: "raccoon",
|
|
153
|
+
name: raccoonDisplayName(m),
|
|
154
|
+
context_length: m.contextWindow,
|
|
155
|
+
max_tokens: m.maxTokens,
|
|
156
|
+
supports_image: m.supportsImage,
|
|
157
|
+
multiplier: m.multiplier,
|
|
158
|
+
mark: raccoonMultiplierLabel(m) || undefined,
|
|
159
|
+
}));
|
|
160
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// raccoon 二维码编码的「码字层」:byte 模式位流 → RS 纠错 → 块切分与交错。
|
|
2
|
+
// 只覆盖 byte 模式与版本 1–10(v10-M 容量 213 字节,够装下扫码登录 URL)。
|
|
3
|
+
// 纠错级固定为 M(约 15% 冗余)——终端字符画本身易被拍照角度影响,M 是稳妥档。
|
|
4
|
+
const DATA_CODEWORDS = [0, 16, 28, 44, 64, 86, 108, 124, 154, 182, 216];
|
|
5
|
+
|
|
6
|
+
/** 纠错级 M 的块结构(QR 规范表):每块 ecPerBlock 个纠错码字 + 若干 [块数, 每块数据码字]。 */
|
|
7
|
+
const EC_BLOCKS_M = [
|
|
8
|
+
null,
|
|
9
|
+
{ ecPerBlock: 10, groups: [[1, 16]] },
|
|
10
|
+
{ ecPerBlock: 16, groups: [[1, 28]] },
|
|
11
|
+
{ ecPerBlock: 26, groups: [[1, 44]] },
|
|
12
|
+
{ ecPerBlock: 18, groups: [[2, 32]] },
|
|
13
|
+
{ ecPerBlock: 24, groups: [[2, 43]] },
|
|
14
|
+
{ ecPerBlock: 16, groups: [[4, 27]] },
|
|
15
|
+
{ ecPerBlock: 18, groups: [[4, 31]] },
|
|
16
|
+
{ ecPerBlock: 22, groups: [[2, 38], [2, 39]] },
|
|
17
|
+
{ ecPerBlock: 22, groups: [[3, 36], [2, 37]] },
|
|
18
|
+
{ ecPerBlock: 26, groups: [[4, 43], [1, 44]] },
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
const GF_EXP = new Uint8Array(512);
|
|
22
|
+
const GF_LOG = new Uint8Array(256);
|
|
23
|
+
(() => {
|
|
24
|
+
let x = 1;
|
|
25
|
+
for (let i = 0; i < 255; i++) {
|
|
26
|
+
GF_EXP[i] = x;
|
|
27
|
+
GF_LOG[x] = i;
|
|
28
|
+
x <<= 1;
|
|
29
|
+
if (x & 0x100) x ^= 0x11d; // 本原多项式 x^8+x^4+x^3+x^2+1
|
|
30
|
+
}
|
|
31
|
+
for (let i = 255; i < 512; i++) GF_EXP[i] = GF_EXP[i - 255];
|
|
32
|
+
})();
|
|
33
|
+
|
|
34
|
+
const gfMul = (a, b) => (a === 0 || b === 0 ? 0 : GF_EXP[GF_LOG[a] + GF_LOG[b]]);
|
|
35
|
+
|
|
36
|
+
function polyMul(a, b) {
|
|
37
|
+
const out = new Array(a.length + b.length - 1).fill(0);
|
|
38
|
+
for (let i = 0; i < a.length; i++) for (let j = 0; j < b.length; j++) out[i + j] ^= gfMul(a[i], b[j]);
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 生成多项式连乘 (x - α^0)…(x - α^(ecCount-1)),再做多项式除法取余数即纠错码字。 */
|
|
43
|
+
function rsEncode(data, ecCount) {
|
|
44
|
+
const gen = qrEcGeneratorPoly(ecCount);
|
|
45
|
+
// qrEcGeneratorPoly 定义在文件末尾(函数声明提升,调用点在前无妨)
|
|
46
|
+
const buf = [...data, ...new Array(ecCount).fill(0)];
|
|
47
|
+
for (let i = 0; i < data.length; i++) {
|
|
48
|
+
const coef = buf[i];
|
|
49
|
+
if (coef === 0) continue;
|
|
50
|
+
for (let j = 0; j < gen.length; j++) buf[i + j] ^= gfMul(gen[j], coef);
|
|
51
|
+
}
|
|
52
|
+
return buf.slice(data.length);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 选能装下 byteLength 字节的最小版本;超出 v10 容量返回 undefined。 */
|
|
56
|
+
export function pickQrVersion(byteLength) {
|
|
57
|
+
for (let version = 1; version <= 10; version++) {
|
|
58
|
+
const capacityBits = DATA_CODEWORDS[version] * 8;
|
|
59
|
+
const overheadBits = 4 + (version <= 9 ? 8 : 16); // 模式指示符 + 字符计数
|
|
60
|
+
if (overheadBits + byteLength * 8 <= capacityBits) return version;
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* byte 模式位流 → 最终码字序列(数据块与纠错块按规范交错)。
|
|
67
|
+
* 位流 = 0100(byte 模式)+ 字符计数 + 数据字节 + 终止符 + 字节对齐 + 0xEC/0x11 补齐。
|
|
68
|
+
*/
|
|
69
|
+
export function buildQrCodewords(bytes, version) {
|
|
70
|
+
const blocks = EC_BLOCKS_M[version];
|
|
71
|
+
if (!blocks) throw new Error(`不支持的二维码版本 ${version}`);
|
|
72
|
+
const capacityBits = DATA_CODEWORDS[version] * 8;
|
|
73
|
+
const bits = [];
|
|
74
|
+
const pushBits = (value, length) => {
|
|
75
|
+
for (let i = length - 1; i >= 0; i--) bits.push((value >> i) & 1);
|
|
76
|
+
};
|
|
77
|
+
pushBits(4, 4);
|
|
78
|
+
pushBits(bytes.length, version <= 9 ? 8 : 16);
|
|
79
|
+
for (const byte of bytes) pushBits(byte, 8);
|
|
80
|
+
pushBits(0, Math.min(4, capacityBits - bits.length));
|
|
81
|
+
while (bits.length % 8 !== 0) bits.push(0);
|
|
82
|
+
for (let i = 0; bits.length < capacityBits; i++) pushBits([0xec, 0x11][i % 2], 8);
|
|
83
|
+
|
|
84
|
+
const dataCodewords = [];
|
|
85
|
+
for (let i = 0; i < bits.length; i += 8) {
|
|
86
|
+
let byte = 0;
|
|
87
|
+
for (let j = 0; j < 8; j++) byte = (byte << 1) | bits[i + j];
|
|
88
|
+
dataCodewords.push(byte);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const dataBlocks = [];
|
|
92
|
+
const ecBlocks = [];
|
|
93
|
+
let offset = 0;
|
|
94
|
+
for (const [count, perBlock] of blocks.groups) {
|
|
95
|
+
for (let b = 0; b < count; b++) {
|
|
96
|
+
const block = dataCodewords.slice(offset, offset + perBlock);
|
|
97
|
+
offset += perBlock;
|
|
98
|
+
dataBlocks.push(block);
|
|
99
|
+
ecBlocks.push(rsEncode(block, blocks.ecPerBlock));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const out = [];
|
|
104
|
+
const maxDataLen = Math.max(...dataBlocks.map((b) => b.length));
|
|
105
|
+
for (let i = 0; i < maxDataLen; i++) for (const block of dataBlocks) if (i < block.length) out.push(block[i]);
|
|
106
|
+
for (let i = 0; i < blocks.ecPerBlock; i++) for (const block of ecBlocks) out.push(block[i]);
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 纠错生成多项式系数(QR 规范定义)。导出供单测用已知向量锚定 GF 运算。 */
|
|
111
|
+
export function qrEcGeneratorPoly(degree) {
|
|
112
|
+
let gen = [1];
|
|
113
|
+
for (let i = 0; i < degree; i++) gen = polyMul(gen, [1, GF_EXP[i]]);
|
|
114
|
+
return gen;
|
|
115
|
+
}
|