one-model-router 0.0.10 → 0.0.11

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 (77) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/src/admin.js +941 -941
  4. package/src/balances.js +61 -61
  5. package/src/boot.js +117 -117
  6. package/src/channels/buddy.js +2031 -2031
  7. package/src/channels/cline.js +753 -753
  8. package/src/channels/codearts.js +2051 -2051
  9. package/src/channels/comate.js +830 -830
  10. package/src/channels/doubaowork.js +1784 -1784
  11. package/src/channels/freebuff.js +1316 -1316
  12. package/src/channels/gemini.js +1721 -1721
  13. package/src/channels/index.js +270 -270
  14. package/src/channels/joycode.js +936 -936
  15. package/src/channels/kimi.js +572 -572
  16. package/src/channels/lobsterai.js +1226 -1226
  17. package/src/channels/loomy.js +1032 -1032
  18. package/src/channels/miaoshou.js +1396 -1396
  19. package/src/channels/mimo.js +474 -474
  20. package/src/channels/minimax.js +1451 -1451
  21. package/src/channels/qoder-wasm.js +434 -434
  22. package/src/channels/qoder.js +1619 -1619
  23. package/src/channels/raccoon.js +1842 -1842
  24. package/src/channels/tabbit.js +1457 -1457
  25. package/src/channels/trae.js +1405 -1405
  26. package/src/channels/zcode-global.js +35 -35
  27. package/src/channels/zcode.js +2085 -2085
  28. package/src/checkin.js +496 -496
  29. package/src/credits.js +464 -464
  30. package/src/crypto.js +132 -132
  31. package/src/free-models.js +683 -683
  32. package/src/gateway.js +596 -578
  33. package/src/health.js +86 -86
  34. package/src/model-key.js +35 -35
  35. package/src/paths.js +96 -96
  36. package/src/probe.js +318 -318
  37. package/src/providers/builtin.js +626 -626
  38. package/src/providers/index.js +483 -457
  39. package/src/providers/kilo.js +111 -111
  40. package/src/providers/last-good.js +69 -69
  41. package/src/providers/modelsdev.js +242 -242
  42. package/src/providers/openai-compat.js +312 -312
  43. package/src/providers/opencode/bun-fetch.js +226 -226
  44. package/src/providers/opencode/lane.js +186 -186
  45. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  46. package/src/providers/opencode/o2a/asset-source.js +43 -43
  47. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  48. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  49. package/src/providers/opencode/o2a/entry.js +17 -17
  50. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  51. package/src/providers/opencode/o2a/headers.js +133 -133
  52. package/src/providers/opencode/o2a/identity.js +148 -148
  53. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  54. package/src/providers/opencode/o2a/official-tools.js +110 -110
  55. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  56. package/src/providers/opencode/o2a/toolshape.js +418 -418
  57. package/src/providers/opencode/o2a/version.js +37 -37
  58. package/src/providers/opencode/upstream.js +403 -403
  59. package/src/providers/opencode/wire.js +496 -496
  60. package/src/providers/opencode.js +652 -652
  61. package/src/router.js +629 -629
  62. package/src/server.js +33 -33
  63. package/src/store.js +467 -467
  64. package/src/sync/index.js +1529 -1529
  65. package/src/sync/login-preload.cjs +52 -52
  66. package/src/sync/noise.js +141 -141
  67. package/src/sync/relay-http.js +176 -176
  68. package/src/sync/remote-host.js +818 -818
  69. package/src/sync/remote-http.js +112 -112
  70. package/src/sync/remote-login.js +657 -657
  71. package/src/sync/remote-pairing.js +204 -204
  72. package/src/sync/remote-protocol.js +321 -321
  73. package/src/sync/snapshot.js +211 -211
  74. package/src/util.js +334 -334
  75. package/web/app.js +3972 -3972
  76. package/web/index.html +32 -32
  77. package/web/style.css +971 -971
