mslxdff 0.1.203 → 0.1.207

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 (330) hide show
  1. package/README.md +3 -3
  2. package/bin/mslxdff.js +1 -1
  3. package/docs/cli_help_mini.md +146 -0
  4. package/package.json +38 -38
  5. package/plugins/README.md +14 -14
  6. package/plugins/prefer-model.mjs.example +14 -14
  7. package/src/anthropic/canonical-json.js +55 -0
  8. package/src/anthropic/count-tokens.js +61 -61
  9. package/src/anthropic/request-body.js +183 -126
  10. package/src/anthropic/request-shape.js +60 -0
  11. package/src/anthropic/session-id.js +58 -0
  12. package/src/anthropic/shared.js +18 -18
  13. package/src/anthropic/sse-aggregate.js +56 -56
  14. package/src/anthropic/tool-media.js +75 -0
  15. package/src/anthropic/translate.js +296 -287
  16. package/src/anthropic/web-search.js +361 -361
  17. package/src/api-kind.js +31 -31
  18. package/src/autostart.js +288 -288
  19. package/src/bench/probe.js +1 -1
  20. package/src/bench/runner.js +1 -1
  21. package/src/bench/via-probe.js +1 -1
  22. package/src/bench/via.js +144 -144
  23. package/src/bench/workbuddy-bench.js +1 -1
  24. package/src/chat/config.js +11 -11
  25. package/src/chat/cooling.js +81 -81
  26. package/src/chat/direct.js +58 -58
  27. package/src/chat/index.js +6 -6
  28. package/src/chat/spinner.js +38 -38
  29. package/src/chat/sse.js +69 -69
  30. package/src/chat/stats.js +247 -247
  31. package/src/chat/store.js +48 -48
  32. package/src/chat/tool-handlers.js +67 -67
  33. package/src/chat/tools.js +1 -1
  34. package/src/chat/upstream.js +59 -59
  35. package/src/chat-pipeline/auto-race.js +158 -158
  36. package/src/chat-pipeline/empty-turn.js +147 -147
  37. package/src/chat-pipeline/engine.js +17 -17
  38. package/src/chat-pipeline/index.js +8 -40
  39. package/src/chat-pipeline/serial-trial.js +279 -283
  40. package/src/chat-pipeline/terminal-verdict.js +132 -147
  41. package/src/chooser.js +54 -54
  42. package/src/claude-desktop/apply.js +101 -101
  43. package/src/claude-desktop/context1m.js +38 -38
  44. package/src/claude-desktop/doctor.js +146 -146
  45. package/src/claude-desktop/slots.js +152 -152
  46. package/src/cli/bootstrap.js +1 -1
  47. package/src/cli/commands/claude-desktop.js +284 -284
  48. package/src/cli/commands/daemon.js +231 -231
  49. package/src/cli/commands/model/list-live.js +22 -22
  50. package/src/cli/commands/model/list-providers.js +76 -76
  51. package/src/cli/commands/model/list-render.js +77 -77
  52. package/src/cli/commands/model/list-sort.js +52 -52
  53. package/src/cli/commands/model/list-tty.js +76 -76
  54. package/src/cli/commands/model/list.js +166 -166
  55. package/src/cli/commands/model/live-models.js +24 -24
  56. package/src/cli/commands/model/stats.js +43 -43
  57. package/src/cli/commands/model/status.js +47 -47
  58. package/src/cli/commands/model.js +51 -51
  59. package/src/cli/commands/provider/add.js +108 -108
  60. package/src/cli/commands/provider/allowlist.js +99 -99
  61. package/src/cli/commands/provider/cline-free.js +99 -99
  62. package/src/cli/commands/provider/cline-login.js +218 -218
  63. package/src/cli/commands/provider/cline-quota.js +65 -65
  64. package/src/cli/commands/provider/codearts-login.js +45 -45
  65. package/src/cli/commands/provider/config.js +119 -119
  66. package/src/cli/commands/provider/globalqwenwork-login.js +126 -126
  67. package/src/cli/commands/provider/keys-guard.js +50 -50
  68. package/src/cli/commands/provider/keys.js +161 -161
  69. package/src/cli/commands/provider/qoder-checkin.js +81 -81
  70. package/src/cli/commands/provider/qoder-login.js +102 -102
  71. package/src/cli/commands/provider/raccoon-login.js +180 -180
  72. package/src/cli/commands/provider/raccoon-password.js +162 -162
  73. package/src/cli/commands/provider/raccoon-quota.js +109 -109
  74. package/src/cli/commands/provider/traework-checkin.js +144 -144
  75. package/src/cli/commands/provider/traework-login.js +164 -164
  76. package/src/cli/commands/provider/workbuddy-login.js +153 -153
  77. package/src/cli/commands/provider/zcode-login.js +77 -77
  78. package/src/cli/commands/provider/zcode-quota.js +55 -55
  79. package/src/cli/commands/provider.js +1 -1
  80. package/src/cli/commands/stats.js +158 -149
  81. package/src/cli/commands/system.js +261 -261
  82. package/src/cli/commands/timezone.js +47 -47
  83. package/src/cli/commands/use-group.js +60 -60
  84. package/src/cli/commands/workbuddy.js +189 -189
  85. package/src/cli/format.js +141 -141
  86. package/src/cli/group-helpers.js +70 -70
  87. package/src/cli/help.js +80 -80
  88. package/src/cli/index.js +70 -70
  89. package/src/cli/interactive.js +121 -121
  90. package/src/cli/join-core.js +99 -99
  91. package/src/cli/join-wizard.js +175 -175
  92. package/src/cli/policy.js +136 -136
  93. package/src/cli/provider-row.js +126 -126
  94. package/src/cli/util.js +24 -24
  95. package/src/compat.js +53 -53
  96. package/src/events.js +38 -38
  97. package/src/free-lane.js +131 -131
  98. package/src/free-watcher.js +63 -63
  99. package/src/groups.js +262 -262
  100. package/src/logs.js +195 -195
  101. package/src/metrics.js +71 -62
  102. package/src/model-capabilities/context-lookup.js +65 -65
  103. package/src/model-capabilities/merge.js +142 -142
  104. package/src/model-trace.js +187 -187
  105. package/src/models.js +1 -1
  106. package/src/opencode-identity.js +72 -72
  107. package/src/peers.js +254 -254
  108. package/src/plugins.js +107 -107
  109. package/src/providers/AGENTS.md +49 -0
  110. package/src/providers/base.js +164 -164
  111. package/src/providers/classify.js +22 -22
  112. package/src/providers/cline/allowlist-sync.js +93 -93
  113. package/src/providers/cline/free-catalog.js +71 -71
  114. package/src/providers/cline/headers.js +37 -37
  115. package/src/providers/cline/index.js +130 -130
  116. package/src/providers/cline/models.js +150 -150
  117. package/src/providers/cline/usage.js +274 -274
  118. package/src/providers/codearts/auth-pool.js +148 -148
  119. package/src/providers/codearts/concurrency.js +34 -34
  120. package/src/providers/codearts/const.js +65 -65
  121. package/src/providers/codearts/dpop.js +95 -95
  122. package/src/providers/codearts/index.js +175 -175
  123. package/src/providers/codearts/login.js +214 -214
  124. package/src/providers/codearts/models.js +182 -182
  125. package/src/providers/codearts/sign.js +96 -96
  126. package/src/providers/codearts/sse.js +204 -204
  127. package/src/providers/codearts/stream.js +209 -209
  128. package/src/providers/codearts/sts.js +124 -124
  129. package/src/providers/codearts.js +1 -1
  130. package/src/providers/dispatcher.js +146 -146
  131. package/src/providers/generic.js +156 -156
  132. package/src/providers/globalqwenwork/account-store.js +141 -141
  133. package/src/providers/globalqwenwork/constants.js +73 -73
  134. package/src/providers/globalqwenwork/crypto.js +2 -2
  135. package/src/providers/globalqwenwork/http.js +2 -2
  136. package/src/providers/globalqwenwork/index.js +331 -331
  137. package/src/providers/globalqwenwork/payload.js +147 -147
  138. package/src/providers/globalqwenwork/rsa.js +2 -2
  139. package/src/providers/globalqwenwork/sse.js +2 -2
  140. package/src/providers/globalqwenwork/stream.js +2 -2
  141. package/src/providers/globalqwenwork.js +1 -1
  142. package/src/providers/globalworkbuddy/account-store.js +198 -198
  143. package/src/providers/globalworkbuddy/auth.js +97 -97
  144. package/src/providers/globalworkbuddy/catalog.js +138 -138
  145. package/src/providers/globalworkbuddy/constants.js +73 -73
  146. package/src/providers/globalworkbuddy/device-auth.js +120 -120
  147. package/src/providers/globalworkbuddy/errors.js +98 -98
  148. package/src/providers/globalworkbuddy/headers.js +89 -89
  149. package/src/providers/globalworkbuddy/models.js +96 -96
  150. package/src/providers/globalworkbuddy/payload.js +80 -80
  151. package/src/providers/index.js +5 -5
  152. package/src/providers/model-id.js +172 -172
  153. package/src/providers/opencode.js +19 -19
  154. package/src/providers/openrouter.js +31 -31
  155. package/src/providers/qoder/account-store.js +106 -106
  156. package/src/providers/qoder/aggregate.js +60 -60
  157. package/src/providers/qoder/baseprompt.json +591 -591
  158. package/src/providers/qoder/checkin.js +160 -160
  159. package/src/providers/qoder/constants.js +44 -44
  160. package/src/providers/qoder/encode.js +41 -41
  161. package/src/providers/qoder/fingerprint.js +38 -38
  162. package/src/providers/qoder/models.js +77 -77
  163. package/src/providers/qoder/oauth.js +84 -84
  164. package/src/providers/qoder/payload.js +162 -162
  165. package/src/providers/qoder/request.js +27 -27
  166. package/src/providers/qoder/session.js +134 -134
  167. package/src/providers/qoder/sticky.js +38 -38
  168. package/src/providers/qoder/stream.js +116 -116
  169. package/src/providers/qoder.js +1 -1
  170. package/src/providers/raccoon/account-store.js +216 -216
  171. package/src/providers/raccoon/auth.js +67 -67
  172. package/src/providers/raccoon/chat.js +228 -228
  173. package/src/providers/raccoon/const.js +180 -180
  174. package/src/providers/raccoon/credits.js +185 -185
  175. package/src/providers/raccoon/crypto.js +43 -43
  176. package/src/providers/raccoon/envelope.js +31 -31
  177. package/src/providers/raccoon/headers.js +45 -45
  178. package/src/providers/raccoon/index.js +216 -216
  179. package/src/providers/raccoon/login.js +279 -279
  180. package/src/providers/raccoon/models.js +160 -160
  181. package/src/providers/raccoon/password-login.js +102 -102
  182. package/src/providers/raccoon/qr-codewords.js +115 -115
  183. package/src/providers/raccoon/qr.js +236 -236
  184. package/src/providers/raccoon/sse.js +135 -135
  185. package/src/providers/responses-channel.js +120 -120
  186. package/src/providers/share-keys.js +53 -53
  187. package/src/providers/traework/account-store.js +234 -234
  188. package/src/providers/traework/chat.js +217 -217
  189. package/src/providers/traework/checkin.js +77 -77
  190. package/src/providers/traework/constants.js +41 -41
  191. package/src/providers/traework/errors.js +52 -52
  192. package/src/providers/traework/headers.js +79 -79
  193. package/src/providers/traework/index.js +132 -132
  194. package/src/providers/traework/market-identity.js +116 -116
  195. package/src/providers/traework/models.js +98 -98
  196. package/src/providers/traework/payload.js +86 -86
  197. package/src/providers/traework/sse.js +184 -184
  198. package/src/providers/traework/token.js +52 -52
  199. package/src/providers/traework.js +2 -2
  200. package/src/providers/workbuddy/account-store.js +186 -186
  201. package/src/providers/workbuddy/auth.js +158 -158
  202. package/src/providers/workbuddy/balance.js +86 -86
  203. package/src/providers/workbuddy/cat-travel.js +125 -125
  204. package/src/providers/workbuddy/checkin.js +75 -75
  205. package/src/providers/workbuddy/desktop-info.js +78 -78
  206. package/src/providers/workbuddy/growth-api.js +67 -67
  207. package/src/providers/workbuddy/growth-plans.js +63 -63
  208. package/src/providers/workbuddy/growth.js +181 -181
  209. package/src/providers/workbuddy/index.js +217 -217
  210. package/src/providers/workbuddy/models.js +126 -126
  211. package/src/providers/workbuddy/payload.js +141 -141
  212. package/src/providers/workbuddy/rotation-log.js +83 -83
  213. package/src/providers/workbuddy/sanitize-tools.js +61 -61
  214. package/src/providers/workbuddy/sdk-chat.js +26 -26
  215. package/src/providers/workbuddy-balance.js +78 -78
  216. package/src/providers/zcode/account-store.js +129 -129
  217. package/src/providers/zcode/auth.js +28 -28
  218. package/src/providers/zcode/chat.js +179 -179
  219. package/src/providers/zcode/const.js +54 -54
  220. package/src/providers/zcode/context-shape.js +162 -162
  221. package/src/providers/zcode/headers.js +93 -93
  222. package/src/providers/zcode/index.js +124 -124
  223. package/src/providers/zcode/models.js +65 -65
  224. package/src/providers/zcode/oauth.js +120 -120
  225. package/src/providers/zcode/quota.js +176 -176
  226. package/src/providers/zcode/sse.js +196 -196
  227. package/src/readline-compat.js +25 -25
  228. package/src/responses/translate.js +311 -311
  229. package/src/routes/AGENTS.md +37 -0
  230. package/src/routes/chat/broadband-handler.js +72 -72
  231. package/src/routes/chat/empty-turn-report.js +31 -31
  232. package/src/routes/chat/exhausted-handler.js +87 -87
  233. package/src/routes/chat/hedge-handler.js +130 -130
  234. package/src/routes/chat/index.js +1 -1
  235. package/src/routes/chat/local-handler.js +63 -63
  236. package/src/routes/chat/peer-handler.js +81 -81
  237. package/src/routes/chat.js +3 -3
  238. package/src/routes/fallback.js +88 -88
  239. package/src/routes/groups-relay.js +214 -214
  240. package/src/routes/groups.js +122 -122
  241. package/src/routes/helpers.js +93 -83
  242. package/src/routes/index.js +147 -147
  243. package/src/routes/messages-route.js +375 -365
  244. package/src/routes/peers.js +10 -2
  245. package/src/routes/relay-queue.js +181 -181
  246. package/src/routes/relay.js +60 -60
  247. package/src/routes/responses-route.js +213 -213
  248. package/src/routes/stream-body.js +84 -84
  249. package/src/routes/stream-hold.js +337 -337
  250. package/src/routes/stream-scan.js +366 -366
  251. package/src/routes.js +3 -3
  252. package/src/runtime/auto-update.js +113 -113
  253. package/src/runtime/broadband-stream.js +79 -79
  254. package/src/runtime/broadband.js +103 -103
  255. package/src/runtime/group-sync.js +81 -81
  256. package/src/runtime/keep-warm.js +120 -120
  257. package/src/runtime/lifecycle-forensics.js +116 -116
  258. package/src/runtime/lifecycle-log.js +87 -87
  259. package/src/runtime/log-stamp.js +73 -73
  260. package/src/runtime/proc-info.js +137 -137
  261. package/src/runtime/qoder-checkin.js +93 -93
  262. package/src/runtime/raccoon-checkin.js +126 -126
  263. package/src/runtime/server-lifecycle.js +189 -189
  264. package/src/runtime/traework-checkin.js +118 -118
  265. package/src/runtime/workbuddy-checkin.js +120 -120
  266. package/src/runtime/workbuddy-growth.js +133 -133
  267. package/src/state/facade.js +58 -58
  268. package/src/state/memory.js +162 -162
  269. package/src/state/merge.js +25 -25
  270. package/src/state/migrations/cline-unify.js +94 -94
  271. package/src/state/migrations.js +33 -33
  272. package/src/state/persist.js +42 -42
  273. package/src/state/provider-config.js +142 -142
  274. package/src/state/schemas/group.js +31 -31
  275. package/src/state/schemas/model.js +94 -94
  276. package/src/state/schemas/peer.js +31 -31
  277. package/src/state/schemas/port.js +10 -10
  278. package/src/state/schemas/provider.js +202 -202
  279. package/src/state/schemas/timezone.js +70 -70
  280. package/src/state/schemas/token.js +48 -48
  281. package/src/state/schemas/use-group.js +102 -102
  282. package/src/state/store.js +176 -176
  283. package/src/state.js +1 -1
  284. package/src/sync-claude-desktop.js +234 -234
  285. package/src/sync-claude.js +152 -152
  286. package/src/sync-codex.js +116 -116
  287. package/src/sync-workbuddy.js +158 -158
  288. package/src/talk-full-redact.js +129 -129
  289. package/src/talk-full.js +131 -131
  290. package/src/talk-log.js +257 -257
  291. package/src/text-tokens.js +52 -52
  292. package/src/thinking-effort.js +67 -67
  293. package/src/time.js +106 -106
  294. package/src/timeline.js +26 -26
  295. package/src/transport/index.js +1 -1
  296. package/src/upstream-engine/index.js +74 -74
  297. package/src/upstream-engine/mode.js +15 -15
  298. package/src/upstream-engine/sdk/attempt.js +221 -221
  299. package/src/upstream-engine/sdk/chat.js +28 -28
  300. package/src/upstream-engine/sdk/convert.js +192 -192
  301. package/src/upstream-engine/sdk/diagnose.js +62 -62
  302. package/src/upstream-engine/sdk/dispatch.js +55 -55
  303. package/src/upstream-engine/sdk/responses.js +176 -176
  304. package/src/upstream-engine/sdk/sse.js +166 -166
  305. package/src/upstream-responses.js +305 -305
  306. package/src/usage/cache-fields.js +58 -0
  307. package/src/usage/record.js +109 -106
  308. package/src/usage/report.js +209 -195
  309. package/src/v6pool/claim.js +157 -157
  310. package/src/v6pool/config.js +65 -65
  311. package/src/v6pool/detect.js +130 -130
  312. package/src/v6pool/index.js +152 -152
  313. package/src/v6pool/prefix.js +140 -140
  314. package/src/v6pool/probe.js +40 -40
  315. package/src/v6pool/report.js +104 -104
  316. package/src/v6pool/rotate.js +263 -263
  317. package/src/warp-pool/config.js +74 -74
  318. package/src/warp-pool/health.js +106 -106
  319. package/src/warp-pool/identity.js +141 -141
  320. package/src/warp-pool/index.js +358 -358
  321. package/src/warp-pool/keys.js +29 -29
  322. package/src/warp-pool/nodes.js +95 -95
  323. package/src/warp-pool/ports.js +160 -160
  324. package/src/warp-pool/register.js +113 -113
  325. package/src/warp-pool/report.js +232 -232
  326. package/src/warp-pool/revive.js +168 -168
  327. package/src/warp-pool/rotate.js +214 -214
  328. package/src/warp-pool/strategy.js +43 -43
  329. package/src/warp-pool/verdict.js +69 -69
  330. package/src/warp-pool/wireproxy.js +162 -162
