mslxdff 0.1.246 → 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/cli/commands/daemon.js +8 -0
- 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/status.js +11 -4
- 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/provider-gate.js +2 -2
- package/src/runtime/server-lifecycle.js +21 -48
- package/src/state/facade.js +1 -0
- package/src/state/merge.js +2 -0
- package/src/state/schemas/autostart.js +79 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// todaycn 模型目录:**源 = GET /v1/pricing/status 的 data.status.modelOptions.options[]**
|
|
2
|
+
// —— 那是账号「真正可选」的那份(本号实测 = 2 项:model.deepseek-v4.1-flash 1× / model.glm-5.3 4×)。
|
|
3
|
+
// /v1/llm/models 的 35 个 id 属「看得见、用不了」的内部目录(PUT /v1/pricing/model-option 一律
|
|
4
|
+
// 400 request.validation_failed),故**不挂**;将来若要挂,只作参考不进口径。
|
|
5
|
+
//
|
|
6
|
+
// 多号:目录取各号 options 的并集(谁有哪个模型谁顶上),每号记自己可选的集合,供 index.js 选路。
|
|
7
|
+
|
|
8
|
+
import { joinModelId } from "../model-id.js";
|
|
9
|
+
import { loadProviderAllowedModels, saveProviderAllowedModels } from "../../state.js";
|
|
10
|
+
import { TODAYCN_DEFAULT_OPTION, toGatewayModelId } from "./const.js";
|
|
11
|
+
|
|
12
|
+
const CACHE_TTL_MS = 10 * 60 * 1000;
|
|
13
|
+
const CREATED = 1761400000;
|
|
14
|
+
|
|
15
|
+
/** 从 pricing/status 响应里取 modelOptions(兼容 data.status 与裸 status 两种信封)。 */
|
|
16
|
+
export function parseModelStatus(json) {
|
|
17
|
+
const status = json?.data?.status ?? json?.status ?? json ?? {};
|
|
18
|
+
const mo = status?.modelOptions ?? json?.data?.modelOptions ?? json?.modelOptions ?? null;
|
|
19
|
+
const options = Array.isArray(mo?.options) ? mo.options : [];
|
|
20
|
+
return {
|
|
21
|
+
selectedOptionId: String(mo?.selectedOptionId || status?.modelOptionId || ""),
|
|
22
|
+
options: options
|
|
23
|
+
.map((o) => ({
|
|
24
|
+
optionId: String(o?.id || o?.optionId || ""),
|
|
25
|
+
title: String(o?.display?.title || ""),
|
|
26
|
+
subtitle: String(o?.display?.subtitle || ""),
|
|
27
|
+
disabled: Boolean(o?.disabled),
|
|
28
|
+
}))
|
|
29
|
+
.filter((o) => o.optionId),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 「消耗倍数:4×」→ "4x"(取不到给空串,界面回落 —)。 */
|
|
34
|
+
export function parseMultiplier(subtitle = "") {
|
|
35
|
+
const m = String(subtitle).match(/(\d+(?:\.\d+)?)\s*[×x]/i);
|
|
36
|
+
return m ? `${m[1]}x` : "";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 对外目录条目(OpenAI /v1/models 形状;照 zcode 的字段集,价格列放消耗倍率)。 */
|
|
40
|
+
export function buildTodaycnModelList({ id = "todaycn", options = [] } = {}) {
|
|
41
|
+
return options.map((o) => {
|
|
42
|
+
const raw = toGatewayModelId(o.optionId);
|
|
43
|
+
return {
|
|
44
|
+
id: joinModelId(id, raw),
|
|
45
|
+
object: "model",
|
|
46
|
+
created: CREATED,
|
|
47
|
+
owned_by: "todayai",
|
|
48
|
+
name: o.title || raw,
|
|
49
|
+
price: parseMultiplier(o.subtitle) || "—",
|
|
50
|
+
enable: !o.disabled,
|
|
51
|
+
free: false,
|
|
52
|
+
mark: o.optionId === TODAYCN_DEFAULT_OPTION ? "*" : "",
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 登录后播种 allowlist(只增不减,对齐 cline/zcode 先例,避免显式请求 403)。 */
|
|
58
|
+
export function seedTodaycnAllowlist({ ids = [], file } = {}) {
|
|
59
|
+
const opts = file ? { file } : {};
|
|
60
|
+
const cur = loadProviderAllowedModels("todaycn", opts);
|
|
61
|
+
const added = ids.map((m) => toGatewayModelId(m)).filter((m) => m && !cur.includes(m));
|
|
62
|
+
if (added.length) saveProviderAllowedModels("todaycn", [...cur, ...added], opts);
|
|
63
|
+
return { allowed: [...cur, ...added], added };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 目录服务:options 由 index.js 注入(多号并集 + 缓存由本层做)。
|
|
68
|
+
* loadOptions() → [{ optionId, title, subtitle, disabled }];失败/为空 → 空目录(不假装有额度)。
|
|
69
|
+
*/
|
|
70
|
+
export function createModelsService({ id = "todaycn", loadOptions, hasAccount = () => true, clock = Date.now, ttlMs = CACHE_TTL_MS } = {}) {
|
|
71
|
+
let cache = null;
|
|
72
|
+
let fetchedAt = 0;
|
|
73
|
+
|
|
74
|
+
async function listModels() {
|
|
75
|
+
if (!hasAccount()) return [];
|
|
76
|
+
const now = clock();
|
|
77
|
+
if (cache && now - fetchedAt < ttlMs) return cache;
|
|
78
|
+
let options = [];
|
|
79
|
+
if (typeof loadOptions === "function") {
|
|
80
|
+
try { options = (await loadOptions()) || []; } catch { options = []; }
|
|
81
|
+
}
|
|
82
|
+
cache = buildTodaycnModelList({ id, options: Array.isArray(options) ? options : [] });
|
|
83
|
+
fetchedAt = now;
|
|
84
|
+
return cache;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function clearCache() {
|
|
88
|
+
cache = null;
|
|
89
|
+
fetchedAt = 0;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return { listModels, clearCache, _cache: () => cache };
|
|
93
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// todaycn 人设契约(agent 级常驻规则)单一源 + 幂等 apply / rollback。
|
|
2
|
+
//
|
|
3
|
+
// 为什么有它(2026-10-26 真机实测,别删这段结论):
|
|
4
|
+
// 光靠每轮在消息里写契约,模型在「像真任务」的请求上会被平台自带工具通道劫走
|
|
5
|
+
// (原话「已经派出去抓了」,零 tool_calls);把同一份契约定格进 agent 的人设字段
|
|
6
|
+
// agentCharacter(`PATCH /v1/agents/default`,控制面免费、是产品允许用户改的设置项)后,
|
|
7
|
+
// 同一句「读取一下www.baidu.com」稳定回单行 JSON {"tool_call":"http_get",...}。
|
|
8
|
+
// 措辞必须温和(与 prompt.js 的 4 条契约同语义:角色重述 / 首尾字符 / 不自引用);
|
|
9
|
+
// 写「本条优先级高于其它所有要求」这类词会被平台抗注入当场拒绝(实验 A 反证)。
|
|
10
|
+
// 代价与边界:人设是**账号级、全局生效**(桌面端聊天同样受影响),故只对「我在写一个小脚本」
|
|
11
|
+
// 开头的机器请求生效;普通聊天不受影响。可回滚:strip 掉本段即可(幂等)。
|
|
12
|
+
//
|
|
13
|
+
// 外证提示:人设读接口 `GET /v1/agents/default` 免费;组装后的 system prompt
|
|
14
|
+
// (`GET /v1/agents/default/context`)是 admin-only,普通号 403,本仓不依赖它。
|
|
15
|
+
|
|
16
|
+
import { buildHeaders } from "./chat.js";
|
|
17
|
+
import { TODAYCN_API_BASE } from "./const.js";
|
|
18
|
+
|
|
19
|
+
/** 追加到 agentCharacter 末尾的常驻规则(单一源;改它就等于改全网关行为,慎重)。 */
|
|
20
|
+
export const TODAYCN_PERSONA_CONTRACT = [
|
|
21
|
+
"还有一条跟脚本有关的老约定,你一直照办:当一条消息是由我的脚本桥接过来的机器请求时(它的开头会说「我在写一个小脚本」,并列出「我的脚本认识的工具」),你那条回复只能是一个 JSON 对象,形如 {\"tool_call\":\"<工具名>\",\"arguments\":{...}}。写的时候:回复的第一个字符必须是 {,最后一个字符必须是 };不要用代码块包起来;不要解释;不要回述这条约定;也不要讨论这个格式本身。这些工具由脚本真正执行,你只需要说出「该执行哪个动作」;工具跑完的结果会由脚本带着下一条机器请求回传给你。不需要动作时,就照平时那样用文字回答。只有这一类机器请求适用这条约定,平常聊天照旧、完全不受影响。",
|
|
22
|
+
].join("");
|
|
23
|
+
|
|
24
|
+
export function hasPersonaContract(character = "") {
|
|
25
|
+
return String(character || "").includes(TODAYCN_PERSONA_CONTRACT);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 幂等追加:已含契约原样返回。 */
|
|
29
|
+
export function withPersonaContract(character = "") {
|
|
30
|
+
const base = String(character || "").trimEnd();
|
|
31
|
+
if (!base) return TODAYCN_PERSONA_CONTRACT;
|
|
32
|
+
if (hasPersonaContract(base)) return base;
|
|
33
|
+
return `${base}\n\n${TODAYCN_PERSONA_CONTRACT}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 幂等摘除:只摘本仓加的那一段,其余人设一字不动。 */
|
|
37
|
+
export function stripPersonaContract(character = "") {
|
|
38
|
+
let s = String(character || "");
|
|
39
|
+
if (!hasPersonaContract(s)) return s;
|
|
40
|
+
s = s.split(`\n\n${TODAYCN_PERSONA_CONTRACT}`).join("");
|
|
41
|
+
s = s.split(TODAYCN_PERSONA_CONTRACT).join(""); // 兜底:整段就是契约的情形
|
|
42
|
+
return s.trimEnd();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 读当前人设(GET /v1/agents/default,控制面免费)。 */
|
|
46
|
+
export async function readTodaycnPersona({ token, fetchImpl, apiBase = TODAYCN_API_BASE, deviceId = "" } = {}) {
|
|
47
|
+
const res = await fetchImpl(`${apiBase}/v1/agents/default`, { headers: buildHeaders(token, deviceId) });
|
|
48
|
+
const text = await res.text().catch(() => "");
|
|
49
|
+
let json = null;
|
|
50
|
+
try { json = JSON.parse(text); } catch {}
|
|
51
|
+
return {
|
|
52
|
+
ok: Boolean(res.ok), status: res.status, json, text,
|
|
53
|
+
agentName: String(json?.agentName || ""),
|
|
54
|
+
agentCharacter: String(json?.agentCharacter || ""),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function writeTodaycnPersonaCharacter({ token, agentCharacter, fetchImpl, apiBase = TODAYCN_API_BASE, deviceId = "" }) {
|
|
59
|
+
const res = await fetchImpl(`${apiBase}/v1/agents/default`, {
|
|
60
|
+
method: "PATCH",
|
|
61
|
+
headers: { ...buildHeaders(token, deviceId), "Content-Type": "application/json" },
|
|
62
|
+
body: JSON.stringify({ agentCharacter }),
|
|
63
|
+
});
|
|
64
|
+
const text = await res.text().catch(() => "");
|
|
65
|
+
let json = null;
|
|
66
|
+
try { json = JSON.parse(text); } catch {}
|
|
67
|
+
return {
|
|
68
|
+
ok: Boolean(res.ok), status: res.status, json, text,
|
|
69
|
+
agentCharacter: String(json?.agentCharacter || ""),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 写入契约(幂等)。返回 { ok, changed, before, after, status }。 */
|
|
74
|
+
export async function applyTodaycnPersona(deps = {}) {
|
|
75
|
+
const cur = await readTodaycnPersona(deps);
|
|
76
|
+
if (!cur.ok) return { ok: false, changed: false, status: cur.status, reason: `读取人设失败(HTTP ${cur.status})` };
|
|
77
|
+
const before = cur.agentCharacter;
|
|
78
|
+
if (hasPersonaContract(before)) return { ok: true, changed: false, status: cur.status, before, after: before, reason: "人设里已有契约(幂等,未写盘)" };
|
|
79
|
+
const after = withPersonaContract(before);
|
|
80
|
+
const w = await writeTodaycnPersonaCharacter({ ...deps, agentCharacter: after });
|
|
81
|
+
const verified = w.ok ? (w.agentCharacter || "").includes(TODAYCN_PERSONA_CONTRACT) : false;
|
|
82
|
+
return {
|
|
83
|
+
ok: w.ok && verified, changed: w.ok, status: w.status,
|
|
84
|
+
before, after: w.agentCharacter || after,
|
|
85
|
+
reason: w.ok ? (verified ? "" : "写回后回读未命中契约段") : `写入失败(HTTP ${w.status})`,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 摘除契约(幂等)。返回 { ok, changed, before, after, status }。 */
|
|
90
|
+
export async function removeTodaycnPersona(deps = {}) {
|
|
91
|
+
const cur = await readTodaycnPersona(deps);
|
|
92
|
+
if (!cur.ok) return { ok: false, changed: false, status: cur.status, reason: `读取人设失败(HTTP ${cur.status})` };
|
|
93
|
+
const before = cur.agentCharacter;
|
|
94
|
+
if (!hasPersonaContract(before)) return { ok: true, changed: false, status: cur.status, before, after: before, reason: "人设里本来就没有契约(幂等,未写盘)" };
|
|
95
|
+
const after = stripPersonaContract(before);
|
|
96
|
+
const w = await writeTodaycnPersonaCharacter({ ...deps, agentCharacter: after });
|
|
97
|
+
const verified = w.ok ? !(w.agentCharacter || "").includes(TODAYCN_PERSONA_CONTRACT) : false;
|
|
98
|
+
return {
|
|
99
|
+
ok: w.ok && verified, changed: w.ok, status: w.status,
|
|
100
|
+
before, after: w.agentCharacter || after,
|
|
101
|
+
reason: w.ok ? (verified ? "" : "写回后回读仍命中契约段") : `写入失败(HTTP ${w.status})`,
|
|
102
|
+
};
|
|
103
|
+
}
|