@@ -1,496 +1,496 @@
1
- /**
2
- * OpenAI Chat 请求 ↔ 上游另外两条线(OpenAI Responses / Anthropic Messages)的投影。
3
- *
4
- * 免密车道不是单一 API:按模型 id 分流到三条线(见 upstream.endpointFor),
5
- * 而 OMR 对外只有 OpenAI Chat Completions。因此本文件承担两头翻译:
6
- *
7
- * - 请求侧:把调用方的 chat 请求体投影成 Responses 的 `input` 项序列,
8
- * 或 Messages 的 `{system, messages, content blocks}`;工具声明同步换成
9
- * 该线的形状(flat `{type,name,parameters}` / Claude `{name,description,input_schema}`)。
10
- * - 响应侧:把该线的 SSE 事件流还原成 OpenAI chat 的 `delta` chunk,
11
- * 并在还原时把线上工具名换回调用方声明的名字(renameMap)。
12
- *
13
- * 投影规则按已实测的三条线形状整理,关键约束:
14
- *
15
- * - Messages 线要求**同角色回合合并**(连续两个 user 回合直接被拒),工具结果必须
16
- * 排在同回合其它内容之前;`tool_result` 无正文时也要填 `(no output)`。
17
- * - Responses 线不回放上一轮的 reasoning 项:`encrypted_content` 只有签发账号能解,
18
- * 而免密凭据是共享池,回传必然 400,因此构造上就不产出。
19
- * - 未配对的工具调用/结果会让上游回 `400 invalid_request_error`,并且该会话后续
20
- * 每一轮都 400(实测);这里统一做一次配对修复。
21
- *
22
- * @module src/providers/opencode/wire
23
- */
24
-
25
- import { MAX_TOOL_NAME_LEN, restoreToolName } from './upstream.js'
26
-
27
- /** 图片能走的媒体类型(Anthropic 侧白名单,实测)。 */
28
- const IMAGE_MEDIA = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
29
-
30
- /** 取内容片段的纯文本。 */
31
- function textOf(content) {
32
- if (typeof content === 'string') return content
33
- if (!Array.isArray(content)) return ''
34
- const parts = []
35
- for (const part of content) {
36
- if (typeof part === 'string') parts.push(part)
37
- else if (typeof part?.text === 'string') parts.push(part.text)
38
- }
39
- return parts.join('\n')
40
- }
41
-
42
- /** OpenAI 内容片段里的图片 URL(`image_url.url`,data URL 或 http(s))。 */
43
- function imageUrlOf(part) {
44
- const raw = part?.image_url?.url ?? (typeof part?.image_url === 'string' ? part.image_url : undefined)
45
- return typeof raw === 'string' && raw !== '' ? raw : undefined
46
- }
47
-
48
- /**
49
- * 丢弃「没人回答的工具调用」与「没有对应调用的工具结果」。
50
- *
51
- * OpenAI Chat 的历史里,一轮被打断(工具没启动、用户中止、上游报错)就正好留下
52
- * 这种半截配对;三条线都强制配对,带着它上线会让该会话后续每一轮都 400。
53
- * 按 OpenAI Chat 的键(tool_calls / tool_call_id)
54
- * 读写,调用方的数组一律浅拷贝替换,不就地改。
55
- */
56
- export function repairChatPairing(messages) {
57
- const list = Array.isArray(messages) ? messages : []
58
- const answered = new Set()
59
- for (const message of list) {
60
- if (message?.role === 'tool' && typeof message.tool_call_id === 'string' && message.tool_call_id !== '') {
61
- answered.add(message.tool_call_id)
62
- }
63
- }
64
- const keptCallIds = new Set()
65
- const out = []
66
- for (const message of list) {
67
- if (message?.role === 'tool') {
68
- const id = typeof message.tool_call_id === 'string' ? message.tool_call_id : ''
69
- if (id === '' || !keptCallIds.has(id)) continue
70
- out.push(message)
71
- continue
72
- }
73
- const calls = Array.isArray(message?.tool_calls) ? message.tool_calls : []
74
- if (message?.role === 'assistant') {
75
- const viable = calls.filter(call => typeof call?.id === 'string' && call.id !== ''
76
- && answered.has(call.id) && String(call?.function?.name ?? '') !== '')
77
- for (const call of viable) keptCallIds.add(call.id)
78
- if (viable.length === calls.length) {
79
- const said = textOf(message.content) !== ''
80
- if (said || viable.length > 0) out.push(message)
81
- continue
82
- }
83
- const said = textOf(message.content) !== ''
84
- if (viable.length === 0) {
85
- if (said) out.push({ ...message, tool_calls: undefined })
86
- continue
87
- }
88
- out.push({ ...message, tool_calls: viable })
89
- continue
90
- }
91
- out.push(message)
92
- }
93
- return out
94
- }
95
-
96
- /** 调用方 tools(OpenAI 两种写法都认)→ 该线的工具形状;名字截到上游上限。 */
97
- export function projectTools(tools, shape) {
98
- const list = []
99
- for (const tool of Array.isArray(tools) ? tools : []) {
100
- const source = tool && typeof tool.function === 'object' && tool.function !== null && !Array.isArray(tool.function)
101
- ? tool.function
102
- : tool
103
- const name = String(source?.name ?? '').trim()
104
- if (name === '') continue
105
- const wire = name.slice(0, MAX_TOOL_NAME_LEN)
106
- const parameters = source.parameters && typeof source.parameters === 'object' && !Array.isArray(source.parameters)
107
- ? source.parameters
108
- : { type: 'object', properties: {} }
109
- const description = typeof source.description === 'string' ? source.description : ''
110
- if (shape === 'claude') list.push({ name: wire, description, input_schema: parameters })
111
- else if (shape === 'flat') list.push({ type: 'function', name: wire, description, parameters })
112
- else list.push({ type: 'function', function: { name: wire, description, parameters } })
113
- }
114
- return list
115
- }
116
-
117
- /** 工具调用参数:非字符串一律按 `{}` 上线(上游要 JSON 文本)。 */
118
- function argumentsOf(call) {
119
- return typeof call?.function?.arguments === 'string' ? call.function.arguments : '{}'
120
- }
121
-
122
- /** data URL → Claude `image` 块;不可搬运返回 undefined(调用方按丢图处理)。 */
123
- function claudeImageBlock(url) {
124
- if (url === undefined) return undefined
125
- const comma = String(url).indexOf(',')
126
- if (comma === -1) return undefined // 外链图片 Claude 侧需要 url 源,本线只带 base64
127
- const media = String(url).slice(0, comma).match(/data:([^;]+)/)?.[1]
128
- if (media === undefined || !IMAGE_MEDIA.has(media)) return undefined
129
- return { type: 'image', source: { type: 'base64', media_type: media, data: String(url).slice(comma + 1) } }
130
- }
131
-
132
- // ── Responses 线 ────────────────────────────────────────────────────────────
133
-
134
- /**
135
- * chat 请求体 → Responses `input` 项序列 + `instructions`。
136
- * system/developer 文本折进 instructions(提示注入层再前插官方提示);
137
- * assistant 的 tool_calls 成 `function_call` 项,tool 消息成 `function_call_output` 项。
138
- */
139
- export function chatToResponses(body) {
140
- const messages = repairChatPairing(body.messages)
141
- const input = []
142
- const instructions = []
143
- for (const message of messages) {
144
- const role = message?.role
145
- if (role === 'system' || role === 'developer') {
146
- const text = textOf(message.content)
147
- if (text !== '') instructions.push(text)
148
- continue
149
- }
150
- if (role === 'tool') {
151
- input.push({ type: 'function_call_output', call_id: String(message.tool_call_id ?? ''), output: textOf(message.content) || '(no output)' })
152
- continue
153
- }
154
- if (role === 'assistant') {
155
- const text = textOf(message.content)
156
- if (text !== '') input.push({ type: 'message', role: 'assistant', content: [{ type: 'output_text', text }] })
157
- for (const call of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
158
- input.push({
159
- type: 'function_call',
160
- call_id: String(call?.id ?? ''),
161
- name: String(call?.function?.name ?? ''),
162
- arguments: argumentsOf(call),
163
- })
164
- }
165
- if (text === '' && (message.tool_calls ?? []).length === 0) continue
166
- continue
167
- }
168
- const parts = []
169
- for (const part of Array.isArray(message?.content) ? message.content : []) {
170
- if (typeof part === 'string') { if (part !== '') parts.push({ type: 'input_text', text: part }); continue }
171
- if (part?.type === 'text' && typeof part.text === 'string' && part.text !== '') parts.push({ type: 'input_text', text: part.text })
172
- else if (part?.type === 'image_url') {
173
- const url = imageUrlOf(part)
174
- if (url !== undefined) parts.push({ type: 'input_image', image_url: url })
175
- }
176
- }
177
- if (parts.length === 0) {
178
- const text = textOf(message?.content)
179
- if (text !== '') parts.push({ type: 'input_text', text })
180
- }
181
- if (parts.length === 0) continue
182
- input.push({ type: 'message', role: role === 'assistant' ? 'assistant' : 'user', content: parts })
183
- }
184
- if (typeof body.system === 'string' && body.system !== '') instructions.unshift(body.system)
185
- const payload = {
186
- model: body.model,
187
- // 空对话也要有形状:用 '...' 占位,避免 input 为空被上游判非法。
188
- input: input.length > 0 ? input : [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: '...' }] }],
189
- stream: true,
190
- store: false,
191
- }
192
- if (instructions.length > 0) payload.instructions = instructions.join('\n\n')
193
- const tools = projectTools(body.tools, 'flat')
194
- if (tools.length > 0) payload.tools = tools
195
- if (body.tool_choice !== undefined) payload.tool_choice = body.tool_choice
196
- if (typeof body.temperature === 'number' && Number.isFinite(body.temperature)) payload.temperature = body.temperature
197
- if (Number.isSafeInteger(body.max_tokens) && body.max_tokens > 0) payload.max_output_tokens = body.max_tokens
198
- else if (Number.isSafeInteger(body.max_completion_tokens) && body.max_completion_tokens > 0) payload.max_output_tokens = body.max_completion_tokens
199
- if (typeof body.reasoning_effort === 'string' && body.reasoning_effort !== '') payload.reasoning = { effort: body.reasoning_effort }
200
- return payload
201
- }
202
-
203
- // ── Messages(Anthropic)线 ─────────────────────────────────────────────────
204
-
205
- /**
206
- * chat 请求体 → Messages `{system, messages}`。
207
- *
208
- * ⚠️ 同角色回合必须合并:Messages 线拒绝连续两个 user 回合(工具结果与随后的
209
- * 文本会正好落成两个),因此这里按角色压入同一回合的 content 数组。
210
- * 工具结果走 `tool_result` 块(属于 user 回合)且排在同回合其它内容之前。
211
- */
212
- export function chatToMessages(body) {
213
- const messages = repairChatPairing(body.messages)
214
- const out = []
215
- const systemParts = []
216
- const push = (role, blocks) => {
217
- const previous = out[out.length - 1]
218
- if (previous?.role === role) previous.content.push(...blocks)
219
- else out.push({ role, content: [...blocks] })
220
- }
221
- for (const message of messages) {
222
- const role = message?.role
223
- if (role === 'system' || role === 'developer') {
224
- const text = textOf(message.content)
225
- if (text !== '') systemParts.push(text)
226
- continue
227
- }
228
- if (role === 'tool') {
229
- push('user', [{
230
- type: 'tool_result',
231
- tool_use_id: String(message.tool_call_id ?? ''),
232
- content: [{ type: 'text', text: textOf(message.content) || '(no output)' }],
233
- }])
234
- continue
235
- }
236
- const blocks = []
237
- if (role === 'assistant') {
238
- const text = textOf(message.content)
239
- if (text !== '') blocks.push({ type: 'text', text })
240
- for (const call of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
241
- let input = {}
242
- try { input = JSON.parse(argumentsOf(call)) } catch { input = {} }
243
- blocks.push({ type: 'tool_use', id: String(call?.id ?? ''), name: String(call?.function?.name ?? ''), input })
244
- }
245
- } else {
246
- for (const part of Array.isArray(message?.content) ? message.content : []) {
247
- if (typeof part === 'string') { if (part !== '') blocks.push({ type: 'text', text: part }); continue }
248
- if (part?.type === 'text' && typeof part.text === 'string' && part.text !== '') blocks.push({ type: 'text', text: part.text })
249
- else if (part?.type === 'image_url') {
250
- const image = claudeImageBlock(imageUrlOf(part))
251
- if (image !== undefined) blocks.push(image)
252
- }
253
- }
254
- if (blocks.length === 0) {
255
- const text = textOf(message?.content)
256
- if (text !== '') blocks.push({ type: 'text', text })
257
- }
258
- }
259
- if (blocks.length === 0) continue
260
- push(role === 'assistant' ? 'assistant' : 'user', blocks)
261
- }
262
- if (typeof body.system === 'string' && body.system !== '') systemParts.unshift(body.system)
263
- const payload = {
264
- model: body.model,
265
- messages: out.length > 0 ? out : [{ role: 'user', content: [{ type: 'text', text: '...' }] }],
266
- stream: true,
267
- max_tokens: Number.isSafeInteger(body.max_tokens) && body.max_tokens > 0 ? body.max_tokens
268
- : Number.isSafeInteger(body.max_completion_tokens) && body.max_completion_tokens > 0 ? body.max_completion_tokens
269
- : 32000,
270
- }
271
- if (systemParts.length > 0) payload.system = systemParts.join('\n\n')
272
- const tools = projectTools(body.tools, 'claude')
273
- if (tools.length > 0) payload.tools = tools
274
- if (body.tool_choice !== undefined) payload.tool_choice = typeof body.tool_choice === 'string' && body.tool_choice === 'auto'
275
- ? { type: 'auto' }
276
- : body.tool_choice
277
- if (typeof body.temperature === 'number' && Number.isFinite(body.temperature)) payload.temperature = body.temperature
278
- return payload
279
- }
280
-
281
- // ── 响应侧:两条线的事件 → OpenAI chat chunk ──────────────────────────────────
282
-
283
- /** 一条流的还原状态:chunk id、模型名、工具槽位、是否出过工具调用、是否已收尾。 */
284
- export function createDecoder(model, renameMap) {
285
- return {
286
- model,
287
- renameMap,
288
- id: '',
289
- created: Math.floor(Date.now() / 1000),
290
- sentRole: false,
291
- toolSlots: new Map(),
292
- sawToolCall: false,
293
- usage: null,
294
- finish: null,
295
- done: false,
296
- }
297
- }
298
-
299
- /** 首个 chunk 之前补一条 role 帧(多数客户端按 role 帧判定流已开始)。 */
300
- function roleChunk(ctx) {
301
- if (ctx.sentRole) return null
302
- ctx.sentRole = true
303
- return chunk(ctx, [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }])
304
- }
305
-
306
- function chunk(ctx, choices, usage) {
307
- const out = {
308
- id: ctx.id !== '' ? ctx.id : `omr-opencode-${Date.now().toString(36)}`,
309
- object: 'chat.completion.chunk',
310
- created: ctx.created,
311
- model: ctx.model,
312
- choices,
313
- }
314
- if (usage !== null && usage !== undefined) out.usage = usage
315
- return out
316
- }
317
-
318
- function deltaContent(ctx, text) {
319
- if (text === undefined || text === null || text === '') return null
320
- const first = roleChunk(ctx)
321
- const body = chunk(ctx, [{ index: 0, delta: { content: text }, finish_reason: null }])
322
- return first === null ? [body] : [first, body]
323
- }
324
-
325
- function deltaReasoning(ctx, text) {
326
- if (text === undefined || text === null || text === '') return null
327
- const first = roleChunk(ctx)
328
- const body = chunk(ctx, [{ index: 0, delta: { reasoning_content: text }, finish_reason: null }])
329
- return first === null ? [body] : [first, body]
330
- }
331
-
332
- function toolStart(ctx, call, name) {
333
- const slot = ctx.toolSlots.size
334
- const wire = typeof name === 'string' ? name : ''
335
- const restored = restoreToolName(wire, ctx.renameMap)
336
- ctx.sawToolCall = true
337
- const first = roleChunk(ctx)
338
- const body = chunk(ctx, [{
339
- index: 0,
340
- delta: {
341
- tool_calls: [{
342
- index: slot,
343
- id: call?.id ?? `call_${Math.random().toString(36).slice(2, 10)}`,
344
- type: 'function',
345
- function: { name: restored === '' ? wire : restored, arguments: '' },
346
- }],
347
- },
348
- finish_reason: null,
349
- }])
350
- return { frames: first === null ? [body] : [first, body], index: slot }
351
- }
352
-
353
- function toolArgs(ctx, index, partial) {
354
- if (typeof index !== 'number' || partial === undefined || partial === '') return null
355
- return [chunk(ctx, [{ index: 0, delta: { tool_calls: [{ index, function: { arguments: partial } }] }, finish_reason: null }])]
356
- }
357
-
358
- /** 统一成帧数组(null / 单帧 / 多帧都归一,方便调用方一次性 emit)。 */
359
- function framesOf(value) {
360
- if (value === null || value === undefined) return null
361
- return Array.isArray(value) ? value : [value]
362
- }
363
-
364
- /** 收尾:finish_reason + usage 帧(usage 单独一帧,choices 为空,OpenAI 口径);重复调用只出一次。 */
365
- export function terminalFrames(ctx, finish, usage) {
366
- if (ctx.done) return null
367
- ctx.done = true
368
- const frames = [chunk(ctx, [{ index: 0, delta: {}, finish_reason: finish ?? (ctx.sawToolCall ? 'tool_calls' : 'stop') }])]
369
- if (usage) frames.push(chunk(ctx, [], usage))
370
- return frames
371
- }
372
-
373
- /** 归一化用量(三线的字段名各不相同 → OpenAI 口径)。 */
374
- function usageObject(input, output, cached, reasoning) {
375
- if (input === undefined && output === undefined) return null
376
- const prompt = Number(input) || 0
377
- const completion = Number(output) || 0
378
- return {
379
- prompt_tokens: prompt,
380
- completion_tokens: completion,
381
- total_tokens: prompt + completion,
382
- ...(Number(cached) > 0 ? { prompt_tokens_details: { cached_tokens: Number(cached) } } : {}),
383
- ...(Number(reasoning) > 0 ? { completion_tokens_details: { reasoning_tokens: Number(reasoning) } } : {}),
384
- }
385
- }
386
-
387
- // ── Responses 事件还原 ──────────────────────────────────────────────────────
388
-
389
- /**
390
- * Responses 线事件 → chat chunk 数组。返回 null 表示该事件无对外可见内容。
391
- * 错误事件(`response.failed` / `{type:'error'}`)由调用方处理:这里抛出,
392
- * 让门面按普通失败分类(换候选/退避)。
393
- */
394
- export function decodeResponsesEvent(ctx, event) {
395
- const type = typeof event?.type === 'string' ? event.type : ''
396
- if (type === 'response.created' || type === 'response.in_progress') {
397
- const id = event?.response?.id
398
- if (typeof id === 'string' && id !== '') ctx.id = id
399
- return null
400
- }
401
- if (type === 'response.output_item.added') {
402
- const item = event?.item
403
- if (item?.type === 'function_call') {
404
- const key = String(event.output_index ?? event.item_index ?? ctx.toolSlots.size)
405
- const started = toolStart(ctx, { id: String(item.call_id ?? item.id ?? '') }, String(item.name ?? ''))
406
- ctx.toolSlots.set(key, started.index)
407
- return started.frames
408
- }
409
- return null
410
- }
411
- if (type === 'response.output_text.delta') return framesOf(deltaContent(ctx, event.delta))
412
- if (type === 'response.reasoning_summary_text.delta' || type === 'response.output_reasoning.text.delta') return framesOf(deltaReasoning(ctx, event.delta))
413
- if (type === 'response.function_call_arguments.delta') {
414
- const key = String(event.output_index ?? event.item_index ?? '')
415
- const slot = ctx.toolSlots.has(key) ? ctx.toolSlots.get(key) : 0
416
- return framesOf(toolArgs(ctx, slot, event.delta))
417
- }
418
- if (type === 'response.completed' || type === 'response.incomplete' || type === 'response.failed' || type === 'response.done') {
419
- const response = event?.response ?? {}
420
- if (type === 'response.failed' && response.error) {
421
- throw { kind: 'server', retryable: true, message: `上游响应失败: ${response.error?.message ?? JSON.stringify(response.error)}` }
422
- }
423
- const usage = usageObject(
424
- response.usage?.input_tokens,
425
- response.usage?.output_tokens,
426
- response.usage?.input_tokens_details?.cached_tokens,
427
- response.usage?.output_tokens_details?.reasoning_tokens,
428
- )
429
- if (ctx.usage === null) ctx.usage = usage
430
- const incomplete = response.incomplete_details?.reason
431
- const status = response.status ?? (type === 'response.failed' ? 'failed' : type === 'response.incomplete' ? 'incomplete' : 'completed')
432
- ctx.finish = incomplete === 'max_output_tokens' ? 'length'
433
- : status !== 'completed' ? 'stop'
434
- : ctx.sawToolCall ? 'tool_calls' : 'stop'
435
- return terminalFrames(ctx, ctx.finish, ctx.usage)
436
- }
437
- if (type === 'error' || event?.error) {
438
- throw { kind: 'server', retryable: true, message: `上游流内错误: ${event?.error?.message ?? JSON.stringify(event?.error ?? event).slice(0, 200)}` }
439
- }
440
- return null
441
- }
442
-
443
- // ── Messages 事件还原 ───────────────────────────────────────────────────────
444
-
445
- /** Anthropic 的 stop_reason → OpenAI finish_reason。 */
446
- const ANTHROPIC_FINISH = { end_turn: 'stop', stop_sequence: 'stop', tool_use: 'tool_calls', max_tokens: 'length' }
447
-
448
- /**
449
- * Messages 线事件 → chat chunk 数组。
450
- *
451
- * ⚠️ Anthropic 没有 `[DONE]`:`message_stop` 是唯一的正常结束标记,
452
- * 收不到就是被截断(调用方据此判完整性)。
453
- */
454
- export function decodeMessagesEvent(ctx, event) {
455
- const type = typeof event?.type === 'string' ? event.type : ''
456
- if (type === 'message_start') {
457
- const message = event?.message ?? {}
458
- if (typeof message.id === 'string' && message.id !== '') ctx.id = message.id
459
- const usage = message.usage ?? {}
460
- ctx.inputTokens = Number(usage.input_tokens) || 0
461
- ctx.cachedTokens = Number(usage.cache_read_input_tokens) || 0
462
- return null
463
- }
464
- if (type === 'content_block_start') {
465
- const block = event?.content_block
466
- if (block?.type === 'tool_use') {
467
- const started = toolStart(ctx, { id: String(block.id ?? '') }, String(block.name ?? ''))
468
- ctx.toolSlots.set(String(event.index), started.index)
469
- return started.frames
470
- }
471
- return null
472
- }
473
- if (type === 'content_block_delta') {
474
- const part = event?.delta
475
- if (part?.type === 'text_delta') return deltaContent(ctx, part.text)
476
- if (part?.type === 'thinking_delta') return deltaReasoning(ctx, part.thinking)
477
- if (part?.type === 'input_json_delta') {
478
- const slot = ctx.toolSlots.has(String(event.index)) ? ctx.toolSlots.get(String(event.index)) : 0
479
- return framesOf(toolArgs(ctx, slot, part.partial_json))
480
- }
481
- if (part?.type === 'signature_delta' || part?.type === 'redacted_thinking') return null
482
- return null
483
- }
484
- if (type === 'message_delta') {
485
- const stop = event?.delta?.stop_reason
486
- const usage = event?.usage ?? {}
487
- ctx.finish = ANTHROPIC_FINISH[stop] ?? (ctx.sawToolCall ? 'tool_calls' : 'stop')
488
- ctx.usage = usageObject(ctx.inputTokens ?? usage.input_tokens, usage.output_tokens, ctx.cachedTokens, usage.output_tokens_details?.reasoning_tokens)
489
- return null
490
- }
491
- if (type === 'message_stop') return terminalFrames(ctx, ctx.finish, ctx.usage)
492
- if (type === 'error') {
493
- throw { kind: 'server', retryable: true, message: `上游流内错误: ${event?.error?.message ?? JSON.stringify(event?.error ?? {}).slice(0, 200)}` }
494
- }
495
- return null
496
- }
1
+ /**
2
+ * OpenAI Chat 请求 ↔ 上游另外两条线(OpenAI Responses / Anthropic Messages)的投影。
3
+ *
4
+ * 免密车道不是单一 API:按模型 id 分流到三条线(见 upstream.endpointFor),
5
+ * 而 OMR 对外只有 OpenAI Chat Completions。因此本文件承担两头翻译:
6
+ *
7
+ * - 请求侧:把调用方的 chat 请求体投影成 Responses 的 `input` 项序列,
8
+ * 或 Messages 的 `{system, messages, content blocks}`;工具声明同步换成
9
+ * 该线的形状(flat `{type,name,parameters}` / Claude `{name,description,input_schema}`)。
10
+ * - 响应侧:把该线的 SSE 事件流还原成 OpenAI chat 的 `delta` chunk,
11
+ * 并在还原时把线上工具名换回调用方声明的名字(renameMap)。
12
+ *
13
+ * 投影规则按已实测的三条线形状整理,关键约束:
14
+ *
15
+ * - Messages 线要求**同角色回合合并**(连续两个 user 回合直接被拒),工具结果必须
16
+ * 排在同回合其它内容之前;`tool_result` 无正文时也要填 `(no output)`。
17
+ * - Responses 线不回放上一轮的 reasoning 项:`encrypted_content` 只有签发账号能解,
18
+ * 而免密凭据是共享池,回传必然 400,因此构造上就不产出。
19
+ * - 未配对的工具调用/结果会让上游回 `400 invalid_request_error`,并且该会话后续
20
+ * 每一轮都 400(实测);这里统一做一次配对修复。
21
+ *
22
+ * @module src/providers/opencode/wire
23
+ */
24
+
25
+ import { MAX_TOOL_NAME_LEN, restoreToolName } from './upstream.js'
26
+
27
+ /** 图片能走的媒体类型(Anthropic 侧白名单,实测)。 */
28
+ const IMAGE_MEDIA = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
29
+
30
+ /** 取内容片段的纯文本。 */
31
+ function textOf(content) {
32
+ if (typeof content === 'string') return content
33
+ if (!Array.isArray(content)) return ''
34
+ const parts = []
35
+ for (const part of content) {
36
+ if (typeof part === 'string') parts.push(part)
37
+ else if (typeof part?.text === 'string') parts.push(part.text)
38
+ }
39
+ return parts.join('\n')
40
+ }
41
+
42
+ /** OpenAI 内容片段里的图片 URL(`image_url.url`,data URL 或 http(s))。 */
43
+ function imageUrlOf(part) {
44
+ const raw = part?.image_url?.url ?? (typeof part?.image_url === 'string' ? part.image_url : undefined)
45
+ return typeof raw === 'string' && raw !== '' ? raw : undefined
46
+ }
47
+
48
+ /**
49
+ * 丢弃「没人回答的工具调用」与「没有对应调用的工具结果」。
50
+ *
51
+ * OpenAI Chat 的历史里,一轮被打断(工具没启动、用户中止、上游报错)就正好留下
52
+ * 这种半截配对;三条线都强制配对,带着它上线会让该会话后续每一轮都 400。
53
+ * 按 OpenAI Chat 的键(tool_calls / tool_call_id)
54
+ * 读写,调用方的数组一律浅拷贝替换,不就地改。
55
+ */
56
+ export function repairChatPairing(messages) {
57
+ const list = Array.isArray(messages) ? messages : []
58
+ const answered = new Set()
59
+ for (const message of list) {
60
+ if (message?.role === 'tool' && typeof message.tool_call_id === 'string' && message.tool_call_id !== '') {
61
+ answered.add(message.tool_call_id)
62
+ }
63
+ }
64
+ const keptCallIds = new Set()
65
+ const out = []
66
+ for (const message of list) {
67
+ if (message?.role === 'tool') {
68
+ const id = typeof message.tool_call_id === 'string' ? message.tool_call_id : ''
69
+ if (id === '' || !keptCallIds.has(id)) continue
70
+ out.push(message)
71
+ continue
72
+ }
73
+ const calls = Array.isArray(message?.tool_calls) ? message.tool_calls : []
74
+ if (message?.role === 'assistant') {
75
+ const viable = calls.filter(call => typeof call?.id === 'string' && call.id !== ''
76
+ && answered.has(call.id) && String(call?.function?.name ?? '') !== '')
77
+ for (const call of viable) keptCallIds.add(call.id)
78
+ if (viable.length === calls.length) {
79
+ const said = textOf(message.content) !== ''
80
+ if (said || viable.length > 0) out.push(message)
81
+ continue
82
+ }
83
+ const said = textOf(message.content) !== ''
84
+ if (viable.length === 0) {
85
+ if (said) out.push({ ...message, tool_calls: undefined })
86
+ continue
87
+ }
88
+ out.push({ ...message, tool_calls: viable })
89
+ continue
90
+ }
91
+ out.push(message)
92
+ }
93
+ return out
94
+ }
95
+
96
+ /** 调用方 tools(OpenAI 两种写法都认)→ 该线的工具形状;名字截到上游上限。 */
97
+ export function projectTools(tools, shape) {
98
+ const list = []
99
+ for (const tool of Array.isArray(tools) ? tools : []) {
100
+ const source = tool && typeof tool.function === 'object' && tool.function !== null && !Array.isArray(tool.function)
101
+ ? tool.function
102
+ : tool
103
+ const name = String(source?.name ?? '').trim()
104
+ if (name === '') continue
105
+ const wire = name.slice(0, MAX_TOOL_NAME_LEN)
106
+ const parameters = source.parameters && typeof source.parameters === 'object' && !Array.isArray(source.parameters)
107
+ ? source.parameters
108
+ : { type: 'object', properties: {} }
109
+ const description = typeof source.description === 'string' ? source.description : ''
110
+ if (shape === 'claude') list.push({ name: wire, description, input_schema: parameters })
111
+ else if (shape === 'flat') list.push({ type: 'function', name: wire, description, parameters })
112
+ else list.push({ type: 'function', function: { name: wire, description, parameters } })
113
+ }
114
+ return list
115
+ }
116
+
117
+ /** 工具调用参数:非字符串一律按 `{}` 上线(上游要 JSON 文本)。 */
118
+ function argumentsOf(call) {
119
+ return typeof call?.function?.arguments === 'string' ? call.function.arguments : '{}'
120
+ }
121
+
122
+ /** data URL → Claude `image` 块;不可搬运返回 undefined(调用方按丢图处理)。 */
123
+ function claudeImageBlock(url) {
124
+ if (url === undefined) return undefined
125
+ const comma = String(url).indexOf(',')
126
+ if (comma === -1) return undefined // 外链图片 Claude 侧需要 url 源,本线只带 base64
127
+ const media = String(url).slice(0, comma).match(/data:([^;]+)/)?.[1]
128
+ if (media === undefined || !IMAGE_MEDIA.has(media)) return undefined
129
+ return { type: 'image', source: { type: 'base64', media_type: media, data: String(url).slice(comma + 1) } }
130
+ }
131
+
132
+ // ── Responses 线 ────────────────────────────────────────────────────────────
133
+
134
+ /**
135
+ * chat 请求体 → Responses `input` 项序列 + `instructions`。
136
+ * system/developer 文本折进 instructions(提示注入层再前插官方提示);
137
+ * assistant 的 tool_calls 成 `function_call` 项,tool 消息成 `function_call_output` 项。
138
+ */
139
+ export function chatToResponses(body) {
140
+ const messages = repairChatPairing(body.messages)
141
+ const input = []
142
+ const instructions = []
143
+ for (const message of messages) {
144
+ const role = message?.role
145
+ if (role === 'system' || role === 'developer') {
146
+ const text = textOf(message.content)
147
+ if (text !== '') instructions.push(text)
148
+ continue
149
+ }
150
+ if (role === 'tool') {
151
+ input.push({ type: 'function_call_output', call_id: String(message.tool_call_id ?? ''), output: textOf(message.content) || '(no output)' })
152
+ continue
153
+ }
154
+ if (role === 'assistant') {
155
+ const text = textOf(message.content)
156
+ if (text !== '') input.push({ type: 'message', role: 'assistant', content: [{ type: 'output_text', text }] })
157
+ for (const call of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
158
+ input.push({
159
+ type: 'function_call',
160
+ call_id: String(call?.id ?? ''),
161
+ name: String(call?.function?.name ?? ''),
162
+ arguments: argumentsOf(call),
163
+ })
164
+ }
165
+ if (text === '' && (message.tool_calls ?? []).length === 0) continue
166
+ continue
167
+ }
168
+ const parts = []
169
+ for (const part of Array.isArray(message?.content) ? message.content : []) {
170
+ if (typeof part === 'string') { if (part !== '') parts.push({ type: 'input_text', text: part }); continue }
171
+ if (part?.type === 'text' && typeof part.text === 'string' && part.text !== '') parts.push({ type: 'input_text', text: part.text })
172
+ else if (part?.type === 'image_url') {
173
+ const url = imageUrlOf(part)
174
+ if (url !== undefined) parts.push({ type: 'input_image', image_url: url })
175
+ }
176
+ }
177
+ if (parts.length === 0) {
178
+ const text = textOf(message?.content)
179
+ if (text !== '') parts.push({ type: 'input_text', text })
180
+ }
181
+ if (parts.length === 0) continue
182
+ input.push({ type: 'message', role: role === 'assistant' ? 'assistant' : 'user', content: parts })
183
+ }
184
+ if (typeof body.system === 'string' && body.system !== '') instructions.unshift(body.system)
185
+ const payload = {
186
+ model: body.model,
187
+ // 空对话也要有形状:用 '...' 占位,避免 input 为空被上游判非法。
188
+ input: input.length > 0 ? input : [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: '...' }] }],
189
+ stream: true,
190
+ store: false,
191
+ }
192
+ if (instructions.length > 0) payload.instructions = instructions.join('\n\n')
193
+ const tools = projectTools(body.tools, 'flat')
194
+ if (tools.length > 0) payload.tools = tools
195
+ if (body.tool_choice !== undefined) payload.tool_choice = body.tool_choice
196
+ if (typeof body.temperature === 'number' && Number.isFinite(body.temperature)) payload.temperature = body.temperature
197
+ if (Number.isSafeInteger(body.max_tokens) && body.max_tokens > 0) payload.max_output_tokens = body.max_tokens
198
+ else if (Number.isSafeInteger(body.max_completion_tokens) && body.max_completion_tokens > 0) payload.max_output_tokens = body.max_completion_tokens
199
+ if (typeof body.reasoning_effort === 'string' && body.reasoning_effort !== '') payload.reasoning = { effort: body.reasoning_effort }
200
+ return payload
201
+ }
202
+
203
+ // ── Messages(Anthropic)线 ─────────────────────────────────────────────────
204
+
205
+ /**
206
+ * chat 请求体 → Messages `{system, messages}`。
207
+ *
208
+ * ⚠️ 同角色回合必须合并:Messages 线拒绝连续两个 user 回合(工具结果与随后的
209
+ * 文本会正好落成两个),因此这里按角色压入同一回合的 content 数组。
210
+ * 工具结果走 `tool_result` 块(属于 user 回合)且排在同回合其它内容之前。
211
+ */
212
+ export function chatToMessages(body) {
213
+ const messages = repairChatPairing(body.messages)
214
+ const out = []
215
+ const systemParts = []
216
+ const push = (role, blocks) => {
217
+ const previous = out[out.length - 1]
218
+ if (previous?.role === role) previous.content.push(...blocks)
219
+ else out.push({ role, content: [...blocks] })
220
+ }
221
+ for (const message of messages) {
222
+ const role = message?.role
223
+ if (role === 'system' || role === 'developer') {
224
+ const text = textOf(message.content)
225
+ if (text !== '') systemParts.push(text)
226
+ continue
227
+ }
228
+ if (role === 'tool') {
229
+ push('user', [{
230
+ type: 'tool_result',
231
+ tool_use_id: String(message.tool_call_id ?? ''),
232
+ content: [{ type: 'text', text: textOf(message.content) || '(no output)' }],
233
+ }])
234
+ continue
235
+ }
236
+ const blocks = []
237
+ if (role === 'assistant') {
238
+ const text = textOf(message.content)
239
+ if (text !== '') blocks.push({ type: 'text', text })
240
+ for (const call of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
241
+ let input = {}
242
+ try { input = JSON.parse(argumentsOf(call)) } catch { input = {} }
243
+ blocks.push({ type: 'tool_use', id: String(call?.id ?? ''), name: String(call?.function?.name ?? ''), input })
244
+ }
245
+ } else {
246
+ for (const part of Array.isArray(message?.content) ? message.content : []) {
247
+ if (typeof part === 'string') { if (part !== '') blocks.push({ type: 'text', text: part }); continue }
248
+ if (part?.type === 'text' && typeof part.text === 'string' && part.text !== '') blocks.push({ type: 'text', text: part.text })
249
+ else if (part?.type === 'image_url') {
250
+ const image = claudeImageBlock(imageUrlOf(part))
251
+ if (image !== undefined) blocks.push(image)
252
+ }
253
+ }
254
+ if (blocks.length === 0) {
255
+ const text = textOf(message?.content)
256
+ if (text !== '') blocks.push({ type: 'text', text })
257
+ }
258
+ }
259
+ if (blocks.length === 0) continue
260
+ push(role === 'assistant' ? 'assistant' : 'user', blocks)
261
+ }
262
+ if (typeof body.system === 'string' && body.system !== '') systemParts.unshift(body.system)
263
+ const payload = {
264
+ model: body.model,
265
+ messages: out.length > 0 ? out : [{ role: 'user', content: [{ type: 'text', text: '...' }] }],
266
+ stream: true,
267
+ max_tokens: Number.isSafeInteger(body.max_tokens) && body.max_tokens > 0 ? body.max_tokens
268
+ : Number.isSafeInteger(body.max_completion_tokens) && body.max_completion_tokens > 0 ? body.max_completion_tokens
269
+ : 32000,
270
+ }
271
+ if (systemParts.length > 0) payload.system = systemParts.join('\n\n')
272
+ const tools = projectTools(body.tools, 'claude')
273
+ if (tools.length > 0) payload.tools = tools
274
+ if (body.tool_choice !== undefined) payload.tool_choice = typeof body.tool_choice === 'string' && body.tool_choice === 'auto'
275
+ ? { type: 'auto' }
276
+ : body.tool_choice
277
+ if (typeof body.temperature === 'number' && Number.isFinite(body.temperature)) payload.temperature = body.temperature
278
+ return payload
279
+ }
280
+
281
+ // ── 响应侧:两条线的事件 → OpenAI chat chunk ──────────────────────────────────
282
+
283
+ /** 一条流的还原状态:chunk id、模型名、工具槽位、是否出过工具调用、是否已收尾。 */
284
+ export function createDecoder(model, renameMap) {
285
+ return {
286
+ model,
287
+ renameMap,
288
+ id: '',
289
+ created: Math.floor(Date.now() / 1000),
290
+ sentRole: false,
291
+ toolSlots: new Map(),
292
+ sawToolCall: false,
293
+ usage: null,
294
+ finish: null,
295
+ done: false,
296
+ }
297
+ }
298
+
299
+ /** 首个 chunk 之前补一条 role 帧(多数客户端按 role 帧判定流已开始)。 */
300
+ function roleChunk(ctx) {
301
+ if (ctx.sentRole) return null
302
+ ctx.sentRole = true
303
+ return chunk(ctx, [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }])
304
+ }
305
+
306
+ function chunk(ctx, choices, usage) {
307
+ const out = {
308
+ id: ctx.id !== '' ? ctx.id : `omr-opencode-${Date.now().toString(36)}`,
309
+ object: 'chat.completion.chunk',
310
+ created: ctx.created,
311
+ model: ctx.model,
312
+ choices,
313
+ }
314
+ if (usage !== null && usage !== undefined) out.usage = usage
315
+ return out
316
+ }
317
+
318
+ function deltaContent(ctx, text) {
319
+ if (text === undefined || text === null || text === '') return null
320
+ const first = roleChunk(ctx)
321
+ const body = chunk(ctx, [{ index: 0, delta: { content: text }, finish_reason: null }])
322
+ return first === null ? [body] : [first, body]
323
+ }
324
+
325
+ function deltaReasoning(ctx, text) {
326
+ if (text === undefined || text === null || text === '') return null
327
+ const first = roleChunk(ctx)
328
+ const body = chunk(ctx, [{ index: 0, delta: { reasoning_content: text }, finish_reason: null }])
329
+ return first === null ? [body] : [first, body]
330
+ }
331
+
332
+ function toolStart(ctx, call, name) {
333
+ const slot = ctx.toolSlots.size
334
+ const wire = typeof name === 'string' ? name : ''
335
+ const restored = restoreToolName(wire, ctx.renameMap)
336
+ ctx.sawToolCall = true
337
+ const first = roleChunk(ctx)
338
+ const body = chunk(ctx, [{
339
+ index: 0,
340
+ delta: {
341
+ tool_calls: [{
342
+ index: slot,
343
+ id: call?.id ?? `call_${Math.random().toString(36).slice(2, 10)}`,
344
+ type: 'function',
345
+ function: { name: restored === '' ? wire : restored, arguments: '' },
346
+ }],
347
+ },
348
+ finish_reason: null,
349
+ }])
350
+ return { frames: first === null ? [body] : [first, body], index: slot }
351
+ }
352
+
353
+ function toolArgs(ctx, index, partial) {
354
+ if (typeof index !== 'number' || partial === undefined || partial === '') return null
355
+ return [chunk(ctx, [{ index: 0, delta: { tool_calls: [{ index, function: { arguments: partial } }] }, finish_reason: null }])]
356
+ }
357
+
358
+ /** 统一成帧数组(null / 单帧 / 多帧都归一,方便调用方一次性 emit)。 */
359
+ function framesOf(value) {
360
+ if (value === null || value === undefined) return null
361
+ return Array.isArray(value) ? value : [value]
362
+ }
363
+
364
+ /** 收尾:finish_reason + usage 帧(usage 单独一帧,choices 为空,OpenAI 口径);重复调用只出一次。 */
365
+ export function terminalFrames(ctx, finish, usage) {
366
+ if (ctx.done) return null
367
+ ctx.done = true
368
+ const frames = [chunk(ctx, [{ index: 0, delta: {}, finish_reason: finish ?? (ctx.sawToolCall ? 'tool_calls' : 'stop') }])]
369
+ if (usage) frames.push(chunk(ctx, [], usage))
370
+ return frames
371
+ }
372
+
373
+ /** 归一化用量(三线的字段名各不相同 → OpenAI 口径)。 */
374
+ function usageObject(input, output, cached, reasoning) {
375
+ if (input === undefined && output === undefined) return null
376
+ const prompt = Number(input) || 0
377
+ const completion = Number(output) || 0
378
+ return {
379
+ prompt_tokens: prompt,
380
+ completion_tokens: completion,
381
+ total_tokens: prompt + completion,
382
+ ...(Number(cached) > 0 ? { prompt_tokens_details: { cached_tokens: Number(cached) } } : {}),
383
+ ...(Number(reasoning) > 0 ? { completion_tokens_details: { reasoning_tokens: Number(reasoning) } } : {}),
384
+ }
385
+ }
386
+
387
+ // ── Responses 事件还原 ──────────────────────────────────────────────────────
388
+
389
+ /**
390
+ * Responses 线事件 → chat chunk 数组。返回 null 表示该事件无对外可见内容。
391
+ * 错误事件(`response.failed` / `{type:'error'}`)由调用方处理:这里抛出,
392
+ * 让门面按普通失败分类(换候选/退避)。
393
+ */
394
+ export function decodeResponsesEvent(ctx, event) {
395
+ const type = typeof event?.type === 'string' ? event.type : ''
396
+ if (type === 'response.created' || type === 'response.in_progress') {
397
+ const id = event?.response?.id
398
+ if (typeof id === 'string' && id !== '') ctx.id = id
399
+ return null
400
+ }
401
+ if (type === 'response.output_item.added') {
402
+ const item = event?.item
403
+ if (item?.type === 'function_call') {
404
+ const key = String(event.output_index ?? event.item_index ?? ctx.toolSlots.size)
405
+ const started = toolStart(ctx, { id: String(item.call_id ?? item.id ?? '') }, String(item.name ?? ''))
406
+ ctx.toolSlots.set(key, started.index)
407
+ return started.frames
408
+ }
409
+ return null
410
+ }
411
+ if (type === 'response.output_text.delta') return framesOf(deltaContent(ctx, event.delta))
412
+ if (type === 'response.reasoning_summary_text.delta' || type === 'response.output_reasoning.text.delta') return framesOf(deltaReasoning(ctx, event.delta))
413
+ if (type === 'response.function_call_arguments.delta') {
414
+ const key = String(event.output_index ?? event.item_index ?? '')
415
+ const slot = ctx.toolSlots.has(key) ? ctx.toolSlots.get(key) : 0
416
+ return framesOf(toolArgs(ctx, slot, event.delta))
417
+ }
418
+ if (type === 'response.completed' || type === 'response.incomplete' || type === 'response.failed' || type === 'response.done') {
419
+ const response = event?.response ?? {}
420
+ if (type === 'response.failed' && response.error) {
421
+ throw { kind: 'server', retryable: true, message: `上游响应失败: ${response.error?.message ?? JSON.stringify(response.error)}` }
422
+ }
423
+ const usage = usageObject(
424
+ response.usage?.input_tokens,
425
+ response.usage?.output_tokens,
426
+ response.usage?.input_tokens_details?.cached_tokens,
427
+ response.usage?.output_tokens_details?.reasoning_tokens,
428
+ )
429
+ if (ctx.usage === null) ctx.usage = usage
430
+ const incomplete = response.incomplete_details?.reason
431
+ const status = response.status ?? (type === 'response.failed' ? 'failed' : type === 'response.incomplete' ? 'incomplete' : 'completed')
432
+ ctx.finish = incomplete === 'max_output_tokens' ? 'length'
433
+ : status !== 'completed' ? 'stop'
434
+ : ctx.sawToolCall ? 'tool_calls' : 'stop'
435
+ return terminalFrames(ctx, ctx.finish, ctx.usage)
436
+ }
437
+ if (type === 'error' || event?.error) {
438
+ throw { kind: 'server', retryable: true, message: `上游流内错误: ${event?.error?.message ?? JSON.stringify(event?.error ?? event).slice(0, 200)}` }
439
+ }
440
+ return null
441
+ }
442
+
443
+ // ── Messages 事件还原 ───────────────────────────────────────────────────────
444
+
445
+ /** Anthropic 的 stop_reason → OpenAI finish_reason。 */
446
+ const ANTHROPIC_FINISH = { end_turn: 'stop', stop_sequence: 'stop', tool_use: 'tool_calls', max_tokens: 'length' }
447
+
448
+ /**
449
+ * Messages 线事件 → chat chunk 数组。
450
+ *
451
+ * ⚠️ Anthropic 没有 `[DONE]`:`message_stop` 是唯一的正常结束标记,
452
+ * 收不到就是被截断(调用方据此判完整性)。
453
+ */
454
+ export function decodeMessagesEvent(ctx, event) {
455
+ const type = typeof event?.type === 'string' ? event.type : ''
456
+ if (type === 'message_start') {
457
+ const message = event?.message ?? {}
458
+ if (typeof message.id === 'string' && message.id !== '') ctx.id = message.id
459
+ const usage = message.usage ?? {}
460
+ ctx.inputTokens = Number(usage.input_tokens) || 0
461
+ ctx.cachedTokens = Number(usage.cache_read_input_tokens) || 0
462
+ return null
463
+ }
464
+ if (type === 'content_block_start') {
465
+ const block = event?.content_block
466
+ if (block?.type === 'tool_use') {
467
+ const started = toolStart(ctx, { id: String(block.id ?? '') }, String(block.name ?? ''))
468
+ ctx.toolSlots.set(String(event.index), started.index)
469
+ return started.frames
470
+ }
471
+ return null
472
+ }
473
+ if (type === 'content_block_delta') {
474
+ const part = event?.delta
475
+ if (part?.type === 'text_delta') return deltaContent(ctx, part.text)
476
+ if (part?.type === 'thinking_delta') return deltaReasoning(ctx, part.thinking)
477
+ if (part?.type === 'input_json_delta') {
478
+ const slot = ctx.toolSlots.has(String(event.index)) ? ctx.toolSlots.get(String(event.index)) : 0
479
+ return framesOf(toolArgs(ctx, slot, part.partial_json))
480
+ }
481
+ if (part?.type === 'signature_delta' || part?.type === 'redacted_thinking') return null
482
+ return null
483
+ }
484
+ if (type === 'message_delta') {
485
+ const stop = event?.delta?.stop_reason
486
+ const usage = event?.usage ?? {}
487
+ ctx.finish = ANTHROPIC_FINISH[stop] ?? (ctx.sawToolCall ? 'tool_calls' : 'stop')
488
+ ctx.usage = usageObject(ctx.inputTokens ?? usage.input_tokens, usage.output_tokens, ctx.cachedTokens, usage.output_tokens_details?.reasoning_tokens)
489
+ return null
490
+ }
491
+ if (type === 'message_stop') return terminalFrames(ctx, ctx.finish, ctx.usage)
492
+ if (type === 'error') {
493
+ throw { kind: 'server', retryable: true, message: `上游流内错误: ${event?.error?.message ?? JSON.stringify(event?.error ?? {}).slice(0, 200)}` }
494
+ }
495
+ return null
496
+ }