@@ -1,126 +1,183 @@
1
- // 请求侧翻译:Anthropic Messages 请求体 → OpenAI chat 请求体(/v1/messages 外壳,ADR-0047)。
2
- // 从 translate.js 拆出(ADR-0055):translate.js 贴 20KB 体积硬门,且「入站请求形状」与
3
- // 「出站响应/usage 翻译」本就是两向关注点,拆后 translate.js 单向 import 本文件,不回环。
4
- // 对外接口不变:调用方与测试仍从 anthropic/translate.js import(那边 re-export)。
5
- //
6
- // 纪律(别改回去):
7
- // * 思考档位**原样透传**(thinking/effort/reasoning_effort/reasoningEffort/extra_body),语义归一交给
8
- // 各 provider 与 src/thinking-effort.js —— 旧版在此丢掉,下游被迫补默认值(workbuddy 恒 high,ADR-0053);
9
- // * 但**必须主动丢** output_config 原始对象 / context_management / 消息块内 thinking:Claude Code 对
10
- // 不认识的 model ID 照发全套字段,块内 thinking 无法签发 signature,回传必被上游拒(ADR-0047)。
11
- import { isServerTool } from "./web-search.js";
12
- import { newToolUseId } from "./shared.js";
13
-
14
- // system 允许字符串或 text 块数组;块间空行连接(缓存语义不保留,上游是 OpenAI)
15
- function systemTextOf(system) {
16
- if (typeof system === "string") return system;
17
- if (!Array.isArray(system)) return "";
18
- return system.map((b) => (b && typeof b.text === "string" ? b.text : "")).filter(Boolean).join("\n\n");
19
- }
20
-
21
- function imagePartOf(block) {
22
- const src = block?.source || {};
23
- if (src.type === "base64" && src.data) {
24
- return { type: "image_url", image_url: { url: `data:${src.media_type || "image/png"};base64,${src.data}` } };
25
- }
26
- if (src.type === "url" && src.url) return { type: "image_url", image_url: { url: String(src.url) } };
27
- return null;
28
- }
29
-
30
- export function toolResultTextOf(content) {
31
- if (typeof content === "string") return content;
32
- if (Array.isArray(content)) {
33
- return content
34
- .map((p) => (typeof p === "string" ? p : p && typeof p.text === "string" ? p.text : ""))
35
- .filter(Boolean)
36
- .join("\n");
37
- }
38
- return content == null ? "" : String(content);
39
- }
40
-
41
- /** Anthropic Messages 请求体 → OpenAI chat 请求体(直接喂既有 ChatPipeline)。 */
42
- export function messagesToChatBody(req = {}) {
43
- const model = String(req.model || "").trim();
44
- if (!model) throw new Error("messages: 缺少 model");
45
- const messages = [];
46
- const sys = systemTextOf(req.system);
47
- if (sys) messages.push({ role: "system", content: sys });
48
-
49
- // 重复 tool_use_id 保首个、丢后续:客户端重试/重放历史会把同一工具结果存两份,
50
- // 部分上游按 call_id 查重直接 400(同 responses/translate.js:57-59 的实测教训)。
51
- const seenToolResult = new Set();
52
-
53
- for (const m of Array.isArray(req.messages) ? req.messages : []) {
54
- if (!m || typeof m !== "object") continue;
55
- // role=system/developer 必须保留:Claude Code ≥2.1.286 的 mid-conversation system beta 就往 messages[] 里塞系统指令,
56
- const role = m.role === "assistant" ? "assistant" : m.role === "system" || m.role === "developer" ? "system" : "user";
57
- const blocks = typeof m.content === "string" ? [{ type: "text", text: m.content }] : Array.isArray(m.content) ? m.content : [];
58
- let text = "";
59
- const imgs = [];
60
- const toolCalls = [];
61
- for (const b of blocks) {
62
- if (!b || typeof b !== "object") continue;
63
- if (b.type === "text") text += typeof b.text === "string" ? b.text : "";
64
- else if (b.type === "image") { const p = imagePartOf(b); if (p) imgs.push(p); }
65
- else if (b.type === "tool_use") {
66
- let args = "{}";
67
- try { args = JSON.stringify(b.input ?? {}); } catch { args = "{}"; }
68
- toolCalls.push({ id: String(b.id || newToolUseId()), type: "function", function: { name: String(b.name || ""), arguments: args } });
69
- } else if (b.type === "tool_result") {
70
- // tool 消息必须先于同轮 user 文本进数组:OpenAI 侧要求 role:tool 紧跟其 assistant
71
- const key = String(b.tool_use_id || "");
72
- if (key) { if (seenToolResult.has(key)) continue; seenToolResult.add(key); }
73
- const body = toolResultTextOf(b.content);
74
- messages.push({ role: "tool", tool_call_id: key, content: b.is_error ? `[tool_error] ${body}` : body });
75
- }
76
- // thinking / redacted_thinking 忽略:我们无法签发 signature,回传必被上游拒(ADR-0047)
77
- }
78
- if (!text && !imgs.length && !toolCalls.length) continue;
79
- const msg = { role, content: imgs.length ? [...(text ? [{ type: "text", text }] : []), ...imgs] : text };
80
- if (toolCalls.length) msg.tool_calls = toolCalls;
81
- messages.push(msg);
82
- }
83
- // 空会话直接 400:绝不伪造一句 "hi" 打上游(那会把假提问写进用户上下文并白烧一发额度)
84
- if (!messages.some((x) => x.role !== "system")) throw new Error("messages: 缺少用户消息");
85
-
86
- const body = { model, messages, stream: Boolean(req.stream) };
87
- // 流式必须让上游把 usage 放进收尾帧,否则 message_delta.usage 恒 0(OpenAI 规范字段)。
88
- // 个别上游不认 stream_options 会 400 → `MSLXDFF_ANTHROPIC_STREAM_USAGE=0` 关掉。
89
- if (body.stream && process.env.MSLXDFF_ANTHROPIC_STREAM_USAGE !== "0") body.stream_options = { include_usage: true };
90
- // Anthropic 的 server tool(web_search_*/web_fetch_*/…)没有 input_schema,折成假 function 会
91
- // 让上游收到「空参数空描述」的工具(严格端点直接 422),本网关不实现的发前一律剥除(ADR-0049)。
92
- const fnTools = (Array.isArray(req.tools) ? req.tools : []).filter((t) => !isServerTool(t));
93
- if (fnTools.length) {
94
- body.tools = fnTools.map((t) => ({
95
- type: "function",
96
- function: { name: String(t?.name || ""), description: String(t?.description || ""), parameters: t?.input_schema || {} },
97
- }));
98
- }
99
- const keptNames = new Set(fnTools.map((t) => String(t?.name || "")));
100
- const tc = req.tool_choice;
101
- if (tc === "auto" || (tc && typeof tc === "object" && tc.type === "auto")) body.tool_choice = "auto";
102
- else if (tc && typeof tc === "object" && tc.type === "any") body.tool_choice = "required";
103
- // 点名一个已被剥掉的工具时降为 auto:上游会按不存在的函数强制点名,那样一定拿不到有用回答
104
- 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";
105
- else if (tc && typeof tc === "object" && tc.type === "none") body.tool_choice = "none";
106
- if (req.max_tokens != null && Number.isFinite(Number(req.max_tokens))) body.max_tokens = Number(req.max_tokens);
107
- if (req.temperature != null) body.temperature = req.temperature;
108
- if (req.top_p != null) body.top_p = req.top_p;
109
- if (Array.isArray(req.stop_sequences) && req.stop_sequences.length) body.stop = req.stop_sequences;
110
- // 思考档位原样透传(不解释语义,语义归一交给各 provider / src/thinking-effort.js):
111
- // 客户端显式声明必须一路带到上游,旧版在此丢掉 → 下游被迫补默认值(workbuddy 恒 high)。
112
- if (req.thinking != null) body.thinking = req.thinking;
113
- // 档位载体只收「非空 trimmed 字符串」:空串声明不算声明,不该发出去顶掉下游默认值。
114
- for (const k of ["effort", "reasoning_effort", "reasoningEffort"]) {
115
- const v = typeof req[k] === "string" ? req[k].trim() : "";
116
- if (v) body[k] = v;
117
- }
118
- if (req.extra_body != null) body.extra_body = req.extra_body;
119
- // output_config.effort 是 Claude Code 的另一档位载体(beta),原始对象上游不认故不外发,
120
- // 但档位本身不能丢 → 归一到 reasoning_effort(客户端已显式声明时以声明为准)。
121
- const ocEffort = req.output_config && typeof req.output_config === "object" ? req.output_config.effort : undefined;
122
- if (ocEffort != null && body.reasoning_effort == null && body.reasoningEffort == null) {
123
- body.reasoning_effort = ocEffort;
124
- }
125
- return body;
126
- }
1
+ // 请求侧翻译:Anthropic Messages 请求体 → OpenAI chat 请求体(/v1/messages 外壳,ADR-0047)。
2
+ // 从 translate.js 拆出(ADR-0055):translate.js 贴 20KB 体积硬门,且「入站请求形状」与
3
+ // 「出站响应/usage 翻译」本就是两向关注点,拆后 translate.js 单向 import 本文件,不回环。
4
+ // 对外接口不变:调用方与测试仍从 anthropic/translate.js import(那边 re-export)。
5
+ //
6
+ // 形状对齐(1:1 照抄 cc-switch `src-tauri/src/proxy/providers/transform.rs:236-402`,只服务 /v1/messages):
7
+ // * system 块间用 "\n" 拼成**一条**;逐块剥开头的 `x-anthropic-billing-header:` 行(#2350:
8
+ // 该行带轮换 `cch=`,留在前缀位置会让上游前缀缓存每轮失效 → 每轮全量 prefill);
9
+ // * `tool_use.arguments` 走 canonical JSON;出站体整体 canonicalize(键序恒定 = 字节前缀稳定);
10
+ // * tool_result 里的媒体外移成一条 user 消息(改前是静默丢图);
11
+ // * tools 过滤 `BatchTool`、description 缺省不写、`input_schema` 过 cleanToolSchema;
12
+ // * o 系列 `max_tokens` → `max_completion_tokens`;`stream_options` 改 merge 不覆盖。
13
+ //
14
+ // 纪律(别改回去):
15
+ // * 思考档位**原样透传**(thinking/effort/reasoning_effort/reasoningEffort/extra_body),语义归一交给
16
+ // 各 provider 与 src/thinking-effort.js —— 旧版在此丢掉,下游被迫补默认值(workbuddy 恒 high,ADR-0053);
17
+ // 此处刻意**不**照抄 cc-switch 的 thinking→reasoning_effort 本地映射表(transform.rs:100-190);
18
+ // * 但**必须主动丢** output_config 原始对象 / context_management / 消息块内 thinking:Claude Code 对
19
+ // 不认识的 model ID 照发全套字段,块内 thinking 无法签发 signature,回传必被上游拒(ADR-0047);
20
+ // * 空会话抛错,绝不伪造一句 "hi" 打上游(会把假提问写进用户上下文并白烧一发额度);
21
+ // * tool_result 重复 tool_use_id 保首个、丢后续(部分上游按 call_id 查重直接 400);
22
+ // `is_error` 保留 `[tool_error]` 前缀(上游可见的错误信号,别照抄 cc-switch 丢掉)。
23
+ import { isServerTool } from "./web-search.js";
24
+ import { newToolUseId } from "./shared.js";
25
+ import { canonicalJson, canonicalizeValue } from "./canonical-json.js";
26
+ import { stripLeadingBillingHeader, cleanToolSchema, isOpenAiOSeries } from "./request-shape.js";
27
+ import { imagePartOf, planToolResultMedia, queueToolMedia, flushToolMedia } from "./tool-media.js";
28
+
29
+ // system 允许字符串或 text 块数组;块间用 "\n" 连接(照抄 cc-switch:跨轮字节稳定)。
30
+ // 逐块剥开头的计费头:它每轮变一次,是前缀缓存失效的头号嫌疑人(cc-switch #2350)。
31
+ function systemTextOf(system) {
32
+ const one = (t) => stripLeadingBillingHeader(typeof t === "string" ? t : "");
33
+ if (typeof system === "string") return one(system);
34
+ if (!Array.isArray(system)) return "";
35
+ return system
36
+ .map((b) => one(b && typeof b.text === "string" ? b.text : ""))
37
+ .filter(Boolean)
38
+ .join("\n");
39
+ }
40
+
41
+ /** tool_result 的 content → 纯文本(字符串原样;块数组取各 text;其余 String())。 */
42
+ export function toolResultTextOf(content) {
43
+ if (typeof content === "string") return content;
44
+ if (Array.isArray(content)) {
45
+ return content
46
+ .map((p) => (typeof p === "string" ? p : p && typeof p.text === "string" ? p.text : ""))
47
+ .filter(Boolean)
48
+ .join("\n");
49
+ }
50
+ return content == null ? "" : String(content);
51
+ }
52
+
53
+ /** Anthropic Messages 请求体 → OpenAI chat 请求体(直接喂既有 ChatPipeline)。 */
54
+ export function messagesToChatBody(req = {}) {
55
+ const model = String(req.model || "").trim();
56
+ if (!model) throw new Error("messages: 缺少 model");
57
+ const messages = [];
58
+ const sys = systemTextOf(req.system);
59
+ if (sys) messages.push({ role: "system", content: sys });
60
+
61
+ // 重复 tool_use_id 保首个、丢后续:客户端重试/重放历史会把同一工具结果存两份,
62
+ // 部分上游按 call_id 查重直接 400(同 responses/translate.js:57-59 的实测教训)。
63
+ const seenToolResult = new Set();
64
+ // 工具结果里的媒体暂存:同轮普通消息之前冲成一条 user 消息(Chat 的 tool 消息不能带图分片)
65
+ const pendingMedia = [];
66
+
67
+ for (const m of Array.isArray(req.messages) ? req.messages : []) {
68
+ if (!m || typeof m !== "object") continue;
69
+ // role=system/developer 必须保留:Claude Code ≥2.1.286 的 mid-conversation system beta 就往 messages[] 里塞系统指令,
70
+ const role = m.role === "assistant" ? "assistant" : m.role === "system" || m.role === "developer" ? "system" : "user";
71
+ if (typeof m.content === "string") {
72
+ if (m.content) messages.push({ role, content: m.content });
73
+ continue;
74
+ }
75
+ const blocks = Array.isArray(m.content) ? m.content : null;
76
+ if (!blocks) {
77
+ if (m.content != null) messages.push({ role, content: m.content }); // 其它形状原样透传
78
+ continue;
79
+ }
80
+ const parts = []; // text / image 分片(照抄 cc-switch 的 content_parts)
81
+ const toolCalls = [];
82
+ for (const b of blocks) {
83
+ if (!b || typeof b !== "object") continue;
84
+ if (b.type === "text") {
85
+ if (typeof b.text === "string" && b.text) parts.push({ type: "text", text: b.text });
86
+ } else if (b.type === "image") {
87
+ const p = imagePartOf(b);
88
+ if (p) parts.push(p);
89
+ } else if (b.type === "tool_use") {
90
+ toolCalls.push({
91
+ id: String(b.id || newToolUseId()),
92
+ type: "function",
93
+ function: { name: String(b.name || ""), arguments: canonicalJson(b.input ?? {}) },
94
+ });
95
+ } else if (b.type === "tool_result") {
96
+ // tool 消息必须先于同轮 user 文本进数组:OpenAI 侧要求 role:tool 紧跟其 assistant
97
+ const key = String(b.tool_use_id || "");
98
+ if (key) { if (seenToolResult.has(key)) continue; seenToolResult.add(key); }
99
+ const plan = planToolResultMedia(b.content, canonicalJson);
100
+ let text;
101
+ if (plan) { queueToolMedia(pendingMedia, key, plan.media); text = plan.text; }
102
+ else text = toolResultTextOf(b.content);
103
+ messages.push({ role: "tool", tool_call_id: key, content: b.is_error ? `[tool_error] ${text}` : text });
104
+ }
105
+ // thinking / redacted_thinking 忽略:我们无法签发 signature,回传必被上游拒(ADR-0047)
106
+ }
107
+ // 媒体先给、再给同轮普通内容(照抄 cc-switch transform.rs:517 的顺序)
108
+ flushToolMedia(messages, pendingMedia);
109
+ if (!parts.length && !toolCalls.length) continue;
110
+ // 单 text 分片化简成纯字符串;无分片给 null(照抄 transform.rs:524-535)
111
+ const content = parts.length === 0 ? null
112
+ : parts.length === 1 && parts[0].type === "text" ? parts[0].text
113
+ : parts;
114
+ const msg = { role, content };
115
+ if (toolCalls.length) msg.tool_calls = toolCalls;
116
+ messages.push(msg);
117
+ }
118
+ flushToolMedia(messages, pendingMedia); // 尾部残余(末条就是工具轮时)
119
+ // 空会话直接 400:绝不伪造一句 "hi" 打上游(那会把假提问写进用户上下文并白烧一发额度)
120
+ if (!messages.some((x) => x.role !== "system")) throw new Error("messages: 缺少用户消息");
121
+
122
+ const body = { model, messages, stream: Boolean(req.stream) };
123
+ // o 系列必须用 max_completion_tokens(照抄 cc-switch transform.rs:278-286)
124
+ if (req.max_tokens != null && Number.isFinite(Number(req.max_tokens))) {
125
+ if (isOpenAiOSeries(model)) body.max_completion_tokens = Number(req.max_tokens);
126
+ else body.max_tokens = Number(req.max_tokens);
127
+ }
128
+ if (req.temperature != null) body.temperature = req.temperature;
129
+ if (req.top_p != null) body.top_p = req.top_p;
130
+ if (Array.isArray(req.stop_sequences) && req.stop_sequences.length) body.stop = req.stop_sequences;
131
+ // 思考档位原样透传(不解释语义,语义归一交给各 provider / src/thinking-effort.js):
132
+ // 客户端显式声明必须一路带到上游,旧版在此丢掉 → 下游被迫补默认值(workbuddy 恒 high)。
133
+ if (req.thinking != null) body.thinking = req.thinking;
134
+ // 档位载体只收「非空 trimmed 字符串」:空串声明不算声明,不该发出去顶掉下游默认值。
135
+ for (const k of ["effort", "reasoning_effort", "reasoningEffort"]) {
136
+ const v = typeof req[k] === "string" ? req[k].trim() : "";
137
+ if (v) body[k] = v;
138
+ }
139
+ if (req.extra_body != null) body.extra_body = req.extra_body;
140
+ // output_config.effort 是 Claude Code 的另一档位载体(beta),原始对象上游不认故不外发,
141
+ // 但档位本身不能丢 → 归一到 reasoning_effort(客户端已显式声明时以声明为准)。
142
+ const ocEffort = req.output_config && typeof req.output_config === "object" ? req.output_config.effort : undefined;
143
+ if (ocEffort != null && body.reasoning_effort == null && body.reasoningEffort == null) {
144
+ body.reasoning_effort = ocEffort;
145
+ }
146
+ // 流式必须让上游把 usage 放进收尾帧,否则 message_delta.usage 恒 0(OpenAI 规范字段)。
147
+ // 照抄 cc-switch transform.rs:349-365:**merge** 客户端既有 stream_options,而不是整段覆盖。
148
+ // 个别上游不认 stream_options 会 400 → `MSLXDFF_ANTHROPIC_STREAM_USAGE=0` 关掉。
149
+ if (body.stream && process.env.MSLXDFF_ANTHROPIC_STREAM_USAGE !== "0") {
150
+ const opts = req.stream_options && typeof req.stream_options === "object" ? req.stream_options : {};
151
+ body.stream_options = { ...opts, include_usage: true };
152
+ }
153
+ // Anthropic 的 server tool(web_search_*/web_fetch_*/…)没有 input_schema,折成假 function 会
154
+ // 让上游收到「空参数空描述」的工具(严格端点直接 422),本网关不实现的发前一律剥除(ADR-0049);
155
+ // 另外照抄 cc-switch 剥 `BatchTool`、description 缺省不写、schema 过 cleanToolSchema。
156
+ const fnTools = (Array.isArray(req.tools) ? req.tools : [])
157
+ .filter((t) => !isServerTool(t))
158
+ .filter((t) => String(t?.type || "") !== "BatchTool");
159
+ if (fnTools.length) {
160
+ body.tools = fnTools.map((t) => {
161
+ const fn = { name: String(t?.name || "") };
162
+ if (typeof t?.description === "string" && t.description) fn.description = t.description;
163
+ fn.parameters = cleanToolSchema(t?.input_schema ?? {});
164
+ return { type: "function", function: fn };
165
+ });
166
+ }
167
+ const keptNames = new Set(fnTools.map((t) => String(t?.name || "")));
168
+ const tc = req.tool_choice;
169
+ if (typeof tc === "string") {
170
+ // 字符串形态:Anthropic 的 "any" → OpenAI 的 "required"(照抄 transform.rs:381-386)
171
+ if (tc === "any") body.tool_choice = "required";
172
+ else if (tc) body.tool_choice = tc;
173
+ } else if (tc && typeof tc === "object") {
174
+ if (tc.type === "auto") body.tool_choice = "auto";
175
+ else if (tc.type === "any") body.tool_choice = "required";
176
+ // 点名一个已被剥掉的工具时降为 auto:上游会按不存在的函数强制点名,那样一定拿不到有用回答
177
+ else if (tc.type === "tool") body.tool_choice = keptNames.has(String(tc.name || "")) ? { type: "function", function: { name: String(tc.name || "") } } : "auto";
178
+ else if (tc.type === "none") body.tool_choice = "none";
179
+ }
180
+ // 出站体键序规范化:同一逻辑内容必然产出同一份字节 → 上游前缀缓存能稳定命中
181
+ // (照抄 cc-switch forwarder.rs prepare_upstream_request_body / json_canonical.rs)。
182
+ return canonicalizeValue(body);
183
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * /v1/messages 请求形状的「取稳与清洗」原语 —— 1:1 照抄 cc-switch。
3
+ *
4
+ * 三件套:
5
+ * 1. `stripLeadingBillingHeader` —— 剥 system 文本**开头**的 `x-anthropic-billing-header:` 行
6
+ * (照抄 transform.rs:17-55,对应 cc-switch #2350)。Claude Code 会把含轮换 `cch=` 的
7
+ * 计费头塞在 system 最前面;它每轮变一次 → 整条前缀缓存失效 → 每轮全量 prefill。
8
+ * 只在开头剥,后文再出现同样的字符串一律保留(那是用户自己写的内容)。
9
+ * 2. `cleanToolSchema` —— 工具参数 schema 清洗(照抄 transform.rs:563-594):根缺 `type` 时补
10
+ * `"object"` 并顺带补 `properties: {}`,全树删 `format: "uri"`(严格上游会拒),嵌套递归。
11
+ * 3. `isOpenAiOSeries` —— o 系列(o1/o3/o4…)需 `max_completion_tokens` 而非 `max_tokens`
12
+ * (照抄 transform.rs:57-63 的意图;本仓模型 id 带供应商前缀,故按末段判定)。
13
+ */
14
+
15
+ const BILLING_HEADER_PREFIX = "x-anthropic-billing-header:";
16
+
17
+ /**
18
+ * 剥 system 开头的计费头行(含紧随的一个空行)。
19
+ * 无换行(整段就是这一行)→ 返回空串,与 cc-switch 一致。
20
+ * @param {unknown} text
21
+ * @returns {string}
22
+ */
23
+ export function stripLeadingBillingHeader(text) {
24
+ const s = typeof text === "string" ? text : "";
25
+ if (!s.startsWith(BILLING_HEADER_PREFIX)) return s;
26
+ const nl = s.search(/[\r\n]/);
27
+ if (nl < 0) return "";
28
+ let rest = s.slice(nl + 1);
29
+ if (s[nl] === "\r" && rest.startsWith("\n")) rest = rest.slice(1);
30
+ if (rest.startsWith("\r\n")) return rest.slice(2);
31
+ if (rest.startsWith("\n") || rest.startsWith("\r")) return rest.slice(1);
32
+ return rest;
33
+ }
34
+
35
+ /** 递归清洗一份 JSON schema(不修改入参:每层都产新对象)。 */
36
+ export function cleanToolSchema(schema) {
37
+ return cleanSchemaInner(schema, true);
38
+ }
39
+
40
+ function cleanSchemaInner(schema, isRoot) {
41
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return schema;
42
+ const out = { ...schema };
43
+ const missingType = isRoot && !("type" in out);
44
+ if (missingType) out.type = "object";
45
+ if (missingType && !("properties" in out)) out.properties = {};
46
+ if (out.format === "uri") delete out.format;
47
+ if (out.properties && typeof out.properties === "object" && !Array.isArray(out.properties)) {
48
+ const props = {};
49
+ for (const k of Object.keys(out.properties)) props[k] = cleanSchemaInner(out.properties[k], false);
50
+ out.properties = props;
51
+ }
52
+ if (out.items !== undefined) out.items = cleanSchemaInner(out.items, false);
53
+ return out;
54
+ }
55
+
56
+ /** OpenAI o 系列(o1/o3/o4-mini…):只看 id 末段,避免供应商前缀(如 `openai/o3`)干扰。 */
57
+ export function isOpenAiOSeries(model) {
58
+ const id = String(model || "").split("/").pop() || "";
59
+ return /^o\d(?:$|[-.])/.test(id.toLowerCase());
60
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Claude 系会话身份提取 —— 1:1 照抄 cc-switch `src-tauri/src/proxy/session.rs:107-231`(Claude 分支)。
3
+ *
4
+ * 为什么需要:会话 id 用来给上游做「缓存亲和 / 粘性路由」(`prompt_cache_key`、会话头)。
5
+ * cc-switch #8236 的教训是:拿不到真实会话身份就每轮生成一个新 id ⇒ 每轮换缓存 key ⇒
6
+ * 前缀缓存永不命中。Claude Code 走 `/v1/messages` 时把会话身份放在**请求体 metadata**里
7
+ * (不是 header),所以只读 header 的实现会一路漏。
8
+ *
9
+ * 优先级(与 cc-switch 一致):
10
+ * 1. header `x-claude-code-session-id`,再 `claude-code-session-id`(非空即用:**不 trim、无长度门槛**)
11
+ * 2. `metadata.user_id`:trim 后以 `{` 开头 → 当 JSON 解析取 `session_id`(trim 后非空才认);
12
+ * 否则找字面量 `_session_`,取其后的整段(旧格式)
13
+ * 3. `metadata.session_id`(字符串,trim 后非空)
14
+ * 4. 都没有 → 返回 null(由调用方走既有兜底,绝不在这里凭空生成:生成值会每轮变)
15
+ *
16
+ * 明确不用(cc-switch 同款判断):Responses 的 `previous_response_id` 之类「每轮变化的响应游标」
17
+ * 不是稳定会话身份,当成缓存 key 会导致每轮换 key。
18
+ */
19
+
20
+ const CLAUDE_SESSION_HEADERS = ["x-claude-code-session-id", "claude-code-session-id"];
21
+ const LEGACY_MARKER = "_session_";
22
+
23
+ /** `metadata.user_id` → 会话 id(JSON 里的 session_id,或旧 `_session_` 后缀)。 */
24
+ function sessionFromUserId(userId) {
25
+ const t = typeof userId === "string" ? userId.trim() : "";
26
+ if (!t) return null;
27
+ if (t.startsWith("{")) {
28
+ try {
29
+ const j = JSON.parse(t);
30
+ const s = typeof j?.session_id === "string" ? j.session_id.trim() : "";
31
+ return s || null;
32
+ } catch {
33
+ return null; // 坏 JSON:不猜,交下一档
34
+ }
35
+ }
36
+ const i = t.indexOf(LEGACY_MARKER);
37
+ if (i < 0) return null;
38
+ return t.slice(i + LEGACY_MARKER.length) || null;
39
+ }
40
+
41
+ /**
42
+ * @param {Record<string, unknown>} headers 入站头(Node 已小写化)
43
+ * @param {any} body 原始 Anthropic 请求体
44
+ * @returns {{sessionId: string, source: string} | null}
45
+ */
46
+ export function claudeSessionId(headers = {}, body = null) {
47
+ for (const name of CLAUDE_SESSION_HEADERS) {
48
+ const v = headers?.[name];
49
+ if (typeof v === "string" && v) return { sessionId: v, source: "header" };
50
+ }
51
+ const meta = body && typeof body === "object" && body.metadata && typeof body.metadata === "object" ? body.metadata : null;
52
+ if (!meta) return null;
53
+ const fromUser = sessionFromUserId(meta.user_id);
54
+ if (fromUser) return { sessionId: fromUser, source: "metadata.user_id" };
55
+ const sid = typeof meta.session_id === "string" ? meta.session_id.trim() : "";
56
+ if (sid) return { sessionId: sid, source: "metadata.session_id" };
57
+ return null;
58
+ }
@@ -1,18 +1,18 @@
1
- // /v1/messages 外壳的公共原语:消息/工具 id 与 Anthropic 协议错误体。
2
- // ADR-0055 把请求侧拆去 request-body.js 时独立成档,让 request-body.js 与 translate.js 单向依赖它,
3
- // 避免两文件互相 import 成环(函数提升虽能跑,顶层常量会 TDZ,属定时炸弹)。
4
- // 共用面:src/anthropic/request-body.js(newToolUseId)、src/anthropic/translate.js(newMessageId/
5
- // newToolUseId,并对外 re-export 三个符号,调用方与测试的 import 路径不变)。
6
-
7
- let seq = 0;
8
- export function newMessageId() {
9
- return `msg_${Date.now().toString(36)}${(seq++).toString(36)}`;
10
- }
11
- export function newToolUseId() {
12
- return `toolu_${Date.now().toString(36)}${(seq++).toString(36)}`;
13
- }
14
-
15
- /** Anthropic 协议错误体形状(非流式 JSON 与流式 in-band error 帧共用)。 */
16
- export function anthropicError(type, message) {
17
- return { type: "error", error: { type: String(type || "api_error"), message: String(message || "error").slice(0, 500) } };
18
- }
1
+ // /v1/messages 外壳的公共原语:消息/工具 id 与 Anthropic 协议错误体。
2
+ // ADR-0055 把请求侧拆去 request-body.js 时独立成档,让 request-body.js 与 translate.js 单向依赖它,
3
+ // 避免两文件互相 import 成环(函数提升虽能跑,顶层常量会 TDZ,属定时炸弹)。
4
+ // 共用面:src/anthropic/request-body.js(newToolUseId)、src/anthropic/translate.js(newMessageId/
5
+ // newToolUseId,并对外 re-export 三个符号,调用方与测试的 import 路径不变)。
6
+
7
+ let seq = 0;
8
+ export function newMessageId() {
9
+ return `msg_${Date.now().toString(36)}${(seq++).toString(36)}`;
10
+ }
11
+ export function newToolUseId() {
12
+ return `toolu_${Date.now().toString(36)}${(seq++).toString(36)}`;
13
+ }
14
+
15
+ /** Anthropic 协议错误体形状(非流式 JSON 与流式 in-band error 帧共用)。 */
16
+ export function anthropicError(type, message) {
17
+ return { type: "error", error: { type: String(type || "api_error"), message: String(message || "error").slice(0, 500) } };
18
+ }
@@ -1,56 +1,56 @@
1
- // 上游只会流式、客户端要非流式时的 SSE 聚合(ADR-0055)。
2
- // 从 `src/routes/messages-route.js` 抽出:该文件贴着 20KB 体积硬门(20306/20480),本单要加的
3
- // usage 兜底接线必须先进一段,故沿用 ADR-0053 把 count_tokens 估算器拆成独立文件的同类先例。
4
- // 共用面:唯一调用方 `src/routes/messages-route.js`(体积门驱动的等价搬移,非新抽象)。
5
- //
6
- // 逐行吃 `data:` 帧聚成 chat.completion JSON(与 qoder/aggregate.js、zcode 非流式聚合同构),
7
- // 出口复用 `chatJsonToAnthropic`;一帧都没有或夹带 in-band 错误帧时返回 null,落回原有 502 + errorText
8
- // 路径 —— 错误绝不聚合成正文。
9
-
10
- /**
11
- * @param text collector 收到的原始响应体(SSE 帧序列)
12
- * @param model 回显给客户端的模型名
13
- * @returns chat.completion 形状对象,或 null(无有效帧 / 夹带错误帧)
14
- */
15
- export function sseToChatJson(text, model) {
16
- let content = "";
17
- let finish = "";
18
- let usage = null;
19
- let sawChunk = false;
20
- const toolSlots = new Map();
21
- for (const raw of String(text || "").split("\n")) {
22
- const line = raw.trim();
23
- if (!line.startsWith("data:")) continue; // 注释帧/keepalive/事件名行全跳过
24
- const payload = line.slice(5).trim();
25
- if (!payload || payload === "[DONE]") continue;
26
- let chunk;
27
- try { chunk = JSON.parse(payload); } catch { continue; }
28
- if (chunk?.error) return null;
29
- sawChunk = true;
30
- const choice = chunk.choices?.[0] || {};
31
- const delta = choice.delta || {};
32
- if (choice.finish_reason) finish = choice.finish_reason;
33
- if (chunk.usage) usage = chunk.usage;
34
- if (typeof delta.content === "string" && delta.content) content += delta.content;
35
- for (const tc of delta.tool_calls || []) {
36
- const slot = Number(tc?.index ?? 0);
37
- let t = toolSlots.get(slot);
38
- if (!t) { t = { id: "", name: "", args: "" }; toolSlots.set(slot, t); }
39
- if (tc?.id) t.id = String(tc.id);
40
- if (tc?.function?.name) t.name += String(tc.function.name);
41
- if (tc?.function?.arguments) t.args += String(tc.function.arguments);
42
- }
43
- }
44
- if (!sawChunk) return null;
45
- const toolCalls = [...toolSlots.values()].map((t, i) => ({ id: t.id || `call_${i}`, type: "function", function: { name: t.name, arguments: t.args || "{}" } }));
46
- const message = { role: "assistant", content: content || (toolCalls.length ? null : "") };
47
- if (toolCalls.length) message.tool_calls = toolCalls;
48
- const out = {
49
- id: "", object: "chat.completion", created: Math.floor(Date.now() / 1000), model,
50
- choices: [{ index: 0, message, finish_reason: finish || (toolCalls.length ? "tool_calls" : "stop") }],
51
- };
52
- // 上游真报过 usage 才带这个字段:旧版合成 `{prompt_tokens:0,…}` 会把「未报」伪装成「报了 0」,
53
- // 让翻译层的兜底判据永远看不到真实形状(ADR-0055 决策 3)。
54
- if (usage) out.usage = usage;
55
- return out;
56
- }
1
+ // 上游只会流式、客户端要非流式时的 SSE 聚合(ADR-0055)。
2
+ // 从 `src/routes/messages-route.js` 抽出:该文件贴着 20KB 体积硬门(20306/20480),本单要加的
3
+ // usage 兜底接线必须先进一段,故沿用 ADR-0053 把 count_tokens 估算器拆成独立文件的同类先例。
4
+ // 共用面:唯一调用方 `src/routes/messages-route.js`(体积门驱动的等价搬移,非新抽象)。
5
+ //
6
+ // 逐行吃 `data:` 帧聚成 chat.completion JSON(与 qoder/aggregate.js、zcode 非流式聚合同构),
7
+ // 出口复用 `chatJsonToAnthropic`;一帧都没有或夹带 in-band 错误帧时返回 null,落回原有 502 + errorText
8
+ // 路径 —— 错误绝不聚合成正文。
9
+
10
+ /**
11
+ * @param text collector 收到的原始响应体(SSE 帧序列)
12
+ * @param model 回显给客户端的模型名
13
+ * @returns chat.completion 形状对象,或 null(无有效帧 / 夹带错误帧)
14
+ */
15
+ export function sseToChatJson(text, model) {
16
+ let content = "";
17
+ let finish = "";
18
+ let usage = null;
19
+ let sawChunk = false;
20
+ const toolSlots = new Map();
21
+ for (const raw of String(text || "").split("\n")) {
22
+ const line = raw.trim();
23
+ if (!line.startsWith("data:")) continue; // 注释帧/keepalive/事件名行全跳过
24
+ const payload = line.slice(5).trim();
25
+ if (!payload || payload === "[DONE]") continue;
26
+ let chunk;
27
+ try { chunk = JSON.parse(payload); } catch { continue; }
28
+ if (chunk?.error) return null;
29
+ sawChunk = true;
30
+ const choice = chunk.choices?.[0] || {};
31
+ const delta = choice.delta || {};
32
+ if (choice.finish_reason) finish = choice.finish_reason;
33
+ if (chunk.usage) usage = chunk.usage;
34
+ if (typeof delta.content === "string" && delta.content) content += delta.content;
35
+ for (const tc of delta.tool_calls || []) {
36
+ const slot = Number(tc?.index ?? 0);
37
+ let t = toolSlots.get(slot);
38
+ if (!t) { t = { id: "", name: "", args: "" }; toolSlots.set(slot, t); }
39
+ if (tc?.id) t.id = String(tc.id);
40
+ if (tc?.function?.name) t.name += String(tc.function.name);
41
+ if (tc?.function?.arguments) t.args += String(tc.function.arguments);
42
+ }
43
+ }
44
+ if (!sawChunk) return null;
45
+ const toolCalls = [...toolSlots.values()].map((t, i) => ({ id: t.id || `call_${i}`, type: "function", function: { name: t.name, arguments: t.args || "{}" } }));
46
+ const message = { role: "assistant", content: content || (toolCalls.length ? null : "") };
47
+ if (toolCalls.length) message.tool_calls = toolCalls;
48
+ const out = {
49
+ id: "", object: "chat.completion", created: Math.floor(Date.now() / 1000), model,
50
+ choices: [{ index: 0, message, finish_reason: finish || (toolCalls.length ? "tool_calls" : "stop") }],
51
+ };
52
+ // 上游真报过 usage 才带这个字段:旧版合成 `{prompt_tokens:0,…}` 会把「未报」伪装成「报了 0」,
53
+ // 让翻译层的兜底判据永远看不到真实形状(ADR-0055 决策 3)。
54
+ if (usage) out.usage = usage;
55
+ return out;
56
+ }