mslxdff 0.1.163 → 0.1.169
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/anthropic/translate.js +397 -0
- package/src/anthropic/web-search.js +361 -0
- package/src/api-kind.js +31 -0
- package/src/chat-pipeline/auto-race.js +8 -0
- package/src/chat-pipeline/empty-turn.js +28 -0
- package/src/chat-pipeline/index.js +8 -4
- package/src/chat-pipeline/serial-trial.js +8 -1
- package/src/claude-desktop/apply.js +64 -0
- package/src/claude-desktop/doctor.js +146 -0
- package/src/claude-desktop/slots.js +86 -0
- package/src/cli/commands/claude-desktop.js +264 -0
- package/src/cli/commands/model/list-providers.js +1 -1
- package/src/cli/commands/provider/index.js +7 -0
- package/src/cli/commands/provider/models.js +3 -0
- package/src/cli/commands/provider/raccoon-login.js +131 -0
- package/src/cli/commands/provider/raccoon-quota.js +109 -0
- package/src/cli/commands/sync.js +80 -2
- package/src/cli/format.js +1 -1
- package/src/cli/help.js +3 -0
- package/src/cli/index.js +2 -0
- package/src/cli/provider-row.js +2 -2
- package/src/model-capabilities/parse.js +1 -1
- package/src/model-trace.js +2 -1
- package/src/providers/classify.js +1 -1
- package/src/providers/dispatcher.js +2 -2
- package/src/providers/keyring.js +1 -1
- package/src/providers/model-id.js +10 -0
- package/src/providers/raccoon/account-store.js +216 -0
- package/src/providers/raccoon/auth.js +67 -0
- package/src/providers/raccoon/chat.js +207 -0
- package/src/providers/raccoon/const.js +111 -0
- package/src/providers/raccoon/credits.js +161 -0
- package/src/providers/raccoon/envelope.js +23 -0
- package/src/providers/raccoon/headers.js +45 -0
- package/src/providers/raccoon/index.js +216 -0
- package/src/providers/raccoon/login.js +195 -0
- package/src/providers/raccoon/models.js +160 -0
- package/src/providers/raccoon/qr-codewords.js +115 -0
- package/src/providers/raccoon/qr.js +236 -0
- package/src/providers/raccoon/sse.js +135 -0
- package/src/providers/registry.js +5 -0
- package/src/providers/share-keys.js +1 -1
- package/src/providers/workbuddy/models.js +29 -14
- package/src/providers/workbuddy/payload.js +34 -0
- package/src/routes/chat/exhausted-handler.js +4 -4
- package/src/routes/chat/relay-pipeline.js +6 -7
- package/src/routes/index.js +13 -0
- package/src/routes/messages-route.js +401 -0
- package/src/routes/responses-route.js +2 -2
- package/src/runtime/bootstrap.js +5 -0
- package/src/runtime/broadband.js +4 -1
- package/src/runtime/provider-gate.js +3 -1
- package/src/runtime/raccoon-checkin.js +126 -0
- package/src/state/provider-config.js +1 -1
- package/src/sync-claude-desktop.js +234 -0
- package/src/sync-claude.js +152 -0
- package/src/talk-full.js +2 -2
- package/src/talk-log.js +9 -6
package/src/runtime/broadband.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { loadGroupsJoined } from "../state.js";
|
|
2
2
|
import { errMsg } from "../cli/util.js";
|
|
3
|
+
import { withOutputFloor } from "../chat-pipeline/empty-turn.js";
|
|
3
4
|
import { startBroadbandStream } from "./broadband-stream.js";
|
|
4
5
|
import { compatFetch, timeoutSignal } from "../compat.js";
|
|
5
6
|
|
|
@@ -18,8 +19,10 @@ export function startBroadband({ token, upstream }) {
|
|
|
18
19
|
})();
|
|
19
20
|
const execAndPost = async (g, reqId, body) => {
|
|
20
21
|
let result;
|
|
22
|
+
const fl = withOutputFloor(body); // 首发输出额度托底:leader 转来的 body 不经 pipeline,成员侧自托(评审 P1)
|
|
23
|
+
if (fl !== body) console.log(`output-floor(broadband): req=${reqId} ${(body?.max_tokens ?? body?.max_completion_tokens)}→${(fl.max_tokens ?? fl.max_completion_tokens)}`);
|
|
21
24
|
try {
|
|
22
|
-
const upRes = await upstream.chat(
|
|
25
|
+
const upRes = await upstream.chat(fl);
|
|
23
26
|
const ct = upRes.headers.get("content-type") || "";
|
|
24
27
|
const isStream = Boolean(body?.stream) || ct.includes("text/event-stream");
|
|
25
28
|
if (isStream && upRes.body) {
|
|
@@ -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"];
|
|
7
|
+
export const AUTH_DOC_PROVIDER_IDS = ["workbuddy", "traework", "qoder", "qwenwork", "globalqwenwork", "raccoon"];
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* - auth 号型:keys 或 auths 或 auth 目录有号 → 启用(baseUrl 可空)
|
|
@@ -26,6 +26,8 @@ export async function loadAuthDocs(gid) {
|
|
|
26
26
|
? await import("../providers/qwenwork/account-store.js")
|
|
27
27
|
: gid === "globalqwenwork"
|
|
28
28
|
? await import("../providers/globalqwenwork/account-store.js")
|
|
29
|
+
: gid === "raccoon"
|
|
30
|
+
? await import("../providers/raccoon/account-store.js")
|
|
29
31
|
: await import("../providers/qoder/account-store.js");
|
|
30
32
|
return store.listAccountDocs();
|
|
31
33
|
} catch {
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* raccoon 登录奖励的 daemon 兜底扫描(仿 src/runtime/qoder-checkin.js 的排程形态)。
|
|
3
|
+
* 开关:MSLXDFF_RACCOON_CHECKIN=0 关闭(默认开);时间:MSLXDFF_RACCOON_CHECKIN_HOUR(默认 9 点本地时)。
|
|
4
|
+
* ⚠ 性质纠偏(2026-10-10 账单实测):**这家没有"每日签到"可领** ——
|
|
5
|
+
* 每日 300 由服务端自动发放且当天 23:59:59 清零(无端点);唯一要领的是「桌面端登录奖励 3000」,**每号一次性**。
|
|
6
|
+
* 正常路径是 `raccoon login` 成功后立刻领掉(那时 token 最新鲜);本任务只是兜底:
|
|
7
|
+
* 扫出"历史上没领过"的号补领一次,领过的号每天只花一次账单查询即判"已领",不再打写端点。
|
|
8
|
+
*/
|
|
9
|
+
import { todayKey, nextRunDelayMs, shouldCatchUp } from "./workbuddy-checkin.js";
|
|
10
|
+
|
|
11
|
+
export function isCheckinEnabled(env = process.env) {
|
|
12
|
+
const v = String(env.MSLXDFF_RACCOON_CHECKIN ?? "1").trim().toLowerCase();
|
|
13
|
+
return !["0", "false", "off", "no"].includes(v);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function getCheckinHour(env = process.env) {
|
|
17
|
+
const h = Number(env.MSLXDFF_RACCOON_CHECKIN_HOUR);
|
|
18
|
+
return Number.isInteger(h) && h >= 0 && h <= 23 ? h : 9;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 账号文档 → credits.js 认的 credential 形状(与 provider 内 credentialFor 同构)。 */
|
|
22
|
+
export function credentialFromAccountDoc(doc) {
|
|
23
|
+
return {
|
|
24
|
+
access_token: doc?.accessToken || "",
|
|
25
|
+
refresh_token: doc?.refreshToken || "",
|
|
26
|
+
// ⚠ expires_at 必须带上:少了它,isRaccoonExpired / isRaccoonExpiringSoon 一律判不出来(只能回落去解 JWT,
|
|
27
|
+
// 而假 token 解不出 → undefined → 保守判「未过期」),结果就是过期号照发请求去撞 401、临期号该续不续。
|
|
28
|
+
expires_at: doc?.expiresAt || "",
|
|
29
|
+
office_identity: doc?.officeIdentity || "",
|
|
30
|
+
device_id: doc?.deviceId || "",
|
|
31
|
+
uid: doc?.uid || "",
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function setupRaccoonCheckin({ bus, logs, fetchImpl, dirs, env = process.env, now } = {}) {
|
|
36
|
+
function emit(type, data = {}) {
|
|
37
|
+
const entry = { ts: Date.now(), type, ...data };
|
|
38
|
+
try { bus?.emit(entry); } catch {}
|
|
39
|
+
try { logs?.appendEvent?.(entry); } catch {}
|
|
40
|
+
try { console.log(`[raccoon-checkin] ${type} ${JSON.stringify(data)}`.slice(0, 500)); } catch {}
|
|
41
|
+
}
|
|
42
|
+
if (!isCheckinEnabled(env)) {
|
|
43
|
+
console.log("[raccoon-checkin] disabled (set MSLXDFF_RACCOON_CHECKIN=1 to enable)");
|
|
44
|
+
emit("raccoon-checkin-disabled");
|
|
45
|
+
return { enabled: false };
|
|
46
|
+
}
|
|
47
|
+
const hour = getCheckinHour(env);
|
|
48
|
+
console.log(`[raccoon-checkin] enabled: daily ${String(hour).padStart(2, "0")}:00 local`);
|
|
49
|
+
emit("raccoon-checkin-enabled", { hour });
|
|
50
|
+
|
|
51
|
+
const stateMod = await import("../state.js");
|
|
52
|
+
const { listRaccoonAccountDocs } = await import("../providers/raccoon/account-store.js");
|
|
53
|
+
const { claimRaccoonLoginReward, raccoonClaimStatus } = await import("../providers/raccoon/credits.js");
|
|
54
|
+
const { isRaccoonExpired } = await import("../providers/raccoon/auth.js");
|
|
55
|
+
|
|
56
|
+
let running = false;
|
|
57
|
+
async function runOnce(reason) {
|
|
58
|
+
if (running) return { skipped: "already-running" };
|
|
59
|
+
running = true;
|
|
60
|
+
try {
|
|
61
|
+
const accounts = listRaccoonAccountDocs(dirs ? { dirs } : {}).filter((d) => d.accessToken);
|
|
62
|
+
if (!accounts.length) {
|
|
63
|
+
emit("raccoon-checkin-no-accounts", { reason });
|
|
64
|
+
return { ok: false, reason: "no-accounts" };
|
|
65
|
+
}
|
|
66
|
+
const results = [];
|
|
67
|
+
for (const a of accounts) {
|
|
68
|
+
const uid = String(a.uid).slice(0, 8);
|
|
69
|
+
const credential = credentialFromAccountDoc(a);
|
|
70
|
+
// access_token 只有约 3 小时寿命。过期的号一律跳过,**绝不去碰 refresh**:网关请求可能正在同一时刻
|
|
71
|
+
// 续同一个号,而 refresh_token 是一次性轮换的,两边抢同一条 token 等于亲手把号烧掉。
|
|
72
|
+
if (isRaccoonExpired(credential)) {
|
|
73
|
+
results.push({ uid, ok: false, claimed: false, status: "auth_stale", msg: "登录态已过期,需重新扫码:mslxdff -provider raccoon login" });
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
const r = await claimRaccoonLoginReward({
|
|
78
|
+
credential,
|
|
79
|
+
...(fetchImpl ? { fetchImpl } : {}),
|
|
80
|
+
env,
|
|
81
|
+
});
|
|
82
|
+
// 四种答复必须分开显示:只有 claimed 是真到账;already 是一次性礼包领过了(正常态);
|
|
83
|
+
// phantom = 上游回 code:0 但账单没这笔(实测行为);unverified = 账单查不动,不下结论。
|
|
84
|
+
const status = raccoonClaimStatus(r);
|
|
85
|
+
results.push({ uid, ok: status === "claimed" || status === "already", claimed: r.claimed, status, points: r.points });
|
|
86
|
+
} catch (e) {
|
|
87
|
+
results.push({ uid, ok: false, claimed: false, status: "error", msg: String(e?.message || e).slice(0, 120) });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const got = results.filter((r) => r.status === "claimed").length;
|
|
91
|
+
const already = results.filter((r) => r.status === "already").length;
|
|
92
|
+
const date = todayKey(now === undefined ? new Date() : new Date(now));
|
|
93
|
+
try {
|
|
94
|
+
stateMod.writeStateImmediate(stateMod.defaultStateFile(), {
|
|
95
|
+
raccoonCheckin: { date, at: Date.now(), ok: got + already, claimed: got, already, total: results.length, accounts: results },
|
|
96
|
+
});
|
|
97
|
+
} catch {}
|
|
98
|
+
for (const r of results) emit("raccoon-checkin-account", { ...r, reason });
|
|
99
|
+
emit("raccoon-checkin-done", { date, ok: got + already, claimed: got, already, total: results.length, reason });
|
|
100
|
+
return { ok: got + already > 0, claimed: got, already, total: results.length, results };
|
|
101
|
+
} catch (e) {
|
|
102
|
+
emit("raccoon-checkin-failed", { error: String(e?.message || e).slice(0, 200), reason });
|
|
103
|
+
return { ok: false, error: String(e?.message || e).slice(0, 200) };
|
|
104
|
+
} finally {
|
|
105
|
+
running = false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// 启动补签:今天已过计划点、且(从没签过 或 上次不是今天)→ 90s 后跑(等网络/上游就绪)
|
|
110
|
+
try {
|
|
111
|
+
const lastDate = stateMod.readState(stateMod.defaultStateFile())?.raccoonCheckin?.date || "";
|
|
112
|
+
if (shouldCatchUp({ lastDate, hour })) {
|
|
113
|
+
setTimeout(() => { runOnce("catch-up").catch(() => {}); }, 90_000).unref?.();
|
|
114
|
+
console.log(`[raccoon-checkin] catch-up scheduled (last=${lastDate || "never"})`);
|
|
115
|
+
}
|
|
116
|
+
} catch {}
|
|
117
|
+
// 每日定时:对齐到下一个计划点,跑完再约 24h 后
|
|
118
|
+
function arm() {
|
|
119
|
+
const delay = nextRunDelayMs(new Date(), hour);
|
|
120
|
+
setTimeout(() => {
|
|
121
|
+
runOnce("daily").catch(() => {}).finally(arm);
|
|
122
|
+
}, delay).unref?.();
|
|
123
|
+
}
|
|
124
|
+
arm();
|
|
125
|
+
return { enabled: true, hour, runOnce };
|
|
126
|
+
}
|
|
@@ -46,7 +46,7 @@ export function normalizeEndpointPath(v) {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
export function defaultModelsPath(id) {
|
|
49
|
-
if (String(id).toLowerCase() === "workbuddy") return "/console/
|
|
49
|
+
if (String(id).toLowerCase() === "workbuddy") return "/v3/config"; // 2026-10-10 现网实测:console 目录对多数 token 恒 401/500,产品文档 /v3/config 才稳定 200(与 globalworkbuddy 同源)
|
|
50
50
|
return "/models";
|
|
51
51
|
}
|
|
52
52
|
export function defaultChatPath(id) {
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, unlinkSync, copyFileSync, chmodSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { toInferenceModels } from "./claude-desktop/slots.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* -setto claude-desktop:把本机网关写成 **Claude Desktop on 3P** 的 profile。
|
|
8
|
+
*
|
|
9
|
+
* 落点与键面(官方 `claude.com/docs/third-party/claude-desktop/configuration` 「How keys are read」):
|
|
10
|
+
* - Windows 本地(非托管):`%LOCALAPPDATA%\Claude-3p\configLibrary\`
|
|
11
|
+
* - macOS:`~/Library/Application Support/Claude-3p/configLibrary/`
|
|
12
|
+
* - Linux:`~/.config/Claude-3p/configLibrary/`(`$XDG_CONFIG_HOME` 优先)
|
|
13
|
+
* 目录里 `_meta.json` 记「哪份配置生效」(`appliedId` + `entries[]`),每份配置是平级的 `<uuid>.json`。
|
|
14
|
+
* in-app 配置窗口(Developer → Configure Third-Party Inference…)写的就是这里,我们代劳。
|
|
15
|
+
*
|
|
16
|
+
* 三条硬红线(照 `src/sync-claude.js` 的既有纪律,不许松):
|
|
17
|
+
* 1. 只登记**自己那一条** entry(uuid 由端口派生 → 重跑原地更新、不堆条目),用户/窗口建的其它 entry 一字不动;
|
|
18
|
+
* 2. 现有 JSON 解析失败 → 一律拒写(那是用户在 App 里配过的东西,不是我们的草稿);
|
|
19
|
+
* 3. 文件里有明文 token → `0600`(新建带 mode + 存量补 chmod),半截 tmp 清理失败要把路径如实交出去。
|
|
20
|
+
*
|
|
21
|
+
* 不碰 `claude_desktop_config.json`(App 自己的 prefs),不碰托管策略(HKLM/HKCU\SOFTWARE\Policies\Claude
|
|
22
|
+
* 一旦存在,App 会整体忽略本地 configLibrary —— 那种情况 `-claude-desktop status` 会明说)。
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** configLibrary 目录(三平台 + env 覆盖,覆盖位专为单测隔离 HOME)。 */
|
|
26
|
+
export function claudeDesktopConfigDir() {
|
|
27
|
+
const env = process.env.MSLXDFF_CLAUDE_DESKTOP_DIR;
|
|
28
|
+
if (typeof env === "string" && env.trim()) return env.trim();
|
|
29
|
+
const home = os.homedir();
|
|
30
|
+
if (process.platform === "win32") {
|
|
31
|
+
const local = process.env.LOCALAPPDATA || join(home, "AppData", "Local");
|
|
32
|
+
return join(local, "Claude-3p", "configLibrary");
|
|
33
|
+
}
|
|
34
|
+
if (process.platform === "darwin") return join(home, "Library", "Application Support", "Claude-3p", "configLibrary");
|
|
35
|
+
const xdg = (process.env.XDG_CONFIG_HOME || "").trim() || join(home, ".config");
|
|
36
|
+
return join(xdg, "Claude-3p", "configLibrary");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 配置条目 id:由端口派生的确定性 UUID 形态(同 cc-switch 的路子,端口不同即不撞车)。 */
|
|
40
|
+
export function desktopConfigId(port) {
|
|
41
|
+
const p = String(Math.max(0, Number(port) || 0) % 1000000).padStart(12, "0");
|
|
42
|
+
return `00000000-0000-4000-8000-${p}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 纯函数:profile 对象(App 侧读的键面)。 */
|
|
46
|
+
export function buildDesktopProfile({ baseUrl = "", apiKey = "", rows = [], maxEffort } = {}) {
|
|
47
|
+
return {
|
|
48
|
+
inferenceProvider: "gateway",
|
|
49
|
+
inferenceCredentialKind: "static",
|
|
50
|
+
inferenceGatewayAuthScheme: "bearer", // 本仓鉴权只认 Authorization: Bearer(src/routes/helpers.js authorized())
|
|
51
|
+
inferenceGatewayBaseUrl: String(baseUrl),
|
|
52
|
+
inferenceGatewayApiKey: String(apiKey),
|
|
53
|
+
inferenceModels: toInferenceModels(rows, { maxEffort }),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function norm(text) {
|
|
58
|
+
return String(text || "").replace(/\r\n/g, "\n").trim();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function parseJsonOrThrow(text, file) {
|
|
62
|
+
try {
|
|
63
|
+
return JSON.parse(text);
|
|
64
|
+
} catch {
|
|
65
|
+
throw new Error(`JSON 解析失败,拒绝覆盖:${file}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function readJsonOr(file, { allowMissing = false } = {}) {
|
|
70
|
+
let raw;
|
|
71
|
+
try {
|
|
72
|
+
raw = readFileSync(file, "utf8");
|
|
73
|
+
} catch {
|
|
74
|
+
if (allowMissing) return null;
|
|
75
|
+
throw new Error(`读不到 ${file}`);
|
|
76
|
+
}
|
|
77
|
+
return parseJsonOrThrow(raw, file);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 一次性备份(已存在不覆盖):那份是「mslxdff 首次接管前」的原文。 */
|
|
81
|
+
function backupOnce(dir, file, backupDir) {
|
|
82
|
+
if (!existsSync(file)) return null;
|
|
83
|
+
const target = join(backupDir, `${desktopBase(file)}.bak`);
|
|
84
|
+
if (existsSync(target)) return null; // 已有更早的备份,不覆盖
|
|
85
|
+
try {
|
|
86
|
+
mkdirSync(backupDir, { recursive: true });
|
|
87
|
+
copyFileSync(file, target);
|
|
88
|
+
return target;
|
|
89
|
+
} catch {
|
|
90
|
+
return null; // 复制失败不阻塞写入,但绝不谎报「已备份」
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function desktopBase(file) {
|
|
94
|
+
return String(file).split(/[\\/]/).pop().replace(/\.json$/i, "");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 原子写(tmp → rename,Windows 占用时退回直写;tmp 里带明文 token 必须先擦再删)。 */
|
|
98
|
+
function writeFileSecure(file, text) {
|
|
99
|
+
const tmp = `${file}.tmp.${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
|
|
100
|
+
let leftover = null;
|
|
101
|
+
const sweep = () => {
|
|
102
|
+
if (!existsSync(tmp)) return;
|
|
103
|
+
try { unlinkSync(tmp); return; } catch { /* 占用,走擦除 */ }
|
|
104
|
+
try { writeFileSync(tmp, "", "utf8"); } catch { /* 擦不动也继续试删 */ }
|
|
105
|
+
try { unlinkSync(tmp); } catch { leftover = tmp; }
|
|
106
|
+
};
|
|
107
|
+
let written = false;
|
|
108
|
+
try {
|
|
109
|
+
try { writeFileSync(tmp, text, { encoding: "utf8", mode: 0o600 }); } catch { writeFileSync(tmp, text, "utf8"); }
|
|
110
|
+
try { chmodSync(tmp, 0o600); } catch { /* Windows 无 posix mode */ }
|
|
111
|
+
try {
|
|
112
|
+
renameSync(tmp, file);
|
|
113
|
+
written = true;
|
|
114
|
+
} catch {
|
|
115
|
+
try { writeFileSync(file, text, { encoding: "utf8", mode: 0o600 }); written = true; } catch { /* 交给下面 throw */ }
|
|
116
|
+
}
|
|
117
|
+
} finally {
|
|
118
|
+
sweep();
|
|
119
|
+
}
|
|
120
|
+
if (!written) throw new Error(`无法写入 ${file}(文件可能被其他进程占用)——配置未更新`);
|
|
121
|
+
try { chmodSync(file, 0o600); } catch { /* ignore */ }
|
|
122
|
+
return leftover;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 写 profile + 登记 `_meta.json`。
|
|
127
|
+
* @param {{port:number, token:string, rows:{slot:string,model:string,label?:string}[], dir?:string, baseUrl?:string, maxEffort?:string}} p
|
|
128
|
+
*/
|
|
129
|
+
export function syncToClaudeDesktop(p = {}) {
|
|
130
|
+
const dir = p.dir || claudeDesktopConfigDir();
|
|
131
|
+
const token = String(p.token || "");
|
|
132
|
+
if (!token) throw new Error("claude-desktop: token required(先跑 mslxdff -showtoken)");
|
|
133
|
+
const rows = Array.isArray(p.rows) ? p.rows : [];
|
|
134
|
+
if (!rows.length) throw new Error("claude-desktop: rows required(模型槽位为空)");
|
|
135
|
+
const port = Number(p.port) || 8989;
|
|
136
|
+
const baseUrl = p.baseUrl || `http://127.0.0.1:${port}`;
|
|
137
|
+
const id = desktopConfigId(port);
|
|
138
|
+
const configFile = join(dir, `${id}.json`);
|
|
139
|
+
const metaFile = join(dir, "_meta.json");
|
|
140
|
+
const backupDir = join(dirname(dir), "configLibrary.pre-mslxdff");
|
|
141
|
+
|
|
142
|
+
const nextProfile = buildDesktopProfile({ baseUrl, apiKey: token, rows, maxEffort: p.maxEffort });
|
|
143
|
+
const nextProfileText = `${JSON.stringify(nextProfile, null, 2)}\n`;
|
|
144
|
+
// 先读后写:任一份现有文件坏了就整体不动(避免「profile 换了、_meta 没登记」的半截状态)
|
|
145
|
+
// 幂等比较一律用**原文 vs 原文**:解析后的对象 stringify 是紧凑形,与盘上缩进形永远不等 → 会把「没变化」误报成「已更新」
|
|
146
|
+
const oldProfileText = existsSync(configFile) ? readFileSync(configFile, "utf8") : null;
|
|
147
|
+
const oldMetaText = existsSync(metaFile) ? readFileSync(metaFile, "utf8") : null;
|
|
148
|
+
const oldProfile = oldProfileText === null ? null : parseJsonOrThrow(oldProfileText, configFile);
|
|
149
|
+
const oldMeta = oldMetaText === null ? null : parseJsonOrThrow(oldMetaText, metaFile);
|
|
150
|
+
const nextMeta = mergeMeta(oldMeta, { id, name: `mslxdff:${port}` });
|
|
151
|
+
const nextMetaText = `${JSON.stringify(nextMeta, null, 2)}\n`;
|
|
152
|
+
const unchanged = oldProfileText !== null && oldMetaText !== null
|
|
153
|
+
&& norm(oldProfileText) === norm(nextProfileText) && norm(oldMetaText) === norm(nextMetaText);
|
|
154
|
+
if (unchanged) {
|
|
155
|
+
return { action: "updated", id, dir, configFile, metaFile, backup: null, changed: false, rows: rows.length, profile: nextProfile, meta: nextMeta };
|
|
156
|
+
}
|
|
157
|
+
const b1 = backupOnce(dir, configFile, backupDir);
|
|
158
|
+
const b2 = backupOnce(dir, metaFile, backupDir);
|
|
159
|
+
mkdirSync(dir, { recursive: true });
|
|
160
|
+
const l1 = writeFileSecure(configFile, nextProfileText);
|
|
161
|
+
const l2 = writeFileSecure(metaFile, nextMetaText);
|
|
162
|
+
return {
|
|
163
|
+
action: oldProfile ? "updated" : "inserted",
|
|
164
|
+
id, dir, configFile, metaFile,
|
|
165
|
+
backup: b1 || b2 || null,
|
|
166
|
+
backups: [b1, b2].filter(Boolean),
|
|
167
|
+
changed: true,
|
|
168
|
+
rows: rows.length,
|
|
169
|
+
profile: nextProfile,
|
|
170
|
+
meta: nextMeta,
|
|
171
|
+
tmpLeftover: [l1, l2].filter(Boolean),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** `_meta.json` 合并:只动我们那一条,其它 entry 与 appliedId 语义原样保留。 */
|
|
176
|
+
export function mergeMeta(existing, { id, name }) {
|
|
177
|
+
const base = existing && typeof existing === "object" && !Array.isArray(existing) ? { ...existing } : {};
|
|
178
|
+
const list = Array.isArray(base.entries) ? base.entries.slice() : [];
|
|
179
|
+
const entries = [];
|
|
180
|
+
let replaced = false;
|
|
181
|
+
for (const e of list) {
|
|
182
|
+
if (!e || typeof e !== "object") continue;
|
|
183
|
+
if (String(e.id || "") === String(id)) { entries.push({ ...e, name: String(name) }); replaced = true; }
|
|
184
|
+
else entries.push(e);
|
|
185
|
+
}
|
|
186
|
+
if (!replaced) entries.push({ id: String(id), name: String(name) });
|
|
187
|
+
return { ...base, appliedId: String(id), entries };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** 读当前生效配置(体检与 `--official` 用)。不抛错,一切异常如实回结构。 */
|
|
191
|
+
export function readClaudeDesktopProfile({ dir } = {}) {
|
|
192
|
+
const d = dir || claudeDesktopConfigDir();
|
|
193
|
+
const metaFile = join(d, "_meta.json");
|
|
194
|
+
const out = { dir: d, exists: existsSync(d), meta: null, appliedId: "", appliedName: "", appliedFile: "", profile: null, entries: [], error: "" };
|
|
195
|
+
if (!out.exists) { out.error = "目录不存在(App 从未进过 3P 模式,或路径不是本机默认)"; return out; }
|
|
196
|
+
let meta;
|
|
197
|
+
try { meta = readJsonOr(metaFile); } catch (e) { out.error = String(e?.message || e); return out; }
|
|
198
|
+
if (!meta || typeof meta !== "object") { out.error = "_meta.json 不是对象"; return out; }
|
|
199
|
+
out.meta = meta;
|
|
200
|
+
out.entries = Array.isArray(meta.entries) ? meta.entries : [];
|
|
201
|
+
out.appliedId = String(meta.appliedId || "");
|
|
202
|
+
const hit = out.entries.find((e) => String(e?.id || "") === out.appliedId) || null;
|
|
203
|
+
out.appliedName = hit ? String(hit.name || "") : "";
|
|
204
|
+
out.appliedFile = join(d, `${out.appliedId}.json`);
|
|
205
|
+
if (!out.appliedId) { out.error = "appliedId 为空(App 里没选任何配置)"; return out; }
|
|
206
|
+
try { out.profile = readJsonOr(out.appliedFile, { allowMissing: true }); } catch (e) { out.error = String(e?.message || e); }
|
|
207
|
+
if (!out.profile) out.error = out.error || `生效配置 ${out.appliedId}.json 读不到`;
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* `--official`:把 mslxdff 那条登记从 `_meta.json` 摘掉(不删配置、不吞别人的 entry)。
|
|
213
|
+
* 摘后若 `appliedId` 正是我们那条 → 置空,让 App 回到「未选配置」,用户在登录界面自选官方或别的配置。
|
|
214
|
+
*/
|
|
215
|
+
export function retireClaudeDesktopProfile({ port, dir } = {}) {
|
|
216
|
+
const d = dir || claudeDesktopConfigDir();
|
|
217
|
+
const metaFile = join(d, "_meta.json");
|
|
218
|
+
const id = desktopConfigId(port);
|
|
219
|
+
const rawText = existsSync(metaFile) ? readFileSync(metaFile, "utf8") : null;
|
|
220
|
+
const meta = rawText === null ? null : parseJsonOrThrow(rawText, metaFile);
|
|
221
|
+
if (!meta || !Array.isArray(meta.entries)) return { action: "none", dir: d, removed: false, remaining: 0 };
|
|
222
|
+
const before = meta.entries.length;
|
|
223
|
+
const entries = meta.entries.filter((e) => String(e?.id || "") !== id);
|
|
224
|
+
const appliedId = String(meta.appliedId || "") === id ? "" : String(meta.appliedId || "");
|
|
225
|
+
const next = { ...meta, entries, appliedId };
|
|
226
|
+
const nextText = `${JSON.stringify(next, null, 2)}\n`;
|
|
227
|
+
// 幂等判据一律「原文 vs 原文」:对象 stringify 是紧凑形,与盘上缩进形永远不等 → 会把「没变化」报成「已摘除」
|
|
228
|
+
if (rawText !== null && norm(rawText) === norm(nextText)) {
|
|
229
|
+
return { action: "unchanged", dir: d, removed: false, remaining: entries.length, appliedId };
|
|
230
|
+
}
|
|
231
|
+
backupOnce(d, metaFile, join(dirname(d), "configLibrary.pre-mslxdff"));
|
|
232
|
+
writeFileSecure(metaFile, nextText);
|
|
233
|
+
return { action: "retired", dir: d, removed: before !== entries.length, remaining: entries.length, appliedId, id };
|
|
234
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, unlinkSync, copyFileSync, chmodSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* -setto claude:把本机网关写进 Claude Code 的用户设置文件。
|
|
7
|
+
* 键面依据 code.claude.com/docs/en/settings-reference(model / modelPicker / env 三节):
|
|
8
|
+
* - `ANTHROPIC_BASE_URL` **不带 /v1** —— 客户端自己拼 `/v1/messages`(参考仓库 README 写 /v1 是它的错)
|
|
9
|
+
* - `env.ANTHROPIC_MODEL` 必须删 —— 它压过顶层 `model` 键,留着会让设置失效
|
|
10
|
+
* - `CLAUDE_CODE_ATTRIBUTION_HEADER=0` —— 我们把 system 折叠成单条,归因块必须在客户端就不发
|
|
11
|
+
* - `modelPicker.options[].behavesAs` 实测必需 —— 见下方 DEFAULT_BEHAVES_AS 注释
|
|
12
|
+
* 只动上述键,其余键与键序原样保留;解析失败一律拒写(那是用户手写的 hooks/permissions)。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const OUR_ENV_KEYS = [
|
|
16
|
+
"ANTHROPIC_BASE_URL",
|
|
17
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
18
|
+
"ANTHROPIC_MODEL", // 只删不写
|
|
19
|
+
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
|
|
20
|
+
"CLAUDE_CODE_ATTRIBUTION_HEADER",
|
|
21
|
+
"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS",
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
// 本机 Claude Code 对「不认识且无 behavesAs 映射」的 model id 直接拒跑,连请求都不发
|
|
25
|
+
// (实测 2026-10-09:`"big-pickle" isn't described by this version's model catalog; …map it with
|
|
26
|
+
// behavesAs on a modelPicker row`,加 behavesAs 后 `claude -p` 正常走通工具往返)。
|
|
27
|
+
// behavesAs 只改客户端的**本地能力推断**(effort / auto-compact 口径),不改变发给上游的模型;
|
|
28
|
+
// 上游不认的字段由 messagesToChatBody 统一丢,所以锚一个通用已知 id 即可。`--behaves-as ""` 可关。
|
|
29
|
+
const DEFAULT_BEHAVES_AS = "claude-sonnet-5";
|
|
30
|
+
|
|
31
|
+
/** Claude Code 用户设置文件路径(`CLAUDE_CONFIG_DIR` 优先,与 Claude Code 自身口径一致)。 */
|
|
32
|
+
export function claudeSettingsPath() {
|
|
33
|
+
const dir = process.env.CLAUDE_CONFIG_DIR;
|
|
34
|
+
if (typeof dir === "string" && dir.trim()) return join(dir.trim(), "settings.json");
|
|
35
|
+
return join(os.homedir(), ".claude", "settings.json");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 纯函数:existing 对象 + 上下文 → 新对象。除我们的键外一律原样保留(含键序,JSON 键序随插入顺序)。 */
|
|
39
|
+
export function buildClaudeSettings(existing, ctx = {}) {
|
|
40
|
+
const out = existing && typeof existing === "object" && !Array.isArray(existing) ? { ...existing } : {};
|
|
41
|
+
const env = { ...(out.env && typeof out.env === "object" && !Array.isArray(out.env) ? out.env : {}) };
|
|
42
|
+
env.ANTHROPIC_BASE_URL = String(ctx.baseUrl || "");
|
|
43
|
+
env.ANTHROPIC_AUTH_TOKEN = String(ctx.token || "");
|
|
44
|
+
env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
|
|
45
|
+
env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0";
|
|
46
|
+
env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = "1";
|
|
47
|
+
delete env.ANTHROPIC_MODEL;
|
|
48
|
+
out.env = env;
|
|
49
|
+
out.model = String(ctx.model || "");
|
|
50
|
+
const picks = Array.isArray(ctx.picks) && ctx.picks.length ? ctx.picks : [ctx.model];
|
|
51
|
+
// behavesAs 的含义是「该 id 不在客户端模型目录里,请按 X 的能力口径推断」。
|
|
52
|
+
// 客户端本来就认识的 claude-* id 不该被这么标:把 claude-opus 标成 behavesAs=claude-sonnet-5,
|
|
53
|
+
// 客户端就会按 sonnet 的 effort / auto-compact 口径去推断它。显式 --behaves-as 仍覆盖一切。
|
|
54
|
+
const override = ctx.behavesAs == null ? null : String(ctx.behavesAs);
|
|
55
|
+
const anchorOf = (m) => (override != null ? override : /^claude[-.]/i.test(String(m)) ? "" : DEFAULT_BEHAVES_AS);
|
|
56
|
+
out.modelPicker = {
|
|
57
|
+
options: picks.filter(Boolean).map((m) => {
|
|
58
|
+
const row = { model: String(m), label: String(m) };
|
|
59
|
+
const anchor = anchorOf(m);
|
|
60
|
+
if (anchor) row.behavesAs = anchor;
|
|
61
|
+
return row;
|
|
62
|
+
}),
|
|
63
|
+
};
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 归一化用于幂等比较(忽略换行符与首尾空白差异)
|
|
68
|
+
function norm(text) {
|
|
69
|
+
return String(text || "").replace(/\r\n/g, "\n").trim();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 写盘。返回 { action, file, id, backup, changed, rows }。
|
|
74
|
+
* @param {{id?:string, token?:string, port?:number, picks?:string[], file?:string, baseUrl?:string, behavesAs?:string}} p
|
|
75
|
+
*/
|
|
76
|
+
export function syncToClaude(p = {}) {
|
|
77
|
+
const targetFile = p.file || claudeSettingsPath();
|
|
78
|
+
const model = String(p.id ?? p.model ?? "").trim();
|
|
79
|
+
if (!model) throw new Error("claude settings: model id required");
|
|
80
|
+
const token = String(p.token || "");
|
|
81
|
+
if (!token) throw new Error("claude settings: token required(先跑 mslxdff -showtoken)");
|
|
82
|
+
const baseUrl = p.baseUrl || `http://127.0.0.1:${Number(p.port) || 8989}`;
|
|
83
|
+
const picks = Array.isArray(p.picks) && p.picks.length ? p.picks : [model];
|
|
84
|
+
|
|
85
|
+
let existed = false;
|
|
86
|
+
let originalText = "";
|
|
87
|
+
try {
|
|
88
|
+
originalText = readFileSync(targetFile, "utf8");
|
|
89
|
+
existed = true;
|
|
90
|
+
} catch {
|
|
91
|
+
existed = false;
|
|
92
|
+
}
|
|
93
|
+
let originalObj = null;
|
|
94
|
+
if (existed) {
|
|
95
|
+
try {
|
|
96
|
+
originalObj = JSON.parse(originalText);
|
|
97
|
+
} catch {
|
|
98
|
+
throw new Error(`claude settings 解析失败,拒绝覆盖:${targetFile}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const next = buildClaudeSettings(originalObj, { baseUrl, token, model, picks, behavesAs: p.behavesAs });
|
|
103
|
+
const nextText = `${JSON.stringify(next, null, 2)}\n`;
|
|
104
|
+
if (existed && norm(originalText) === norm(nextText)) {
|
|
105
|
+
return { action: "updated", file: targetFile, id: model, backup: null, changed: false, rows: next.modelPicker.options.length };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 备份只保留「mslxdff 首次接管前」那一份:已存在就不覆盖(代价:用户后来手改的内容不进备份)
|
|
109
|
+
let backup = null;
|
|
110
|
+
if (existed) {
|
|
111
|
+
const backupFile = join(dirname(targetFile), "settings.pre-mslxdff.json");
|
|
112
|
+
if (!existsSync(backupFile)) {
|
|
113
|
+
try { copyFileSync(targetFile, backupFile); backup = backupFile; } catch { /* 复制失败不阻塞写入,但绝不谎报「已备份」 */ }
|
|
114
|
+
}
|
|
115
|
+
// 只在**本次真复制过**时返回路径(spec R6「打印备份路径(若本次生成)」);已有旧备份时返回 null,
|
|
116
|
+
// 由 CLI 换成「已存在更早的备份」提示 —— 免得用户拿首份旧备份去覆盖自己后来的手改。
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
mkdirSync(dirname(targetFile), { recursive: true });
|
|
120
|
+
const tmp = `${targetFile}.tmp.${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
|
|
121
|
+
// 凭据落地红线:文件里有明文 token → 0600(mode 只在新建时生效,故存量补 chmod)
|
|
122
|
+
let written = false;
|
|
123
|
+
let tmpLeftover = null;
|
|
124
|
+
// 半截 tmp 里带明文 token:unlink 也可能被占用(Windows 上正是 rename 失败的同因),
|
|
125
|
+
// 所以先擦内容再试一次;仍清不掉就把路径如实交出去,让 CLI 告警,绝不静默。
|
|
126
|
+
const sweepTmp = () => {
|
|
127
|
+
if (!existsSync(tmp)) return;
|
|
128
|
+
try { unlinkSync(tmp); return; } catch { /* 占用,走擦除 */ }
|
|
129
|
+
try { writeFileSync(tmp, "", { encoding: "utf8" }); } catch { /* 擦不动也继续试删 */ }
|
|
130
|
+
try { unlinkSync(tmp); } catch { tmpLeftover = tmp; }
|
|
131
|
+
};
|
|
132
|
+
try {
|
|
133
|
+
try { writeFileSync(tmp, nextText, { encoding: "utf8", mode: 0o600 }); } catch { writeFileSync(tmp, nextText, "utf8"); }
|
|
134
|
+
try { chmodSync(tmp, 0o600); } catch { /* Windows 无 posix mode,忽略 */ }
|
|
135
|
+
try {
|
|
136
|
+
renameSync(tmp, targetFile);
|
|
137
|
+
written = true;
|
|
138
|
+
} catch {
|
|
139
|
+
// rename 失败多见于目标被别的进程占用(Windows 常态):退回直写;仍失败就报错,绝不谎报「已同步」
|
|
140
|
+
try { writeFileSync(targetFile, nextText, { encoding: "utf8", mode: 0o600 }); written = true; } catch { /* 交给下面的 throw */ }
|
|
141
|
+
}
|
|
142
|
+
} finally {
|
|
143
|
+
sweepTmp();
|
|
144
|
+
}
|
|
145
|
+
if (!written) {
|
|
146
|
+
throw new Error(`无法写入 ${targetFile}(文件可能被其他进程占用)——配置未更新;原文见同目录 settings.pre-mslxdff.json${tmpLeftover ? `;另有清理失败的临时文件 ${tmpLeftover}(内含明文 token,请手动删除)` : ""}`);
|
|
147
|
+
}
|
|
148
|
+
try { chmodSync(targetFile, 0o600); } catch { /* ignore */ }
|
|
149
|
+
return { action: existed ? "updated" : "inserted", file: targetFile, id: model, backup, changed: true, rows: next.modelPicker.options.length, tmpLeftover };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export { OUR_ENV_KEYS, DEFAULT_BEHAVES_AS };
|
package/src/talk-full.js
CHANGED
|
@@ -94,7 +94,7 @@ export async function flushAgentLoop() {
|
|
|
94
94
|
* ① 开关 ② hops>0(组员转发的对话不落盘,spec「只捕获本机自发流量」)③ 两侧全空且 status≠200 ④ 受理。
|
|
95
95
|
* 任何异常吞掉返回 false,MUST NOT 抛出影响请求。
|
|
96
96
|
*/
|
|
97
|
-
export function recordAgentLoop({ reqId, model, via, hops, body, out, sessionKey, clientIp, echo, attemptMs, relayMs } = {}) {
|
|
97
|
+
export function recordAgentLoop({ reqId, model, via, hops, body, out, sessionKey, clientIp, echo, attemptMs, relayMs, api } = {}) {
|
|
98
98
|
if (!agentLoopEnabled()) return false;
|
|
99
99
|
try {
|
|
100
100
|
if (Number(hops) > 0) return false;
|
|
@@ -109,7 +109,7 @@ export function recordAgentLoop({ reqId, model, via, hops, body, out, sessionKey
|
|
|
109
109
|
const rec = {
|
|
110
110
|
ts: at, time: fmtShanghaiYMDHMS(new Date(at)),
|
|
111
111
|
reqId: reqId ?? null, sessionKey: normSessionKey(sessionKey, msgs), clientIp: clientIp ?? null,
|
|
112
|
-
model: String(model || "unknown"), via: via ?? null,
|
|
112
|
+
model: String(model || "unknown"), via: via ?? null, ...(api ? { api: String(api) } : {}),
|
|
113
113
|
hops: hops == null || hops === "" || !Number.isFinite(Number(hops)) ? null : Number(hops),
|
|
114
114
|
status, stream: body?.stream ? 1 : 0, elapsedMs: elapsedOf(attemptMs, out?.totalMs),
|
|
115
115
|
usage: out?.detail?.usage ?? null, finishReason: out?.detail?.sawFinishReason ?? null,
|
package/src/talk-log.js
CHANGED
|
@@ -94,17 +94,20 @@ function pushBlock(out, label, text, cap) {
|
|
|
94
94
|
// 撞捕获上限时紧跟头部行的人类可读提醒:不必先认识 truncated=1 这个键名也能一眼看出「可能不完整」。
|
|
95
95
|
const TRUNC_NOTE = "[!] 本轮已撞捕获上限(truncated=1):思考/正文后半段未落盘,内容可能不完整 —— 别当成模型的完整回答";
|
|
96
96
|
|
|
97
|
-
/** 一条对话 = 一个可读块:头部一行元信息(ts= 是环形淘汰的唯一依据),正文三段。elapsed= 取本次尝试墙钟(design D3),finish=/relayMs= 为 ADR-0046
|
|
98
|
-
export function formatTalkEntry({ reqId, model, via, hops, status, stream, elapsedMs, question, thinking, answer, tools, usage, upstream, account, pick, ts, talkCapped = false, talkChars, talkCap, finishReason, relayMs } = {}) {
|
|
97
|
+
/** 一条对话 = 一个可读块:头部一行元信息(ts= 是环形淘汰的唯一依据),正文三段。elapsed= 取本次尝试墙钟(design D3),finish=/relayMs= 为 ADR-0046 新读数,api= 为入站协议门短码(认不出的路 = other;未拿到判定值则整段省略,绝不伪造)。 */
|
|
98
|
+
export function formatTalkEntry({ reqId, api, model, via, hops, status, stream, elapsedMs, question, thinking, answer, tools, usage, upstream, account, pick, ts, talkCapped = false, talkChars, talkCap, finishReason, relayMs, ttftMs } = {}) {
|
|
99
99
|
const fval = finishReason || "-"; // 缺值占位(grill Q5):「没给 finish」不得被读成 stop;字段恒在场
|
|
100
100
|
const now = Number.isFinite(ts) && ts > 0 ? ts : Date.now();
|
|
101
101
|
const trunc = talkCapped === true;
|
|
102
102
|
const head = [
|
|
103
103
|
`${MARK} ts=${now}`, `time=${fmtShanghaiYMDHMS(new Date(now))}`, `req=${reqId || "-"}`, `model=${model || "-"}`,
|
|
104
|
-
via ? `via=${via}` : "", hops != null ? `hops=${hops}` : "", `status=${status ?? "-"}`,
|
|
104
|
+
api ? `api=${api}` : "", via ? `via=${via}` : "", hops != null ? `hops=${hops}` : "", `status=${status ?? "-"}`,
|
|
105
105
|
stream ? "stream=1" : "stream=0", Number.isFinite(elapsedMs) ? `elapsed=${Math.round(elapsedMs)}ms` : "",
|
|
106
106
|
// 尝试墙钟与 relay 内部计时同值时不重复打印(头行噪音克制,grill Q3);两值不同(hedge/缓冲重放)才另列 relayMs
|
|
107
107
|
Number.isFinite(relayMs) && Number.isFinite(elapsedMs) && Math.round(relayMs) !== Math.round(elapsedMs) ? `relayMs=${Math.round(relayMs)}ms` : "",
|
|
108
|
+
// 首字耗时(客户端从本次尝试起点到网关写出第一帧,含上游 prefill):「答案忽然冒出」类问题的第一读数。
|
|
109
|
+
// 只在真有值时出现(非流式/拿不到首块 = null,不打印而非写 0,0 会被读成「秒回」)。
|
|
110
|
+
Number.isFinite(ttftMs) ? `ttft=${Math.round(ttftMs)}ms` : "",
|
|
108
111
|
`finish=${fval}`,
|
|
109
112
|
usage ? `usage(prompt=${usage.prompt_tokens ?? "-"},completion=${usage.completion_tokens ?? "-"})` : "",
|
|
110
113
|
upstream ? `upstream=${upstream}` : "", account ? `account=${account}` : "", pick ? `pick=${pick}` : "",
|
|
@@ -203,7 +206,7 @@ export function trimTalkLog(file, nowTs = Date.now()) {
|
|
|
203
206
|
* 桶的 capped/n/cap 必须一路传到 formatTalkEntry:撞顶的那条要能看出「后半截没了」。
|
|
204
207
|
* attemptMs(本次上游尝试墙钟)由调用点传入;未传(拿不到尝试起点)回退 out.totalMs —— 此时 elapsed 与 relayMs 同值(spec 降级 scenario)。
|
|
205
208
|
*/
|
|
206
|
-
export function recordRelayTalk({ reqId, model, via, hops, body, out, echo = {}, attemptMs, finishReason } = {}) {
|
|
209
|
+
export function recordRelayTalk({ reqId, api, model, via, hops, body, out, echo = {}, attemptMs, ttftMs, finishReason } = {}) {
|
|
207
210
|
if (!talkLogEnabled()) return false;
|
|
208
211
|
try {
|
|
209
212
|
const talk = out?.detail?.talk;
|
|
@@ -215,9 +218,9 @@ export function recordRelayTalk({ reqId, model, via, hops, body, out, echo = {},
|
|
|
215
218
|
if (!answer && !thinking && !tools) return false;
|
|
216
219
|
const ts = Date.now();
|
|
217
220
|
const block = formatTalkEntry({
|
|
218
|
-
reqId, model, via, hops, status, stream: Boolean(body?.stream), finishReason: finishReason ?? out?.detail?.sawFinishReason,
|
|
221
|
+
reqId, api, model, via, hops, status, stream: Boolean(body?.stream), finishReason: finishReason ?? out?.detail?.sawFinishReason,
|
|
219
222
|
elapsedMs: Number.isFinite(Number(attemptMs)) ? Number(attemptMs) : out?.totalMs, // 新口径:本次尝试墙钟优先(design D3)
|
|
220
|
-
relayMs: out?.totalMs, question: lastUserQuestion(body || {}),
|
|
223
|
+
relayMs: out?.totalMs, ttftMs, question: lastUserQuestion(body || {}),
|
|
221
224
|
thinking, answer, tools, usage: out?.detail?.usage, ...echo, ts,
|
|
222
225
|
talkCapped: talk?.capped === true, talkChars: talk?.n, talkCap: talk?.cap,
|
|
223
226
|
});
|