mslxdff 0.1.164 → 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.
Files changed (56) hide show
  1. package/package.json +1 -1
  2. package/src/anthropic/translate.js +23 -5
  3. package/src/anthropic/web-search.js +361 -0
  4. package/src/api-kind.js +31 -0
  5. package/src/chat-pipeline/auto-race.js +8 -0
  6. package/src/chat-pipeline/empty-turn.js +28 -0
  7. package/src/chat-pipeline/index.js +8 -4
  8. package/src/chat-pipeline/serial-trial.js +8 -1
  9. package/src/claude-desktop/apply.js +64 -0
  10. package/src/claude-desktop/doctor.js +146 -0
  11. package/src/claude-desktop/slots.js +86 -0
  12. package/src/cli/commands/claude-desktop.js +264 -0
  13. package/src/cli/commands/model/list-providers.js +1 -1
  14. package/src/cli/commands/provider/index.js +7 -0
  15. package/src/cli/commands/provider/models.js +3 -0
  16. package/src/cli/commands/provider/raccoon-login.js +131 -0
  17. package/src/cli/commands/provider/raccoon-quota.js +109 -0
  18. package/src/cli/commands/sync.js +8 -2
  19. package/src/cli/format.js +1 -1
  20. package/src/cli/help.js +2 -0
  21. package/src/cli/index.js +2 -0
  22. package/src/cli/provider-row.js +2 -2
  23. package/src/model-capabilities/parse.js +1 -1
  24. package/src/model-trace.js +2 -1
  25. package/src/providers/classify.js +1 -1
  26. package/src/providers/dispatcher.js +2 -2
  27. package/src/providers/keyring.js +1 -1
  28. package/src/providers/model-id.js +10 -0
  29. package/src/providers/raccoon/account-store.js +216 -0
  30. package/src/providers/raccoon/auth.js +67 -0
  31. package/src/providers/raccoon/chat.js +207 -0
  32. package/src/providers/raccoon/const.js +111 -0
  33. package/src/providers/raccoon/credits.js +161 -0
  34. package/src/providers/raccoon/envelope.js +23 -0
  35. package/src/providers/raccoon/headers.js +45 -0
  36. package/src/providers/raccoon/index.js +216 -0
  37. package/src/providers/raccoon/login.js +195 -0
  38. package/src/providers/raccoon/models.js +160 -0
  39. package/src/providers/raccoon/qr-codewords.js +115 -0
  40. package/src/providers/raccoon/qr.js +236 -0
  41. package/src/providers/raccoon/sse.js +135 -0
  42. package/src/providers/registry.js +5 -0
  43. package/src/providers/share-keys.js +1 -1
  44. package/src/providers/workbuddy/models.js +29 -14
  45. package/src/providers/workbuddy/payload.js +34 -0
  46. package/src/routes/chat/exhausted-handler.js +4 -4
  47. package/src/routes/chat/relay-pipeline.js +6 -7
  48. package/src/routes/messages-route.js +114 -3
  49. package/src/runtime/bootstrap.js +5 -0
  50. package/src/runtime/broadband.js +4 -1
  51. package/src/runtime/provider-gate.js +3 -1
  52. package/src/runtime/raccoon-checkin.js +126 -0
  53. package/src/state/provider-config.js +1 -1
  54. package/src/sync-claude-desktop.js +234 -0
  55. package/src/talk-full.js +2 -2
  56. package/src/talk-log.js +9 -6
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * POST /v1/messages + /v1/messages/count_tokens — 给 Claude Code 用的 Anthropic Messages 外壳(ADR-0047)。
3
3
  * 复用 ChatPipeline 全链路(auto/hedge/failover/tool_calls/空轮重试),只做形状翻译:
4
- * 非流式:收集 chat JSON → 转 Anthropic message;流式:逐块实时翻成 Anthropic 具名事件。
4
+ * 非流式:收集 chat JSON → 转 Anthropic message(上游只会流式时先把 SSE 聚合成 chat JSON);流式:逐块实时翻成 Anthropic 具名事件。
5
5
  *
