mslxdff 0.1.164 → 0.1.170

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 (57) 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/daemon.js +13 -2
  24. package/src/model-capabilities/parse.js +1 -1
  25. package/src/model-trace.js +2 -1
  26. package/src/providers/classify.js +1 -1
  27. package/src/providers/dispatcher.js +2 -2
  28. package/src/providers/keyring.js +1 -1
  29. package/src/providers/model-id.js +10 -0
  30. package/src/providers/raccoon/account-store.js +216 -0
  31. package/src/providers/raccoon/auth.js +67 -0
  32. package/src/providers/raccoon/chat.js +207 -0
  33. package/src/providers/raccoon/const.js +111 -0
  34. package/src/providers/raccoon/credits.js +161 -0
  35. package/src/providers/raccoon/envelope.js +23 -0
  36. package/src/providers/raccoon/headers.js +45 -0
  37. package/src/providers/raccoon/index.js +216 -0
  38. package/src/providers/raccoon/login.js +195 -0
  39. package/src/providers/raccoon/models.js +160 -0
  40. package/src/providers/raccoon/qr-codewords.js +115 -0
  41. package/src/providers/raccoon/qr.js +236 -0
  42. package/src/providers/raccoon/sse.js +135 -0
  43. package/src/providers/registry.js +5 -0
  44. package/src/providers/share-keys.js +1 -1
  45. package/src/providers/workbuddy/models.js +29 -14
  46. package/src/providers/workbuddy/payload.js +34 -0
  47. package/src/routes/chat/exhausted-handler.js +4 -4
  48. package/src/routes/chat/relay-pipeline.js +6 -7
  49. package/src/routes/messages-route.js +114 -3
  50. package/src/runtime/bootstrap.js +5 -0
  51. package/src/runtime/broadband.js +4 -1
  52. package/src/runtime/provider-gate.js +3 -1
  53. package/src/runtime/raccoon-checkin.js +126 -0
  54. package/src/state/provider-config.js +1 -1
  55. package/src/sync-claude-desktop.js +234 -0
  56. package/src/talk-full.js +2 -2
  57. 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.164",
3
+ "version": "0.1.170",
4
4
  "description": "测试项目,请勿使用。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,6 +11,7 @@
11
11
  * model ID 照发全套字段,而 `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` 不清 thinking 与 effort。
12
12
  */
13
13
  import { chunkToString } from "../responses/translate.js";
14
+ import { isServerTool } from "./web-search.js";
14
15
 
15
16
  let seq = 0;
16
17
  export function newMessageId() {
@@ -68,7 +69,8 @@ export function messagesToChatBody(req = {}) {
68
69
 
69
70
  for (const m of Array.isArray(req.messages) ? req.messages : []) {
70
71
  if (!m || typeof m !== "object") continue;
71
- const role = m.role === "assistant" ? "assistant" : "user";
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";
72
74
  const blocks = typeof m.content === "string" ? [{ type: "text", text: m.content }] : Array.isArray(m.content) ? m.content : [];
73
75
  let text = "";
74
76
  const imgs = [];
@@ -102,16 +104,21 @@ export function messagesToChatBody(req = {}) {
102
104
  // 流式必须让上游把 usage 放进收尾帧,否则 message_delta.usage 恒 0(OpenAI 规范字段)。
103
105
  // 个别上游不认 stream_options 会 400 → `MSLXDFF_ANTHROPIC_STREAM_USAGE=0` 关掉。
104
106
  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
+ // 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) => ({
107
112
  type: "function",
108
113
  function: { name: String(t?.name || ""), description: String(t?.description || ""), parameters: t?.input_schema || {} },
109
114
  }));
110
115
  }
116
+ const keptNames = new Set(fnTools.map((t) => String(t?.name || "")));
111
117
  const tc = req.tool_choice;
112
118
  if (tc === "auto" || (tc && typeof tc === "object" && tc.type === "auto")) body.tool_choice = "auto";
113
119
  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 || "") } };
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";
115
122
  else if (tc && typeof tc === "object" && tc.type === "none") body.tool_choice = "none";
116
123
  if (req.max_tokens != null && Number.isFinite(Number(req.max_tokens))) body.max_tokens = Number(req.max_tokens);
117
124
  if (req.temperature != null) body.temperature = req.temperature;
