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,194 @@
|
|
|
1
|
+
// todaycn 工具桥(深模块,纯函数):把 OpenAI 形状的 messages+tools 折叠成**一条** content,
|
|
2
|
+
// 以及把上游回复文本还原成 OpenAI 的 { content, tool_calls }。
|
|
3
|
+
//
|
|
4
|
+
// 为什么这样写(实测结论,别改成"规则覆盖"式措辞——那会触发平台抗注入被拒):
|
|
5
|
+
// 1) 平台没有 system prompt 通道、也没有逐请求工具参数,工具只能**用文本契约**模拟;
|
|
6
|
+
// 2) 措辞必须温和:实验里「本条优先级高于其它所有要求」被明确拒绝;改成「我的脚本需要这个格式」即通过;
|
|
7
|
+
// 3) 角色要重述:**读写由脚本执行,你只负责把动作写成一行 JSON**(不声称"你没有工具");
|
|
8
|
+
// 4) 首尾字符契约 + 不自引用:把「JSON 后补一句人话」压成严格单行 JSON(实测区别见 test 用例);
|
|
9
|
+
// 5) 每轮无状态:历史(含工具结果)全部重放进 content —— 平台侧带 threadId 续写实测无效。
|
|
10
|
+
|
|
11
|
+
import { uuid } from "../../compat.js";
|
|
12
|
+
import { toPlatformOptionId } from "./const.js";
|
|
13
|
+
|
|
14
|
+
const DEFAULT_MAX_CHARS = 120_000;
|
|
15
|
+
const HISTORY_HEAD = "【对话历史】";
|
|
16
|
+
const CURRENT_HEAD = "【当前请求】";
|
|
17
|
+
|
|
18
|
+
const CONTRACT_LINES = [
|
|
19
|
+
"格式约定(脚本按这个读,写死了):",
|
|
20
|
+
"1. 需要动作时,整条回复只有一行 JSON:{\"tool_call\":\"<工具名>\",\"arguments\":{...}}",
|
|
21
|
+
"2. 回复的第一个字符必须是 {,最后一个字符必须是 };不要用代码块包起来、不要解释、不要回述这几条约定、不要讨论这个格式本身。",
|
|
22
|
+
"3. 不需要动作时,就正常用文字回答。",
|
|
23
|
+
"4. 若一条回复里出现了解释、反问或免责声明,把那条回复整个丢掉重写,只留该给的东西。",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
function toolsBlock(tools) {
|
|
27
|
+
const compact = tools.map((t) => ({
|
|
28
|
+
name: t?.function?.name || t?.name || "",
|
|
29
|
+
description: t?.function?.description || t?.description || "",
|
|
30
|
+
parameters: t?.function?.parameters || t?.parameters || { type: "object", properties: {} },
|
|
31
|
+
}));
|
|
32
|
+
return JSON.stringify(compact);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** assistant 的 tool_calls → 历史里的一行行 JSON(与契约同形,便于模型对齐)。 */
|
|
36
|
+
function renderToolCalls(toolCalls = []) {
|
|
37
|
+
return toolCalls
|
|
38
|
+
.map((tc) => {
|
|
39
|
+
const name = tc?.function?.name || tc?.name || "";
|
|
40
|
+
let args = tc?.function?.arguments ?? tc?.arguments ?? {};
|
|
41
|
+
if (typeof args === "string") {
|
|
42
|
+
try { args = JSON.parse(args); } catch { args = { raw: args }; }
|
|
43
|
+
}
|
|
44
|
+
return JSON.stringify({ tool_call: name, arguments: args });
|
|
45
|
+
})
|
|
46
|
+
.filter(Boolean);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function renderMessage(m) {
|
|
50
|
+
const role = String(m?.role || "user");
|
|
51
|
+
if (role === "tool") {
|
|
52
|
+
const payload = { tool_call: m?.name || m?.tool_call_id || "tool", result: m?.content ?? "" };
|
|
53
|
+
return `[工具结果] ${JSON.stringify(payload)}`;
|
|
54
|
+
}
|
|
55
|
+
if (role === "assistant") {
|
|
56
|
+
const lines = [];
|
|
57
|
+
if (Array.isArray(m?.tool_calls) && m.tool_calls.length) lines.push(...renderToolCalls(m.tool_calls));
|
|
58
|
+
if (m?.content) lines.push(`[assistant] ${String(m.content)}`);
|
|
59
|
+
return lines.join("\n");
|
|
60
|
+
}
|
|
61
|
+
const text = Array.isArray(m?.content)
|
|
62
|
+
? m.content.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("")
|
|
63
|
+
: String(m?.content ?? "");
|
|
64
|
+
return `[${role === "system" ? "客户端背景说明" : role}] ${text}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function clipHistory(parts, maxChars) {
|
|
68
|
+
// 从最新往回留;超出即丢最旧的,并留一行标记(不做摘要,避免伪造)。
|
|
69
|
+
const kept = [];
|
|
70
|
+
let used = 0;
|
|
71
|
+
for (let i = parts.length - 1; i >= 0; i -= 1) {
|
|
72
|
+
const p = parts[i];
|
|
73
|
+
if (used + p.length > maxChars && kept.length) break;
|
|
74
|
+
kept.unshift(p);
|
|
75
|
+
used += p.length;
|
|
76
|
+
}
|
|
77
|
+
const dropped = parts.length - kept.length;
|
|
78
|
+
return { text: kept.join("\n"), dropped };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 折叠成一条 content。
|
|
83
|
+
* @param messages OpenAI 形状 messages(system/user/assistant/tool 都吃)
|
|
84
|
+
* @param tools OpenAI 形状 tools(空数组 = 纯文本退化,不注入契约)
|
|
85
|
+
* @param model 目标模型(仅供脚本文案不带 model 字段时的一致性;平台模型位在账号设置里)
|
|
86
|
+
*/
|
|
87
|
+
export function buildTodaycnContent({ messages = [], tools = [], model = "", maxChars = DEFAULT_MAX_CHARS, requestId = "" } = {}) {
|
|
88
|
+
const list = Array.isArray(messages) ? messages.filter(Boolean) : [];
|
|
89
|
+
const heads = [HISTORY_HEAD];
|
|
90
|
+
if (model) heads.push(`(脚本这一轮按 ${toPlatformOptionId(model)} 账号位发;不需要你复述。)`);
|
|
91
|
+
|
|
92
|
+
const rendered = [];
|
|
93
|
+
for (const m of list) {
|
|
94
|
+
const r = renderMessage(m);
|
|
95
|
+
if (r) rendered.push(r);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 客户端常把系统提示塞进 messages[0](各种编码 agent 的身份说明):渲染成【客户端背景说明】——
|
|
99
|
+
// **不给它特殊权重文案**(平台只认 content 文本,写"系统/最高优先级"反而触发抗注入)。
|
|
100
|
+
const hasTools = Array.isArray(tools) && tools.length > 0;
|
|
101
|
+
const preamble = hasTools
|
|
102
|
+
? [
|
|
103
|
+
"我在写一个小脚本,文件、命令、取数这些动作都由这个脚本执行。你每一步只做一件事:把「该执行哪个动作」按格式写成一行 JSON,我拿去跑;该给结论时就用文字说。",
|
|
104
|
+
"",
|
|
105
|
+
"我的脚本认识的工具(就下面这些):",
|
|
106
|
+
toolsBlock(tools),
|
|
107
|
+
"",
|
|
108
|
+
// 契约段不放这里:它必须出现在**最末尾**。2026-10-26 真机实测——契约在最前时,
|
|
109
|
+
// 25+ 条历史会把契约挤出注意力,模型改说「已接单/等待结果中」,零 tool_calls。
|
|
110
|
+
]
|
|
111
|
+
: ["我在写一个小脚本,它一次只吃一段文字。下面是我们之前说过的话和这次要办的事。", ""];
|
|
112
|
+
const tail = hasTools ? ["", "本轮就是一次机器请求,按下面的格式回答:", ...CONTRACT_LINES] : [];
|
|
113
|
+
const budget = Math.max(0, maxChars - preamble.join("\n").length - tail.join("\n").length - 64);
|
|
114
|
+
const { text: hist, dropped } = clipHistory(rendered, budget);
|
|
115
|
+
const out = [...preamble, HISTORY_HEAD];
|
|
116
|
+
if (dropped > 0) out.push(`(更早的 ${dropped} 段因长度限制已省略。)`);
|
|
117
|
+
out.push(hist, "", CURRENT_HEAD, "(上面最后一段就是本轮要办的事。)");
|
|
118
|
+
if (requestId) out.push(`(本轮 requestId:${requestId})`);
|
|
119
|
+
return [...out, ...tail].join("\n");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 从文本里扫出顶层平衡 JSON 对象(跳过字符串与转义),返回 [{ obj, raw, start, end }]。 */
|
|
123
|
+
export function extractJsonObjects(text = "") {
|
|
124
|
+
const s = String(text);
|
|
125
|
+
const out = [];
|
|
126
|
+
let i = 0;
|
|
127
|
+
while (i < s.length) {
|
|
128
|
+
if (s[i] !== "{") { i += 1; continue; }
|
|
129
|
+
let depth = 0, inStr = false, esc = false, end = -1;
|
|
130
|
+
for (let j = i; j < s.length; j += 1) {
|
|
131
|
+
const c = s[j];
|
|
132
|
+
if (inStr) {
|
|
133
|
+
if (esc) esc = false;
|
|
134
|
+
else if (c === "\\") esc = true;
|
|
135
|
+
else if (c === '"') inStr = false;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (c === '"') { inStr = true; continue; }
|
|
139
|
+
if (c === "{") depth += 1;
|
|
140
|
+
else if (c === "}") {
|
|
141
|
+
depth -= 1;
|
|
142
|
+
if (depth === 0) { end = j; break; }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (end === -1) break;
|
|
146
|
+
const raw = s.slice(i, end + 1);
|
|
147
|
+
try { out.push({ obj: JSON.parse(raw), raw, start: i, end: end + 1 }); } catch {}
|
|
148
|
+
i = end + 1;
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function normalizeArgs(args) {
|
|
154
|
+
if (typeof args === "string") {
|
|
155
|
+
try { return JSON.stringify(JSON.parse(args)); } catch { return JSON.stringify({ raw: args }); }
|
|
156
|
+
}
|
|
157
|
+
return JSON.stringify(args ?? {});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 把一条已解析对象认成 tool call(兼容 tool_call / name+arguments / function 三种包装)。 */
|
|
161
|
+
function asToolCall(obj) {
|
|
162
|
+
if (!obj || typeof obj !== "object") return null;
|
|
163
|
+
const name = obj.tool_call ?? obj.name ?? obj?.function?.name;
|
|
164
|
+
if (!name || typeof name !== "string") return null;
|
|
165
|
+
const args = obj.arguments ?? obj?.function?.arguments ?? {};
|
|
166
|
+
return { name, arguments: normalizeArgs(args) };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 解析上游回复。返回 { content, tool_calls, strict }:
|
|
171
|
+
* - content:JSON 之外的正文(严格回复时为 "")
|
|
172
|
+
* - tool_calls:OpenAI 形状 [{ id, type:'function', function:{ name, arguments(JSON 串) } }]
|
|
173
|
+
* - strict:整条回复(去空白、剥代码围栏后)恰好等于那一个 JSON 对象
|
|
174
|
+
*/
|
|
175
|
+
export function parseTodaycnReply(text = "", { idFactory } = {}) {
|
|
176
|
+
const rawText = String(text ?? "");
|
|
177
|
+
const stripped = rawText.replace(/^\s*```(?:json)?\s*/i, "").replace(/\s*```\s*$/i, "");
|
|
178
|
+
const found = extractJsonObjects(stripped);
|
|
179
|
+
const calls = [];
|
|
180
|
+
const spans = [];
|
|
181
|
+
for (const f of found) {
|
|
182
|
+
const tc = asToolCall(f.obj);
|
|
183
|
+
if (tc) {
|
|
184
|
+
calls.push({ id: (idFactory || (() => `call_${uuid().replace(/-/g, "").slice(0, 24)}`))(), type: "function", function: { name: tc.name, arguments: tc.arguments } });
|
|
185
|
+
spans.push([f.start, f.end]);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// 正文 = 去掉被认成 tool call 的 JSON 段之后剩下的部分
|
|
189
|
+
let content = stripped;
|
|
190
|
+
for (const [s, e] of spans.reverse()) content = content.slice(0, s) + content.slice(e);
|
|
191
|
+
content = content.replace(/\n{3,}/g, "\n\n").trim();
|
|
192
|
+
const strict = calls.length === 1 && content === "" && stripped.trim() === found[0]?.raw;
|
|
193
|
+
return { content, tool_calls: calls, strict };
|
|
194
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// todaycn 本机登录态导入(Windows/DPAPI 专用):Local State → DPAPI(os_crypt.encrypted_key)
|
|
2
|
+
// → AES-256-GCM(v10 信封) → account-credentials.slot-{a,b} → { uid, refreshCredential }。
|
|
3
|
+
// 只读客户端文件,绝不写回;非 Windows 平台无 DPAPI,返回 ok:false 并指引手填。
|
|
4
|
+
//
|
|
5
|
+
// 弹窗教训(对齐 src/providers/curl-fetch.js):daemon 是无控制台后台进程,spawn **必须** windowsHide,
|
|
6
|
+
// 否则每次导入都弹一个 powershell 控制台窗口。
|
|
7
|
+
|
|
8
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import { execFileSync } from "node:child_process";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { createDecipheriv } from "node:crypto";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { TODAYCN_DESKTOP_DIR_ENV } from "./const.js";
|
|
14
|
+
|
|
15
|
+
const SLOTS = ["account-credentials.slot-b", "account-credentials.slot-a"];
|
|
16
|
+
const V10_MAGIC = "v10";
|
|
17
|
+
const NONCE_LEN = 12;
|
|
18
|
+
const TAG_LEN = 16;
|
|
19
|
+
|
|
20
|
+
/** 候选数据目录:显式 env > 平台默认(Windows %APPDATA%/Today CN)。 */
|
|
21
|
+
export function todaycnDesktopDirs({ env = process.env, platform = process.platform, home = homedir() } = {}) {
|
|
22
|
+
const explicit = String(env[TODAYCN_DESKTOP_DIR_ENV] || "").trim();
|
|
23
|
+
if (explicit) return [explicit];
|
|
24
|
+
if (platform === "win32") {
|
|
25
|
+
const out = [];
|
|
26
|
+
if (env.APPDATA) out.push(join(env.APPDATA, "Today CN"));
|
|
27
|
+
out.push(join(home, "AppData", "Roaming", "Today CN"));
|
|
28
|
+
return [...new Set(out)];
|
|
29
|
+
}
|
|
30
|
+
if (platform === "darwin") return [join(home, "Library", "Application Support", "Today CN")];
|
|
31
|
+
return [join(home, ".config", "Today CN")];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 命中第一个带 Local State 的目录;无则空串。 */
|
|
35
|
+
export function findTodaycnDesktopDir(opts) {
|
|
36
|
+
for (const dir of todaycnDesktopDirs(opts)) {
|
|
37
|
+
try { if (existsSync(join(dir, "Local State"))) return dir; } catch {}
|
|
38
|
+
}
|
|
39
|
+
return "";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** DPAPI 解封:base64 进 / base64 出,不落临时文件(命令行长度足够,encrypted_key 约 200 字符)。 */
|
|
43
|
+
export function dpapiUnprotect(b64) {
|
|
44
|
+
const cmd =
|
|
45
|
+
"$ErrorActionPreference='Stop';Add-Type -AssemblyName System.Security;" +
|
|
46
|
+
`$b=[Convert]::FromBase64String('${b64}');` +
|
|
47
|
+
"$k=[Security.Cryptography.ProtectedData]::Unprotect($b,$null,1);" +
|
|
48
|
+
"[Convert]::ToBase64String($k)";
|
|
49
|
+
const out = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", cmd], {
|
|
50
|
+
windowsHide: true,
|
|
51
|
+
timeout: 15_000,
|
|
52
|
+
encoding: "utf8",
|
|
53
|
+
});
|
|
54
|
+
return Buffer.from(String(out).trim(), "base64");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** AES-256-GCM 密钥:Local State 的 os_crypt.encrypted_key(DPAPI 前缀 5 字节需剥)。 */
|
|
58
|
+
export function todaycnAesKey(dir) {
|
|
59
|
+
const ls = JSON.parse(readFileSync(join(dir, "Local State"), "utf8"));
|
|
60
|
+
const enc = Buffer.from(ls?.os_crypt?.encrypted_key || "", "base64");
|
|
61
|
+
if (!enc.length) throw new Error("Local State 缺 os_crypt.encrypted_key");
|
|
62
|
+
const head = enc.subarray(0, 5).toString("latin1");
|
|
63
|
+
const dpapi = head === "DPAPI" ? enc.subarray(5) : enc;
|
|
64
|
+
return dpapiUnprotect(dpapi.toString("base64"));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** v10 信封:3 字节前缀 + 12 字节 nonce + 密文 + 16 字节 tag。 */
|
|
68
|
+
export function decryptV10(key, blob) {
|
|
69
|
+
if (blob.subarray(0, 3).toString("latin1") !== V10_MAGIC) throw new Error("非 v10 信封");
|
|
70
|
+
const nonce = blob.subarray(3, 3 + NONCE_LEN);
|
|
71
|
+
const tag = blob.subarray(blob.length - TAG_LEN);
|
|
72
|
+
const ct = blob.subarray(3 + NONCE_LEN, blob.length - TAG_LEN);
|
|
73
|
+
const d = createDecipheriv("aes-256-gcm", key, nonce);
|
|
74
|
+
d.setAuthTag(tag);
|
|
75
|
+
return Buffer.concat([d.update(ct), d.final()]);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 读本机登录态。返回 { ok, uid, name, email, refreshCredential, dir } 或 { ok:false, reason }。
|
|
80
|
+
* 不抛异常:调用方(CLI login / provider 装配)需要拿到人话原因。
|
|
81
|
+
*/
|
|
82
|
+
export function readTodaycnDesktopSession({ dir, platform = process.platform } = {}) {
|
|
83
|
+
const root = dir || findTodaycnDesktopDir();
|
|
84
|
+
if (!root) return { ok: false, reason: "未找到本机 Today 客户端数据目录(没装或没登录过)" };
|
|
85
|
+
if (platform !== "win32") {
|
|
86
|
+
return { ok: false, reason: "本机登录态解密目前仅支持 Windows(DPAPI);其它平台请用 -provider todaycn login --refresh <串> 手填" };
|
|
87
|
+
}
|
|
88
|
+
let key = null;
|
|
89
|
+
try { key = todaycnAesKey(root); } catch (e) { return { ok: false, reason: `取密钥失败:${String(e?.message || e).slice(0, 160)}` }; }
|
|
90
|
+
for (const slot of SLOTS) {
|
|
91
|
+
try {
|
|
92
|
+
const raw = readFileSync(join(root, slot));
|
|
93
|
+
const rec = JSON.parse(decryptV10(key, raw).toString("utf8"))?.record;
|
|
94
|
+
if (rec?.environment === "prod" && rec.refreshCredential) {
|
|
95
|
+
return {
|
|
96
|
+
ok: true,
|
|
97
|
+
dir: root,
|
|
98
|
+
uid: String(rec?.user?.id || ""),
|
|
99
|
+
name: String(rec?.user?.displayName || ""),
|
|
100
|
+
email: String(rec?.user?.email || ""),
|
|
101
|
+
refreshCredential: String(rec.refreshCredential),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
} catch {}
|
|
105
|
+
}
|
|
106
|
+
return { ok: false, reason: "slot-a/b 里没有 prod 登录记录(先在桌面客户端登录一次)" };
|
|
107
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// todaycn 出站成形:上游没有流式(202 + 轮询),客户端要 stream:true 时由本层**自造** OpenAI SSE 帧。
|
|
2
|
+
// 帧序(对齐 OpenAI 形状,客户端无需特判):role delta → content delta / tool_calls delta → finish_reason → [DONE]。
|
|
3
|
+
// 非流式直接给 chat.completion JSON(同一份 completion 两种出法,避免两处口径漂移)。
|
|
4
|
+
|
|
5
|
+
const encoder = new TextEncoder();
|
|
6
|
+
|
|
7
|
+
/** OpenAI chat.completion 对象(message.content 为空且无 tool_calls 时 content 置 null,符合 OpenAI 约定)。 */
|
|
8
|
+
export function createCompletion({ id, model, content = "", toolCalls = [], created = Math.floor(Date.now() / 1000), usage = null } = {}) {
|
|
9
|
+
const message = { role: "assistant", content: content || null };
|
|
10
|
+
if (Array.isArray(toolCalls) && toolCalls.length) message.tool_calls = toolCalls;
|
|
11
|
+
const completion = {
|
|
12
|
+
id: id || `chatcmpl_${Math.random().toString(36).slice(2, 14)}`,
|
|
13
|
+
object: "chat.completion",
|
|
14
|
+
created,
|
|
15
|
+
model: model || "todaycn",
|
|
16
|
+
choices: [
|
|
17
|
+
{
|
|
18
|
+
index: 0,
|
|
19
|
+
message,
|
|
20
|
+
logprobs: null,
|
|
21
|
+
finish_reason: message.tool_calls ? "tool_calls" : "stop",
|
|
22
|
+
},
|
|
23
|
+
],
|
|
24
|
+
};
|
|
25
|
+
if (usage) completion.usage = usage;
|
|
26
|
+
return completion;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function chunkFrame(completion, delta, finishReason = null) {
|
|
30
|
+
return {
|
|
31
|
+
id: completion.id,
|
|
32
|
+
object: "chat.completion.chunk",
|
|
33
|
+
created: completion.created,
|
|
34
|
+
model: completion.model,
|
|
35
|
+
choices: [{ index: 0, delta, logprobs: null, finish_reason: finishReason }],
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function frame(payload) {
|
|
40
|
+
return encoder.encode(`data: ${JSON.stringify(payload)}\n\n`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** completion → OpenAI SSE 流。chunkChars>0 时把正文按该长度切多个 content delta(默认整段一帧)。 */
|
|
44
|
+
export function completionToSseStream(completion, { chunkChars = 0 } = {}) {
|
|
45
|
+
const choice = completion?.choices?.[0] || {};
|
|
46
|
+
const message = choice.message || {};
|
|
47
|
+
const text = String(message.content ?? "");
|
|
48
|
+
const calls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
|
|
49
|
+
const finish = choice.finish_reason || "stop";
|
|
50
|
+
return new ReadableStream({
|
|
51
|
+
start(controller) {
|
|
52
|
+
controller.enqueue(frame(chunkFrame(completion, { role: "assistant" })));
|
|
53
|
+
if (calls.length) {
|
|
54
|
+
controller.enqueue(
|
|
55
|
+
frame(
|
|
56
|
+
chunkFrame(completion, {
|
|
57
|
+
tool_calls: calls.map((c, i) => ({ index: i, id: c.id, type: c.type || "function", function: c.function })),
|
|
58
|
+
}),
|
|
59
|
+
),
|
|
60
|
+
);
|
|
61
|
+
} else if (text) {
|
|
62
|
+
const step = chunkChars > 0 ? chunkChars : text.length;
|
|
63
|
+
for (let i = 0; i < text.length; i += step) {
|
|
64
|
+
controller.enqueue(frame(chunkFrame(completion, { content: text.slice(i, i + step) })));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
controller.enqueue(frame(chunkFrame(completion, {}, finish)));
|
|
68
|
+
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
|
|
69
|
+
controller.close();
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 同一份 completion:stream=true 出 SSE,否则出 JSON。 */
|
|
75
|
+
export function completionToResponse(completion, { stream = false, streamChunkChars = 0 } = {}) {
|
|
76
|
+
if (!stream) {
|
|
77
|
+
return new Response(JSON.stringify(completion), {
|
|
78
|
+
status: 200,
|
|
79
|
+
headers: { "Content-Type": "application/json" },
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
return new Response(completionToSseStream(completion, { chunkChars: streamChunkChars }), {
|
|
83
|
+
status: 200,
|
|
84
|
+
headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// todaycn accessToken 缓存:每枚 refreshCredential 换一枚 10 分钟 JWT,按 exp 提前刷新。
|
|
2
|
+
// refresh 端点实测:GET {AUTH}/api/auth/token,Authorization: Bearer <refreshCredential> → { token }。
|
|
3
|
+
// refreshCredential 实测**不轮换**(连续多次刷新同一枚仍有效)→ 本模块不回写凭据,只缓存 token。
|
|
4
|
+
|
|
5
|
+
import { compatFetch } from "../../compat.js";
|
|
6
|
+
import { TODAYCN_AUTH_BASE, TODAYCN_TOKEN_SKEW_MS } from "./const.js";
|
|
7
|
+
|
|
8
|
+
/** JWT payload 解码(不验签,只取 exp;失败给 0 = 视为立即过期)。 */
|
|
9
|
+
export function decodeJwtExpMs(token = "") {
|
|
10
|
+
try {
|
|
11
|
+
const part = String(token).split(".")[1];
|
|
12
|
+
if (!part) return 0;
|
|
13
|
+
const json = JSON.parse(Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
|
|
14
|
+
return Number(json?.exp || 0) * 1000;
|
|
15
|
+
} catch {
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createTokenStore({ fetchImpl, authBase = TODAYCN_AUTH_BASE, skewMs = TODAYCN_TOKEN_SKEW_MS, timeoutMs = 15_000, clock = Date.now } = {}) {
|
|
21
|
+
const call = fetchImpl || compatFetch;
|
|
22
|
+
const cache = new Map(); // credential → { token, expMs }
|
|
23
|
+
|
|
24
|
+
async function refresh(credential, { signal } = {}) {
|
|
25
|
+
const ctrl = signal ? null : new AbortController();
|
|
26
|
+
const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
|
|
27
|
+
try {
|
|
28
|
+
const res = await call(`${authBase}/api/auth/token`, {
|
|
29
|
+
headers: {
|
|
30
|
+
Authorization: `Bearer ${credential}`,
|
|
31
|
+
Accept: "application/json",
|
|
32
|
+
Origin: "https://todayai.cn",
|
|
33
|
+
},
|
|
34
|
+
signal: signal || (ctrl ? ctrl.signal : undefined),
|
|
35
|
+
});
|
|
36
|
+
const text = await res.text().catch(() => "");
|
|
37
|
+
if (!res.ok) {
|
|
38
|
+
return { ok: false, status: res.status, reason: `refresh ${res.status} ${text.slice(0, 160)}`, authFailed: res.status === 401 || res.status === 403 };
|
|
39
|
+
}
|
|
40
|
+
let token = "";
|
|
41
|
+
try { token = String(JSON.parse(text)?.token || ""); } catch {}
|
|
42
|
+
if (!token) return { ok: false, status: res.status, reason: "refresh 响应里没有 token", authFailed: false };
|
|
43
|
+
cache.set(credential, { token, expMs: decodeJwtExpMs(token) });
|
|
44
|
+
return { ok: true, token, status: res.status };
|
|
45
|
+
} catch (e) {
|
|
46
|
+
return { ok: false, status: 0, reason: `refresh 网络失败 ${String(e?.message || e).slice(0, 120)}`, authFailed: false };
|
|
47
|
+
} finally {
|
|
48
|
+
if (timer) clearTimeout(timer);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 取可用 token:缓存未过期直接给;否则刷新。force=true 忽略缓存(上游 401 后重试用)。 */
|
|
53
|
+
async function getToken(credential, { force = false, signal } = {}) {
|
|
54
|
+
const cred = String(credential || "").trim();
|
|
55
|
+
if (!cred) return { ok: false, status: 401, reason: "empty credential", authFailed: true };
|
|
56
|
+
const hit = cache.get(cred);
|
|
57
|
+
if (!force && hit && hit.expMs - clock() > skewMs) return { ok: true, token: hit.token, cached: true };
|
|
58
|
+
return refresh(cred, { signal });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function forget(credential) {
|
|
62
|
+
cache.delete(String(credential || "").trim());
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return { getToken, forget, _cache: () => cache };
|
|
66
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { underSystemd } from "./proc-info.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 开机自启「重注入」的唯一执行者 —— daemon 启动自愈与 CLI `-restart` 共用这一份。
|
|
8
|
+
*
|
|
9
|
+
* 为什么要抽出来(2026-10-26,ADR-0074 二次修订):用户点名「`-restart` 里没查吗?」——
|
|
10
|
+
* 第一版把体检只埋在 daemon 启动路径(`server-lifecycle.js`),于是 `-restart` 的输出一行
|
|
11
|
+
* 相关回执都没有,也说不清「查过没查过」。判据与动作散在调用方 = 迟早长第二套真相。
|
|
12
|
+
*
|
|
13
|
+
* 三条不变量(改动时一条都不能破):
|
|
14
|
+
* 1. **绝不在本进程里调 `enableAutostart()`**:它在 Linux 的语义是「停掉裸 daemon、把端口
|
|
15
|
+
* 让给 systemd」,由裸 daemon 自己调用 = 举手自杀(0.1.236 真机,ADR-0069)。CLI 侧同样
|
|
16
|
+
* 危险:`-restart` 刚把新 daemon 起来,inline 一句 `enableAutostart()` 就会把它当裸 daemon 停掉。
|
|
17
|
+
* ⇒ 动作一律交给 detached helper 子进程。
|
|
18
|
+
* 2. **在途互斥**:CLI 刚派完 helper,2.5s 后 daemon 启动自愈会**再看一次**(那时注册往往还没
|
|
19
|
+
* 写完)⇒ 不去重就会连派两个进程抢着 `schtasks /create /f`。判据 = 台账 `autostartRepair.at`
|
|
20
|
+
* 距今 < `REPAIR_INFLIGHT_MS` 就认「已经有人在补了」,本轮只报 deferred。
|
|
21
|
+
* 3. **systemd 托管下整块跳过**:supervisor 已保证单实例+自启;且本块查的是 **user** unit,
|
|
22
|
+
* 被**系统** unit 托管时必得 enabled=false ⇒ 误判成「没注册」而反复接管(2026-10-19 无限重启)。
|
|
23
|
+
*/
|
|
24
|
+
export const REPAIR_INFLIGHT_MS = 60_000;
|
|
25
|
+
|
|
26
|
+
/** helper 走的是正经 CLI 入口 `-enable-autostart`;带 NO_AUTOSTART 防它自己再触发一次自愈。 */
|
|
27
|
+
export function spawnAutostartHelper() {
|
|
28
|
+
const entry = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "bin", "mslxdff.js");
|
|
29
|
+
const child = spawn(process.execPath, [entry, "-enable-autostart"], {
|
|
30
|
+
detached: true,
|
|
31
|
+
stdio: "ignore",
|
|
32
|
+
windowsHide: true,
|
|
33
|
+
env: { ...process.env, MSLXDFF_DAEMON: "", MSLXDFF_NO_AUTOSTART: "1" },
|
|
34
|
+
});
|
|
35
|
+
child.unref();
|
|
36
|
+
return child;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 平台与 env 开关:macOS 排除(没有 systemd,走 linuxEnable 必连败三次)。 */
|
|
40
|
+
export function autostartRepairEnabled(env = process.env, platform = process.platform) {
|
|
41
|
+
if (platform !== "win32" && platform !== "linux") return false;
|
|
42
|
+
if (env.MSLXDFF_NO_AUTOSTART) return false;
|
|
43
|
+
const off = String(env.MSLXDFF_AUTOSTART_REPAIR ?? "").trim().toLowerCase();
|
|
44
|
+
return off !== "0" && off !== "off" && off !== "false";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 体检一次,必要时派 helper 重注入。返回结构化判决(`action`),并把人话回执交给 `log`。
|
|
49
|
+
* `reportOk=true`(CLI 用)时连「体检通过」也打一行 —— restart 要看得见自己查过了。
|
|
50
|
+
*/
|
|
51
|
+
export async function repairAutostartOnce({
|
|
52
|
+
log = () => {},
|
|
53
|
+
onEvent = () => {},
|
|
54
|
+
reportOk = false,
|
|
55
|
+
check = null,
|
|
56
|
+
env = process.env,
|
|
57
|
+
platform = process.platform,
|
|
58
|
+
inflightMs = REPAIR_INFLIGHT_MS,
|
|
59
|
+
now = () => Date.now(),
|
|
60
|
+
spawnHelper = null,
|
|
61
|
+
mark = null,
|
|
62
|
+
} = {}) {
|
|
63
|
+
if (!autostartRepairEnabled(env, platform)) return { action: "skip-env" };
|
|
64
|
+
if (platform === "linux" && underSystemd()) return { action: "skip-systemd" };
|
|
65
|
+
const doSpawn = spawnHelper || spawnAutostartHelper;
|
|
66
|
+
const { checkAutostartHealth } = check ? { checkAutostartHealth: check } : await import("../autostart.js");
|
|
67
|
+
const doMark = mark || (await import("../state.js")).markAutostartRepairAttempt;
|
|
68
|
+
let h;
|
|
69
|
+
try {
|
|
70
|
+
h = check ? await check() : await checkAutostartHealth();
|
|
71
|
+
} catch (e) {
|
|
72
|
+
return { action: "error", reason: String(e?.message || e) };
|
|
73
|
+
}
|
|
74
|
+
if (h.supervised) {
|
|
75
|
+
// 有 supervisor 在管就别抢:systemd 已保证单实例+自启,重复注入只会与它互踢(ADR-0064/0069)
|
|
76
|
+
if (reportOk) log("autostart: 由 supervisor 托管中(systemd),体检不接管、不重注入");
|
|
77
|
+
return { action: "skip-supervised" };
|
|
78
|
+
}
|
|
79
|
+
if (!h.wanted) {
|
|
80
|
+
if (reportOk) log("autostart: 按意愿关闭(-disable-autostart 过),本次不补注册");
|
|
81
|
+
return { action: "unwanted" };
|
|
82
|
+
}
|
|
83
|
+
if (h.ok) {
|
|
84
|
+
if (reportOk) log(`autostart: 体检通过 — 注册在,且里面的路径都还在${h.paths.length ? `(${h.paths.length} 条)` : ""}`);
|
|
85
|
+
return { action: "ok" };
|
|
86
|
+
}
|
|
87
|
+
const prev = String(h.status?.taskToRun || h.status?.execStart || "").trim();
|
|
88
|
+
const since = now() - (h.repair?.at || 0);
|
|
89
|
+
if (h.repair?.at && since < inflightMs) {
|
|
90
|
+
log(`autostart 失效(${h.reason})→ 已有重注入在途(${Math.round(since / 1000)}s 前派的),本轮不重复派`);
|
|
91
|
+
return { action: "deferred", reason: h.reason, sinceMs: since };
|
|
92
|
+
}
|
|
93
|
+
if (h.budget <= 0) {
|
|
94
|
+
log(`autostart 已失效(${h.reason}),但连续重注入已失败 ${h.repair?.fails ?? "?"} 次 —— 停手,只告警:查权限或手动 mslxdff -enable-autostart(整块开关 MSLXDFF_AUTOSTART_REPAIR=0)`);
|
|
95
|
+
onEvent({ ts: now(), type: "autostart-repair-giveup", reason: h.reason, fails: h.repair?.fails ?? null });
|
|
96
|
+
return { action: "giveup", reason: h.reason };
|
|
97
|
+
}
|
|
98
|
+
const helper = doSpawn();
|
|
99
|
+
if (!helper?.pid) {
|
|
100
|
+
log("autostart 已失效且接管进程未启动:请手动运行 mslxdff -enable-autostart");
|
|
101
|
+
return { action: "spawn-failed", reason: h.reason };
|
|
102
|
+
}
|
|
103
|
+
// 先立在途标记再返回:否则 daemon 侧 2.5s 后的第二次体检看不到「刚有人派过」
|
|
104
|
+
try { doMark(); } catch {}
|
|
105
|
+
log(`autostart 失效(${h.reason})→ 已派接管进程 (pid ${helper.pid}) 重注入,剩余预算 ${h.budget - 1} 次${prev ? `;旧注册值:${prev}` : ""}`);
|
|
106
|
+
onEvent({ ts: now(), type: "autostart-takeover-spawned", pid: helper.pid, reason: h.reason, prev, platform });
|
|
107
|
+
return { action: "spawned", reason: h.reason, helperPid: helper.pid, prev };
|
|
108
|
+
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// Note: auth 号型不要求 baseUrl 是硬约束(旧门禁 baseUrl&&keys 曾静默跳过整家 qoder)— 见 .agents/notes/implemented/bug-fix/2026-09-21-auth-doc-provider-gate.md
|
|
5
5
|
|
|
6
6
|
/** 凭证在 auth 目录、无需 baseUrl 的「auth 号型」定制供应商(端点由各自 constants 决定)。 */
|
|
7
|
-
export const AUTH_DOC_PROVIDER_IDS = ["workbuddy", "traework", "qoder", "qwenwork", "globalqwenwork", "raccoon"];
|
|
7
|
+
export const AUTH_DOC_PROVIDER_IDS = ["workbuddy", "traework", "qoder", "qwenwork", "globalqwenwork", "raccoon", "todaycn"];
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* 免凭证供应商:上游就是 opencode zen 的免费层代理,没有 key 也能用(按出口 IP 计额度)。
|
|
@@ -35,7 +35,7 @@ export async function loadAuthDocs(gid) { try {
|
|
|
35
35
|
? await import("../providers/globalqwenwork/account-store.js")
|
|
36
36
|
: gid === "raccoon"
|
|
37
37
|
? await import("../providers/raccoon/account-store.js")
|
|
38
|
-
: await import("../providers/qoder/account-store.js");
|
|
38
|
+
: (gid === "todaycn" ? await import("../providers/todaycn/account-store.js") : await import("../providers/qoder/account-store.js"));
|
|
39
39
|
return store.listAccountDocs();
|
|
40
40
|
} catch {
|
|
41
41
|
return [];
|