6
6
  * 出站格式与 /v1/responses **不兼容**,故不能复用 createLiveForwarder(它写死 `data:` + `[DONE]`):
7
7
  * Anthropic 用 `event: <type>` 具名帧、无 `[DONE]`,且需网关自发 `ping` 扛过客户端 idle watchdog。
@@ -22,13 +22,23 @@ import {
22
22
  estimateTokens,
23
23
  anthropicError,
24
24
  } from "../anthropic/translate.js";
25
+ import {
26
+ detectSearchRequest,
27
+ runWebSearch,
28
+ searchConfig,
29
+ buildSearchMessage,
30
+ searchEvents,
31
+ } from "../anthropic/web-search.js";
25
32
 
26
33
  const ADEBUG = process.env.MSLXDFF_ANTHROPIC_DEBUG === "1";
27
34
  function alog(...a) {
28
35
  if (ADEBUG) console.log("[messages]", ...a);
29
36
  }
30
37
 
31
- const THINKING = process.env.MSLXDFF_ANTHROPIC_THINKING === "1";
38
+ // thinking 块外发:默认开,`MSLXDFF_ANTHROPIC_THINKING=0` 才关。外发的 thinking 块必须在封口前交一帧占位
39
+ // signature_delta(translate.js 的 thinkingSignature),缺它 Claude Code 整块丢弃 — ADR-0051 外发 / ADR-0052 签名
40
+ function emitThinking() { return process.env.MSLXDFF_ANTHROPIC_THINKING !== "0"; }
41
+
32
42
  // 空闲 ping 周期(ms):`0` 关闭;客户端长思考期靠它扛过 streaming idle timeout
33
43
  const PING_MS = (() => {
34
44
  const raw = Number(process.env.MSLXDFF_ANTHROPIC_PING_MS);
@@ -90,6 +100,48 @@ function tryAggregate(text) {
90
100
  return null;
91
101
  }
92
102
  }
103
+ // 客户端要非流式而上游只会流式(workbuddy 在 provider 层写死 stream:true,SSE 硬吃回来):
104
+ // collector 收到的 text 是 SSE 帧序列而非 JSON,JSON.parse 必炸 → 此前恒 502。逐行吃 data: 帧
105
+ // 聚成 chat.completion JSON(与 qoder/aggregate.js、zcode 非流式聚合同构),出口复用 chatJsonToAnthropic;
106
+ // 一帧都没有或夹带 in-band 错误帧时返回 null,落回原有 502 + errorText 路径(错误绝不聚合成正文)。
107
+ function sseToChatJson(text, model) {
108
+ let content = "";
109
+ let finish = "";
110
+ let usage = null;
111
+ let sawChunk = false;
112
+ const toolSlots = new Map();
113
+ for (const raw of String(text || "").split("\n")) {
114
+ const line = raw.trim();
115
+ if (!line.startsWith("data:")) continue; // 注释帧/keepalive/事件名行全跳过
116
+ const payload = line.slice(5).trim();
117
+ if (!payload || payload === "[DONE]") continue;
118
+ let chunk;
119
+ try { chunk = JSON.parse(payload); } catch { continue; }
120
+ if (chunk?.error) return null;
121
+ sawChunk = true;
122
+ const choice = chunk.choices?.[0] || {};
123
+ const delta = choice.delta || {};
124
+ if (choice.finish_reason) finish = choice.finish_reason;
125
+ if (chunk.usage) usage = chunk.usage;
126
+ if (typeof delta.content === "string" && delta.content) content += delta.content;
127
+ for (const tc of delta.tool_calls || []) {
128
+ const slot = Number(tc?.index ?? 0);
129
+ let t = toolSlots.get(slot);
130
+ if (!t) { t = { id: "", name: "", args: "" }; toolSlots.set(slot, t); }
131
+ if (tc?.id) t.id = String(tc.id);
132
+ if (tc?.function?.name) t.name += String(tc.function.name);
133
+ if (tc?.function?.arguments) t.args += String(tc.function.arguments);
134
+ }
135
+ }
136
+ if (!sawChunk) return null;
137
+ const toolCalls = [...toolSlots.values()].map((t, i) => ({ id: t.id || `call_${i}`, type: "function", function: { name: t.name, arguments: t.args || "{}" } }));
138
+ const message = { role: "assistant", content: content || (toolCalls.length ? null : "") };
139
+ if (toolCalls.length) message.tool_calls = toolCalls;
140
+ return { id: "", object: "chat.completion", created: Math.floor(Date.now() / 1000), model,
141
+ choices: [{ index: 0, message, finish_reason: finish || (toolCalls.length ? "tool_calls" : "stop") }],
142
+ usage: usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 } };
143
+ }
144
+
93
145
 
