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.
Files changed (59) hide show
  1. package/package.json +1 -1
  2. package/src/anthropic/translate.js +397 -0
  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 +80 -2
  19. package/src/cli/format.js +1 -1
  20. package/src/cli/help.js +3 -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/index.js +13 -0
  49. package/src/routes/messages-route.js +401 -0
  50. package/src/routes/responses-route.js +2 -2
  51. package/src/runtime/bootstrap.js +5 -0
  52. package/src/runtime/broadband.js +4 -1
  53. package/src/runtime/provider-gate.js +3 -1
  54. package/src/runtime/raccoon-checkin.js +126 -0
  55. package/src/state/provider-config.js +1 -1
  56. package/src/sync-claude-desktop.js +234 -0
  57. package/src/sync-claude.js +152 -0
  58. package/src/talk-full.js +2 -2
  59. package/src/talk-log.js +9 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mslxdff",
3
- "version": "0.1.163",
3
+ "version": "0.1.169",
4
4
  "description": "测试项目,请勿使用。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,397 @@
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
+ import { isServerTool } from "./web-search.js";
15
+
16
+ let seq = 0;
17
+ export function newMessageId() {
18
+ return `msg_${Date.now().toString(36)}${(seq++).toString(36)}`;
19
+ }
20
+ export function newToolUseId() {
21
+ return `toolu_${Date.now().toString(36)}${(seq++).toString(36)}`;
22
+ }
23
+
24
+ /** Anthropic 协议错误体形状(非流式 JSON 与流式 in-band error 帧共用)。 */
25
+ export function anthropicError(type, message) {
26
+ return { type: "error", error: { type: String(type || "api_error"), message: String(message || "error").slice(0, 500) } };
27
+ }
28
+
29
+ // ---------- 请求:Anthropic → chat ----------
30
+
31
+ // system 允许字符串或 text 块数组;块间空行连接(缓存语义不保留,上游是 OpenAI)
32
+ function systemTextOf(system) {
33
+ if (typeof system === "string") return system;
34
+ if (!Array.isArray(system)) return "";
35
+ return system.map((b) => (b && typeof b.text === "string" ? b.text : "")).filter(Boolean).join("\n\n");
36
+ }
37
+
38
+ function imagePartOf(block) {
39
+ const src = block?.source || {};
40
+ if (src.type === "base64" && src.data) {
41
+ return { type: "image_url", image_url: { url: `data:${src.media_type || "image/png"};base64,${src.data}` } };
42
+ }
43
+ if (src.type === "url" && src.url) return { type: "image_url", image_url: { url: String(src.url) } };
44
+ return null;
45
+ }
46
+
47
+ function toolResultTextOf(content) {
48
+ if (typeof content === "string") return content;
49
+ if (Array.isArray(content)) {
50
+ return content
51
+ .map((p) => (typeof p === "string" ? p : p && typeof p.text === "string" ? p.text : ""))
52
+ .filter(Boolean)
53
+ .join("\n");
54
+ }
55
+ return content == null ? "" : String(content);
56
+ }
57
+
58
+ /** Anthropic Messages 请求体 → OpenAI chat 请求体(直接喂既有 ChatPipeline)。 */
59
+ export function messagesToChatBody(req = {}) {
60
+ const model = String(req.model || "").trim();
61
+ if (!model) throw new Error("messages: 缺少 model");
62
+ const messages = [];
63
+ const sys = systemTextOf(req.system);
64
+ if (sys) messages.push({ role: "system", content: sys });
65
+
66
+ // 重复 tool_use_id 保首个、丢后续:客户端重试/重放历史会把同一工具结果存两份,
67
+ // 部分上游按 call_id 查重直接 400(同 responses/translate.js:57-59 的实测教训)。
68
+ const seenToolResult = new Set();
69
+
70
+ for (const m of Array.isArray(req.messages) ? req.messages : []) {
71
+ if (!m || typeof m !== "object") continue;
72
+ // role=system/developer 必须保留:Claude Code ≥2.1.286 的 mid-conversation system beta 就往 messages[] 里塞系统指令,
73
+ const role = m.role === "assistant" ? "assistant" : m.role === "system" || m.role === "developer" ? "system" : "user";
74
+ const blocks = typeof m.content === "string" ? [{ type: "text", text: m.content }] : Array.isArray(m.content) ? m.content : [];
75
+ let text = "";
76
+ const imgs = [];
77
+ const toolCalls = [];
78
+ for (const b of blocks) {
79
+ if (!b || typeof b !== "object") continue;
80
+ if (b.type === "text") text += typeof b.text === "string" ? b.text : "";
81
+ else if (b.type === "image") { const p = imagePartOf(b); if (p) imgs.push(p); }
82
+ else if (b.type === "tool_use") {
83
+ let args = "{}";
84
+ try { args = JSON.stringify(b.input ?? {}); } catch { args = "{}"; }
85
+ toolCalls.push({ id: String(b.id || newToolUseId()), type: "function", function: { name: String(b.name || ""), arguments: args } });
86
+ } else if (b.type === "tool_result") {
87
+ // tool 消息必须先于同轮 user 文本进数组:OpenAI 侧要求 role:tool 紧跟其 assistant
88
+ const key = String(b.tool_use_id || "");
89
+ if (key) { if (seenToolResult.has(key)) continue; seenToolResult.add(key); }
90
+ const body = toolResultTextOf(b.content);
91
+ messages.push({ role: "tool", tool_call_id: key, content: b.is_error ? `[tool_error] ${body}` : body });
92
+ }
93
+ // thinking / redacted_thinking 忽略:我们无法签发 signature,回传必被上游拒(ADR-0047)
94
+ }
95
+ if (!text && !imgs.length && !toolCalls.length) continue;
96
+ const msg = { role, content: imgs.length ? [...(text ? [{ type: "text", text }] : []), ...imgs] : text };
97
+ if (toolCalls.length) msg.tool_calls = toolCalls;
98
+ messages.push(msg);
99
+ }
100
+ // 空会话直接 400:绝不伪造一句 "hi" 打上游(那会把假提问写进用户上下文并白烧一发额度)
101
+ if (!messages.some((x) => x.role !== "system")) throw new Error("messages: 缺少用户消息");
102
+
103
+ const body = { model, messages, stream: Boolean(req.stream) };
104
+ // 流式必须让上游把 usage 放进收尾帧,否则 message_delta.usage 恒 0(OpenAI 规范字段)。
105
+ // 个别上游不认 stream_options 会 400 → `MSLXDFF_ANTHROPIC_STREAM_USAGE=0` 关掉。
106
+ if (body.stream && process.env.MSLXDFF_ANTHROPIC_STREAM_USAGE !== "0") body.stream_options = { include_usage: true };
107
+ // Anthropic 的 server tool(web_search_*/web_fetch_*/…)没有 input_schema,折成假 function 会
108
+ // 让上游收到「空参数空描述」的工具(严格端点直接 422),本网关不实现的发前一律剥除(ADR-0049)。
109
+ const fnTools = (Array.isArray(req.tools) ? req.tools : []).filter((t) => !isServerTool(t));
110
+ if (fnTools.length) {
111
+ body.tools = fnTools.map((t) => ({
112
+ type: "function",
113
+ function: { name: String(t?.name || ""), description: String(t?.description || ""), parameters: t?.input_schema || {} },
114
+ }));
115
+ }
116
+ const keptNames = new Set(fnTools.map((t) => String(t?.name || "")));
117
+ const tc = req.tool_choice;
118
+ if (tc === "auto" || (tc && typeof tc === "object" && tc.type === "auto")) body.tool_choice = "auto";
119
+ else if (tc && typeof tc === "object" && tc.type === "any") body.tool_choice = "required";
120
+ // 点名一个已被剥掉的工具时降为 auto:上游会按不存在的函数强制点名,那样一定拿不到有用回答
121
+ else if (tc && typeof tc === "object" && tc.type === "tool") body.tool_choice = keptNames.has(String(tc.name || "")) ? { type: "function", function: { name: String(tc.name || "") } } : "auto";
122
+ else if (tc && typeof tc === "object" && tc.type === "none") body.tool_choice = "none";
123
+ if (req.max_tokens != null && Number.isFinite(Number(req.max_tokens))) body.max_tokens = Number(req.max_tokens);
124
+ if (req.temperature != null) body.temperature = req.temperature;
125
+ if (req.top_p != null) body.top_p = req.top_p;
126
+ if (Array.isArray(req.stop_sequences) && req.stop_sequences.length) body.stop = req.stop_sequences;
127
+ return body;
128
+ }
129
+
130
+ // ---------- usage / stop_reason ----------
131
+
132
+ /**
133
+ * chat 口径 usage → Anthropic 口径。
134
+ * Anthropic 的 `input_tokens` **不含**缓存读命中的部分(两者分开计费),而上游
135
+ * `prompt_tokens` 是含缓存的总输入 —— 故命中数要从 input 里扣掉,否则客户端把同一段
136
+ * 前缀算两遍(读数虚高)。
137
+ */
138
+ export function toAnthropicUsage(u = {}) {
139
+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
140
+ const src = u && typeof u === "object" ? u : {};
141
+ const prompt = num(src.prompt_tokens ?? src.input_tokens);
142
+ const output = num(src.completion_tokens ?? src.output_tokens);
143
+ const cacheRead = num(src.cache_read_input_tokens ?? src.prompt_tokens_details?.cached_tokens ?? src.input_tokens_details?.cached_tokens);
144
+ const cacheWrite = num(src.cache_creation_input_tokens ?? src.prompt_tokens_details?.cache_creation_input_tokens);
145
+ return {
146
+ input_tokens: Math.max(0, prompt - cacheRead - cacheWrite),
147
+ output_tokens: output,
148
+ cache_read_input_tokens: cacheRead,
149
+ cache_creation_input_tokens: cacheWrite,
150
+ };
151
+ }
152
+
153
+ function toStopReason(finish, hasToolUse) {
154
+ if (hasToolUse || finish === "tool_calls" || finish === "function_call") return "tool_use";
155
+ if (finish === "length") return "max_tokens";
156
+ return "end_turn";
157
+ }
158
+
159
+ // ---------- 非流式响应:chat JSON → Anthropic message ----------
160
+
161
+ function parseToolInput(args) {
162
+ const raw = String(args || "");
163
+ if (!raw.trim()) return {};
164
+ try {
165
+ const v = JSON.parse(raw);
166
+ return v && typeof v === "object" && !Array.isArray(v) ? v : { value: v };
167
+ } catch {
168
+ return { raw }; // 上游吐出发散 JSON:退化成 raw,不整轮失败
169
+ }
170
+ }
171
+
172
+ /**
173
+ * 上游 chat 的 `message.content` 既可能是字符串,也可能是部件数组(`[{type:"text",text:…}, {type:"image_url",…}]`,
174
+ * 多模态上游与部分聚合网关都这么回)。统一抽成正文文本;图片部件在本外壳里无法映射成 Anthropic 的 image 块,只能弃(见 ADR-0047 边界 11)。
175
+ */
176
+ export function textFromChatContent(c) {
177
+ if (typeof c === "string") return c;
178
+ if (!Array.isArray(c)) return "";
179
+ let t = "";
180
+ for (const p of c) {
181
+ if (p && typeof p === "object" && typeof p.text === "string") t += p.text;
182
+ }
183
+ return t;
184
+ }
185
+
186
+ export function chatJsonToAnthropic(chatJson = {}, model = "") {
187
+ const choice = chatJson.choices?.[0] || {};
188
+ const message = choice.message || {};
189
+ const content = [];
190
+ const text = textFromChatContent(message.content);
191
+ if (text) content.push({ type: "text", text });
192
+ for (const tc of message.tool_calls || []) {
193
+ content.push({ type: "tool_use", id: String(tc.id || newToolUseId()), name: String(tc.function?.name || ""), input: parseToolInput(tc.function?.arguments) });
194
+ }
195
+ return {
196
+ id: typeof chatJson.id === "string" && chatJson.id.startsWith("msg_") ? chatJson.id : newMessageId(),
197
+ type: "message",
198
+ role: "assistant",
199
+ model: model || chatJson.model || "",
200
+ content: content.length ? content : [{ type: "text", text: "" }],
201
+ stop_reason: toStopReason(choice.finish_reason, content.some((b) => b.type === "tool_use")),
202
+ stop_sequence: null,
203
+ usage: toAnthropicUsage(chatJson.usage),
204
+ };
205
+ }
206
+
207
+ // ---------- 流式响应:chat SSE chunk → Anthropic 具名事件 ----------
208
+
209
+ // thinking 块必须在 content_block_stop **之前**交一帧 signature_delta,缺它 Claude Code 把整块静默丢弃
210
+ // (routatic/proxy#51 真机复现、PR#133 修)。下面是**身份占位**:不含思考原文、不冒充密码学签名,理由与风险见 ADR-0052。
211
+ const SIG_PREFIX = "mslxdff:thinking:v1:";
212
+ function thinkingSignature(messageId, index) {
213
+ return Buffer.from(`${SIG_PREFIX}${messageId}:${index}`, "utf8").toString("base64url");
214
+ }
215
+
216
+ /**
217
+ * @param model 回显给客户端的模型名
218
+ * @param opts { id?, thinking?: boolean } thinking=true 才把 reasoning_content 发成 thinking 块
219
+ */
220
+ export function createAnthropicChunkTranslator(model = "", opts = {}) {
221
+ const id = opts.id || newMessageId();
222
+ const emitThinking = opts.thinking === true;
223
+ const created = Math.floor(Date.now() / 1000);
224
+ const ev = (type, extra = {}) => ({ type, ...extra });
225
+
226
+ let buf = "";
227
+ let nextIndex = 0;
228
+ let open = null; // 当前未封口块:{ index, kind: "text"|"thinking"|"tool_use", text? }
229
+ const tools = new Map(); // 上游 tc.index → { id, name, args, announced, index }
230
+ let sawToolUse = false;
231
+ let lastFinish = null;
232
+ let lastUsage = null;
233
+ const dbg = { chunks: 0, textChars: 0, toolDeltas: 0, thinkingChars: 0, skippedLines: 0, jsonFails: 0, lateToolDeltas: 0, blocks: 0 };
234
+
235
+ function closeOpen(out) {
236
+ if (!open) return;
237
+ if (open.kind === "thinking") out.push(ev("content_block_delta", { index: open.index, delta: { type: "signature_delta", signature: thinkingSignature(id, open.index) } }));
238
+ out.push(ev("content_block_stop", { index: open.index }));
239
+ open = null;
240
+ }
241
+ function openBlock(kind, contentBlock, out) {
242
+ closeOpen(out);
243
+ open = { index: nextIndex++, kind, text: "" };
244
+ dbg.blocks = open.index + 1;
245
+ out.push(ev("content_block_start", { index: open.index, content_block: contentBlock }));
246
+ return open;
247
+ }
248
+ function pushText(delta) {
249
+ const out = [];
250
+ if (!open || open.kind !== "text") openBlock("text", { type: "text", text: "" }, out);
251
+ open.text += delta;
252
+ out.push(ev("content_block_delta", { index: open.index, delta: { type: "text_delta", text: delta } }));
253
+ return out;
254
+ }
255
+ function pushThinking(delta) {
256
+ const out = [];
257
+ if (!open || open.kind !== "thinking") openBlock("thinking", { type: "thinking", thinking: "", signature: "" }, out);
258
+ open.text += delta;
259
+ out.push(ev("content_block_delta", { index: open.index, delta: { type: "thinking_delta", thinking: delta } }));
260
+ return out;
261
+ }
262
+ function announceTool(t, out) {
263
+ t.announced = true;
264
+ sawToolUse = true;
265
+ // 统一走 openBlock:自动封掉当前 text/thinking/上一个工具块,本块成为新的待封 open
266
+ openBlock("tool_use", { type: "tool_use", id: t.id, name: t.name, input: {} }, out);
267
+ t.index = open.index;
268
+ // 增量早于 id/name 到达时先攒着,announce 后补发(事件顺序仍合规)
269
+ if (t.args) out.push(ev("content_block_delta", { index: t.index, delta: { type: "input_json_delta", partial_json: t.args } }));
270
+ }
271
+ function pushTool(tc) {
272
+ const slot = Number(tc?.index ?? 0);
273
+ const out = [];
274
+ let t = tools.get(slot);
275
+ if (!t) { t = { id: "", name: "", args: "", announced: false, index: null }; tools.set(slot, t); }
276
+ if (tc?.id) t.id = String(tc.id);
277
+ if (tc?.function?.name) t.name += String(tc.function.name);
278
+ const frag = tc?.function?.arguments ? String(tc.function.arguments) : "";
279
+ if (frag) { dbg.toolDeltas++; t.args += frag; }
280
+ if (!t.announced && t.id && t.name) announceTool(t, out);
281
+ 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 } }));
282
+ else if (t.announced && frag) dbg.lateToolDeltas++; // 块已封口后才来的参数增量:发出即违规帧,丢弃并留读数
283
+ return out;
284
+ }
285
+
286
+ function begin() {
287
+ 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 } } })];
288
+ }
289
+
290
+ function push(data) {
291
+ buf += chunkToString(data);
292
+ const out = [];
293
+ let nl;
294
+ while ((nl = buf.indexOf("\n")) >= 0) {
295
+ const line = buf.slice(0, nl).trim();
296
+ buf = buf.slice(nl + 1);
297
+ // 注释帧/keepalive(`:` 开头)与上游 `[DONE]` 都不进 Anthropic 事件序列(grill Q6)
298
+ if (!line || line.startsWith(":")) continue;
299
+ if (!line.startsWith("data:")) { dbg.skippedLines++; continue; }
300
+ const payload = line.slice(5).trim();
301
+ if (!payload || payload === "[DONE]") continue;
302
+ let chunk;
303
+ try { chunk = JSON.parse(payload); } catch { dbg.jsonFails++; continue; }
304
+ dbg.chunks++;
305
+ const choice = chunk.choices?.[0] || {};
306
+ const delta = choice.delta || {};
307
+ if (choice.finish_reason) lastFinish = choice.finish_reason;
308
+ if (chunk.usage) lastUsage = chunk.usage;
309
+ if (typeof delta.content === "string" && delta.content) { dbg.textChars += delta.content.length; out.push(...pushText(delta.content)); }
310
+ for (const tc of delta.tool_calls || []) out.push(...pushTool(tc));
311
+ const rc = typeof delta.reasoning_content === "string" ? delta.reasoning_content : "";
312
+ if (rc) {
313
+ dbg.thinkingChars += rc.length;
314
+ if (emitThinking) out.push(...pushThinking(rc)); // 只发 thinking_delta,无 signature 可发
315
+ }
316
+ }
317
+ return out;
318
+ }
319
+
320
+ function end({ finish = null, usage = null } = {}) {
321
+ const out = [];
322
+ const fr = finish || lastFinish;
323
+ for (const t of tools.values()) {
324
+ if (!t.announced && (t.id || t.name || t.args)) announceTool(t, out); // 只有 arguments 无 name 的退化收尾
325
+ }
326
+ closeOpen(out);
327
+ out.push(ev("message_delta", { delta: { stop_reason: toStopReason(fr, sawToolUse), stop_sequence: null }, usage: toAnthropicUsage(usage || lastUsage) }));
328
+ out.push(ev("message_stop"));
329
+ return out;
330
+ }
331
+
332
+ // 上游给聚合 JSON(非 SSE,muse-spark / workbuddy 聚合 / zcode 非流式都是这种)时,
333
+ // 把整包喂进同一套 pushText/pushTool 状态机 —— 与流式共用封口规则,不出第二套形状。
334
+ function fromChatJson(chatJson = {}) {
335
+ const out = [];
336
+ const choice = chatJson.choices?.[0] || {};
337
+ const m = choice.message || {};
338
+ const ct = textFromChatContent(m.content); // 字符串或部件数组都吃,别把数组正文整段丢掉
339
+ // 聚合上游把思考放在 message.reasoning_content(muse-spark / workbuddy 聚合 / zcode 非流式):thinking 块须排 text 前。
340
+ const rt = typeof m.reasoning_content === "string" ? m.reasoning_content : "";
341
+ if (rt && emitThinking) out.push(...pushThinking(rt));
342
+ if (ct) out.push(...pushText(ct));
343
+ (Array.isArray(m.tool_calls) ? m.tool_calls : []).forEach((tc, i) => {
344
+ out.push(...pushTool({ index: i, id: tc?.id, function: { name: tc?.function?.name, arguments: tc?.function?.arguments } }));
345
+ });
346
+ if (choice.finish_reason) lastFinish = choice.finish_reason;
347
+ if (chatJson.usage) lastUsage = chatJson.usage;
348
+ return out;
349
+ }
350
+
351
+ function getFinal() {
352
+ return { finish: lastFinish, usage: lastUsage, sawToolUse };
353
+ }
354
+ function stats() {
355
+ return { ...dbg, openKind: open?.kind || null, toolSlots: tools.size };
356
+ }
357
+
358
+ return { id, created, begin, push, end, fromChatJson, getFinal, stats };
359
+ }
360
+
361
+ // ---------- count_tokens 字符估算 ----------
362
+
363
+ // 图片不吃字符但占真实上下文,按固定面值计;总长设硬上限防极端请求把除法推到 Infinity
364
+ const IMAGE_TOKENS = 2000;
365
+ const CHARS_PER_TOKEN = 4;
366
+ const CHAR_CAP = 32_000_000;
367
+
368
+ function countMessage(m, acc) {
369
+ if (!m || typeof m !== "object") return;
370
+ const blocks = typeof m.content === "string" ? [{ type: "text", text: m.content }] : Array.isArray(m.content) ? m.content : null;
371
+ if (!blocks) { acc.chars += JSON.stringify(m.content ?? "").length; return; }
372
+ for (const b of blocks) {
373
+ if (!b || typeof b !== "object") continue;
374
+ if (typeof b.text === "string") acc.chars += b.text.length;
375
+ else if (b.type === "tool_use") acc.chars += String(b.name || "").length + JSON.stringify(b.input ?? {}).length;
376
+ else if (b.type === "tool_result") acc.chars += toolResultTextOf(b.content).length; // 工具结果是大头,必须算(grill Q7)
377
+ else if (b.type === "thinking") acc.chars += String(b.thinking || "").length;
378
+ else if (b.type === "image") acc.images += 1;
379
+ }
380
+ }
381
+
382
+ /** 字符估算版 token 计数(Anthropic 官方:端点缺失时客户端本来就退回字符估算,精度非目标)。 */
383
+ export function estimateTokens(req = {}) {
384
+ let chars = 0;
385
+ let images = 0;
386
+ const acc = { chars: 0, images: 0 };
387
+ const sys = typeof req.system === "string" ? [{ type: "text", text: req.system }] : Array.isArray(req.system) ? req.system : [];
388
+ for (const b of sys) acc.chars += b && typeof b.text === "string" ? b.text.length : 0;
389
+ for (const m of Array.isArray(req.messages) ? req.messages : []) countMessage(m, acc);
390
+ if (Array.isArray(req.tools)) acc.chars += JSON.stringify(req.tools).length;
391
+ chars = Math.min(acc.chars, CHAR_CAP);
392
+ images = acc.images;
393
+ // 字段名以 Anthropic 线上为准:`POST /v1/messages/count_tokens` 回 `{"input_tokens": N}`;
394
+ // 额外带一份 count_tokens 仅作人读兼容(Claude Code 读的是 input_tokens)。
395
+ const n = Math.max(1, Math.ceil(chars / CHARS_PER_TOKEN) + images * IMAGE_TOKENS);
396
+ return { input_tokens: n, count_tokens: n };
397
+ }