mslxdff 0.1.162 → 0.1.164

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 (37) hide show
  1. package/package.json +1 -1
  2. package/src/anthropic/translate.js +379 -0
  3. package/src/chat-pipeline/index.js +3 -2
  4. package/src/cli/commands/stats.js +21 -9
  5. package/src/cli/commands/sync.js +74 -2
  6. package/src/cli/help.js +2 -1
  7. package/src/providers/globalworkbuddy/account-store.js +198 -0
  8. package/src/providers/globalworkbuddy/auth.js +97 -0
  9. package/src/providers/globalworkbuddy/catalog.js +138 -0
  10. package/src/providers/globalworkbuddy/constants.js +73 -0
  11. package/src/providers/globalworkbuddy/device-auth.js +120 -0
  12. package/src/providers/globalworkbuddy/errors.js +98 -0
  13. package/src/providers/globalworkbuddy/headers.js +89 -0
  14. package/src/providers/globalworkbuddy/models.js +96 -0
  15. package/src/providers/globalworkbuddy/payload.js +80 -0
  16. package/src/providers/qoder/aggregate.js +12 -3
  17. package/src/providers/qoder/chat.js +9 -2
  18. package/src/providers/qoder/index.js +13 -3
  19. package/src/providers/qoder/models.js +7 -3
  20. package/src/providers/qoder/payload.js +7 -1
  21. package/src/providers/qoder/request.js +2 -1
  22. package/src/providers/qoder/sse.js +5 -1
  23. package/src/providers/qoder/stream.js +16 -4
  24. package/src/routes/chat/exhausted-handler.js +13 -2
  25. package/src/routes/chat/relay-pipeline.js +18 -2
  26. package/src/routes/index.js +13 -0
  27. package/src/routes/messages-route.js +290 -0
  28. package/src/routes/responses-route.js +2 -2
  29. package/src/routes/stream-scan.js +22 -5
  30. package/src/routes/stream.js +2 -3
  31. package/src/server.js +5 -0
  32. package/src/sync-claude.js +152 -0
  33. package/src/talk-full-redact.js +129 -0
  34. package/src/talk-full.js +130 -0
  35. package/src/talk-log.js +42 -15
  36. package/src/upstream-engine/sdk/responses.js +5 -0
  37. package/src/usage/report.js +14 -8
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mslxdff",
3
- "version": "0.1.162",
3
+ "version": "0.1.164",
4
4
  "description": "测试项目,请勿使用。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Anthropic Messages ⇄ OpenAI chat 翻译层(/v1/messages 外壳,ADR-0047)。
