mslxdff 0.1.245 → 0.1.247
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/autostart-health.js +65 -0
- package/src/autostart.js +57 -1
- package/src/chat-pipeline/terminal-verdict.js +4 -4
- package/src/cli/commands/daemon.js +9 -1
- package/src/cli/commands/provider/index.js +6 -1
- package/src/cli/commands/provider/models.js +3 -0
- package/src/cli/commands/provider/todaycn-login.js +121 -0
- package/src/cli/commands/provider/todaycn-persona.js +117 -0
- package/src/cli/commands/system.js +21 -5
- package/src/cli/help.js +4 -4
- package/src/cli/index.js +0 -5
- package/src/cli/status.js +11 -4
- package/src/daemon.js +3 -3
- package/src/providers/classify.js +1 -1
- package/src/providers/codearts/stream.js +17 -0
- package/src/providers/dispatcher.js +1 -1
- package/src/providers/railway-endpoints.js +192 -0
- package/src/providers/railway.js +111 -45
- package/src/providers/registry.js +8 -2
- package/src/providers/share-keys.js +2 -1
- package/src/providers/todaycn/account-store.js +169 -0
- package/src/providers/todaycn/chat.js +168 -0
- package/src/providers/todaycn/const.js +59 -0
- package/src/providers/todaycn/index.js +202 -0
- package/src/providers/todaycn/models.js +93 -0
- package/src/providers/todaycn/persona.js +103 -0
- package/src/providers/todaycn/prompt.js +194 -0
- package/src/providers/todaycn/session.js +107 -0
- package/src/providers/todaycn/sse.js +86 -0
- package/src/providers/todaycn/token.js +66 -0
- package/src/providers/todaycn.js +2 -0
- package/src/runtime/autostart-repair.js +108 -0
- package/src/runtime/bootstrap.js +1 -1
- package/src/runtime/proc-info.js +2 -2
- package/src/runtime/provider-gate.js +2 -2
- package/src/runtime/providers-setup.js +2 -4
- package/src/runtime/server-lifecycle.js +21 -48
- package/src/server.js +3 -3
- package/src/state/facade.js +1 -0
- package/src/state/merge.js +2 -0
- package/src/state/schemas/autostart.js +79 -0
- package/src/upstream-engine/index.js +2 -17
- package/src/upstream.js +1 -61
- package/src/cli/commands/multi-ip-pool-fetch.js +0 -173
- package/src/cli/commands/multi-ip-pool-test.js +0 -136
- package/src/cli/commands/multi-ip-pool.js +0 -83
- package/src/cli/commands/v6-pool.js +0 -123
- package/src/multi-ip-pool/config.js +0 -157
- package/src/multi-ip-pool/diagnose.js +0 -159
- package/src/multi-ip-pool/dial.js +0 -179
- package/src/multi-ip-pool/dispatch.js +0 -244
- package/src/multi-ip-pool/index.js +0 -174
- package/src/multi-ip-pool/nodes-fetch.js +0 -160
- package/src/multi-ip-pool/nodes.js +0 -205
- package/src/multi-ip-pool/report.js +0 -162
- package/src/multi-ip-pool/selftest.js +0 -168
- package/src/multi-ip-pool/standby.js +0 -157
- package/src/multi-ip-pool/tunnel.js +0 -291
- package/src/v6pool/claim.js +0 -157
- package/src/v6pool/config.js +0 -65
- package/src/v6pool/detect.js +0 -130
- package/src/v6pool/index.js +0 -157
- package/src/v6pool/prefix.js +0 -140
- package/src/v6pool/probe.js +0 -40
- package/src/v6pool/report.js +0 -104
- package/src/v6pool/rotate.js +0 -263
- package/src/v6pool/selftest.js +0 -178
- package/src/warp-pool/config.js +0 -74
- package/src/warp-pool/health.js +0 -106
- package/src/warp-pool/identity.js +0 -141
- package/src/warp-pool/index.js +0 -358
- package/src/warp-pool/keys.js +0 -29
- package/src/warp-pool/nodes.js +0 -95
- package/src/warp-pool/ports.js +0 -160
- package/src/warp-pool/register.js +0 -113
- package/src/warp-pool/report.js +0 -232
- package/src/warp-pool/revive.js +0 -168
- package/src/warp-pool/rotate.js +0 -214
- package/src/warp-pool/strategy.js +0 -43
- package/src/warp-pool/verdict.js +0 -69
- package/src/warp-pool/wireproxy.js +0 -162
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// todaycn 账号落盘单一源:auths/todaycn-<uid>.json(0600,tmp+rename)与 state.providerConfigs.todaycn.keys 同步。
|
|
2
|
+
// 号 = refreshCredential(实测不轮换,可长期复用);uid/name/deviceId 只进账号文档,
|
|
3
|
+
// 不进 providerConfigs —— 规避「providerConfig 重建路径静默丢字段」的既有故障类(对齐 zcode 的 deviceMid 处理)。
|
|
4
|
+
|
|
5
|
+
import { writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync, readdirSync, readFileSync, chmodSync } from "node:fs";
|
|
6
|
+
import { join, dirname } from "node:path";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { isTestEnv, defaultStateFile } from "../../state/store.js";
|
|
9
|
+
|
|
10
|
+
const ACCOUNT_PREFIX = "todaycn-";
|
|
11
|
+
const PROVIDER = "todayai";
|
|
12
|
+
|
|
13
|
+
export function todaycnAuthDir({ explicit = "", testEnv = false, stateFile } = {}) {
|
|
14
|
+
if (explicit) return explicit;
|
|
15
|
+
if (testEnv) return join(tmpdir(), "mslxdff-test-auths");
|
|
16
|
+
return join(dirname(stateFile), "auths");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function resolveTodaycnAuthDir() {
|
|
20
|
+
return todaycnAuthDir({
|
|
21
|
+
explicit: process.env.MSLXDFF_TODAYCN_AUTH_DIR || "",
|
|
22
|
+
testEnv: isTestEnv(),
|
|
23
|
+
stateFile: defaultStateFile(),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 只读兜底:账本旁 auths/ 为主,cwd/auths 为辅(旧副本不复活靠 remove 扫全部,见下)。 */
|
|
28
|
+
export function resolveTodaycnAuthDirs() {
|
|
29
|
+
const primary = resolveTodaycnAuthDir();
|
|
30
|
+
const cwdDir = join(process.cwd(), "auths");
|
|
31
|
+
return primary === cwdDir ? [primary] : [primary, cwdDir];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function accountFilePath(uid, dir) {
|
|
35
|
+
return join(dir, `${ACCOUNT_PREFIX}${uid}.json`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 列出全部落盘账号(去重按 uid,文件损坏即跳过)。 */
|
|
39
|
+
export function listTodaycnAccountDocs({ dirs } = {}) {
|
|
40
|
+
const out = [];
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
for (const dir of dirs || resolveTodaycnAuthDirs()) {
|
|
43
|
+
let files = [];
|
|
44
|
+
try {
|
|
45
|
+
if (!existsSync(dir)) continue;
|
|
46
|
+
files = readdirSync(dir).filter((f) => f.startsWith(ACCOUNT_PREFIX) && f.endsWith(".json"));
|
|
47
|
+
} catch { continue; }
|
|
48
|
+
for (const f of files) {
|
|
49
|
+
try {
|
|
50
|
+
const doc = JSON.parse(readFileSync(join(dir, f), "utf8"));
|
|
51
|
+
const uid = doc?.account?.uid;
|
|
52
|
+
const cred = doc?.auth?.refreshCredential;
|
|
53
|
+
if (!uid || !cred) continue;
|
|
54
|
+
if (seen.has(String(uid))) continue;
|
|
55
|
+
seen.add(String(uid));
|
|
56
|
+
out.push({
|
|
57
|
+
uid: String(uid),
|
|
58
|
+
refreshCredential: String(cred),
|
|
59
|
+
name: String(doc?.account?.name || ""),
|
|
60
|
+
email: String(doc?.account?.email || ""),
|
|
61
|
+
deviceId: String(doc?.auth?.deviceId || ""),
|
|
62
|
+
optionId: String(doc?.auth?.optionId || ""),
|
|
63
|
+
file: join(dir, f),
|
|
64
|
+
dir,
|
|
65
|
+
doc,
|
|
66
|
+
});
|
|
67
|
+
} catch {}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function readTodaycnAccountDoc(uid, { dir = resolveTodaycnAuthDir() } = {}) {
|
|
74
|
+
try { return JSON.parse(readFileSync(accountFilePath(uid, dir), "utf8")); } catch { return null; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function writeTodaycnAccountFile({ uid, refreshCredential, name = "", email = "", deviceId = "", optionId = "" }, { dir = resolveTodaycnAuthDir() } = {}) {
|
|
78
|
+
if (!uid || !refreshCredential) throw new Error("writeTodaycnAccountFile: 缺少 uid/refreshCredential");
|
|
79
|
+
mkdirSync(dir, { recursive: true });
|
|
80
|
+
const doc = { account: { uid, name, email }, auth: { provider: PROVIDER, refreshCredential, deviceId, optionId } };
|
|
81
|
+
const fp = accountFilePath(uid, dir);
|
|
82
|
+
const tmp = `${fp}.tmp`;
|
|
83
|
+
writeFileSync(tmp, JSON.stringify(doc, null, 2), { mode: 0o600 });
|
|
84
|
+
try {
|
|
85
|
+
if (existsSync(fp)) { try { chmodSync(fp, 0o600); } catch {} unlinkSync(fp); }
|
|
86
|
+
renameSync(tmp, fp);
|
|
87
|
+
} catch {
|
|
88
|
+
writeFileSync(fp, JSON.stringify(doc, null, 2), { mode: 0o600 });
|
|
89
|
+
try { unlinkSync(tmp); } catch {}
|
|
90
|
+
}
|
|
91
|
+
try { chmodSync(fp, 0o600); } catch {}
|
|
92
|
+
return fp;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 落盘 + 同步 providerConfigs.keys(只增不减;spread cur 保留 allowlist/allowAnyModels 等既有字段)。 */
|
|
96
|
+
export async function saveTodaycnAccount({ uid, refreshCredential, name = "", email = "", deviceId = "", optionId = "", dir, file } = {}) {
|
|
97
|
+
if (!uid || !refreshCredential) throw new Error("saveTodaycnAccount: 缺少 uid/refreshCredential");
|
|
98
|
+
const targetDir = dir || resolveTodaycnAuthDir();
|
|
99
|
+
const existing = readTodaycnAccountDoc(uid, { dir: targetDir });
|
|
100
|
+
const fp = writeTodaycnAccountFile(
|
|
101
|
+
{
|
|
102
|
+
uid,
|
|
103
|
+
refreshCredential,
|
|
104
|
+
name: name || String(existing?.account?.name || ""),
|
|
105
|
+
email: email || String(existing?.account?.email || ""),
|
|
106
|
+
deviceId: deviceId || String(existing?.auth?.deviceId || ""),
|
|
107
|
+
optionId: optionId || String(existing?.auth?.optionId || ""),
|
|
108
|
+
},
|
|
109
|
+
{ dir: targetDir },
|
|
110
|
+
);
|
|
111
|
+
const { loadProviderConfig, saveProviderConfig } = await import("../../state.js");
|
|
112
|
+
const opts = file ? { file } : {};
|
|
113
|
+
const cur = loadProviderConfig("todaycn", opts) || {};
|
|
114
|
+
const keys = [...new Set([...(Array.isArray(cur.keys) ? cur.keys : []), refreshCredential])];
|
|
115
|
+
saveProviderConfig("todaycn", { ...cur, keys }, opts);
|
|
116
|
+
return { file: fp, keys: keys.length, updated: Boolean(existing) };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 删号:扫全部候选目录(防旧副本复活),并从 providerConfigs.keys 摘掉该号。 */
|
|
120
|
+
export async function removeTodaycnAccount({ uid, refreshCredential = "", dirs, file } = {}) {
|
|
121
|
+
const removed = [];
|
|
122
|
+
for (const dir of dirs || resolveTodaycnAuthDirs()) {
|
|
123
|
+
const docs = [];
|
|
124
|
+
try {
|
|
125
|
+
if (!existsSync(dir)) continue;
|
|
126
|
+
for (const f of readdirSync(dir).filter((x) => x.startsWith(ACCOUNT_PREFIX) && x.endsWith(".json"))) {
|
|
127
|
+
try {
|
|
128
|
+
const doc = JSON.parse(readFileSync(join(dir, f), "utf8"));
|
|
129
|
+
if (uid && String(doc?.account?.uid) !== String(uid)) continue;
|
|
130
|
+
if (!uid && refreshCredential && String(doc?.auth?.refreshCredential) !== refreshCredential) continue;
|
|
131
|
+
docs.push({ f, cred: String(doc?.auth?.refreshCredential || "") });
|
|
132
|
+
} catch {}
|
|
133
|
+
}
|
|
134
|
+
} catch { continue; }
|
|
135
|
+
for (const d of docs) {
|
|
136
|
+
try { unlinkSync(join(dir, d.f)); removed.push({ file: join(dir, d.f), refreshCredential: d.cred }); } catch {}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (removed.length) {
|
|
140
|
+
const { loadProviderConfig, saveProviderConfig } = await import("../../state.js");
|
|
141
|
+
const opts = file ? { file } : {};
|
|
142
|
+
const cur = loadProviderConfig("todaycn", opts) || {};
|
|
143
|
+
const drop = new Set(removed.map((r) => r.refreshCredential).filter(Boolean));
|
|
144
|
+
const keys = (Array.isArray(cur.keys) ? cur.keys : []).filter((k) => !drop.has(String(k)));
|
|
145
|
+
saveProviderConfig("todaycn", { ...cur, keys }, opts);
|
|
146
|
+
}
|
|
147
|
+
return { removed };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 记「号↔模型位」绑定:账号级设置的本地事实缓存,供选路与状态展示;失败静默,不影响请求。 */
|
|
151
|
+
export async function setTodaycnAccountOption({ uid, optionId, dir } = {}) {
|
|
152
|
+
if (!uid || !optionId) return { ok: false, reason: "缺少 uid/optionId" };
|
|
153
|
+
const targetDir = dir || resolveTodaycnAuthDir();
|
|
154
|
+
const doc = readTodaycnAccountDoc(uid, { dir: targetDir });
|
|
155
|
+
const cred = String(doc?.auth?.refreshCredential || "");
|
|
156
|
+
if (!cred) return { ok: false, reason: "账号文档不存在" };
|
|
157
|
+
writeTodaycnAccountFile(
|
|
158
|
+
{
|
|
159
|
+
uid,
|
|
160
|
+
refreshCredential: cred,
|
|
161
|
+
name: String(doc?.account?.name || ""),
|
|
162
|
+
email: String(doc?.account?.email || ""),
|
|
163
|
+
deviceId: String(doc?.auth?.deviceId || ""),
|
|
164
|
+
optionId: String(optionId),
|
|
165
|
+
},
|
|
166
|
+
{ dir: targetDir },
|
|
167
|
+
);
|
|
168
|
+
return { ok: true, optionId: String(optionId) };
|
|
169
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// todaycn 单次上游尝试(不含轮换):一枚 refreshCredential → 一次 POST /v1/messages + 轮询 /v2/messages。
|
|
2
|
+
// 失败经内部头 x-mslxdff-todaycn-kind 交回 index.js 决定冷却档位(对齐 zcode/agentrouter 的分工):
|
|
3
|
+
// auth(号失效)| quota(限流/额度)| empty(发出去但超时无 final 回复)| server | network | param | unknown
|
|
4
|
+
//
|
|
5
|
+
// 实测约束(别再改回去):
|
|
6
|
+
// 1) 无流式:上游 202 + GET 轮询;客户端要 stream:true 时由 sse.js 自造帧。
|
|
7
|
+
// 2) threadId 续写无效(消息不落库、无回复)→ 每轮新建 thread,历史全部重放进 content。
|
|
8
|
+
// 3) 轮询按 originClientMessageId 认自己的回复;认不到再退化为「发送时间之后的最新 final」。
|
|
9
|
+
|
|
10
|
+
import { compatFetch, uuid } from "../../compat.js";
|
|
11
|
+
import { buildTodaycnContent, parseTodaycnReply } from "./prompt.js";
|
|
12
|
+
import { completionToResponse } from "./sse.js";
|
|
13
|
+
import {
|
|
14
|
+
TODAYCN_API_BASE,
|
|
15
|
+
TODAYCN_APP_VERSION,
|
|
16
|
+
TODAYCN_CAPABILITIES,
|
|
17
|
+
TODAYCN_CLIENT_PLATFORM,
|
|
18
|
+
TODAYCN_DEFAULT_DEVICE_ID,
|
|
19
|
+
TODAYCN_POLL_INTERVAL_MS,
|
|
20
|
+
TODAYCN_POLL_TIMEOUT_MS,
|
|
21
|
+
TODAYCN_UA,
|
|
22
|
+
} from "./const.js";
|
|
23
|
+
|
|
24
|
+
export const TODAYCN_KIND_HEADER = "x-mslxdff-todaycn-kind";
|
|
25
|
+
export const TODAYCN_ACCOUNT_HEADER = "x-mslxdff-todaycn-account";
|
|
26
|
+
|
|
27
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
28
|
+
|
|
29
|
+
export function classifyStatus(status) {
|
|
30
|
+
if (status === 401 || status === 403) return "auth";
|
|
31
|
+
if (status === 429) return "quota";
|
|
32
|
+
if (status >= 500) return "server";
|
|
33
|
+
if (status >= 400) return "param";
|
|
34
|
+
return "unknown";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function errRes(status, msg, kind = "", extra = {}) {
|
|
38
|
+
return new Response(JSON.stringify({ error: { message: msg, type: kind || "upstream_error" } }), {
|
|
39
|
+
status,
|
|
40
|
+
headers: { "Content-Type": "application/json", ...(kind ? { [TODAYCN_KIND_HEADER]: kind } : {}), ...extra },
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function withHeaders(res, extra = {}) {
|
|
45
|
+
const h = new Headers(res.headers);
|
|
46
|
+
for (const [k, v] of Object.entries(extra)) if (v !== undefined && v !== null && v !== "") h.set(k, v);
|
|
47
|
+
return new Response(res.body, { status: res.status, headers: h });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function buildHeaders(token, deviceId) {
|
|
51
|
+
return {
|
|
52
|
+
Authorization: `Bearer ${token}`,
|
|
53
|
+
"User-Agent": TODAYCN_UA,
|
|
54
|
+
Origin: "https://todayai.cn",
|
|
55
|
+
Accept: "application/json",
|
|
56
|
+
"Content-Type": "application/json",
|
|
57
|
+
"Accept-Language": "zh-CN",
|
|
58
|
+
"X-App-Version": TODAYCN_APP_VERSION,
|
|
59
|
+
"X-Client-Platform": TODAYCN_CLIENT_PLATFORM,
|
|
60
|
+
"X-Device-Id": deviceId || TODAYCN_DEFAULT_DEVICE_ID,
|
|
61
|
+
"X-Client-Capabilities": TODAYCN_CAPABILITIES,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** HTTP 通道(可注入 exchange 顶掉,便于单测不触网)。 */
|
|
66
|
+
export function createTodaycnHttp({ fetchImpl, apiBase = TODAYCN_API_BASE } = {}) {
|
|
67
|
+
const call = fetchImpl || compatFetch;
|
|
68
|
+
async function send(payload, token, deviceId) {
|
|
69
|
+
const res = await call(`${apiBase}/v1/messages`, { method: "POST", headers: buildHeaders(token, deviceId), body: JSON.stringify(payload) });
|
|
70
|
+
const text = await res.text().catch(() => "");
|
|
71
|
+
let json = null;
|
|
72
|
+
try { json = JSON.parse(text); } catch {}
|
|
73
|
+
return { status: res.status, json, text };
|
|
74
|
+
}
|
|
75
|
+
async function poll(threadId, token, deviceId) {
|
|
76
|
+
const res = await call(`${apiBase}/v2/messages?threadId=${encodeURIComponent(threadId)}&limit=20`, { headers: buildHeaders(token, deviceId) });
|
|
77
|
+
const json = await res.json().catch(() => null);
|
|
78
|
+
return { status: res.status, json };
|
|
79
|
+
}
|
|
80
|
+
return { send, poll };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 从列表里认这一轮的最终回复:优先 originClientMessageId 命中,退化为发送时间后的最新 final。 */
|
|
84
|
+
export function pickFinalReply(json, clientMessageId, sinceIso = "") {
|
|
85
|
+
const data = Array.isArray(json?.data) ? json.data : [];
|
|
86
|
+
const finals = data.filter((m) => m?.role === "assistant" && m?.isFinal);
|
|
87
|
+
const mine = finals.filter(
|
|
88
|
+
(m) => m.originClientMessageId === clientMessageId ||
|
|
89
|
+
(Array.isArray(m.originClientMessageIds) && m.originClientMessageIds.includes(clientMessageId)),
|
|
90
|
+
);
|
|
91
|
+
if (mine.length) return mine[mine.length - 1];
|
|
92
|
+
const after = finals.filter((m) => !sinceIso || String(m.createdAt || "") >= sinceIso);
|
|
93
|
+
return after.length ? after[after.length - 1] : null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** v2 typed 正文在 messages[].content.text;v1 legacy 在 content 字符串。 */
|
|
97
|
+
export function messageText(m) {
|
|
98
|
+
if (Array.isArray(m?.messages) && m.messages.length) {
|
|
99
|
+
return m.messages.map((p) => String(p?.content?.text ?? p?.text ?? "")).join("\n");
|
|
100
|
+
}
|
|
101
|
+
return String(m?.content ?? "");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 单次尝试。返回 Response:
|
|
106
|
+
* 成功 = 200(stream:true 出 SSE,否则 JSON chat.completion;带 x-mslxdff-todaycn-account 回显号)
|
|
107
|
+
* 失败 = 非 200 + x-mslxdff-todaycn-kind(auth/quota/empty/server/network/param/unknown)
|
|
108
|
+
*/
|
|
109
|
+
export async function forwardTodaycnChat({
|
|
110
|
+
body = {},
|
|
111
|
+
credential,
|
|
112
|
+
uid = "",
|
|
113
|
+
deviceId = "",
|
|
114
|
+
tokenStore,
|
|
115
|
+
exchange,
|
|
116
|
+
fetchImpl,
|
|
117
|
+
pollIntervalMs = TODAYCN_POLL_INTERVAL_MS,
|
|
118
|
+
pollTimeoutMs = TODAYCN_POLL_TIMEOUT_MS,
|
|
119
|
+
contentMaxChars,
|
|
120
|
+
clock = Date.now,
|
|
121
|
+
} = {}) {
|
|
122
|
+
const ex = exchange || createTodaycnHttp({ fetchImpl });
|
|
123
|
+
const tok = await tokenStore.getToken(credential);
|
|
124
|
+
if (!tok.ok) {
|
|
125
|
+
const kind = tok.authFailed ? "auth" : "network";
|
|
126
|
+
return errRes(tok.authFailed ? 401 : 502, `todaycn: 令牌获取失败(${tok.reason})`, kind);
|
|
127
|
+
}
|
|
128
|
+
const model = String(body.model || "");
|
|
129
|
+
const content = buildTodaycnContent({ messages: body.messages || [], tools: body.tools || [], model, maxChars: contentMaxChars });
|
|
130
|
+
const clientMessageId = uuid();
|
|
131
|
+
const sent = await ex.send({ clientMessageId, messageType: "text", content, sourceDeviceId: deviceId || undefined }, tok.token, deviceId);
|
|
132
|
+
if (sent.status !== 202) {
|
|
133
|
+
const kind = classifyStatus(sent.status);
|
|
134
|
+
return errRes(kind === "auth" ? 401 : kind === "quota" ? 429 : kind === "param" ? 400 : 502,
|
|
135
|
+
`todaycn: 发送失败 ${sent.status} ${String(sent.text || "").slice(0, 200)}`, kind);
|
|
136
|
+
}
|
|
137
|
+
const threadId = String(sent.json?.threadId || "");
|
|
138
|
+
if (!threadId) return errRes(502, "todaycn: 202 响应里没有 threadId", "unknown");
|
|
139
|
+
const sinceIso = String(sent.json?.createdAt || "");
|
|
140
|
+
|
|
141
|
+
const deadline = clock() + pollTimeoutMs;
|
|
142
|
+
let lastPollStatus = 0;
|
|
143
|
+
while (clock() < deadline) {
|
|
144
|
+
await sleep(pollIntervalMs);
|
|
145
|
+
const p = await ex.poll(threadId, tok.token, deviceId);
|
|
146
|
+
lastPollStatus = p.status;
|
|
147
|
+
if (p.status === 401 || p.status === 403) return errRes(401, `todaycn: 轮询授权失效 ${p.status}`, "auth");
|
|
148
|
+
if (p.status !== 200) continue;
|
|
149
|
+
const hit = pickFinalReply(p.json, clientMessageId, sinceIso);
|
|
150
|
+
if (!hit) continue;
|
|
151
|
+
const parsed = parseTodaycnReply(messageText(hit));
|
|
152
|
+
const completion = {
|
|
153
|
+
id: `chatcmpl_${String(hit.id || uuid()).replace(/[^A-Za-z0-9]/g, "").slice(0, 24)}`,
|
|
154
|
+
object: "chat.completion",
|
|
155
|
+
created: Math.floor(new Date(hit.createdAt || clock()).getTime() / 1000) || Math.floor(clock() / 1000),
|
|
156
|
+
model: model || "todaycn",
|
|
157
|
+
choices: [{
|
|
158
|
+
index: 0,
|
|
159
|
+
message: { role: "assistant", content: parsed.content || null, ...(parsed.tool_calls.length ? { tool_calls: parsed.tool_calls } : {}) },
|
|
160
|
+
logprobs: null,
|
|
161
|
+
finish_reason: parsed.tool_calls.length ? "tool_calls" : "stop",
|
|
162
|
+
}],
|
|
163
|
+
};
|
|
164
|
+
const res = completionToResponse(completion, { stream: body.stream === true });
|
|
165
|
+
return withHeaders(res, { [TODAYCN_ACCOUNT_HEADER]: uid, "x-mslxdff-todaycn-strict": parsed.strict ? "1" : "0" });
|
|
166
|
+
}
|
|
167
|
+
return errRes(504, `todaycn: 上游 ${Math.round(pollTimeoutMs / 1000)}s 内没有给出最终回复(轮询末次状态 ${lastPollStatus})`, "empty");
|
|
168
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// todaycn(Today AI · 今日工作助手,api.todayai.cn)常量:域名、端点、客户端指纹、轮询与令牌默认值。
|
|
2
|
+
// 指纹头复刻桌面端(TodayCN/1.23.0 / Electron 33)——上游按客户端形状判决,缺头可能落不同路由。
|
|
3
|
+
// 凭据(refreshCredential)一律不进本文件:落盘见 account-store.js,本机导入见 session.js。
|
|
4
|
+
|
|
5
|
+
export const TODAYCN_ID = "todaycn";
|
|
6
|
+
export const TODAYCN_AUTH_BASE = "https://auth.todayai.cn";
|
|
7
|
+
export const TODAYCN_API_BASE = "https://api.todayai.cn";
|
|
8
|
+
|
|
9
|
+
export const TODAYCN_UA =
|
|
10
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " +
|
|
11
|
+
"TodayCN/1.23.0 Chrome/130.0.0.0 Electron/33.0.0 Safari/537.36";
|
|
12
|
+
|
|
13
|
+
/** 桌面端 X-Client-Capabilities 全量(实测随聊天请求一起发,缺项不影响文本链路,但保持复刻)。 */
|
|
14
|
+
export const TODAYCN_CAPABILITIES = [
|
|
15
|
+
"chat.automation_card.v1",
|
|
16
|
+
"chat.brief_card.v1",
|
|
17
|
+
"chat.browser.v1",
|
|
18
|
+
"chat.connector_automation_card.v1",
|
|
19
|
+
"chat.connector_auth_card.v1",
|
|
20
|
+
"chat.follow_up_recommendations.v1",
|
|
21
|
+
"chat.qa_single_select.immediate.v1",
|
|
22
|
+
"chat.qa_cardflow_single.v1",
|
|
23
|
+
"chat.message_reactions.unicode.v1",
|
|
24
|
+
"connectors.account_management.v1",
|
|
25
|
+
"pricing.cn_usage_locked_recovery.v1",
|
|
26
|
+
].join(",");
|
|
27
|
+
|
|
28
|
+
export const TODAYCN_APP_VERSION = "2.0.0";
|
|
29
|
+
export const TODAYCN_CLIENT_PLATFORM = "windows";
|
|
30
|
+
/** 缺省设备 id:云设备恒在线(真机设备 id 由 auths 文档带,见 account-store.js)。 */
|
|
31
|
+
export const TODAYCN_DEFAULT_DEVICE_ID = "d_cloud";
|
|
32
|
+
|
|
33
|
+
/** 平台模型位前缀:对外剥掉(todaycn/deepseek-v4.1-flash),切设置时补回。 */
|
|
34
|
+
export const TODAYCN_MODEL_PREFIX = "model.";
|
|
35
|
+
export const TODAYCN_DEFAULT_OPTION = "model.deepseek-v4.1-flash";
|
|
36
|
+
|
|
37
|
+
export const TODAYCN_POLL_INTERVAL_MS = 2500;
|
|
38
|
+
/** 发出后等 final 回复的上限;超时按 empty(本号此刻不出话)换号。 */
|
|
39
|
+
export const TODAYCN_POLL_TIMEOUT_MS = 75_000;
|
|
40
|
+
/** accessToken 实测 10 分钟 TTL,提前 1 分钟重刷。 */
|
|
41
|
+
export const TODAYCN_TOKEN_SKEW_MS = 60_000;
|
|
42
|
+
|
|
43
|
+
/** 本机客户端数据目录覆盖(自动化/多账号测试用)。 */
|
|
44
|
+
export const TODAYCN_DESKTOP_DIR_ENV = "MSLXDFF_TODAYCN_STATE_DIR";
|
|
45
|
+
|
|
46
|
+
/** 平台 optionId → 对外模型 id(model.deepseek-v4.1-flash → deepseek-v4.1-flash;mode.* 原样留)。 */
|
|
47
|
+
export function toGatewayModelId(optionId = "") {
|
|
48
|
+
const raw = String(optionId).trim();
|
|
49
|
+
if (!raw) return "";
|
|
50
|
+
return raw.startsWith(TODAYCN_MODEL_PREFIX) ? raw.slice(TODAYCN_MODEL_PREFIX.length) : raw;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 对外模型 id → 平台 optionId(幂等:已带 model./mode. 前缀的原样返回)。 */
|
|
54
|
+
export function toPlatformOptionId(modelId = "") {
|
|
55
|
+
const raw = String(modelId).trim();
|
|
56
|
+
if (!raw) return "";
|
|
57
|
+
if (raw.startsWith(TODAYCN_MODEL_PREFIX) || raw.startsWith("mode.")) return raw;
|
|
58
|
+
return TODAYCN_MODEL_PREFIX + raw;
|
|
59
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// todaycn(Today AI · 今日工作助手)供应商工厂:
|
|
2
|
+
// 多号轮换(keyring 多枚 refreshCredential)+ 分档冷却 + 目录(pricing/status 的 modelOptions)
|
|
3
|
+
// + 模型位(账号级,故按「号↔模型」绑定:能切就切,切不了就换号)。
|
|
4
|
+
//
|
|
5
|
+
// 冷却分档(kind 由 chat.js 经内部头交回):
|
|
6
|
+
// auth → 长冷却(号失效,refresh 也失败) quota → 长冷却(限流/额度,按日重置口径)
|
|
7
|
+
// empty → 中冷却 + **当场换号**(发出去但超时无 final:本号此刻不出话,Today 特有的一类)
|
|
8
|
+
// server/network → 短冷却;param/unknown → 不冷却(换号无意义,如实透出)
|
|
9
|
+
|
|
10
|
+
import { compatFetch } from "../../compat.js";
|
|
11
|
+
import { envInt } from "../base.js";
|
|
12
|
+
import { createKeyRing } from "../keyring.js";
|
|
13
|
+
import { loadProviderKeys } from "../../state.js";
|
|
14
|
+
import { createTokenStore } from "./token.js";
|
|
15
|
+
import { createModelsService, parseModelStatus } from "./models.js";
|
|
16
|
+
import { buildHeaders, forwardTodaycnChat, TODAYCN_ACCOUNT_HEADER, TODAYCN_KIND_HEADER } from "./chat.js";
|
|
17
|
+
import { listTodaycnAccountDocs, setTodaycnAccountOption } from "./account-store.js";
|
|
18
|
+
import {
|
|
19
|
+
TODAYCN_API_BASE,
|
|
20
|
+
TODAYCN_DEFAULT_OPTION,
|
|
21
|
+
TODAYCN_DEFAULT_DEVICE_ID,
|
|
22
|
+
TODAYCN_POLL_INTERVAL_MS,
|
|
23
|
+
TODAYCN_POLL_TIMEOUT_MS,
|
|
24
|
+
toPlatformOptionId,
|
|
25
|
+
} from "./const.js";
|
|
26
|
+
|
|
27
|
+
const COOLDOWN_BY_KIND = { auth: "long", quota: "long", empty: "empty", server: "short", network: "short" };
|
|
28
|
+
|
|
29
|
+
function jsonRes(status, payload, extra = {}) {
|
|
30
|
+
return new Response(JSON.stringify(payload), { status, headers: { "Content-Type": "application/json", ...extra } });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function createTodaycnProvider({
|
|
34
|
+
id = "todaycn",
|
|
35
|
+
apiKeys,
|
|
36
|
+
file,
|
|
37
|
+
fetchImpl,
|
|
38
|
+
cooldownMs = envInt("MSLXDFF_TODAYCN_COOLDOWN_MS", 30_000),
|
|
39
|
+
quotaCooldownMs = envInt("MSLXDFF_TODAYCN_QUOTA_COOLDOWN_MS", 3_600_000),
|
|
40
|
+
emptyCooldownMs = envInt("MSLXDFF_TODAYCN_EMPTY_COOLDOWN_MS", 120_000),
|
|
41
|
+
pollIntervalMs = envInt("MSLXDFF_TODAYCN_POLL_INTERVAL_MS", TODAYCN_POLL_INTERVAL_MS),
|
|
42
|
+
pollTimeoutMs = envInt("MSLXDFF_TODAYCN_POLL_TIMEOUT_MS", TODAYCN_POLL_TIMEOUT_MS),
|
|
43
|
+
apiBase = TODAYCN_API_BASE,
|
|
44
|
+
switchModel = process.env.MSLXDFF_TODAYCN_SWITCH_MODEL !== "0",
|
|
45
|
+
} = {}) {
|
|
46
|
+
const keys = (() => {
|
|
47
|
+
if (Array.isArray(apiKeys) && apiKeys.length) return [...new Set(apiKeys.map((k) => String(k).trim()).filter(Boolean))];
|
|
48
|
+
try { return loadProviderKeys(id, file ? { file } : {}); } catch { return []; }
|
|
49
|
+
})();
|
|
50
|
+
const ring = createKeyRing(keys, { cooldownMs });
|
|
51
|
+
const tokenStore = createTokenStore({ fetchImpl });
|
|
52
|
+
// 切模型位的串行队列:同号并发请求不能同时改账号级设置(改串行,避免互相踩)
|
|
53
|
+
const switchLocks = new Map();
|
|
54
|
+
|
|
55
|
+
function accountFor(credential) {
|
|
56
|
+
try {
|
|
57
|
+
const hit = listTodaycnAccountDocs().find((d) => d.refreshCredential === credential);
|
|
58
|
+
return hit || null;
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 404 说明账号文档缺 uid;此时仍可发(uid 只用于回显/记账)。 */
|
|
65
|
+
function identityFor(credential) {
|
|
66
|
+
const acct = accountFor(credential);
|
|
67
|
+
return { uid: acct?.uid || "", deviceId: acct?.deviceId || "", optionId: acct?.optionId || "" };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function callApi(path, { method = "GET", token, body } = {}) {
|
|
71
|
+
const call = fetchImpl || compatFetch;
|
|
72
|
+
const res = await call(`${apiBase}${path}`, {
|
|
73
|
+
method,
|
|
74
|
+
headers: {
|
|
75
|
+
...buildHeaders(token, ""),
|
|
76
|
+
},
|
|
77
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
78
|
+
});
|
|
79
|
+
const text = await res.text().catch(() => "");
|
|
80
|
+
let json = null;
|
|
81
|
+
try { json = JSON.parse(text); } catch {}
|
|
82
|
+
return { status: res.status, json, text };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const modelsSvc = createModelsService({
|
|
86
|
+
id,
|
|
87
|
+
hasAccount: () => ring.keys.length > 0,
|
|
88
|
+
loadOptions: async () => {
|
|
89
|
+
const seen = new Map(); // optionId → option(多号并集:谁有哪个模型谁顶上)
|
|
90
|
+
for (const key of ring.keys) {
|
|
91
|
+
try {
|
|
92
|
+
const tok = await tokenStore.getToken(key);
|
|
93
|
+
if (!tok.ok) continue;
|
|
94
|
+
const r = await callApi("/v1/pricing/status", { token: tok.token });
|
|
95
|
+
if (r.status !== 200) continue;
|
|
96
|
+
for (const o of parseModelStatus(r.json).options) if (!seen.has(o.optionId)) seen.set(o.optionId, o);
|
|
97
|
+
} catch {}
|
|
98
|
+
}
|
|
99
|
+
return [...seen.values()];
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 让本号处于请求的模型位:已是目标位直接通过;否则切设置(账号级、控制面免费)。
|
|
105
|
+
* 切不动(400)说明该号没有这个模型 → 交调用方换号。
|
|
106
|
+
*/
|
|
107
|
+
async function ensureOption(credential, want, current) {
|
|
108
|
+
if (!want || want === current) return { ok: true, switched: false };
|
|
109
|
+
if (!switchModel) return { ok: false, reason: "MSLXDFF_TODAYCN_SWITCH_MODEL=0 且本号未绑定该模型" };
|
|
110
|
+
const prev = switchLocks.get(credential) || Promise.resolve();
|
|
111
|
+
const task = prev.then(async () => {
|
|
112
|
+
const tok = await tokenStore.getToken(credential);
|
|
113
|
+
if (!tok.ok) return { ok: false, reason: `令牌获取失败(${tok.reason})` };
|
|
114
|
+
const r = await callApi("/v1/pricing/model-option", { method: "PUT", token: tok.token, body: { optionId: want } });
|
|
115
|
+
if (r.status === 200) {
|
|
116
|
+
const acct = accountFor(credential);
|
|
117
|
+
if (acct?.uid) { try { await setTodaycnAccountOption({ uid: acct.uid, optionId: want }); } catch {} }
|
|
118
|
+
return { ok: true, switched: true };
|
|
119
|
+
}
|
|
120
|
+
return { ok: false, reason: `切模型位失败 ${r.status} ${String(r.text || "").slice(0, 120)}`, status: r.status };
|
|
121
|
+
});
|
|
122
|
+
switchLocks.set(credential, task.catch(() => {}));
|
|
123
|
+
return task;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function chat(body, opts = {}) {
|
|
127
|
+
if (!ring.keys.length) {
|
|
128
|
+
return jsonRes(401, { error: { message: "todaycn: 无可用账号 —— 先运行 mslxdff -provider todaycn login", type: "auth_error" } });
|
|
129
|
+
}
|
|
130
|
+
const want = toPlatformOptionId(String(body?.model || "").replace(/^todaycn\//, "")) || TODAYCN_DEFAULT_OPTION;
|
|
131
|
+
const total = ring.keys.length;
|
|
132
|
+
let lastRes = null;
|
|
133
|
+
for (let hop = 0; hop <= total; hop += 1) {
|
|
134
|
+
const key = ring.next();
|
|
135
|
+
if (!key) break;
|
|
136
|
+
const cx = identityFor(key);
|
|
137
|
+
const bind = await ensureOption(key, want, cx.optionId);
|
|
138
|
+
if (!bind.ok) {
|
|
139
|
+
lastRes = jsonRes(400, { error: { message: `todaycn: ${bind.reason}`, type: "model_unavailable" } }, { "x-mslxdff-todaycn-model-unavailable": want });
|
|
140
|
+
continue; // 该号没有这个模型:换号,不冷却
|
|
141
|
+
}
|
|
142
|
+
const res = await forwardTodaycnChat({
|
|
143
|
+
body,
|
|
144
|
+
credential: key,
|
|
145
|
+
uid: cx.uid,
|
|
146
|
+
deviceId: cx.deviceId || TODAYCN_DEFAULT_DEVICE_ID,
|
|
147
|
+
tokenStore,
|
|
148
|
+
fetchImpl,
|
|
149
|
+
pollIntervalMs,
|
|
150
|
+
pollTimeoutMs,
|
|
151
|
+
contentMaxChars: envInt("MSLXDFF_TODAYCN_MAX_CHARS", 120_000),
|
|
152
|
+
});
|
|
153
|
+
const kind = res.headers.get(TODAYCN_KIND_HEADER);
|
|
154
|
+
if (!kind) return res; // 成功(或非可冷却错误)
|
|
155
|
+
const mode = COOLDOWN_BY_KIND[kind] || "none";
|
|
156
|
+
if (mode === "long") ring.onError(key, quotaCooldownMs);
|
|
157
|
+
else if (mode === "empty") ring.onError(key, emptyCooldownMs);
|
|
158
|
+
else if (mode === "short") ring.onError(key, cooldownMs);
|
|
159
|
+
lastRes = res;
|
|
160
|
+
if (opts?.onAttempt) { try { opts.onAttempt({ credential: key, kind, uid: cx.uid }); } catch {} }
|
|
161
|
+
if (mode === "none") break;
|
|
162
|
+
if (ring.available() === 0) break;
|
|
163
|
+
}
|
|
164
|
+
if (lastRes) return lastRes;
|
|
165
|
+
return jsonRes(429, { error: { message: "todaycn: 账号暂不可用(冷却中,可能额度用尽或限流),请稍后重试", type: "all_cooling" } }, { "x-mslxdff-todaycn-all-cooling": "1" });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function listModels() {
|
|
169
|
+
return modelsSvc.listModels();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function preheat() {
|
|
173
|
+
try {
|
|
174
|
+
const list = await modelsSvc.listModels();
|
|
175
|
+
return list.length ? { ok: true } : { ok: false, error: "no catalog" };
|
|
176
|
+
} catch (e) {
|
|
177
|
+
return { ok: false, error: String(e?.message || e).slice(0, 120) };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function close() {}
|
|
182
|
+
|
|
183
|
+
async function chatWithKeys(body, keysOverride, opts) {
|
|
184
|
+
const tmp = createTodaycnProvider({ id, apiKeys: keysOverride, file, fetchImpl, cooldownMs, quotaCooldownMs, emptyCooldownMs, pollIntervalMs, pollTimeoutMs, apiBase, switchModel });
|
|
185
|
+
return tmp.chat(body, opts);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
id,
|
|
190
|
+
chat,
|
|
191
|
+
chatWithKeys,
|
|
192
|
+
listModels,
|
|
193
|
+
preheat,
|
|
194
|
+
close,
|
|
195
|
+
keyRing: ring,
|
|
196
|
+
tokenStore,
|
|
197
|
+
baseUrl: "todaycn://native",
|
|
198
|
+
// 测试/CLI 用:账号与号↔模型绑定的读出入口
|
|
199
|
+
accounts: () => ring.keys.map((k) => ({ credential: k, ...identityFor(k) })),
|
|
200
|
+
_accountHeader: TODAYCN_ACCOUNT_HEADER,
|
|
201
|
+
};
|
|
202
|
+
}
|