@@ -199,6 +206,13 @@ export function chatJsonToAnthropic(chatJson = {}, model = "") {
199
206
 
200
207
  // ---------- 流式响应:chat SSE chunk → Anthropic 具名事件 ----------
201
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
+
202
216
  /**
203
217
  * @param model 回显给客户端的模型名
204
218
  * @param opts { id?, thinking?: boolean } thinking=true 才把 reasoning_content 发成 thinking 块
@@ -220,6 +234,7 @@ export function createAnthropicChunkTranslator(model = "", opts = {}) {
220
234
 
221
235
  function closeOpen(out) {
222
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) } }));
223
238
  out.push(ev("content_block_stop", { index: open.index }));
224
239
  open = null;
225
240
  }
@@ -239,7 +254,7 @@ export function createAnthropicChunkTranslator(model = "", opts = {}) {
239
254
  }
240
255
  function pushThinking(delta) {
241
256
  const out = [];
242
- if (!open || open.kind !== "thinking") openBlock("thinking", { type: "thinking", thinking: "" }, out);
257
+ if (!open || open.kind !== "thinking") openBlock("thinking", { type: "thinking", thinking: "", signature: "" }, out);
243
258
  open.text += delta;
244
259
  out.push(ev("content_block_delta", { index: open.index, delta: { type: "thinking_delta", thinking: delta } }));
245
260
  return out;
@@ -321,6 +336,9 @@ export function createAnthropicChunkTranslator(model = "", opts = {}) {
321
336
  const choice = chatJson.choices?.[0] || {};
322
337
  const m = choice.message || {};
323
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));
324
342
  if (ct) out.push(...pushText(ct));
325
343
  (Array.isArray(m.tool_calls) ? m.tool_calls : []).forEach((tc, i) => {
326
344
  out.push(...pushTool({ index: i, id: tc?.id, function: { name: tc?.function?.name, arguments: tc?.function?.arguments } }));
@@ -0,0 +1,361 @@
1
+ /**
2
+ * 网关代跑 Anthropic 的 `web_search` 服务端工具(ADR-0049)。
3
+ *
4
+ * 为什么需要它:Claude Code 的内置 WebSearch 不是客户端搜索——它单发一发 `/v1/messages`
5
+ * 旁路请求,把 `{type:"web_search_20250305",name:"web_search",max_uses:8}`(**没有** input_schema)
6
+ * 交给推理服务端,由服务端执行搜索、以 `server_tool_use` + `web_search_tool_result` 块回结果。
7
+ * 本网关的上游是 OpenAI 兼容端点,没人执行搜索,于是那次旁路只能拿到模型瞎猜的假工具调用
8
+ * (实测:CLI 判 0 次搜索并连开 5 轮空转)。这里由**网关自己**跑搜索并把合规块还回去。
9
+ *
10
+ * 纯逻辑 + 可注入 fetch:判据与形状不碰网络,便于单测;出网统一走 compatFetch。
11
+ */
12
+ import { compatFetch, timeoutSignal } from "../compat.js";
13
+
14
+ const PARALLEL_URL = "https://search.parallel.ai/mcp";
15
+ const EXA_URL = "https://mcp.exa.ai/mcp";
16
+ const TAVILY_URL = "https://api.tavily.com/search";
17
+ // 客户端旁路请求里那句固定 prompt(CLI 内部常量,版本可能变:认不出来就退回既有链路)
18
+ export const SEARCH_PROMPT_PREFIX = "Perform a web search for the query: ";
19
+ // 旁路 prompt 是 CLI 内部常量,理论上一条查询词很短;截一刀防畸形请求把整段上下文当查询送出去网
20
+ const MAX_QUERY_CHARS = 400;
21
+ // 搜索端点回包的读取上限(字符):边读边判,到顶即 cancel,不让 `*_URL` 指向的端点把内存吃穿
22
+ const MAX_RESPONSE_CHARS = 2_000_000;
23
+ // 结果条目 type 的唯一开关:真 Anthropic 用 `web_search_result`,若 CLI 侧口径不同只改这一行
24
+ const RESULT_ITEM_TYPE = "web_search_result";
25
+
26
+ let seq = 0;
27
+ export function newSearchMessageId() {
28
+ return `msg_${Date.now().toString(36)}${(seq++).toString(36)}`;
29
+ }
30
+ export function newServerToolUseId() {
31
+ return `srvtoolu_${Date.now().toString(36)}${(seq++).toString(36)}`;
32
+ }
33
+
34
+ // ---------- 判据 ----------
35
+
36
+ /**
37
+ * server tool:Anthropic 的 `tools[]` 条目里,用户态工具要么带 `input_schema`,要么是 OpenAI 风格
38
+ * `type:"function"`,要么是自由文本的 `type:"custom"`(按 Anthropic 形状它**不带** `input_schema`,
39
+ * 只有 `format`,剥掉就把用户自己的工具吞了)。除此之外带字符串 `type` 的就是服务端工具——
40
+ * **反向判据**(而非枚举前缀白名单)才不会被 Anthropic 新发的带日期类型绕过(ADR-0049)。
41
+ */
42
+ export function isServerTool(t) {
43
+ if (!t || typeof t !== "object") return false;
44
+ if (t.input_schema) return false;
45
+ const type = t.type;
46
+ return typeof type === "string" && type !== "function" && type !== "custom";
47
+ }
48
+
49
+ /** 这一发是不是 web_search 的 server tool 条目。 */
50
+ export function isSearchTool(t) {
51
+ return !!t && typeof t === "object" && t.name === "web_search" && /^web_search(_\d{8})?$/.test(String(t.type || ""));
52
+ }
53
+
54
+ function messageText(m) {
55
+ if (!m || typeof m !== "object") return "";
56
+ const c = m.content;
57
+ if (typeof c === "string") return c;
58
+ if (!Array.isArray(c)) return "";
59
+ let t = "";
60
+ for (const b of c) if (b && typeof b === "object" && typeof b.text === "string") t += (t ? "\n" : "") + b.text;
61
+ return t;
62
+ }
63
+
64
+ /**
65
+ * 命中判据(ADR-0049 D2,五条件与):
66
+ * 1. `tools[]` 里存在 web_search 的 server tool 条目(type + name 双对,见 `isSearchTool`)
67
+ * 2. **同一份 `tools[]` 里没有任何用户态工具**(带 `input_schema`、`type:"function"` 或 `type:"custom"`)
68
+ * ——主循环请求永远全套都带着,这一条把「用户正文恰好以那句套话开头」的劫持口堵死
69
+ * 3. 某条非 system 消息的文本**以** CLI 固定套话开头(`startsWith`,不是「正文里包含」)
70
+ * 4. 剥掉套话后**不含换行**(旁路的查询词是一行;粘贴套话再续写指令的多半是主循环)
71
+ * 5. 剥出的查询词截到 `MAX_QUERY_CHARS`
72
+ * `hit` 为真时 `query` 仍可能是空串(调用方据此不打后端)。
73
+ */
74
+ export function detectSearchRequest(req = {}) {
75
+ const tools = Array.isArray(req.tools) ? req.tools : [];
76
+ const tool = tools.find(isSearchTool);
77
+ if (!tool) return { hit: false, query: "" };
78
+ if (tools.some((t) => !isServerTool(t) && !isSearchTool(t))) return { hit: false, query: "" };
79
+ for (const m of Array.isArray(req.messages) ? req.messages : []) {
80
+ if (m && m.role === "system") continue;
81
+ const text = messageText(m).trimStart(); // 只去前导空白:整段 trim 会吃掉前缀结尾那个空格,导致「空前缀」判不命中
82
+ if (!text.startsWith(SEARCH_PROMPT_PREFIX)) continue;
83
+ const query = text.slice(SEARCH_PROMPT_PREFIX.length).trim();
84
+ if (query.includes("\n")) return { hit: false, query: "" };
85
+ return { hit: true, query: query.slice(0, MAX_QUERY_CHARS) };
86
+ }
87
+ return { hit: false, query: "" };
88
+ }
89
+
90
+ // ---------- 配置 ----------
91
+
92
+ /** env 面:`MSLXDFF_WEB_SEARCH` = 后端顺序(逗号分隔)或 `off`;非法列表值退缺省。 */
93
+ export function searchConfig(env = process.env) {
94
+ const raw = String(env.MSLXDFF_WEB_SEARCH ?? "").trim().toLowerCase();
95
+ const known = ["tavily", "exa", "parallel"]; // 缺省顺序=首腿最稳的那个(grill Q13)
96
+ let backends;
97
+ if (raw === "off" || raw === "none" || raw === "0") backends = [];
98
+ else if (!raw) backends = [...known];
99
+ else {
100
+ backends = raw.split(",").map((s) => s.trim()).filter((b) => known.includes(b));
101
+ if (!backends.length) backends = [...known]; // 写错了别静默变成「关」
102
+ }
103
+ const int = (v, d) => {
104
+ const n = Number(v);
105
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : d;
106
+ };
107
+ const str = (v) => String(v || "").trim();
108
+ return {
109
+ enabled: backends.length > 0,
110
+ backends,
111
+ timeoutMs: int(env.MSLXDFF_WEB_SEARCH_TIMEOUT_MS, 15000),
112
+ maxResults: int(env.MSLXDFF_WEB_SEARCH_MAX_RESULTS, 8),
113
+ maxChars: int(env.MSLXDFF_WEB_SEARCH_MAX_CHARS, 700),
114
+ tavilyKey: str(env.MSLXDFF_WEB_SEARCH_TAVILY_KEY),
115
+ parallelKey: str(env.MSLXDFF_WEB_SEARCH_PARALLEL_KEY),
116
+ exaKey: str(env.MSLXDFF_WEB_SEARCH_EXA_KEY),
117
+ // `_URL` 三个覆盖点:自建/换端点用,测试也走它(不 mock 模块,少一层假象)
118
+ parallelUrl: str(env.MSLXDFF_WEB_SEARCH_PARALLEL_URL) || PARALLEL_URL,
119
+ exaUrl: str(env.MSLXDFF_WEB_SEARCH_EXA_URL) || EXA_URL,
120
+ tavilyUrl: str(env.MSLXDFF_WEB_SEARCH_TAVILY_URL) || TAVILY_URL,
121
+ };
122
+ }
123
+
124
+ // ---------- 后端(免 key 可用的公开端点:Tavily 走 REST,Exa/Parallel 走 MCP) ----------
125
+
126
+ function rpcBody(name, args) {
127
+ return JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
128
+ }
129
+
130
+ /** MCP 端点可能回整包 JSON,也可能回 SSE 帧;两种都认。RPC error 一律抛(200 也可能是错)。 */
131
+ export function unwrapRpcText(bodyText) {
132
+ const trimmed = String(bodyText || "").trim();
133
+ if (!trimmed) return "";
134
+ const candidates = [];
135
+ if (trimmed.startsWith("{")) candidates.push(trimmed);
136
+ for (const line of trimmed.split("\n")) {
137
+ const row = line.trim();
138
+ if (row.startsWith("data:")) candidates.push(row.slice(5).trim());
139
+ }
140
+ for (const c of candidates) {
141
+ let parsed;
142
+ try { parsed = JSON.parse(c); } catch { continue; }
143
+ if (parsed && parsed.error) {
144
+ const msg = typeof parsed.error.message === "string" ? parsed.error.message : "rpc error";
145
+ throw new Error(`search endpoint rejected the request: ${msg}`.slice(0, 200));
146
+ }
147
+ const content = parsed && parsed.result && parsed.result.content;
148
+ if (Array.isArray(content)) {
149
+ const hit = content.find((i) => i && typeof i.text === "string" && i.text.trim());
150
+ if (hit) return hit.text;
151
+ }
152
+ }
153
+ return "";
154
+ }
155
+
156
+ /**
157
+ * 有上限地读响应体:`await res.text()` 会把整包先物化进内存(`_URL` 可指向任意端点,
158
+ * 恶意/异常的大回包会按并发数放大),故能拿 reader 就边读边判、到顶即 cancel。
159
+ * 拿不到 reader(假 fetch / 已消费)才退回一次性 text() 后再截。
160
+ */
161
+ async function readCapped(res, cap) {
162
+ const body = res && res.body;
163
+ if (!body || typeof body.getReader !== "function") {
164
+ return String((await res.text?.()) ?? "").slice(0, cap);
165
+ }
166
+ const reader = body.getReader();
167
+ const decoder = new TextDecoder("utf-8");
168
+ let out = "";
169
+ try {
170
+ for (;;) {
171
+ const { done, value } = await reader.read();
172
+ if (done) break;
173
+ if (!value) continue;
174
+ out += decoder.decode(value, { stream: true });
175
+ if (out.length >= cap) {
176
+ try { await reader.cancel(); } catch { /* 已尽 */ }
177
+ break;
178
+ }
179
+ }
180
+ out += decoder.decode();
181
+ } finally {
182
+ try { reader.releaseLock(); } catch { /* ignore */ }
183
+ }
184
+ return out.slice(0, cap);
185
+ }
186
+
187
+ async function callMcp(url, tool, args, { timeoutMs, bearer, fetchImpl }) {
188
+ const headers = { "Content-Type": "application/json", Accept: "application/json, text/event-stream" };
189
+ if (bearer) headers.Authorization = `Bearer ${bearer}`;
190
+ const res = await (fetchImpl || compatFetch)(url, {
191
+ method: "POST",
192
+ headers,
193
+ body: rpcBody(tool, args),
194
+ signal: timeoutSignal(timeoutMs),
195
+ });
196
+ const text = await readCapped(res, MAX_RESPONSE_CHARS);
197
+ if (Number(res.status) >= 400) throw new Error(`HTTP ${res.status}`);
198
+ return unwrapRpcText(text);
199
+ }
200
+
201
+ /** Parallel 的回包是 JSON 字符串:`results[].{url,title,excerpts[]}`。 */
202
+ export function parseParallelItems(text) {
203
+ let parsed;
204
+ try { parsed = JSON.parse(text); } catch { return []; }
205
+ const out = [];
206
+ for (const r of Array.isArray(parsed?.results) ? parsed.results : []) {
207
+ const url = typeof r?.url === "string" ? r.url.trim() : "";
208
+ if (!url) continue;
209
+ out.push({ title: typeof r.title === "string" && r.title.trim() ? r.title.trim() : url, url, snippet: Array.isArray(r.excerpts) ? r.excerpts.join("\n") : "" });
210
+ }
211
+ return out;
212
+ }
213
+
214
+ /** Exa 的回包是预排好的文本块:`Title:` / `URL:` / `Highlights:`,块间 `---`。 */
215
+ export function parseExaItems(text) {
216
+ const out = [];
217
+ for (const block of String(text || "").split(/\n-{3,}\n/)) {
218
+ const url = /^URL:\s*(.+)$/m.exec(block);
219
+ if (!url) continue;
220
+ const title = /^Title:\s*(.+)$/m.exec(block);
221
+ const at = block.search(/^Highlights:/m);
222
+ out.push({ title: (title && title[1].trim()) || url[1].trim(), url: url[1].trim(), snippet: at === -1 ? "" : block.slice(at).replace(/^Highlights:\s*/, "").trim() });
223
+ }
224
+ return out;
225
+ }
226
+
227
+ /** Tavily 的回包是普通 REST JSON:`results[].{title,url,content}`;免 key 档限流回 4xx(≥400 已在调用处抛)。 */
228
+ export function parseTavilyItems(text) {
229
+ let parsed;
230
+ try { parsed = JSON.parse(text); } catch { return []; }
231
+ const out = [];
232
+ for (const r of Array.isArray(parsed?.results) ? parsed.results : []) {
233
+ const url = typeof r?.url === "string" ? r.url.trim() : "";
234
+ if (!url) continue;
235
+ out.push({ title: typeof r.title === "string" && r.title.trim() ? r.title.trim() : url, url, snippet: typeof r.content === "string" ? r.content : "" });
236
+ }
237
+ return out;
238
+ }
239
+
240
+ const BACKENDS = {
241
+ async parallel(query, cfg, fetchImpl) {
242
+ const text = await callMcp(cfg.parallelUrl, "web_search", { objective: query, search_queries: [query] }, { timeoutMs: cfg.timeoutMs, bearer: cfg.parallelKey, fetchImpl });
243
+ return parseParallelItems(text);
244
+ },
245
+ async exa(query, cfg, fetchImpl) {
246
+ const url = cfg.exaKey ? `${cfg.exaUrl}?exaApiKey=${encodeURIComponent(cfg.exaKey)}` : cfg.exaUrl;
247
+ const text = await callMcp(url, "web_search_exa", { query, type: "auto", numResults: cfg.maxResults, livecrawl: "fallback" }, { timeoutMs: cfg.timeoutMs, fetchImpl });
248
+ return parseExaItems(text);
249
+ },
250
+ // 首腿:免注册的 keyless REST(2026-10-09 压测 10 路并发 10/10;exa/parallel 免 key 档当刻 429/空回)
251
+ async tavily(query, cfg, fetchImpl) {
252
+ const headers = { "Content-Type": "application/json" };
253
+ if (cfg.tavilyKey) headers.Authorization = `Bearer ${cfg.tavilyKey}`;
254
+ else headers["X-Tavily-Access-Mode"] = "keyless";
255
+ const res = await (fetchImpl || compatFetch)(cfg.tavilyUrl, {
256
+ method: "POST",
257
+ headers,
258
+ body: JSON.stringify({ query, max_results: cfg.maxResults, search_depth: "basic" }),
259
+ signal: timeoutSignal(cfg.timeoutMs),
260
+ });
261
+ const text = await readCapped(res, MAX_RESPONSE_CHARS);
262
+ if (Number(res.status) >= 400) throw new Error(`HTTP ${res.status}`);
263
+ return parseTavilyItems(text);
264
+ },
265
+ };
266
+
267
+ /**
268
+ * 按 cfg.backends 顺序试;**只有拿到 ≥1 条带 url 的结果才算成功**
269
+ * (免 key 档的限流文案也是 HTTP 200,见 ADR-0049 已知边界)。
270
+ */
271
+ export async function runWebSearch(query, cfg, { fetchImpl } = {}) {
272
+ const q = String(query || "").trim();
273
+ const t0 = Date.now();
274
+ if (!q) return { ok: false, provider: "", query: "", results: [], error: "empty query", ms: 0, chain: [] };
275
+ const errs = [];
276
+ // 一条后端链共享一个 deadline(不是每发一个超时):各后端串行最坏也只等 cfg.timeoutMs
277
+ const deadline = t0 + cfg.timeoutMs;
278
+ const chain = []; // 逐后端耗时与失败原因:只有总账看不出是谁花的(grill Q15)
279
+ for (const name of cfg.backends) {
280
+ const run = BACKENDS[name];
281
+ if (!run) continue;
282
+ const left = deadline - Date.now();
283
+ const legT0 = Date.now();
284
+ if (left < 250) {
285
+ errs.push(`${name}: skipped (search budget ${cfg.timeoutMs}ms exhausted)`);
286
+ chain.push({ name, ms: 0, error: `skipped (search budget ${cfg.timeoutMs}ms exhausted)` });
287
+ break;
288
+ }
289
+ try {
290
+ const items = await run(q, { ...cfg, timeoutMs: left }, fetchImpl);
291
+ const results = items.slice(0, cfg.maxResults).map((r) => ({
292
+ title: String(r.title || r.url).slice(0, 200),
293
+ url: String(r.url).slice(0, 500),
294
+ snippet: String(r.snippet || "").replace(/[ \t]+\n/g, "\n").trim().slice(0, cfg.maxChars),
295
+ }));
296
+ if (results.length) return { ok: true, provider: name, query: q, results, ms: Date.now() - t0, chain: chain.concat({ name, ms: Date.now() - legT0 }) };
297
+ errs.push(`${name}: no usable results`);
298
+ chain.push({ name, ms: Date.now() - legT0, error: "no usable results" });
299
+ } catch (e) {
300
+ errs.push(`${name}: ${String(e?.message || e).slice(0, 200)}`);
301
+ chain.push({ name, ms: Date.now() - legT0, error: String(e?.message || e).slice(0, 200) });
302
+ }
303
+ }
304
+ return { ok: false, provider: "", query: q, results: [], error: errs.join("; ") || "all search backends failed", ms: Date.now() - t0, chain };
305
+ }
306
+
307
+ // ---------- 自造响应(块定义只此一份,流式与非流式共用) ----------
308
+
309
+ export function buildSearchBlocks({ query, results }) {
310
+ const id = newServerToolUseId();
311
+ const content = (Array.isArray(results) ? results : []).map((r) => {
312
+ const item = { type: RESULT_ITEM_TYPE, title: String(r.title || r.url), url: String(r.url) };
313
+ if (r.snippet) item.snippet = String(r.snippet);
314
+ return item;
315
+ });
316
+ return [
317
+ { type: "server_tool_use", id, name: "web_search", input: { query: String(query || "") } },
318
+ { type: "web_search_tool_result", tool_use_id: id, content },
319
+ ];
320
+ }
321
+
322
+ export function buildSearchMessage({ model = "", query, results }) {
323
+ return {
324
+ id: newSearchMessageId(),
325
+ type: "message",
326
+ role: "assistant",
327
+ model,
328
+ content: buildSearchBlocks({ query, results }),
329
+ stop_reason: "end_turn",
330
+ stop_sequence: null,
331
+ usage: {
332
+ input_tokens: 0,
333
+ output_tokens: 0,
334
+ cache_read_input_tokens: 0,
335
+ cache_creation_input_tokens: 0,
336
+ // 没打模型,但按 Anthropic 口径报「跑了 N 次搜索」:客户端上报的正是这个字段
337
+ server_tool_use: { web_search_requests: 1, web_fetch_requests: 0 },
338
+ },
339
+ };
340
+ }
341
+
342
+ /** 由同一份块数组生成 Anthropic 具名事件序列(无 `[DONE]`;见 ADR-0047 收场口径)。 */
343
+ export function searchEvents(message) {
344
+ const ev = (type, extra) => ({ type, ...extra });
345
+ const out = [
346
+ ev("message_start", { message: { id: message.id, type: message.type, role: message.role, model: message.model, content: [], stop_reason: null, stop_sequence: null, usage: message.usage } }),
347
+ ];
348
+ message.content.forEach((block, index) => {
349
+ if (block.type === "server_tool_use") {
350
+ out.push(ev("content_block_start", { index, content_block: { type: block.type, id: block.id, name: block.name, input: {} } }));
351
+ out.push(ev("content_block_delta", { index, delta: { type: "input_json_delta", partial_json: JSON.stringify(block.input || {}) } }));
352
+ } else {
353
+ // 结果块一次性给全(真 API 也不逐字滴结果)
354
+ out.push(ev("content_block_start", { index, content_block: block }));
355
+ }
356
+ out.push(ev("content_block_stop", { index }));
357
+ });
358
+ out.push(ev("message_delta", { delta: { stop_reason: message.stop_reason, stop_sequence: null }, usage: message.usage }));
359
+ out.push(ev("message_stop"));
360
+ return out;
361
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * 入站协议门短码(api kind)——「这一发是从哪扇门进来的」的唯一判定。
3
+ *
4
+ * 为什么单独成模块:三道门(`/v1/chat/completions`、`/v1/responses`、`/v1/messages`)汇入同一条
5
+ * ChatPipeline、同一批模型,四类日志形状完全相同 → 门信息一旦在各写点各判一次,就会出现第二份
6
+ * 前缀匹配并迟早互相漂移。故判定**只做一次**(ChatPipeline inlet),结果随 `handlerCtx` 透传。
7
+ *
8
+ * 缺值口径:认不出的路 = `other`(恒有值、绝不空串/undefined);**写点拿不到值时省略该字段**,
9
+ * 使「缺字段」只可能是旧行或漏传,而不会被误读成一次未知门的判定。
10
+ */
11
+
12
+ export const API_KINDS = ["chat", "responses", "messages", "other"];
13
+ export const API_KIND_OTHER = "other";
14
+
15
+ /**
16
+ * 路径 → 短码。只认段边界:`/v1/messagesXYZ` 不是 `/v1/messages` 的子段(那是别的路由,不许冒充门)。
17
+ * query(`?beta=true`)与 `count_tokens` 子路径都归同一扇门。
18
+ */
19
+ export function apiKindOfUrl(url) {
20
+ if (typeof url !== "string" || !url) return API_KIND_OTHER;
21
+ const path = url.split("?")[0].split("#")[0];
22
+ if (path === "/v1/chat/completions" || path.startsWith("/v1/chat/completions/")) return "chat";
23
+ if (path === "/v1/responses" || path.startsWith("/v1/responses/")) return "responses";
24
+ if (path === "/v1/messages" || path.startsWith("/v1/messages/")) return "messages";
25
+ return API_KIND_OTHER;
26
+ }
27
+
28
+ /** req → 短码(读 `req.url`;缺失/非字符串 = `other`)。 */
29
+ export function apiKindOf(req) {
30
+ return apiKindOfUrl(req && typeof req === "object" ? req.url : undefined);
31
+ }
@@ -2,6 +2,7 @@ import { performance } from "node:perf_hooks";
2
2
  import { injectReasoningContent } from "../reasoning.js";
3
3
  import { runHook } from "../plugins.js";
4
4
  import { errMsg } from "../routes/helpers.js";
5
+ import { withOutputFloor } from "./empty-turn.js";
5
6
  import { handleLocalRelay } from "../routes/chat/local-handler.js";
6
7
  import { handleExhaustedAll } from "../routes/chat/exhausted-handler.js";
7
8
 
@@ -56,6 +57,13 @@ export async function runAutoRace(ctx, deps = {}) {
56
57
  const raceStart = performance.now();
57
58
  const attempts = raceModels.map(async (m) => {
58
59
  let f = { ...injectReasoningContent(m, body), model: m };
60
+ // 首发输出额度托底(同 serial-trial;auto 竞速路径独立组装,不能漏)
61
+ const _fl = withOutputFloor(f);
62
+ if (_fl !== f) {
63
+ const _fk = ["max_tokens", "max_completion_tokens"].find((k) => _fl[k] !== f[k]) || "max_tokens";
64
+ evt("output-floor", { reqId, model: m, key: _fk, raiseFrom: Number(f[_fk]), raiseTo: Number(_fl[_fk]) });
65
+ f = _fl;
66
+ }
59
67
  if (plugins?.length) {
60
68
  const u = await runHook(plugins, "upstream:request", { reqId, requested, model: m, payload: f, stream: Boolean(body.stream) });
61
69
  if (u.changed && u.value?.payload) f = u.value.payload;
@@ -93,6 +93,34 @@ export function withRaisedMaxTokens(payload, cap, floor = 0) {
93
93
  if (floor) return { ...payload, max_tokens: Math.min(floor, cap || floor) }; // 客户端没设额度:兜底发明一次
94
94
  return payload;
95
95
  }
96
+
97
+ // 首发输出额度托底:客户端"剩余上下文"算术算爆会把 max_tokens/max_completion_tokens 写成 1
98
+ // (实测 442 条消息 PI agent 会话 → 上游按 1 token 截断 finish=length、正文 0~5 字,循环停摆);
99
+ // 既有空转翻倍抬额 1→2→4 救不回来,且正文非零(2~5 字)进不了空转重试 → 首发前托平。
100
+ // 只托"存在且 <门槛"的值,不发明额度(发明归 emptyTurnMinRaiseTo)。
101
+ // MSLXDFF_EMPTY_TURN_MIN_TOKENS=0 关闭;MSLXDFF_EMPTY_TURN_TINY_MAX 改门槛。
102
+ export function outputFloorCfg() {
103
+ const rawMin = String(process.env.MSLXDFF_EMPTY_TURN_MIN_TOKENS ?? "").trim();
104
+ const min = rawMin === "" ? NaN : Number(rawMin);
105
+ const rawTiny = String(process.env.MSLXDFF_EMPTY_TURN_TINY_MAX ?? "").trim();
106
+ const tiny = rawTiny === "" ? NaN : Number(rawTiny);
107
+ return {
108
+ min: Number.isFinite(min) && min <= 0 ? 0 : (Number.isFinite(min) ? Math.floor(min) : 8192), // 0/负数=关(对齐 emptyTurnMinRaiseTo);非法/未设=8192
109
+ tiny: Number.isFinite(tiny) && tiny >= 0 ? Math.floor(tiny) : 64, // 非法/未设=64
110
+ };
111
+ }
112
+ export function withOutputFloor(payload) {
113
+ if (!payload || typeof payload !== "object") return payload;
114
+ const { min, tiny } = outputFloorCfg();
115
+ if (!min) return payload; // 0=关闭托底(空串=未设由 cfg 兜底成 8192)
116
+ let out = payload;
117
+ for (const key of ["max_tokens", "max_completion_tokens"]) {
118
+ if (payload[key] == null || payload[key] === "") continue; // 没设=原样,不发明
119
+ const cur = Number(payload[key]);
120
+ if (Number.isFinite(cur) && cur > 0 && cur < tiny) { const to = Math.max(Math.floor(cur), min); if (to > cur) out = { ...out, [key]: to }; } // >0 才算设过(0=上游默认值,抬了反降额——评审 P1);只加不减
121
+ }
122
+ return out;
123
+ }
96
124
  // 空转追问:最后一次空转重试前追加一句 user 兜底(content 空轮大概率是模型“收尾犹豫”,
97
125
  // 追问把它逼出一句“任务完成了”即可终结;前面重试仍原样重拉,防改写正常对话)。
98
126
  // MSLXDFF_EMPTY_NUDGE=0 关闭;MSLXDFF_EMPTY_NUDGE_TEXT 改话术。
@@ -6,6 +6,7 @@ import { isFreeModel } from "../models.js";
6
6
  import { clientIp, summarizePrompt } from "../routes/helpers.js";
7
7
  import { formatTimeline } from "../timeline.js";
8
8
  import { summarizeRequest, shouldTraceModel } from "../model-trace.js";
9
+ import { apiKindOf } from "../api-kind.js";
9
10
 
10
11
  /**
11
12
  * ChatPipeline 深模块门面 — 对外 execute(req) 单一 inlet
@@ -18,6 +19,9 @@ export function createChatPipeline({ upstream, auto, logs, peers, groups, bus, t
18
19
  async function execute({ req, res } = {}) {
19
20
  const startedAt = Date.now();
20
21
  const reqId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
22
+ // 入站协议门(chat|responses|messages|other):全场只在这里判一次,之后随 handlerCtx 透传;
23
+ // 各日志写点不得再各自匹配路径(第二份判定迟早漂移)—— 见 src/api-kind.js
24
+ const api = apiKindOf(req);
21
25
  const perf0 = performance.now();
22
26
  const stages = [];
23
27
  const mark = (name) => stages.push([name, Math.round(performance.now() - perf0)]);
@@ -34,10 +38,10 @@ export function createChatPipeline({ upstream, auto, logs, peers, groups, bus, t
34
38
 
35
39
  // 事件/日志帮手先于 order 推导声明:evt 在 auto-scope 分支即被使用,
36
40
  // 声明置后会让 useAuto && autoProvider 的请求在 TDZ 上崩(线上 -chat 回退路径)
37
- const logCall = (model, status) => logs?.appendCall({ reqId, model, auto: useAuto, status, durationMs: Date.now() - startedAt, stream: Boolean(req?.body?.stream), stages });
38
- const logError = (model, status, message) => logs?.appendError({ reqId, model, auto: useAuto, status, message, stages });
41
+ const logCall = (model, status) => logs?.appendCall({ reqId, api, model, auto: useAuto, status, durationMs: Date.now() - startedAt, stream: Boolean(req?.body?.stream), stages });
42
+ const logError = (model, status, message) => logs?.appendError({ reqId, api, model, auto: useAuto, status, message, stages });
39
43
  const evt = (type, data) => {
40
- const entry = { ts: Date.now(), reqId, type, ...data, model: data.model ?? requested, auto: useAuto, durationMs: Date.now() - startedAt, stages: [...stages] };
44
+ const entry = { ts: Date.now(), reqId, type, ...data, api, model: data.model ?? requested, auto: useAuto, durationMs: Date.now() - startedAt, stages: [...stages] };
41
45
  const traceModel = entry.model || requested;
42
46
  if (shouldTraceModel(type)) {
43
47
  // Note: 模型日志只投影安全字段,不能把含 prompt 的 entry 原样下传 — 见 .agents/notes/implemented/feature/2026-09-25-model-trace-log.md
@@ -111,7 +115,7 @@ export function createChatPipeline({ upstream, auto, logs, peers, groups, bus, t
111
115
  // 客户端会话标识(opencode 插件 chat.headers 注入)→ 透传上游做粘性路由/缓存亲和;
112
116
  // 无头时由 upstream.js 按对话首两条消息哈希兜底(不再每请求随机)
113
117
  const clientSession = String(req?.headers?.["x-session-affinity"] || req?.headers?.["x-session-id"] || "").trim() || null;
114
- const handlerCtx = { reqId, model: null, body: req?.body, hops, peers, plugins, evt, logError, logCall, logs, workbuddyUid, sessionId: clientSession, clientIp: reqIp };
118
+ const handlerCtx = { reqId, api, model: null, body: req?.body, hops, peers, plugins, evt, logError, logCall, logs, workbuddyUid, sessionId: clientSession, clientIp: reqIp };
115
119
  if (clientSession) evt("client-session", { reqId, sessionId: clientSession.slice(0, 24) });
116
120
 
117
121
  await engine.run({
@@ -12,7 +12,7 @@ import { handleExhaustedLocal, handleExhaustedAll } from "../routes/chat/exhaust
12
12
  import { shouldUseGroupForModel, isHardLocalOnly, isKeyProviderDirectOnly } from "../state/schemas/use-group.js";
13
13
  import { summarizeRequest, upstreamEcho } from "../model-trace.js";
14
14
  import { isEmptyTurnError } from "../routes/chat/relay-pipeline.js";
15
- import { emptyRetryCfg, emptyRaiseCap, withRaisedMaxTokens, emptyNudgeCfg, withEmptyNudge, computeNextDelay, emptyTurnBudgetMs, emptyTurnMinRaiseTo } from "./empty-turn.js";
15
+ import { emptyRetryCfg, emptyRaiseCap, withRaisedMaxTokens, withOutputFloor, emptyNudgeCfg, withEmptyNudge, computeNextDelay, emptyTurnBudgetMs, emptyTurnMinRaiseTo } from "./empty-turn.js";
16
16
 
17
17
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
18
 
@@ -74,6 +74,13 @@ export async function runSerialTrial(ctx, deps = {}) {
74
74
  }
75
75
  let upRes = null;
76
76
  let forwarded = { ...injectReasoningContent(model, body), model };
77
+ // 首发输出额度托底(plugin hook 前——plugin 有最终发言权,硬底线只约束客户端直发 body)
78
+ const _floored = withOutputFloor(forwarded);
79
+ if (_floored !== forwarded) {
80
+ const _fk = ["max_tokens", "max_completion_tokens"].find((k) => _floored[k] !== forwarded[k]) || "max_tokens";
81
+ evt("output-floor", { reqId, model, key: _fk, raiseFrom: Number(forwarded[_fk]), raiseTo: Number(_floored[_fk]) });
82
+ forwarded = _floored;
83
+ }
77
84
  if (plugins?.length) {
78
85
  const ur = await runHook(plugins, "upstream:request", { reqId, requested, model, payload: forwarded, stream: Boolean(body.stream) });
79
86
  for (const e of ur.errors) evt("plugin-hook-error", { reqId, hook: "upstream:request", plugin: e.plugin, error: e.error });