3
+ * 纯函数,无网络、无副作用;出站形状依据 code.claude.com/docs/en/llm-gateway-protocol
4
+ * 与参考实现 lamdt1/ms-copilot365-2api/app/formatters/anthropic_sse.py。
5
+ *
6
+ * 与 src/responses/translate.js 的三点关键差异:
7
+ * 1) Anthropic 的 content block **只封口不复用**(Responses 侧 ensureTextItem 会复用已开项);
8
+ * 2) 事件是具名的(`event: <type>` + `data:`),且**没有 `data: [DONE]`**,收场只有
9
+ * `message_delta`+`message_stop`(成功)或一帧 `error`(失败)——见 grill-decisions.md Q2;
10
+ * 3) 请求侧 **必须主动丢** thinking/output_config/context_management:Claude Code 对不认识的
11
+ * model ID 照发全套字段,而 `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` 不清 thinking 与 effort。
12
+ */
13
+ import { chunkToString } from "../responses/translate.js";
14
+
15
+ let seq = 0;
16
+ export function newMessageId() {
17
+ return `msg_${Date.now().toString(36)}${(seq++).toString(36)}`;
18
+ }
19
+ export function newToolUseId() {
20
+ return `toolu_${Date.now().toString(36)}${(seq++).toString(36)}`;
21
+ }
22
+
23
+ /** Anthropic 协议错误体形状(非流式 JSON 与流式 in-band error 帧共用)。 */
24
+ export function anthropicError(type, message) {
25
+ return { type: "error", error: { type: String(type || "api_error"), message: String(message || "error").slice(0, 500) } };
26
+ }
27
+
28
+ // ---------- 请求:Anthropic → chat ----------
29
+
30
+ // system 允许字符串或 text 块数组;块间空行连接(缓存语义不保留,上游是 OpenAI)
31
+ function systemTextOf(system) {
32
+ if (typeof system === "string") return system;
33
+ if (!Array.isArray(system)) return "";
34
+ return system.map((b) => (b && typeof b.text === "string" ? b.text : "")).filter(Boolean).join("\n\n");
35
+ }
36
+
37
+ function imagePartOf(block) {
38
+ const src = block?.source || {};
39
+ if (src.type === "base64" && src.data) {
40
+ return { type: "image_url", image_url: { url: `data:${src.media_type || "image/png"};base64,${src.data}` } };
41
+ }
42
+ if (src.type === "url" && src.url) return { type: "image_url", image_url: { url: String(src.url) } };
43
+ return null;
44
+ }
45
+
46
+ function toolResultTextOf(content) {
47
+ if (typeof content === "string") return content;
48
+ if (Array.isArray(content)) {
49
+ return content
50
+ .map((p) => (typeof p === "string" ? p : p && typeof p.text === "string" ? p.text : ""))
51
+ .filter(Boolean)
52
+ .join("\n");
53
+ }
54
+ return content == null ? "" : String(content);
55
+ }
56
+
57
+ /** Anthropic Messages 请求体 → OpenAI chat 请求体(直接喂既有 ChatPipeline)。 */
58
+ export function messagesToChatBody(req = {}) {
59
+ const model = String(req.model || "").trim();
60
+ if (!model) throw new Error("messages: 缺少 model");
61
+ const messages = [];
62
+ const sys = systemTextOf(req.system);
63
+ if (sys) messages.push({ role: "system", content: sys });
64
+
65
+ // 重复 tool_use_id 保首个、丢后续:客户端重试/重放历史会把同一工具结果存两份,
66
+ // 部分上游按 call_id 查重直接 400(同 responses/translate.js:57-59 的实测教训)。
67
+ const seenToolResult = new Set();
68
+
69
+ for (const m of Array.isArray(req.messages) ? req.messages : []) {
70
+ if (!m || typeof m !== "object") continue;
71
+ const role = m.role === "assistant" ? "assistant" : "user";
72
+ const blocks = typeof m.content === "string" ? [{ type: "text", text: m.content }] : Array.isArray(m.content) ? m.content : [];
73
+ let text = "";
74
+ const imgs = [];
75
+ const toolCalls = [];
76
+ for (const b of blocks) {
77
+ if (!b || typeof b !== "object") continue;
78
+ if (b.type === "text") text += typeof b.text === "string" ? b.text : "";
79
+ else if (b.type === "image") { const p = imagePartOf(b); if (p) imgs.push(p); }
80
+ else if (b.type === "tool_use") {
81
+ let args = "{}";
82
+ try { args = JSON.stringify(b.input ?? {}); } catch { args = "{}"; }
83
+ toolCalls.push({ id: String(b.id || newToolUseId()), type: "function", function: { name: String(b.name || ""), arguments: args } });
84
+ } else if (b.type === "tool_result") {
85
+ // tool 消息必须先于同轮 user 文本进数组:OpenAI 侧要求 role:tool 紧跟其 assistant
86
+ const key = String(b.tool_use_id || "");
87
+ if (key) { if (seenToolResult.has(key)) continue; seenToolResult.add(key); }
88
+ const body = toolResultTextOf(b.content);
89
+ messages.push({ role: "tool", tool_call_id: key, content: b.is_error ? `[tool_error] ${body}` : body });
90
+ }
91
+ // thinking / redacted_thinking 忽略:我们无法签发 signature,回传必被上游拒(ADR-0047)
92
+ }
93
+ if (!text && !imgs.length && !toolCalls.length) continue;
94
+ const msg = { role, content: imgs.length ? [...(text ? [{ type: "text", text }] : []), ...imgs] : text };
95
+ if (toolCalls.length) msg.tool_calls = toolCalls;
96
+ messages.push(msg);
97
+ }
98
+ // 空会话直接 400:绝不伪造一句 "hi" 打上游(那会把假提问写进用户上下文并白烧一发额度)
99
+ if (!messages.some((x) => x.role !== "system")) throw new Error("messages: 缺少用户消息");
100
+
101
+ const body = { model, messages, stream: Boolean(req.stream) };
102
+ // 流式必须让上游把 usage 放进收尾帧,否则 message_delta.usage 恒 0(OpenAI 规范字段)。
103
+ // 个别上游不认 stream_options 会 400 → `MSLXDFF_ANTHROPIC_STREAM_USAGE=0` 关掉。
104
+ if (body.stream && process.env.MSLXDFF_ANTHROPIC_STREAM_USAGE !== "0") body.stream_options = { include_usage: true };
105
+ if (Array.isArray(req.tools) && req.tools.length) {
106
+ body.tools = req.tools.map((t) => ({
107
+ type: "function",
108
+ function: { name: String(t?.name || ""), description: String(t?.description || ""), parameters: t?.input_schema || {} },
109
+ }));
110
+ }
111
+ const tc = req.tool_choice;
112
+ if (tc === "auto" || (tc && typeof tc === "object" && tc.type === "auto")) body.tool_choice = "auto";
113
+ else if (tc && typeof tc === "object" && tc.type === "any") body.tool_choice = "required";
114
+ else if (tc && typeof tc === "object" && tc.type === "tool") body.tool_choice = { type: "function", function: { name: String(tc.name || "") } };
115
+ else if (tc && typeof tc === "object" && tc.type === "none") body.tool_choice = "none";
116
+ if (req.max_tokens != null && Number.isFinite(Number(req.max_tokens))) body.max_tokens = Number(req.max_tokens);
117
+ if (req.temperature != null) body.temperature = req.temperature;
118
+ if (req.top_p != null) body.top_p = req.top_p;
119
+ if (Array.isArray(req.stop_sequences) && req.stop_sequences.length) body.stop = req.stop_sequences;
120
+ return body;
121
+ }
122
+
123
+ // ---------- usage / stop_reason ----------
124
+
125
+ /**
126
+ * chat 口径 usage → Anthropic 口径。
127
+ * Anthropic 的 `input_tokens` **不含**缓存读命中的部分(两者分开计费),而上游
128
+ * `prompt_tokens` 是含缓存的总输入 —— 故命中数要从 input 里扣掉,否则客户端把同一段
129
+ * 前缀算两遍(读数虚高)。
130
+ */
131
+ export function toAnthropicUsage(u = {}) {
132
+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
133
+ const src = u && typeof u === "object" ? u : {};
134
+ const prompt = num(src.prompt_tokens ?? src.input_tokens);
135
+ const output = num(src.completion_tokens ?? src.output_tokens);
136
+ const cacheRead = num(src.cache_read_input_tokens ?? src.prompt_tokens_details?.cached_tokens ?? src.input_tokens_details?.cached_tokens);
137
+ const cacheWrite = num(src.cache_creation_input_tokens ?? src.prompt_tokens_details?.cache_creation_input_tokens);
138
+ return {
139
+ input_tokens: Math.max(0, prompt - cacheRead - cacheWrite),
140
+ output_tokens: output,
141
+ cache_read_input_tokens: cacheRead,
142
+ cache_creation_input_tokens: cacheWrite,
143
+ };
144
+ }
145
+
146
+ function toStopReason(finish, hasToolUse) {
147
+ if (hasToolUse || finish === "tool_calls" || finish === "function_call") return "tool_use";
148
+ if (finish === "length") return "max_tokens";
149
+ return "end_turn";
150
+ }
151
+
152
+ // ---------- 非流式响应:chat JSON → Anthropic message ----------
153
+
154
+ function parseToolInput(args) {
155
+ const raw = String(args || "");
156
+ if (!raw.trim()) return {};
157
+ try {
158
+ const v = JSON.parse(raw);
159
+ return v && typeof v === "object" && !Array.isArray(v) ? v : { value: v };
160
+ } catch {
161
+ return { raw }; // 上游吐出发散 JSON:退化成 raw,不整轮失败
162
+ }
163
+ }
164
+
165
+ /**
166
+ * 上游 chat 的 `message.content` 既可能是字符串,也可能是部件数组(`[{type:"text",text:…}, {type:"image_url",…}]`,
167
+ * 多模态上游与部分聚合网关都这么回)。统一抽成正文文本;图片部件在本外壳里无法映射成 Anthropic 的 image 块,只能弃(见 ADR-0047 边界 11)。
168
+ */
169
+ export function textFromChatContent(c) {
170
+ if (typeof c === "string") return c;
171
+ if (!Array.isArray(c)) return "";
172
+ let t = "";
173
+ for (const p of c) {
174
+ if (p && typeof p === "object" && typeof p.text === "string") t += p.text;
175
+ }
176
+ return t;
177
+ }
178
+
179
+ export function chatJsonToAnthropic(chatJson = {}, model = "") {
180
+ const choice = chatJson.choices?.[0] || {};
181
+ const message = choice.message || {};
182
+ const content = [];
183
+ const text = textFromChatContent(message.content);
184
+ if (text) content.push({ type: "text", text });
185
+ for (const tc of message.tool_calls || []) {
186
+ content.push({ type: "tool_use", id: String(tc.id || newToolUseId()), name: String(tc.function?.name || ""), input: parseToolInput(tc.function?.arguments) });
187
+ }
188
+ return {
189
+ id: typeof chatJson.id === "string" && chatJson.id.startsWith("msg_") ? chatJson.id : newMessageId(),
190
+ type: "message",
191
+ role: "assistant",
192
+ model: model || chatJson.model || "",
193
+ content: content.length ? content : [{ type: "text", text: "" }],
194
+ stop_reason: toStopReason(choice.finish_reason, content.some((b) => b.type === "tool_use")),
195
+ stop_sequence: null,
196
+ usage: toAnthropicUsage(chatJson.usage),
197
+ };
198
+ }
199
+
200
+ // ---------- 流式响应:chat SSE chunk → Anthropic 具名事件 ----------
201
+
202
+ /**
203
+ * @param model 回显给客户端的模型名
204
+ * @param opts { id?, thinking?: boolean } thinking=true 才把 reasoning_content 发成 thinking 块
205
+ */
206
+ export function createAnthropicChunkTranslator(model = "", opts = {}) {
207
+ const id = opts.id || newMessageId();
208
+ const emitThinking = opts.thinking === true;
209
+ const created = Math.floor(Date.now() / 1000);
210
+ const ev = (type, extra = {}) => ({ type, ...extra });
211
+
212
+ let buf = "";
213
+ let nextIndex = 0;
214
+ let open = null; // 当前未封口块:{ index, kind: "text"|"thinking"|"tool_use", text? }
215
+ const tools = new Map(); // 上游 tc.index → { id, name, args, announced, index }
216
+ let sawToolUse = false;
217
+ let lastFinish = null;
218
+ let lastUsage = null;
219
+ const dbg = { chunks: 0, textChars: 0, toolDeltas: 0, thinkingChars: 0, skippedLines: 0, jsonFails: 0, lateToolDeltas: 0, blocks: 0 };
220
+
221
+ function closeOpen(out) {
222
+ if (!open) return;
223
+ out.push(ev("content_block_stop", { index: open.index }));
224
+ open = null;
225
+ }
226
+ function openBlock(kind, contentBlock, out) {
227
+ closeOpen(out);
228
+ open = { index: nextIndex++, kind, text: "" };
229
+ dbg.blocks = open.index + 1;
230
+ out.push(ev("content_block_start", { index: open.index, content_block: contentBlock }));
231
+ return open;
232
+ }
233
+ function pushText(delta) {
234
+ const out = [];
235
+ if (!open || open.kind !== "text") openBlock("text", { type: "text", text: "" }, out);
236
+ open.text += delta;
237
+ out.push(ev("content_block_delta", { index: open.index, delta: { type: "text_delta", text: delta } }));
238
+ return out;
239
+ }
240
+ function pushThinking(delta) {
241
+ const out = [];
242
+ if (!open || open.kind !== "thinking") openBlock("thinking", { type: "thinking", thinking: "" }, out);
243
+ open.text += delta;
244
+ out.push(ev("content_block_delta", { index: open.index, delta: { type: "thinking_delta", thinking: delta } }));
245
+ return out;
246
+ }
247
+ function announceTool(t, out) {
248
+ t.announced = true;
249
+ sawToolUse = true;
250
+ // 统一走 openBlock:自动封掉当前 text/thinking/上一个工具块,本块成为新的待封 open
251
+ openBlock("tool_use", { type: "tool_use", id: t.id, name: t.name, input: {} }, out);
252
+ t.index = open.index;
253
+ // 增量早于 id/name 到达时先攒着,announce 后补发(事件顺序仍合规)
254
+ if (t.args) out.push(ev("content_block_delta", { index: t.index, delta: { type: "input_json_delta", partial_json: t.args } }));
255
+ }
256
+ function pushTool(tc) {
257
+ const slot = Number(tc?.index ?? 0);
258
+ const out = [];
259
+ let t = tools.get(slot);
260
+ if (!t) { t = { id: "", name: "", args: "", announced: false, index: null }; tools.set(slot, t); }
261
+ if (tc?.id) t.id = String(tc.id);
262
+ if (tc?.function?.name) t.name += String(tc.function.name);
263
+ const frag = tc?.function?.arguments ? String(tc.function.arguments) : "";
264
+ if (frag) { dbg.toolDeltas++; t.args += frag; }
265
+ if (!t.announced && t.id && t.name) announceTool(t, out);
266
+ else if (t.announced && frag && open && open.index === t.index) out.push(ev("content_block_delta", { index: t.index, delta: { type: "input_json_delta", partial_json: frag } }));
267
+ else if (t.announced && frag) dbg.lateToolDeltas++; // 块已封口后才来的参数增量:发出即违规帧,丢弃并留读数
268
+ return out;
269
+ }
270
+
271
+ function begin() {
272
+ return [ev("message_start", { message: { id, type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } } })];
273
+ }
274
+
275
+ function push(data) {
276
+ buf += chunkToString(data);
277
+ const out = [];
278
+ let nl;
279
+ while ((nl = buf.indexOf("\n")) >= 0) {
280
+ const line = buf.slice(0, nl).trim();
281
+ buf = buf.slice(nl + 1);
282
+ // 注释帧/keepalive(`:` 开头)与上游 `[DONE]` 都不进 Anthropic 事件序列(grill Q6)
283
+ if (!line || line.startsWith(":")) continue;
284
+ if (!line.startsWith("data:")) { dbg.skippedLines++; continue; }
285
+ const payload = line.slice(5).trim();
286
+ if (!payload || payload === "[DONE]") continue;
287
+ let chunk;
288
+ try { chunk = JSON.parse(payload); } catch { dbg.jsonFails++; continue; }
289
+ dbg.chunks++;
290
+ const choice = chunk.choices?.[0] || {};
291
+ const delta = choice.delta || {};
292
+ if (choice.finish_reason) lastFinish = choice.finish_reason;
293
+ if (chunk.usage) lastUsage = chunk.usage;
294
+ if (typeof delta.content === "string" && delta.content) { dbg.textChars += delta.content.length; out.push(...pushText(delta.content)); }
295
+ for (const tc of delta.tool_calls || []) out.push(...pushTool(tc));
296
+ const rc = typeof delta.reasoning_content === "string" ? delta.reasoning_content : "";
297
+ if (rc) {
298
+ dbg.thinkingChars += rc.length;
299
+ if (emitThinking) out.push(...pushThinking(rc)); // 只发 thinking_delta,无 signature 可发
300
+ }
301
+ }
302
+ return out;
303
+ }
304
+
305
+ function end({ finish = null, usage = null } = {}) {
306
+ const out = [];
307
+ const fr = finish || lastFinish;
308
+ for (const t of tools.values()) {
309
+ if (!t.announced && (t.id || t.name || t.args)) announceTool(t, out); // 只有 arguments 无 name 的退化收尾
310
+ }
311
+ closeOpen(out);
312
+ out.push(ev("message_delta", { delta: { stop_reason: toStopReason(fr, sawToolUse), stop_sequence: null }, usage: toAnthropicUsage(usage || lastUsage) }));
313
+ out.push(ev("message_stop"));
314
+ return out;
315
+ }
316
+
317
+ // 上游给聚合 JSON(非 SSE,muse-spark / workbuddy 聚合 / zcode 非流式都是这种)时,
318
+ // 把整包喂进同一套 pushText/pushTool 状态机 —— 与流式共用封口规则,不出第二套形状。
319
+ function fromChatJson(chatJson = {}) {
320
+ const out = [];
321
+ const choice = chatJson.choices?.[0] || {};
322
+ const m = choice.message || {};
323
+ const ct = textFromChatContent(m.content); // 字符串或部件数组都吃,别把数组正文整段丢掉
324
+ if (ct) out.push(...pushText(ct));
325
+ (Array.isArray(m.tool_calls) ? m.tool_calls : []).forEach((tc, i) => {
326
+ out.push(...pushTool({ index: i, id: tc?.id, function: { name: tc?.function?.name, arguments: tc?.function?.arguments } }));
327
+ });
328
+ if (choice.finish_reason) lastFinish = choice.finish_reason;
329
+ if (chatJson.usage) lastUsage = chatJson.usage;
330
+ return out;
331
+ }
332
+
333
+ function getFinal() {
334
+ return { finish: lastFinish, usage: lastUsage, sawToolUse };
335
+ }
336
+ function stats() {
337
+ return { ...dbg, openKind: open?.kind || null, toolSlots: tools.size };
338
+ }
339
+
340
+ return { id, created, begin, push, end, fromChatJson, getFinal, stats };
341
+ }
342
+
343
+ // ---------- count_tokens 字符估算 ----------
344
+
345
+ // 图片不吃字符但占真实上下文,按固定面值计;总长设硬上限防极端请求把除法推到 Infinity
346
+ const IMAGE_TOKENS = 2000;
347
+ const CHARS_PER_TOKEN = 4;
348
+ const CHAR_CAP = 32_000_000;
349
+
350
+ function countMessage(m, acc) {
351
+ if (!m || typeof m !== "object") return;
352
+ const blocks = typeof m.content === "string" ? [{ type: "text", text: m.content }] : Array.isArray(m.content) ? m.content : null;
353
+ if (!blocks) { acc.chars += JSON.stringify(m.content ?? "").length; return; }
354
+ for (const b of blocks) {
355
+ if (!b || typeof b !== "object") continue;
356
+ if (typeof b.text === "string") acc.chars += b.text.length;
357
+ else if (b.type === "tool_use") acc.chars += String(b.name || "").length + JSON.stringify(b.input ?? {}).length;
358
+ else if (b.type === "tool_result") acc.chars += toolResultTextOf(b.content).length; // 工具结果是大头,必须算(grill Q7)
359
+ else if (b.type === "thinking") acc.chars += String(b.thinking || "").length;
360
+ else if (b.type === "image") acc.images += 1;
361
+ }
362
+ }
363
+
364
+ /** 字符估算版 token 计数(Anthropic 官方:端点缺失时客户端本来就退回字符估算,精度非目标)。 */
365
+ export function estimateTokens(req = {}) {
366
+ let chars = 0;
367
+ let images = 0;
368
+ const acc = { chars: 0, images: 0 };
369
+ const sys = typeof req.system === "string" ? [{ type: "text", text: req.system }] : Array.isArray(req.system) ? req.system : [];
370
+ for (const b of sys) acc.chars += b && typeof b.text === "string" ? b.text.length : 0;
371
+ for (const m of Array.isArray(req.messages) ? req.messages : []) countMessage(m, acc);
372
+ if (Array.isArray(req.tools)) acc.chars += JSON.stringify(req.tools).length;
373
+ chars = Math.min(acc.chars, CHAR_CAP);
374
+ images = acc.images;
375
+ // 字段名以 Anthropic 线上为准:`POST /v1/messages/count_tokens` 回 `{"input_tokens": N}`;
376
+ // 额外带一份 count_tokens 仅作人读兼容(Claude Code 读的是 input_tokens)。
377
+ const n = Math.max(1, Math.ceil(chars / CHARS_PER_TOKEN) + images * IMAGE_TOKENS);
378
+ return { input_tokens: n, count_tokens: n };
379
+ }
@@ -92,7 +92,8 @@ export function createChatPipeline({ upstream, auto, logs, peers, groups, bus, t
92
92
  const canForwardPeers = Boolean(peers) && hops < (maxHops ?? 3);
93
93
  mark("ordered");
94
94
 
95
- evt("request", { reqId, hops, ip: clientIp(req), stream: Boolean(req?.body?.stream), prompt: summarizePrompt(req?.body), rawModel: policy.rawModel, requested, lockModel: lockModel || null });
95
+ const reqIp = clientIp(req); // 一次解析两处用:request 事件的 ip 字段 + 回路语料的 clientIp(routes/helpers.js 取 x-forwarded-for 首段)
96
+ evt("request", { reqId, hops, ip: reqIp, stream: Boolean(req?.body?.stream), prompt: summarizePrompt(req?.body), rawModel: policy.rawModel, requested, lockModel: lockModel || null });
96
97
  if (aliasInfo) evt("alias", { reqId, alias: aliasInfo, rawModel: policy.rawModel, requested });
97
98
  if (Object.keys(shareKeys).length) evt("share-keys", { reqId, providers: Object.keys(shareKeys) });
98
99
  evt("ordered", { reqId, order, canFallback, canForwardPeers, useAuto, statuses: auto?.statuses?.() ?? null });
@@ -110,7 +111,7 @@ export function createChatPipeline({ upstream, auto, logs, peers, groups, bus, t
110
111
  // 客户端会话标识(opencode 插件 chat.headers 注入)→ 透传上游做粘性路由/缓存亲和;
111
112
  // 无头时由 upstream.js 按对话首两条消息哈希兜底(不再每请求随机)
112
113
  const clientSession = String(req?.headers?.["x-session-affinity"] || req?.headers?.["x-session-id"] || "").trim() || null;
113
- const handlerCtx = { reqId, model: null, body: req?.body, hops, peers, plugins, evt, logError, logCall, logs, workbuddyUid, sessionId: clientSession };
114
+ const handlerCtx = { reqId, model: null, body: req?.body, hops, peers, plugins, evt, logError, logCall, logs, workbuddyUid, sessionId: clientSession, clientIp: reqIp };
114
115
  if (clientSession) evt("client-session", { reqId, sessionId: clientSession.slice(0, 24) });
115
116
 
116
117
  await engine.run({
@@ -1,4 +1,4 @@
1
- // `-stats` 模型用量报表:近 N 小时每模型 token 消耗 + 首字/总耗时/速度。
1
+ // `-stats` 模型用量报表:每窗口每模型 token 消耗 + 首字/总耗时/速度。默认窗口 = 今日 0 点至现在,--hours N 切近 N 小时滚动。
2
2
  // 数据来自 src/usage/(逐请求 JSONL),不是 state.json 的终生 EMA —— 见 .scratch/stats-report/SPEC.md
3
3
  import { usageReport } from "../../usage/report.js";
4
4
  import { usageEnabled, usageKeepDays } from "../../usage/record.js";
@@ -9,10 +9,18 @@ export function isStatsFlag(args) {
9
9
  return FLAGS.some((f) => args.includes(f));
10
10
  }
11
11
 
12
+ // 默认窗口起点 = 本地当日 0 点(setHours 归零,随系统本地时区)。
13
+ export function startOfTodayMs(now = Date.now()) {
14
+ const d = new Date(now);
15
+ d.setHours(0, 0, 0, 0);
16
+ return d.getTime();
17
+ }
18
+
12
19
  export function parseStatsArgs(args) {
13
20
  const hoursIdx = args.findIndex((a) => a === "--hours" || a === "-hours");
14
21
  const rawHours = hoursIdx >= 0 ? Number(args[hoursIdx + 1]) : NaN;
15
- const hours = Number.isFinite(rawHours) && rawHours > 0 ? Math.min(168, Math.floor(rawHours)) : 24;
22
+ // null = 默认「今日 00:00 至今」窗口;显式但非法(非数/≤0)的 --hours 同样视为 null,不再回退 24h
23
+ const hours = Number.isFinite(rawHours) && Math.floor(rawHours) >= 1 ? Math.min(168, Math.floor(rawHours)) : null; // 0<N<1 折成 0 会造成「近 0h 标签配 24h 数据」,与非法同路走当日窗口
16
24
  const modelIdx = args.findIndex((a) => a === "--model" || a === "-model");
17
25
  const rawModel = modelIdx >= 0 && args[modelIdx + 1] && !String(args[modelIdx + 1]).startsWith("-") ? args[modelIdx + 1] : null;
18
26
  return { hours, model: rawModel, json: args.includes("--json") };
@@ -80,11 +88,12 @@ function performanceRow(id, r) {
80
88
  return [id, ttfb, fmtMs(r.avgTotalMs), fmtTps(r.avgTps), `${Number(r.ttfSamples) || 0}/${samples}`];
81
89
  }
82
90
 
83
- export function renderStats(report, { hours = 24, model = null } = {}) {
91
+ export function renderStats(report, { hours = null, model = null } = {}) {
92
+ const rangeLabel = hours == null ? "今日 00:00 至今" : `近 ${hours}h`;
84
93
  const lines = [];
85
94
  const { models, totals } = report;
86
95
  if (!models.length) {
87
- lines.push(`暂无用量记录(近 ${hours}h${model ? ` · 模型 ${model}` : ""})— 经 8989 网关发一次请求后出现`);
96
+ lines.push(`暂无用量记录(${rangeLabel}${model ? ` · 模型 ${model}` : ""})— 经 8989 网关发一次请求后出现`);
88
97
  lines.push("提示:mslxdff -status 看当前体检 · mslxdff -log 20 看最近事件");
89
98
  lines.push("说明:-chat 直连 mimo/big-pickle 不经网关,不计入本表");
90
99
  return lines.join("\n");
@@ -93,7 +102,7 @@ export function renderStats(report, { hours = 24, model = null } = {}) {
93
102
  const right = "right";
94
103
  const tokenRows = [...models.map((m) => tokenRow(m.id, m)), tokenRow("合计", totals)];
95
104
  const performanceRows = [...models.map((m) => performanceRow(m.id, m)), performanceRow("合计", totals)];
96
- lines.push(`模型用量报告(近 ${hours}h${model ? ` · 筛选 ${model}` : ""})`);
105
+ lines.push(`模型用量报告(${rangeLabel}${model ? ` · 筛选 ${model}` : ""})`);
97
106
  lines.push(`成功请求:${totals.requests} 次 · 模型:${models.length} 个`);
98
107
  lines.push("");
99
108
  lines.push("Token 用量");
@@ -109,14 +118,15 @@ export function renderStats(report, { hours = 24, model = null } = {}) {
109
118
  lines.push("口径差异:-status / -model stats 的首字仍取自 state 的终生 EMA(按转发入口量),与本表**不同源**。");
110
119
  lines.push("范围:只含经 8989 网关的成功请求;不含失败请求和 -chat 直连。");
111
120
  const keepDays = usageKeepDays();
112
- if (hours > keepDays * 24) {
113
- lines.push(`警告:查询 ${hours}h 超过数据保留 ${keepDays} 天,历史可能不完整。`);
121
+ if (hours != null && hours > keepDays * 24) {
122
+ lines.push(`警告:查询窗口 ${hours}h 超过数据保留 ${keepDays} 天,历史可能不完整。`);
114
123
  } else {
115
124
  lines.push(`数据保留 ${keepDays} 天;更早的历史已删除。`);
116
125
  }
117
126
  lines.push("明细口径:本表按模型聚合,不展开 via、interrupted 和单次 tps。");
118
127
  lines.push("数值使用 k/M 缩写;需要精确值或机器处理请加 --json。");
119
- lines.push("可调:mslxdff -stats --hours 1 | --model <id> | --json");
128
+ lines.push("可调:默认统计今日 0 点至现在 · mslxdff -stats --hours N(近 N 小时滚动,上限 168)| --model <id> | --json");
129
+ lines.push("时区:「今日 0 点」按系统本地时区计,与用量日文件的日切同源。");
120
130
  return lines.join("\n");
121
131
  }
122
132
 
@@ -127,7 +137,9 @@ export async function handleStats(args) {
127
137
  console.log("用量记录已关闭(MSLXDFF_USAGE_LOG=0)—— 去掉该 env 后重启 daemon 即可恢复采集。");
128
138
  return true;
129
139
  }
130
- const report = await usageReport({ hours, model, now: Date.now() });
140
+ const now = Date.now();
141
+ const since = hours == null ? startOfTodayMs(now) : null; // 缺省/非法 --hours → 当日 0 点起,毫秒精确不漂移
142
+ const report = await usageReport({ hours, since, model, now });
131
143
  if (json) {
132
144
  console.log(JSON.stringify(report, null, 2));
133
145
  return true;
@@ -5,6 +5,7 @@ import { normalizeModel } from "../../reasoning.js";
5
5
  import { syncToWorkbuddy, workbuddyModelsPath } from "../../sync-workbuddy.js";
6
6
  import { syncToOpencode, opencodeConfigPath } from "../../sync-opencode.js";
7
7
  import { syncToCodex, codexConfigPath } from "../../sync-codex.js";
8
+ import { syncToClaude, claudeSettingsPath } from "../../sync-claude.js";
8
9
  import { createModelsService } from "../../models.js";
9
10
  import { createUpstreamClient } from "../../upstream.js";
10
11
  import { logDir } from "../../logs.js";
@@ -20,8 +21,8 @@ export async function handleSetto(args) {
20
21
  if (!(args.includes("-setto") || args.includes("--setto"))) return false;
21
22
  const idx = args.findIndex((x) => x === "-setto" || x === "--setto");
22
23
  const target = args[idx + 1];
23
- if (!["workbuddy", "opencode", "chatgpt", "codex"].includes(target)) {
24
- console.error("usage: mslxdff -setto workbuddy [modelId] | mslxdff -setto opencode [modelId|--all] | mslxdff -setto chatgpt [modelId]");
24
+ if (!["workbuddy", "opencode", "chatgpt", "codex", "claude"].includes(target)) {
25
+ console.error("usage: mslxdff -setto workbuddy [modelId] | mslxdff -setto opencode [modelId|--all] | mslxdff -setto chatgpt [modelId] | mslxdff -setto claude [modelId] [--behaves-as <id>] (claude: 不带 modelId = 写入 modelPicks 勾选集全集,--all 与之同义)");
25
26
  process.exit(1);
26
27
  }
27
28
  if (target === "chatgpt" || target === "codex") {
@@ -63,6 +64,77 @@ export async function handleSetto(args) {
63
64
  }
64
65
  process.exit(0);
65
66
  }
67
+ if (target === "claude") {
68
+ // Claude Code 用户设置 ~/.claude/settings.json:走本机 /v1/messages 外壳(ADR-0047)
69
+ // 参数校验一律先于任何写盘(含 savePreferredModel):校验不过不得碰 state.json 与 settings.json
70
+ // --behaves-as <已知 claude-* id> 覆盖能力锚;`--behaves-as ""` 显式关掉(关掉后本机 Claude Code 可能对未知 id 拒跑)
71
+ const baIdx = args.findIndex((x) => x === "--behaves-as");
72
+ if (baIdx >= 0 && args[baIdx + 1] === undefined) {
73
+ console.error("--behaves-as 需要取值:给一个已知 claude-* id,或显式传空串关闭(--behaves-as \"\")");
74
+ process.exit(1);
75
+ }
76
+ const behavesAs = baIdx >= 0 ? String(args[baIdx + 1]) : undefined;
77
+ const raw = args[idx + 2] && !String(args[idx + 2]).startsWith("-") && args[idx + 2] !== "all" ? String(args[idx + 2]).trim() : null;
78
+ const picksAll = loadModelPicks();
79
+ let id;
80
+ let batch = false;
81
+ if (raw) {
82
+ if (raw === "auto" || !normalizeModel(raw)) {
83
+ console.error("modelId 不能为 auto 或空");
84
+ process.exit(1);
85
+ }
86
+ const norm = normalizeModel(raw);
87
+ if (!norm) {
88
+ console.error("modelId 不能为空");
89
+ process.exit(1);
90
+ }
91
+ if (picksAll.length && !picksAll.includes(norm)) {
92
+ console.log(` ⚠ "${norm}" 不在勾选集 modelPicks 内 —— 可能是拼错或已失效;仍按你显式指定的写入`);
93
+ }
94
+ savePreferredModel(norm);
95
+ console.log(`default model set to: ${norm} (daemon hot-reloads on next request)`);
96
+ id = norm;
97
+ } else {
98
+ // 不带参数(含 --all / 裸 all)= 写入全部勾选模型:modelPicker.options = modelPicks 全集,
99
+ // 顶层 model 也只在勾选集内取。**不再兜底 preferredModel** —— 它可能是一个已从池子消失的 id
100
+ // (真实踩坑:preferredModel=mimo-v2.5-free 被写进 Claude Code 后,每次请求只会得到 502)。
101
+ batch = true;
102
+ if (!picksAll.length) {
103
+ console.error("modelPicks 勾选集为空 → 无可写入的模型;先跑 mslxdff -model pick 勾选,或直接 mslxdff -setto claude <modelId>");
104
+ process.exit(1);
105
+ }
106
+ const pref = normalizeModel(loadPreferredModel() || getPref() || "");
107
+ if (pref && picksAll.includes(pref)) {
108
+ id = pref;
109
+ } else {
110
+ if (pref) console.log(` ⚠ 网关首选模型 "${pref}" 不在勾选集内(可能已失效)→ claude 默认改用勾选集首个 "${picksAll[0]}"`);
111
+ id = normalizeModel(picksAll[0]);
112
+ }
113
+ }
114
+ try {
115
+ const { token } = await loadToken();
116
+ const persisted = getPort();
117
+ const envPort = Number(process.env.MSLXDFF_PORT);
118
+ const port = persisted !== null ? persisted : (Number.isInteger(envPort) && envPort > 0 ? envPort : 8989);
119
+ // options 由本命令全权管理:默认/`--all` 用勾选集整体替换,显式单模型则只留一条。
120
+ const picks = batch ? picksAll : null;
121
+ const file = claudeSettingsPath();
122
+ const r = syncToClaude({ id, token, port, picks, file, behavesAs });
123
+ console.log(`synced to claude: ${r.action} "${r.id}" @ ${r.file}${r.changed ? "" : "(已是目标状态,未改字节)"}`);
124
+ if (r.backup) { console.log(` backup: ${r.backup}`); console.log(` 还原: Copy-Item "${r.backup}" "${r.file}"`); }
125
+ else console.log(` backup: 未生成(本次无变化,或同目录已有更早的 settings.pre-mslxdff.json —— 那份是首次接管前的原文)`);
126
+ if (r.tmpLeftover) console.error(` ⚠ 临时文件清理失败:${r.tmpLeftover}(内含明文 token,请手动删除)`);
127
+ console.log(` url: http://127.0.0.1:${port} (不带 /v1 —— Claude Code 自己拼 /v1/messages)`);
128
+ console.log(` modelPicker: ${r.rows} 行${batch ? "(勾选集全集)" : "(单模型)"}`);
129
+ console.log(` 冒烟: curl -H "Authorization: Bearer $(mslxdff -showtoken)" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d '{"model":"${r.id}","max_tokens":1024,"messages":[{"role":"user","content":"hi"}]}' http://127.0.0.1:${port}/v1/messages (max_tokens 别给太小:思考型模型会把额度全花在 reasoning 上而吐空正文轮)`);
130
+ console.log(` ⚠ env 与 model 均为 Claude Code 启动时读取 → 重启 claude 生效;token 轮换后需重跑本命令`);
131
+ console.log(` ℹ 客户端不认识的模型 id 一律按 200K 窗口假设(带 \`[1m]\` 后缀才按 1M),需要更大窗口另设 env.CLAUDE_CODE_MAX_CONTEXT_TOKENS`);
132
+ } catch (err) {
133
+ console.error(`failed to sync to claude: ${String(err?.message || err)}`);
134
+ process.exit(1);
135
+ }
136
+ process.exit(0);
137
+ }
66
138
  if (target === "opencode") {
67
139
  const wantsAll = args.includes("--all") || args.includes("-a") || args[idx + 2] === "all";
68
140
  if (wantsAll) {
package/src/cli/help.js CHANGED
@@ -5,7 +5,7 @@ Usage:
5
5
  mslxdff start as a background daemon and exit (status + help if one is already running)
6
6
  mslxdff -d start as a background daemon
7
7
  mslxdff -status show current status (daemon/health/port/config, upstream providers, models + metrics/体检表, autostart/plugins, groups/peers, recent calls with ttfb/tps, last error)
8
- mslxdff -stats [--hours N] [--json] [--model <id>] per-model token usage + speed over the last N hours (default 24; success requests only, from the local usage JSONL)
8
+ mslxdff -stats [--hours N] [--json] [--model <id>] per-model token usage + speed; default window: today 00:00 → now (local timezone); with --hours N a rolling last-N-hours window (max 168; success requests only, from the local usage JSONL)
9
9
 
10
10
  mslxdff -log [N] show last N events (default 10, e.g. -log 100)
11
11
  mslxdff -models interactive picker: ↑/↓ select a model, Enter sets it as the default (non-TTY: plain list)
@@ -24,6 +24,7 @@ Usage:
24
24
  mslxdff -refresh-token rotate the auth token (prints the new one)
25
25
  mslxdff -setto workbuddy [modelId] set default model and sync to WorkBuddy models.json (insert or update 127.0.0.1/v1 entry)
26
26
  mslxdff -setto chatgpt [modelId] set default model and sync to Codex/ChatGPT ~/.codex/config.toml (model_providers.mslxdff → 127.0.0.1/v1/responses, auth via mslxdff -showtoken)
27
+ mslxdff -setto claude [modelId] [--behaves-as <id>] set default model and sync to Claude Code ~/.claude/settings.json (no modelId = write ALL modelPicks rows, --all is the same thing; env.ANTHROPIC_BASE_URL → 127.0.0.1 without /v1, /v1/messages shell; modelPicker rows carry behavesAs only for ids the client cannot recognize, default claude-sonnet-5; first write backs up settings.pre-mslxdff.json)
27
28
  mslxdff -provider add <id> <baseUrl> <key> [allowedModel...] add a generic OpenAI-compatible provider (myapi/gpt-4, baseUrl https://api.example.com/v1; extra models = allowlist)
28
29
  mslxdff -provider add workbuddy https://copilot.tencent.com <key> [allow...] add WorkBuddy专用供应商(workbuddy/hy3 前缀路由,auths 与 keys 一一对应)
29
30
  mslxdff -provider <id> [key...|add|remove|list|clear|share|set-url] configure provider API keys/URL (multiple keys = rotating, set-url for generic)