94
146
  /**
95
147
  * Anthropic 出站垫片:具名事件 + 无 [DONE] + 空闲自发 ping + 真 headersSent。
@@ -217,6 +269,29 @@ export function createAnthropicForwarder(realRes, translator, opts = {}) {
217
269
  return res;
218
270
  }
219
271
 
272
+ /**
273
+ * 代跑结果回给客户端:非流式整包 JSON,流式由同一份块生成的具名事件(无 `[DONE]`)。
274
+ * 搜索在调用前就跑完了,这里一次写完即可,不需要 createAnthropicForwarder 的 ping 垫片。
275
+ */
276
+ function respondSearch(res, { message, stream, provider }, isDead) {
277
+ if (isDead && isDead()) return undefined; // 搜索期间客户端断连:别再写任何字节
278
+ if (!stream) {
279
+ try { res.setHeader?.("x-mslxdff-web-search", provider); } catch { /* 已 flush */ }
280
+ try { return json(res, 200, message); } catch { return undefined; /* 下游已断 */ }
281
+ }
282
+ try {
283
+ res.writeHead(200, {
284
+ "Content-Type": "text/event-stream",
285
+ "Cache-Control": "no-cache",
286
+ Connection: "keep-alive",
287
+ "x-mslxdff-web-search": provider,
288
+ });
289
+ for (const e of searchEvents(message)) res.write(frameOf(e.type, e));
290
+ res.end();
291
+ } catch { /* 下游已断 */ }
292
+ return undefined;
293
+ }
294
+
220
295
  export async function messagesHandler(ctx) {
221
296
  const { req, res } = ctx;
222
297
  const t0 = Date.now();
@@ -226,6 +301,39 @@ export async function messagesHandler(ctx) {
226
301
  } catch {
227
302
  return json(res, 400, anthropicError("invalid_request_error", "Invalid JSON body"));
228
303
  }
304
+ // —— 网关代跑 web_search(ADR-0049):旁路请求**一律由网关作答**——命中判据即不打模型。
305
+ // 搜到就回结果块;关了/全挂/空查询就回一条明确的 400(把无工具的旁路丢给上游,只会让模型凭空
306
+ // 编 URL 并让客户端按「0 次搜索」空转重试,那才是改前的老毛病)。主循环请求不受影响。
307
+ // 整段包 try:搜索期最长 15s,其间客户端可能已断连(`isDead`),任何意外都不得逃逸成 5xx。
308
+ const det = detectSearchRequest(body);
309
+ if (det.hit) {
310
+ const isDead = () => res.writableEnded === true || res.destroyed === true || res.headersSent === true;
311
+ const wsCfg = searchConfig();
312
+ let r;
313
+ if (!wsCfg.enabled) r = { ok: false, error: "disabled by MSLXDFF_WEB_SEARCH=off" };
314
+ else {
315
+ try {
316
+ r = det.query ? await runWebSearch(det.query, wsCfg) : { ok: false, error: "empty query" };
317
+ } catch (e) {
318
+ r = { ok: false, error: String(e?.message || e) };
319
+ }
320
+ }
321
+ if (r.ok) {
322
+ const readout = { provider: r.provider, ms: r.ms, results: r.results.length, queryChars: r.query.length, chain: r.chain || [] };
323
+ alog("web-search", JSON.stringify(readout));
324
+ try { ctx.logs?.appendEvent?.({ type: "web-search", ...readout }); } catch { /* 观测产物不参与判决 */ }
325
+ return respondSearch(res, {
326
+ message: buildSearchMessage({ model: String(body.model || ""), query: r.query, results: r.results }),
327
+ stream: Boolean(body.stream),
328
+ provider: r.provider,
329
+ }, isDead);
330
+ }
331
+ const why = String(r.error || "unknown").slice(0, 200);
332
+ alog("web-search-unavailable", why);
333
+ try { ctx.logs?.appendEvent?.({ type: "web-search-unavailable", queryChars: (det.query || "").length, error: why, chain: r.chain || [] }); } catch { /* 同上 */ }
334
+ if (isDead()) return undefined;
335
+ try { return json(res, 400, anthropicError("invalid_request_error", `web search failed at the gateway: ${why}`)); } catch { return undefined; }
336
+ }
229
337
  let chatBody;
230
338
  try {
231
339
  chatBody = messagesToChatBody(body);
@@ -243,7 +351,7 @@ export async function messagesHandler(ctx) {
243
351
  const forwardClose = (shim) => { try { req.on?.("close", () => shim.emit("close")); } catch { /* ignore */ } };
244
352
  try {
245
353
  if (chatBody.stream) {
246
- const translator = createAnthropicChunkTranslator(chatBody.model, { thinking: THINKING });
354
+ const translator = createAnthropicChunkTranslator(chatBody.model, { thinking: emitThinking() });
247
355
  const live = createAnthropicForwarder(res, translator);
248
356
  forwardClose(live);
249
357
  await pipeline.execute({ req: fakeReq, res: live });
@@ -256,6 +364,9 @@ export async function messagesHandler(ctx) {
256
364
  if (status >= 400) return json(res, status, anthropicError("api_error", errorText(text) || String(text).slice(0, 500)));
257
365
  let chatJson = null;
258
366
  try { chatJson = JSON.parse(text); } catch { /* 非 JSON */ }
367
+ // 上游只会流式(workbuddy 写死 stream:true):非流式收到的 text 是 SSE → 聚成 chat JSON 再走同一翻译出口;
368
+ // 空流/错误帧聚合不出 JSON 时仍落回下方原 502 路径。
369
+ if (!chatJson) chatJson = sseToChatJson(text, chatBody.model);
259
370
  if (!chatJson || chatJson.error || chatJson.object === "error") {
260
371
  return json(res, status >= 400 ? status : 502, anthropicError("api_error", errorText(text) || String(text).slice(0, 500)));
261
372
  }
@@ -38,6 +38,11 @@ export async function startDaemonMain(VERSION) {
38
38
  try { logs.appendEvent({ ts: Date.now(), type: "qoder-checkin-setup-failed", error: String(e?.message || e).slice(0, 200) }); } catch {}
39
39
  });
40
40
 
41
+ const { setupRaccoonCheckin } = await import("./raccoon-checkin.js");
42
+ void setupRaccoonCheckin({ bus, logs }).catch((e) => {
43
+ try { logs.appendEvent({ ts: Date.now(), type: "raccoon-checkin-setup-failed", error: String(e?.message || e).slice(0, 200) }); } catch {}
44
+ });
45
+
41
46
  const { setupWorkbuddyGrowth } = await import("./workbuddy-growth.js");
42
47
  void setupWorkbuddyGrowth({ bus, logs }).catch((e) => {
43
48
  try { logs.appendEvent({ ts: Date.now(), type: "workbuddy-growth-setup-failed", error: String(e?.message || e).slice(0, 200) }); } catch {}
@@ -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(body);
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/enterprises/personal/models";
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
+ }
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
  });