mslxdff 0.1.163 → 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.
- package/package.json +1 -1
- package/src/anthropic/translate.js +379 -0
- package/src/cli/commands/sync.js +74 -2
- package/src/cli/help.js +1 -0
- package/src/routes/index.js +13 -0
- package/src/routes/messages-route.js +290 -0
- package/src/routes/responses-route.js +2 -2
- package/src/sync-claude.js +152 -0
package/package.json
CHANGED
|
@@ -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
|
+
}
|
package/src/cli/commands/sync.js
CHANGED
|
@@ -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
|
@@ -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)
|
package/src/routes/index.js
CHANGED
|
@@ -7,6 +7,7 @@ import { heartbeatHandler, pollHandler, resultHandler, forwardHandler, streamHan
|
|
|
7
7
|
import { modelsHandler, modelsStatusHandler, providerModelsHandler, capabilitiesHandler } from "./models-route.js";
|
|
8
8
|
import { relayHandler } from "./relay.js";
|
|
9
9
|
import { responsesHandler } from "./responses-route.js";
|
|
10
|
+
import { messagesHandler, countTokensHandler } from "./messages-route.js";
|
|
10
11
|
|
|
11
12
|
export function createRouter({ token, upstream, models, auto, logs, peers, maxHops = DEFAULT_MAX_HOPS, groups, bans, bus, plugins }) {
|
|
12
13
|
return async function router(req, res) {
|
|
@@ -50,6 +51,18 @@ const ROUTES = [
|
|
|
50
51
|
requiresAuth: true,
|
|
51
52
|
handler: responsesHandler,
|
|
52
53
|
},
|
|
54
|
+
{
|
|
55
|
+
method: "POST",
|
|
56
|
+
path: "/v1/messages",
|
|
57
|
+
requiresAuth: true,
|
|
58
|
+
handler: messagesHandler,
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
method: "POST",
|
|
62
|
+
path: "/v1/messages/count_tokens",
|
|
63
|
+
requiresAuth: true,
|
|
64
|
+
handler: countTokensHandler,
|
|
65
|
+
},
|
|
53
66
|
{
|
|
54
67
|
method: "POST",
|
|
55
68
|
path: "/v1/groups/join",
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* POST /v1/messages + /v1/messages/count_tokens — 给 Claude Code 用的 Anthropic Messages 外壳(ADR-0047)。
|
|
3
|
+
* 复用 ChatPipeline 全链路(auto/hedge/failover/tool_calls/空轮重试),只做形状翻译:
|
|
4
|
+
* 非流式:收集 chat JSON → 转 Anthropic message;流式:逐块实时翻成 Anthropic 具名事件。
|
|
5
|
+
*
|
|
6
|
+
* 出站格式与 /v1/responses **不兼容**,故不能复用 createLiveForwarder(它写死 `data:` + `[DONE]`):
|
|
7
|
+
* Anthropic 用 `event: <type>` 具名帧、无 `[DONE]`,且需网关自发 `ping` 扛过客户端 idle watchdog。
|
|
8
|
+
*
|
|
9
|
+
* 三条收口纪律(第 1 轮评审 P0-2/P0-3 立下的,别改回去):
|
|
10
|
+
* 1. 上游一有动静(含 pipeline 的 keepalive 注释帧)就发头 + `message_start` + 武装 ping —— 首块前的静默期正是客户端 watchdog 咬人的窗口;
|
|
11
|
+
* 2. `headersSent`/`getHeader` 必须真反映已发头,否则 `helpers.js:32` 的「已 flush 走 in-band 错误帧」守卫永远判假,
|
|
12
|
+
* 错误会被当成普通文本喂进 push() 后静默消失;
|
|
13
|
+
* 3. 没等到 `finish_reason`(也没有 `[DONE]`)就收线 = 截断,发 `event: error`,**不伪装成功收场**。
|
|
14
|
+
*/
|
|
15
|
+
import { json, readBody } from "./helpers.js";
|
|
16
|
+
import { createChatPipeline } from "../chat-pipeline/index.js";
|
|
17
|
+
import { withBody, createCollector, createEmitter } from "./responses-route.js";
|
|
18
|
+
import {
|
|
19
|
+
messagesToChatBody,
|
|
20
|
+
chatJsonToAnthropic,
|
|
21
|
+
createAnthropicChunkTranslator,
|
|
22
|
+
estimateTokens,
|
|
23
|
+
anthropicError,
|
|
24
|
+
} from "../anthropic/translate.js";
|
|
25
|
+
|
|
26
|
+
const ADEBUG = process.env.MSLXDFF_ANTHROPIC_DEBUG === "1";
|
|
27
|
+
function alog(...a) {
|
|
28
|
+
if (ADEBUG) console.log("[messages]", ...a);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const THINKING = process.env.MSLXDFF_ANTHROPIC_THINKING === "1";
|
|
32
|
+
// 空闲 ping 周期(ms):`0` 关闭;客户端长思考期靠它扛过 streaming idle timeout
|
|
33
|
+
const PING_MS = (() => {
|
|
34
|
+
const raw = Number(process.env.MSLXDFF_ANTHROPIC_PING_MS);
|
|
35
|
+
return Number.isFinite(raw) && raw >= 0 ? raw : 15000;
|
|
36
|
+
})();
|
|
37
|
+
|
|
38
|
+
function frameOf(type, data) {
|
|
39
|
+
return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// pipeline 在已 flush 的流里用 OpenAI 形状收口(`{error:{...}}` + `[DONE]`):
|
|
43
|
+
// 检出后改发 Anthropic 的 `error` 帧,别把错误伪装成正常收场(grill-decisions Q2)
|
|
44
|
+
function detectInBandError(text) {
|
|
45
|
+
let msg = null;
|
|
46
|
+
for (const line of String(text || "").split("\n")) {
|
|
47
|
+
const t = line.trim();
|
|
48
|
+
if (!t.startsWith("data:")) continue;
|
|
49
|
+
const payload = t.slice(5).trim();
|
|
50
|
+
if (!payload || payload === "[DONE]") continue;
|
|
51
|
+
try {
|
|
52
|
+
const j = JSON.parse(payload);
|
|
53
|
+
const e = j?.error;
|
|
54
|
+
if (e) msg = String(e?.message || e).slice(0, 500);
|
|
55
|
+
} catch { /* 非 JSON 帧忽略 */ }
|
|
56
|
+
}
|
|
57
|
+
return msg;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
// pipeline 未 flush 时用 json() 直写聚合错误体(无 `data:` 前缀):认出来只取 message,
|
|
62
|
+
// 别把整坨 OpenAI JSON 当人话塞进 Anthropic error.message。
|
|
63
|
+
function jsonErrorText(text) {
|
|
64
|
+
const t = String(text || "").trim();
|
|
65
|
+
if (!t || t.startsWith(":") || t.includes("data:")) return null;
|
|
66
|
+
try {
|
|
67
|
+
const j = JSON.parse(t);
|
|
68
|
+
const e = j?.error;
|
|
69
|
+
if (!e) return null;
|
|
70
|
+
return String(e?.message || e).slice(0, 500);
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 两种上游收场形状(in-band `data:` 帧 / 聚合 JSON 体)统一取错误文案。 */
|
|
77
|
+
function errorText(text) {
|
|
78
|
+
return detectInBandError(text) || jsonErrorText(text);
|
|
79
|
+
}
|
|
80
|
+
// 客户端要流式而上游给了聚合 JSON(muse-spark / workbuddy 聚合 / zcode 非流式聚合都是现网常态):
|
|
81
|
+
// 那体没有 `data:` 前缀,会被 push() 当噪声整段丢掉 → 正文静默消失。认出来交给 fromChatJson 兜底。
|
|
82
|
+
function tryAggregate(text) {
|
|
83
|
+
const t = String(text || "").trim();
|
|
84
|
+
if (!t || t.includes("data:") || t.startsWith(":")) return null;
|
|
85
|
+
try {
|
|
86
|
+
const j = JSON.parse(t);
|
|
87
|
+
// 只认「非空 choices」:`{choices:[]}` 之类的空包什么也带不来,若当合法聚合包会跳过截断检测 → 零正文还谎报成功
|
|
88
|
+
return j && Array.isArray(j.choices) && j.choices.length > 0 ? j : null;
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Anthropic 出站垫片:具名事件 + 无 [DONE] + 空闲自发 ping + 真 headersSent。
|
|
96
|
+
* @param realRes 真 HTTP response
|
|
97
|
+
* @param translator createAnthropicChunkTranslator 实例
|
|
98
|
+
* @param opts { pingMs?: number } 测试注入口,缺省读 env
|
|
99
|
+
*/
|
|
100
|
+
export function createAnthropicForwarder(realRes, translator, opts = {}) {
|
|
101
|
+
const pingMs = opts.pingMs ?? PING_MS;
|
|
102
|
+
let status = 200;
|
|
103
|
+
let headSent = false;
|
|
104
|
+
let ended = false;
|
|
105
|
+
let timer = null;
|
|
106
|
+
let pendingError = null;
|
|
107
|
+
let aggregate = null;
|
|
108
|
+
let rawAcc = ""; // 攒住无事件字节,供聚合回落识别
|
|
109
|
+
const sent = () => headSent || realRes.headersSent === true; // headersSent 与 getHeader 的唯一口径
|
|
110
|
+
// 上游按字节粒度喂 Buffer/Uint8Array:非流式解码会把多字节汉字切成 U+FFFD 并永久固化在行缓冲里
|
|
111
|
+
const decoder = new TextDecoder("utf-8");
|
|
112
|
+
const decode = (c, flush) => {
|
|
113
|
+
if (c == null) return flush ? String(decoder.decode()) : "";
|
|
114
|
+
if (typeof c === "string") return c;
|
|
115
|
+
const bytes = (typeof Buffer !== "undefined" && Buffer.isBuffer(c)) || c instanceof Uint8Array ? c : null;
|
|
116
|
+
if (bytes) return decoder.decode(bytes, { stream: !flush });
|
|
117
|
+
return String(c);
|
|
118
|
+
};
|
|
119
|
+
const dead = () => ended || realRes.writableEnded === true || realRes.destroyed === true;
|
|
120
|
+
const raw = (type, data) => { if (dead()) return; try { realRes.write(frameOf(type, data)); } catch { /* 下游已断 */ } };
|
|
121
|
+
const stopPing = () => { if (timer) { clearTimeout(timer); timer = null; } };
|
|
122
|
+
const armPing = () => {
|
|
123
|
+
if (!pingMs || dead()) return;
|
|
124
|
+
stopPing();
|
|
125
|
+
timer = setTimeout(() => { if (dead()) return; raw("ping", { type: "ping" }); armPing(); }, pingMs);
|
|
126
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
127
|
+
};
|
|
128
|
+
const sendHead = () => {
|
|
129
|
+
if (headSent) return;
|
|
130
|
+
headSent = true;
|
|
131
|
+
try { realRes.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" }); } catch { /* 已发 */ }
|
|
132
|
+
for (const e of translator.begin()) raw(e.type, e);
|
|
133
|
+
armPing();
|
|
134
|
+
};
|
|
135
|
+
const finish = () => { if (ended) return; ended = true; stopPing(); try { realRes.end(); } catch { /* ignore */ } };
|
|
136
|
+
// 错误收场:一帧 error 后关连接,不补 message_delta/message_stop(真 Anthropic API 即此行为)
|
|
137
|
+
const closeError = (msg) => { sendHead(); raw("error", { type: "error", error: { type: "api_error", message: String(msg || "upstream error").slice(0, 500) } }); finish(); };
|
|
138
|
+
|
|
139
|
+
// 整包聚合体可能被分多次 write:攒住「没产出任何事件」的字节再判一次(有事件即清空,防陈旧拼接)
|
|
140
|
+
const RAW_ACC_CAP = 262144;
|
|
141
|
+
let rawOverflow = false;
|
|
142
|
+
const tryAccumulate = (text) => {
|
|
143
|
+
if (aggregate || !text || rawOverflow) return;
|
|
144
|
+
rawAcc += text;
|
|
145
|
+
if (rawAcc.length > RAW_ACC_CAP) {
|
|
146
|
+
// 超上限就停手并留标记:继续攒也拼不出完整 JSON,静默攒下去只会让错误文案说谎
|
|
147
|
+
rawAcc = rawAcc.slice(0, RAW_ACC_CAP);
|
|
148
|
+
rawOverflow = true;
|
|
149
|
+
}
|
|
150
|
+
const agg = tryAggregate(rawAcc);
|
|
151
|
+
if (agg) aggregate = agg;
|
|
152
|
+
};
|
|
153
|
+
const res = {
|
|
154
|
+
...createEmitter(),
|
|
155
|
+
set statusCode(v) { status = v; },
|
|
156
|
+
get statusCode() { return status; },
|
|
157
|
+
// helpers.js 的 json() 靠 headersSent + getHeader("content-type") 判「能不能回头」;
|
|
158
|
+
// 两者必须同源说真话,否则会出现「判成已 flush、却又拿不到 event-stream」的全静默窗口(错误既不 in-band 也不 JSON)。
|
|
159
|
+
get headersSent() { return sent(); },
|
|
160
|
+
// json() 的幂等早退判据;补上它才不会在我们已收场后再被当「可写」的响应对待
|
|
161
|
+
get writableEnded() { return ended || realRes.writableEnded === true; },
|
|
162
|
+
setHeader() { /* Anthropic SSE 的头由 sendHead 统一发,逐键 set 无意义 */ },
|
|
163
|
+
getHeader(name) {
|
|
164
|
+
if (String(name).toLowerCase() === "content-type" && sent()) return "text/event-stream";
|
|
165
|
+
return undefined;
|
|
166
|
+
},
|
|
167
|
+
write(c) {
|
|
168
|
+
if (ended) { alog("late-write-ignored", JSON.stringify({ id: translator.id, bytes: String(c?.length ?? 0) })); return true; }
|
|
169
|
+
const text = decode(c);
|
|
170
|
+
const err = errorText(text);
|
|
171
|
+
if (err) { pendingError = err; return true; } // 留给 end() 统一收口,不在这里半截发
|
|
172
|
+
// 上游一有动静(连 pipeline 的 keepalive 注释帧都算)就落头 + message_start + 武装 ping:
|
|
173
|
+
// 首块前的静默期正是客户端 idle watchdog 咬人的窗口。没收到任何字节时错误仍走干净 JSON(见 end())。
|
|
174
|
+
sendHead();
|
|
175
|
+
const evs = translator.push(text);
|
|
176
|
+
for (const e of evs) raw(e.type, e);
|
|
177
|
+
if (evs.length) rawAcc = ""; else tryAccumulate(text);
|
|
178
|
+
armPing();
|
|
179
|
+
return true;
|
|
180
|
+
},
|
|
181
|
+
end(c) {
|
|
182
|
+
if (ended) return;
|
|
183
|
+
const tail = decode(c, true);
|
|
184
|
+
const err = pendingError || errorText(tail);
|
|
185
|
+
if (status >= 400 && !headSent) {
|
|
186
|
+
ended = true;
|
|
187
|
+
stopPing();
|
|
188
|
+
json(realRes, status, anthropicError("api_error", err || String(tail).slice(0, 500) || "upstream error"));
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (err) { closeError(err); return; }
|
|
192
|
+
// 客户端要的是流:先落头 + message_start + 武装 ping,再处理残余
|
|
193
|
+
sendHead();
|
|
194
|
+
if (tail) {
|
|
195
|
+
const evs = translator.push(tail);
|
|
196
|
+
for (const e of evs) raw(e.type, e);
|
|
197
|
+
if (evs.length) rawAcc = ""; else tryAccumulate(tail);
|
|
198
|
+
}
|
|
199
|
+
// 末帧常常没有收尾换行:补一个 `\n` 把残行逼出来,否则合法正文与 finish_reason 会一起烂在缓冲里(被误判成截断)
|
|
200
|
+
for (const e of translator.push("\n")) raw(e.type, e);
|
|
201
|
+
// 上游整包聚合(无 SSE 帧):喂同一套状态机兜底,别让正文静默消失
|
|
202
|
+
if (aggregate && !translator.stats().blocks) { for (const e of translator.fromChatJson(aggregate)) raw(e.type, e); }
|
|
203
|
+
const fin = translator.getFinal();
|
|
204
|
+
if (!fin.finish && !aggregate) {
|
|
205
|
+
alog("truncated", JSON.stringify({ id: translator.id, ...translator.stats() }));
|
|
206
|
+
closeError(rawOverflow
|
|
207
|
+
? "upstream sent an oversized non-SSE body that could not be aggregated (no finish_reason)"
|
|
208
|
+
: "upstream stream ended before the model finished its turn (no finish_reason)");
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
for (const e of translator.end({ finish: fin.finish, usage: fin.usage })) raw(e.type, e);
|
|
212
|
+
finish();
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
// 客户端提前断开:pipeline 会感知 close,但 ping 定时器归本垫片管,必须自己停
|
|
216
|
+
try { realRes.on?.("close", () => { if (!ended) { ended = true; stopPing(); } }); } catch { /* ignore */ }
|
|
217
|
+
return res;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export async function messagesHandler(ctx) {
|
|
221
|
+
const { req, res } = ctx;
|
|
222
|
+
const t0 = Date.now();
|
|
223
|
+
let body;
|
|
224
|
+
try {
|
|
225
|
+
body = await readBody(req);
|
|
226
|
+
} catch {
|
|
227
|
+
return json(res, 400, anthropicError("invalid_request_error", "Invalid JSON body"));
|
|
228
|
+
}
|
|
229
|
+
let chatBody;
|
|
230
|
+
try {
|
|
231
|
+
chatBody = messagesToChatBody(body);
|
|
232
|
+
} catch (e) {
|
|
233
|
+
alog("translate-req-400", String(e?.message || e));
|
|
234
|
+
return json(res, 400, anthropicError("invalid_request_error", String(e?.message || e)));
|
|
235
|
+
}
|
|
236
|
+
alog("req", JSON.stringify({
|
|
237
|
+
model: chatBody.model, stream: chatBody.stream,
|
|
238
|
+
msgs: chatBody.messages.map((m) => `${m.role}:${(typeof m.content === "string" ? m.content : "[parts]").length}${m.tool_calls ? `+${m.tool_calls.length}tc` : ""}`),
|
|
239
|
+
tools: Array.isArray(chatBody.tools) ? chatBody.tools.length : 0,
|
|
240
|
+
}));
|
|
241
|
+
const pipeline = createChatPipeline(ctx);
|
|
242
|
+
const fakeReq = withBody(req, chatBody);
|
|
243
|
+
const forwardClose = (shim) => { try { req.on?.("close", () => shim.emit("close")); } catch { /* ignore */ } };
|
|
244
|
+
try {
|
|
245
|
+
if (chatBody.stream) {
|
|
246
|
+
const translator = createAnthropicChunkTranslator(chatBody.model, { thinking: THINKING });
|
|
247
|
+
const live = createAnthropicForwarder(res, translator);
|
|
248
|
+
forwardClose(live);
|
|
249
|
+
await pipeline.execute({ req: fakeReq, res: live });
|
|
250
|
+
alog("done-stream", JSON.stringify({ ms: Date.now() - t0, id: translator.id, ...translator.stats(), ...translator.getFinal() }));
|
|
251
|
+
} else {
|
|
252
|
+
const cap = createCollector();
|
|
253
|
+
forwardClose(cap.res);
|
|
254
|
+
await pipeline.execute({ req: fakeReq, res: cap.res });
|
|
255
|
+
const { status, text } = cap.get();
|
|
256
|
+
if (status >= 400) return json(res, status, anthropicError("api_error", errorText(text) || String(text).slice(0, 500)));
|
|
257
|
+
let chatJson = null;
|
|
258
|
+
try { chatJson = JSON.parse(text); } catch { /* 非 JSON */ }
|
|
259
|
+
if (!chatJson || chatJson.error || chatJson.object === "error") {
|
|
260
|
+
return json(res, status >= 400 ? status : 502, anthropicError("api_error", errorText(text) || String(text).slice(0, 500)));
|
|
261
|
+
}
|
|
262
|
+
// 上游偶发非 chat 形状(无 choices):包成单 text 块,绝不 500(照 responses-route.js 先例)
|
|
263
|
+
if (!Array.isArray(chatJson.choices)) {
|
|
264
|
+
const r = chatJsonToAnthropic({ choices: [{ message: { content: String(text).slice(0, 8000) } }] }, chatBody.model);
|
|
265
|
+
alog("done-nonchat", JSON.stringify({ ms: Date.now() - t0, bytes: text.length }));
|
|
266
|
+
return json(res, 200, r);
|
|
267
|
+
}
|
|
268
|
+
const out = chatJsonToAnthropic(chatJson, chatBody.model);
|
|
269
|
+
alog("done-json", JSON.stringify({ ms: Date.now() - t0, status, blocks: out.content.length, stop: out.stop_reason, usage: out.usage }));
|
|
270
|
+
return json(res, 200, out);
|
|
271
|
+
}
|
|
272
|
+
} catch (err) {
|
|
273
|
+
alog("execute-throw", String(err?.message || err).slice(0, 300));
|
|
274
|
+
if (!res.headersSent) return json(res, 502, anthropicError("api_error", String(err?.message || err)));
|
|
275
|
+
try { res.end(); } catch { /* ignore */ }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export async function countTokensHandler(ctx) {
|
|
280
|
+
const { req, res } = ctx;
|
|
281
|
+
let body;
|
|
282
|
+
try {
|
|
283
|
+
body = await readBody(req);
|
|
284
|
+
} catch {
|
|
285
|
+
return json(res, 400, anthropicError("invalid_request_error", "Invalid JSON body"));
|
|
286
|
+
}
|
|
287
|
+
const out = estimateTokens(body);
|
|
288
|
+
alog("count-tokens", JSON.stringify({ model: body?.model, input_tokens: out.input_tokens }));
|
|
289
|
+
return json(res, 200, out);
|
|
290
|
+
}
|
|
@@ -8,7 +8,7 @@ import { responsesToChatBody, chatJsonToResponse, createChunkTranslator, chunkTo
|
|
|
8
8
|
* 非流式:收集 chat JSON → 转 Response 对象;流式:逐块实时翻成 responses SSE。
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
function withBody(req, body) {
|
|
11
|
+
export function withBody(req, body) {
|
|
12
12
|
return Object.assign(Object.create(Object.getPrototypeOf(req)), req, { body });
|
|
13
13
|
}
|
|
14
14
|
|
|
@@ -22,7 +22,7 @@ function errorShape(text, status) {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
// 最小事件发射器:pipeline 靠 res.on("close") 感知下游断开,垫片必须有
|
|
25
|
-
function createEmitter() {
|
|
25
|
+
export function createEmitter() {
|
|
26
26
|
const map = new Map();
|
|
27
27
|
const self = {
|
|
28
28
|
on(ev, fn) { if (typeof fn === "function") { if (!map.has(ev)) map.set(ev, []); map.get(ev).push(fn); } return self; },
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, unlinkSync, copyFileSync, chmodSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* -setto claude:把本机网关写进 Claude Code 的用户设置文件。
|
|
7
|
+
* 键面依据 code.claude.com/docs/en/settings-reference(model / modelPicker / env 三节):
|
|
8
|
+
* - `ANTHROPIC_BASE_URL` **不带 /v1** —— 客户端自己拼 `/v1/messages`(参考仓库 README 写 /v1 是它的错)
|
|
9
|
+
* - `env.ANTHROPIC_MODEL` 必须删 —— 它压过顶层 `model` 键,留着会让设置失效
|
|
10
|
+
* - `CLAUDE_CODE_ATTRIBUTION_HEADER=0` —— 我们把 system 折叠成单条,归因块必须在客户端就不发
|
|
11
|
+
* - `modelPicker.options[].behavesAs` 实测必需 —— 见下方 DEFAULT_BEHAVES_AS 注释
|
|
12
|
+
* 只动上述键,其余键与键序原样保留;解析失败一律拒写(那是用户手写的 hooks/permissions)。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const OUR_ENV_KEYS = [
|
|
16
|
+
"ANTHROPIC_BASE_URL",
|
|
17
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
18
|
+
"ANTHROPIC_MODEL", // 只删不写
|
|
19
|
+
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
|
|
20
|
+
"CLAUDE_CODE_ATTRIBUTION_HEADER",
|
|
21
|
+
"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS",
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
// 本机 Claude Code 对「不认识且无 behavesAs 映射」的 model id 直接拒跑,连请求都不发
|
|
25
|
+
// (实测 2026-10-09:`"big-pickle" isn't described by this version's model catalog; …map it with
|
|
26
|
+
// behavesAs on a modelPicker row`,加 behavesAs 后 `claude -p` 正常走通工具往返)。
|
|
27
|
+
// behavesAs 只改客户端的**本地能力推断**(effort / auto-compact 口径),不改变发给上游的模型;
|
|
28
|
+
// 上游不认的字段由 messagesToChatBody 统一丢,所以锚一个通用已知 id 即可。`--behaves-as ""` 可关。
|
|
29
|
+
const DEFAULT_BEHAVES_AS = "claude-sonnet-5";
|
|
30
|
+
|
|
31
|
+
/** Claude Code 用户设置文件路径(`CLAUDE_CONFIG_DIR` 优先,与 Claude Code 自身口径一致)。 */
|
|
32
|
+
export function claudeSettingsPath() {
|
|
33
|
+
const dir = process.env.CLAUDE_CONFIG_DIR;
|
|
34
|
+
if (typeof dir === "string" && dir.trim()) return join(dir.trim(), "settings.json");
|
|
35
|
+
return join(os.homedir(), ".claude", "settings.json");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 纯函数:existing 对象 + 上下文 → 新对象。除我们的键外一律原样保留(含键序,JSON 键序随插入顺序)。 */
|
|
39
|
+
export function buildClaudeSettings(existing, ctx = {}) {
|
|
40
|
+
const out = existing && typeof existing === "object" && !Array.isArray(existing) ? { ...existing } : {};
|
|
41
|
+
const env = { ...(out.env && typeof out.env === "object" && !Array.isArray(out.env) ? out.env : {}) };
|
|
42
|
+
env.ANTHROPIC_BASE_URL = String(ctx.baseUrl || "");
|
|
43
|
+
env.ANTHROPIC_AUTH_TOKEN = String(ctx.token || "");
|
|
44
|
+
env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
|
|
45
|
+
env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0";
|
|
46
|
+
env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = "1";
|
|
47
|
+
delete env.ANTHROPIC_MODEL;
|
|
48
|
+
out.env = env;
|
|
49
|
+
out.model = String(ctx.model || "");
|
|
50
|
+
const picks = Array.isArray(ctx.picks) && ctx.picks.length ? ctx.picks : [ctx.model];
|
|
51
|
+
// behavesAs 的含义是「该 id 不在客户端模型目录里,请按 X 的能力口径推断」。
|
|
52
|
+
// 客户端本来就认识的 claude-* id 不该被这么标:把 claude-opus 标成 behavesAs=claude-sonnet-5,
|
|
53
|
+
// 客户端就会按 sonnet 的 effort / auto-compact 口径去推断它。显式 --behaves-as 仍覆盖一切。
|
|
54
|
+
const override = ctx.behavesAs == null ? null : String(ctx.behavesAs);
|
|
55
|
+
const anchorOf = (m) => (override != null ? override : /^claude[-.]/i.test(String(m)) ? "" : DEFAULT_BEHAVES_AS);
|
|
56
|
+
out.modelPicker = {
|
|
57
|
+
options: picks.filter(Boolean).map((m) => {
|
|
58
|
+
const row = { model: String(m), label: String(m) };
|
|
59
|
+
const anchor = anchorOf(m);
|
|
60
|
+
if (anchor) row.behavesAs = anchor;
|
|
61
|
+
return row;
|
|
62
|
+
}),
|
|
63
|
+
};
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 归一化用于幂等比较(忽略换行符与首尾空白差异)
|
|
68
|
+
function norm(text) {
|
|
69
|
+
return String(text || "").replace(/\r\n/g, "\n").trim();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 写盘。返回 { action, file, id, backup, changed, rows }。
|
|
74
|
+
* @param {{id?:string, token?:string, port?:number, picks?:string[], file?:string, baseUrl?:string, behavesAs?:string}} p
|
|
75
|
+
*/
|
|
76
|
+
export function syncToClaude(p = {}) {
|
|
77
|
+
const targetFile = p.file || claudeSettingsPath();
|
|
78
|
+
const model = String(p.id ?? p.model ?? "").trim();
|
|
79
|
+
if (!model) throw new Error("claude settings: model id required");
|
|
80
|
+
const token = String(p.token || "");
|
|
81
|
+
if (!token) throw new Error("claude settings: token required(先跑 mslxdff -showtoken)");
|
|
82
|
+
const baseUrl = p.baseUrl || `http://127.0.0.1:${Number(p.port) || 8989}`;
|
|
83
|
+
const picks = Array.isArray(p.picks) && p.picks.length ? p.picks : [model];
|
|
84
|
+
|
|
85
|
+
let existed = false;
|
|
86
|
+
let originalText = "";
|
|
87
|
+
try {
|
|
88
|
+
originalText = readFileSync(targetFile, "utf8");
|
|
89
|
+
existed = true;
|
|
90
|
+
} catch {
|
|
91
|
+
existed = false;
|
|
92
|
+
}
|
|
93
|
+
let originalObj = null;
|
|
94
|
+
if (existed) {
|
|
95
|
+
try {
|
|
96
|
+
originalObj = JSON.parse(originalText);
|
|
97
|
+
} catch {
|
|
98
|
+
throw new Error(`claude settings 解析失败,拒绝覆盖:${targetFile}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const next = buildClaudeSettings(originalObj, { baseUrl, token, model, picks, behavesAs: p.behavesAs });
|
|
103
|
+
const nextText = `${JSON.stringify(next, null, 2)}\n`;
|
|
104
|
+
if (existed && norm(originalText) === norm(nextText)) {
|
|
105
|
+
return { action: "updated", file: targetFile, id: model, backup: null, changed: false, rows: next.modelPicker.options.length };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 备份只保留「mslxdff 首次接管前」那一份:已存在就不覆盖(代价:用户后来手改的内容不进备份)
|
|
109
|
+
let backup = null;
|
|
110
|
+
if (existed) {
|
|
111
|
+
const backupFile = join(dirname(targetFile), "settings.pre-mslxdff.json");
|
|
112
|
+
if (!existsSync(backupFile)) {
|
|
113
|
+
try { copyFileSync(targetFile, backupFile); backup = backupFile; } catch { /* 复制失败不阻塞写入,但绝不谎报「已备份」 */ }
|
|
114
|
+
}
|
|
115
|
+
// 只在**本次真复制过**时返回路径(spec R6「打印备份路径(若本次生成)」);已有旧备份时返回 null,
|
|
116
|
+
// 由 CLI 换成「已存在更早的备份」提示 —— 免得用户拿首份旧备份去覆盖自己后来的手改。
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
mkdirSync(dirname(targetFile), { recursive: true });
|
|
120
|
+
const tmp = `${targetFile}.tmp.${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
|
|
121
|
+
// 凭据落地红线:文件里有明文 token → 0600(mode 只在新建时生效,故存量补 chmod)
|
|
122
|
+
let written = false;
|
|
123
|
+
let tmpLeftover = null;
|
|
124
|
+
// 半截 tmp 里带明文 token:unlink 也可能被占用(Windows 上正是 rename 失败的同因),
|
|
125
|
+
// 所以先擦内容再试一次;仍清不掉就把路径如实交出去,让 CLI 告警,绝不静默。
|
|
126
|
+
const sweepTmp = () => {
|
|
127
|
+
if (!existsSync(tmp)) return;
|
|
128
|
+
try { unlinkSync(tmp); return; } catch { /* 占用,走擦除 */ }
|
|
129
|
+
try { writeFileSync(tmp, "", { encoding: "utf8" }); } catch { /* 擦不动也继续试删 */ }
|
|
130
|
+
try { unlinkSync(tmp); } catch { tmpLeftover = tmp; }
|
|
131
|
+
};
|
|
132
|
+
try {
|
|
133
|
+
try { writeFileSync(tmp, nextText, { encoding: "utf8", mode: 0o600 }); } catch { writeFileSync(tmp, nextText, "utf8"); }
|
|
134
|
+
try { chmodSync(tmp, 0o600); } catch { /* Windows 无 posix mode,忽略 */ }
|
|
135
|
+
try {
|
|
136
|
+
renameSync(tmp, targetFile);
|
|
137
|
+
written = true;
|
|
138
|
+
} catch {
|
|
139
|
+
// rename 失败多见于目标被别的进程占用(Windows 常态):退回直写;仍失败就报错,绝不谎报「已同步」
|
|
140
|
+
try { writeFileSync(targetFile, nextText, { encoding: "utf8", mode: 0o600 }); written = true; } catch { /* 交给下面的 throw */ }
|
|
141
|
+
}
|
|
142
|
+
} finally {
|
|
143
|
+
sweepTmp();
|
|
144
|
+
}
|
|
145
|
+
if (!written) {
|
|
146
|
+
throw new Error(`无法写入 ${targetFile}(文件可能被其他进程占用)——配置未更新;原文见同目录 settings.pre-mslxdff.json${tmpLeftover ? `;另有清理失败的临时文件 ${tmpLeftover}(内含明文 token,请手动删除)` : ""}`);
|
|
147
|
+
}
|
|
148
|
+
try { chmodSync(targetFile, 0o600); } catch { /* ignore */ }
|
|
149
|
+
return { action: existed ? "updated" : "inserted", file: targetFile, id: model, backup, changed: true, rows: next.modelPicker.options.length, tmpLeftover };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export { OUR_ENV_KEYS, DEFAULT_BEHAVES_AS };
|