@maplezzk/llm-proxy 0.1.0

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 (153) hide show
  1. package/README.md +85 -0
  2. package/bin/llm-proxy.js +17 -0
  3. package/dist/adapter/handlers.d.ts +5 -0
  4. package/dist/adapter/handlers.d.ts.map +1 -0
  5. package/dist/adapter/handlers.js +61 -0
  6. package/dist/adapter/handlers.js.map +1 -0
  7. package/dist/adapter/router.d.ts +12 -0
  8. package/dist/adapter/router.d.ts.map +1 -0
  9. package/dist/adapter/router.js +40 -0
  10. package/dist/adapter/router.js.map +1 -0
  11. package/dist/api/admin/app.d.ts +2 -0
  12. package/dist/api/admin/app.d.ts.map +1 -0
  13. package/dist/api/admin/app.js +35 -0
  14. package/dist/api/admin/app.js.map +1 -0
  15. package/dist/api/admin/components/adapters.d.ts +33 -0
  16. package/dist/api/admin/components/adapters.d.ts.map +1 -0
  17. package/dist/api/admin/components/adapters.js +144 -0
  18. package/dist/api/admin/components/adapters.js.map +1 -0
  19. package/dist/api/admin/components/capture.d.ts +23 -0
  20. package/dist/api/admin/components/capture.d.ts.map +1 -0
  21. package/dist/api/admin/components/capture.js +198 -0
  22. package/dist/api/admin/components/capture.js.map +1 -0
  23. package/dist/api/admin/components/dashboard.d.ts +14 -0
  24. package/dist/api/admin/components/dashboard.d.ts.map +1 -0
  25. package/dist/api/admin/components/dashboard.js +48 -0
  26. package/dist/api/admin/components/dashboard.js.map +1 -0
  27. package/dist/api/admin/components/logs.d.ts +24 -0
  28. package/dist/api/admin/components/logs.d.ts.map +1 -0
  29. package/dist/api/admin/components/logs.js +89 -0
  30. package/dist/api/admin/components/logs.js.map +1 -0
  31. package/dist/api/admin/components/providers.d.ts +33 -0
  32. package/dist/api/admin/components/providers.d.ts.map +1 -0
  33. package/dist/api/admin/components/providers.js +165 -0
  34. package/dist/api/admin/components/providers.js.map +1 -0
  35. package/dist/api/admin/components/proxy-key.d.ts +10 -0
  36. package/dist/api/admin/components/proxy-key.d.ts.map +1 -0
  37. package/dist/api/admin/components/proxy-key.js +34 -0
  38. package/dist/api/admin/components/proxy-key.js.map +1 -0
  39. package/dist/api/admin/components/test-panel.d.ts +14 -0
  40. package/dist/api/admin/components/test-panel.d.ts.map +1 -0
  41. package/dist/api/admin/components/test-panel.js +58 -0
  42. package/dist/api/admin/components/test-panel.js.map +1 -0
  43. package/dist/api/admin/store.d.ts +2 -0
  44. package/dist/api/admin/store.d.ts.map +1 -0
  45. package/dist/api/admin/store.js +86 -0
  46. package/dist/api/admin/store.js.map +1 -0
  47. package/dist/api/admin/types.d.ts +41 -0
  48. package/dist/api/admin/types.d.ts.map +1 -0
  49. package/dist/api/admin/types.js +2 -0
  50. package/dist/api/admin/types.js.map +1 -0
  51. package/dist/api/admin-app.js +5 -0
  52. package/dist/api/admin-ui.html +799 -0
  53. package/dist/api/handlers/adapter-crud.d.ts +7 -0
  54. package/dist/api/handlers/adapter-crud.d.ts.map +1 -0
  55. package/dist/api/handlers/adapter-crud.js +118 -0
  56. package/dist/api/handlers/adapter-crud.js.map +1 -0
  57. package/dist/api/handlers/base.d.ts +15 -0
  58. package/dist/api/handlers/base.d.ts.map +1 -0
  59. package/dist/api/handlers/base.js +103 -0
  60. package/dist/api/handlers/base.js.map +1 -0
  61. package/dist/api/handlers/index.d.ts +7 -0
  62. package/dist/api/handlers/index.d.ts.map +1 -0
  63. package/dist/api/handlers/index.js +9 -0
  64. package/dist/api/handlers/index.js.map +1 -0
  65. package/dist/api/handlers/model-handlers.d.ts +7 -0
  66. package/dist/api/handlers/model-handlers.d.ts.map +1 -0
  67. package/dist/api/handlers/model-handlers.js +239 -0
  68. package/dist/api/handlers/model-handlers.js.map +1 -0
  69. package/dist/api/handlers/provider-crud.d.ts +6 -0
  70. package/dist/api/handlers/provider-crud.d.ts.map +1 -0
  71. package/dist/api/handlers/provider-crud.js +106 -0
  72. package/dist/api/handlers/provider-crud.js.map +1 -0
  73. package/dist/api/handlers.d.ts +16 -0
  74. package/dist/api/handlers.d.ts.map +1 -0
  75. package/dist/api/handlers.js +45 -0
  76. package/dist/api/handlers.js.map +1 -0
  77. package/dist/api/server.d.ts +26 -0
  78. package/dist/api/server.d.ts.map +1 -0
  79. package/dist/api/server.js +114 -0
  80. package/dist/api/server.js.map +1 -0
  81. package/dist/cli/commands.d.ts +15 -0
  82. package/dist/cli/commands.d.ts.map +1 -0
  83. package/dist/cli/commands.js +165 -0
  84. package/dist/cli/commands.js.map +1 -0
  85. package/dist/config/parser.d.ts +4 -0
  86. package/dist/config/parser.d.ts.map +1 -0
  87. package/dist/config/parser.js +75 -0
  88. package/dist/config/parser.js.map +1 -0
  89. package/dist/config/store.d.ts +16 -0
  90. package/dist/config/store.d.ts.map +1 -0
  91. package/dist/config/store.js +59 -0
  92. package/dist/config/store.js.map +1 -0
  93. package/dist/config/types.d.ts +72 -0
  94. package/dist/config/types.d.ts.map +1 -0
  95. package/dist/config/types.js +2 -0
  96. package/dist/config/types.js.map +1 -0
  97. package/dist/config/validator.d.ts +3 -0
  98. package/dist/config/validator.d.ts.map +1 -0
  99. package/dist/config/validator.js +109 -0
  100. package/dist/config/validator.js.map +1 -0
  101. package/dist/index.d.ts +3 -0
  102. package/dist/index.d.ts.map +1 -0
  103. package/dist/index.js +68 -0
  104. package/dist/index.js.map +1 -0
  105. package/dist/lib/http-utils.d.ts +4 -0
  106. package/dist/lib/http-utils.d.ts.map +1 -0
  107. package/dist/lib/http-utils.js +21 -0
  108. package/dist/lib/http-utils.js.map +1 -0
  109. package/dist/log/logger.d.ts +31 -0
  110. package/dist/log/logger.d.ts.map +1 -0
  111. package/dist/log/logger.js +170 -0
  112. package/dist/log/logger.js.map +1 -0
  113. package/dist/proxy/capture.d.ts +28 -0
  114. package/dist/proxy/capture.d.ts.map +1 -0
  115. package/dist/proxy/capture.js +49 -0
  116. package/dist/proxy/capture.js.map +1 -0
  117. package/dist/proxy/handlers.d.ts +6 -0
  118. package/dist/proxy/handlers.d.ts.map +1 -0
  119. package/dist/proxy/handlers.js +30 -0
  120. package/dist/proxy/handlers.js.map +1 -0
  121. package/dist/proxy/pipeline.d.ts +32 -0
  122. package/dist/proxy/pipeline.d.ts.map +1 -0
  123. package/dist/proxy/pipeline.js +120 -0
  124. package/dist/proxy/pipeline.js.map +1 -0
  125. package/dist/proxy/provider.d.ts +21 -0
  126. package/dist/proxy/provider.d.ts.map +1 -0
  127. package/dist/proxy/provider.js +231 -0
  128. package/dist/proxy/provider.js.map +1 -0
  129. package/dist/proxy/router.d.ts +4 -0
  130. package/dist/proxy/router.d.ts.map +1 -0
  131. package/dist/proxy/router.js +20 -0
  132. package/dist/proxy/router.js.map +1 -0
  133. package/dist/proxy/stream-converter.d.ts +16 -0
  134. package/dist/proxy/stream-converter.d.ts.map +1 -0
  135. package/dist/proxy/stream-converter.js +1050 -0
  136. package/dist/proxy/stream-converter.js.map +1 -0
  137. package/dist/proxy/translation.d.ts +23 -0
  138. package/dist/proxy/translation.d.ts.map +1 -0
  139. package/dist/proxy/translation.js +913 -0
  140. package/dist/proxy/translation.js.map +1 -0
  141. package/dist/proxy/types.d.ts +8 -0
  142. package/dist/proxy/types.d.ts.map +1 -0
  143. package/dist/proxy/types.js +2 -0
  144. package/dist/proxy/types.js.map +1 -0
  145. package/dist/status/token-tracker.d.ts +24 -0
  146. package/dist/status/token-tracker.d.ts.map +1 -0
  147. package/dist/status/token-tracker.js +65 -0
  148. package/dist/status/token-tracker.js.map +1 -0
  149. package/dist/status/tracker.d.ts +14 -0
  150. package/dist/status/tracker.d.ts.map +1 -0
  151. package/dist/status/tracker.js +44 -0
  152. package/dist/status/tracker.js.map +1 -0
  153. package/package.json +55 -0
@@ -0,0 +1,1050 @@
1
+ import { createHash } from 'node:crypto';
2
+ function newAccumulator() {
3
+ return { role: 'assistant', content: '', thinkingSignature: '', toolCalls: new Map() };
4
+ }
5
+ function ts() {
6
+ const d = new Date();
7
+ const pad = (n) => String(n).padStart(2, '0');
8
+ const ms = String(d.getMilliseconds()).padStart(3, '0');
9
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms}`;
10
+ }
11
+ /** 从 thinking 内容生成确定性伪签名 */
12
+ function makeSignature(thinkingText) {
13
+ return createHash('sha256').update(thinkingText).digest('hex').slice(0, 16);
14
+ }
15
+ // --- Anthropic SSE → OpenAI SSE ---
16
+ export async function convertAnthropicStreamToOpenAI(reader, res, logger, capture, pairId) {
17
+ const decoder = new TextDecoder();
18
+ const acc = newAccumulator();
19
+ let buffer = '';
20
+ let totalChunks = 0;
21
+ let thinkingChunks = [];
22
+ let rawLines = [];
23
+ let outLines = [];
24
+ let anthropicUsage = {};
25
+ let thinkingText = '';
26
+ let reasoningSignature = '';
27
+ const write = (data) => {
28
+ const line = JSON.stringify(data);
29
+ outLines.push(`[${ts()}] data: ${line}\n\n`);
30
+ res.write(`data: ${line}\n\n`);
31
+ };
32
+ while (true) {
33
+ const { done, value } = await reader.read();
34
+ if (done)
35
+ break;
36
+ buffer += decoder.decode(value, { stream: true });
37
+ const blocks = buffer.split('\n\n');
38
+ buffer = blocks.pop() ?? '';
39
+ totalChunks += blocks.length;
40
+ for (const block of blocks) {
41
+ if (!block.trim())
42
+ continue;
43
+ const eventLine = block.split('\n').find((l) => l.startsWith('event: '));
44
+ const dataLine = block.split('\n').find((l) => l.startsWith('data: '));
45
+ if (!dataLine)
46
+ continue;
47
+ const dataStr = dataLine.slice(6);
48
+ const eventType = eventLine?.slice(7) ?? '';
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(dataStr);
52
+ }
53
+ catch {
54
+ continue;
55
+ }
56
+ rawLines.push(`[${ts()}] data: ${dataStr}`);
57
+ const innerType = parsed?.type ?? '';
58
+ if (eventType === 'ping' || innerType === 'ping')
59
+ continue;
60
+ if (eventType === 'error' || innerType === 'error') {
61
+ write({ choices: [{ delta: { content: `\n\n[代理错误: 上游返回错误]` }, finish_reason: 'error', index: 0 }] });
62
+ continue;
63
+ }
64
+ if (eventType === 'message_start' || innerType === 'message_start') {
65
+ write({ choices: [{ delta: { role: 'assistant' }, index: 0 }] });
66
+ continue;
67
+ }
68
+ if (innerType === 'content_block_start') {
69
+ const cblock = parsed?.content_block;
70
+ if (cblock?.type === 'tool_use') {
71
+ const index = parsed?.index ?? acc.toolCalls.size;
72
+ acc.toolCalls.set(index, { id: cblock.id, type: 'function', function: { name: cblock.name, arguments: '' } });
73
+ write({ choices: [{ delta: { tool_calls: [{ index, id: cblock.id, type: 'function', function: { name: cblock.name, arguments: '' } }] }, index: 0 }] });
74
+ }
75
+ continue;
76
+ }
77
+ if (innerType === 'content_block_delta') {
78
+ const delta = parsed?.delta;
79
+ if (!delta)
80
+ continue;
81
+ const deltaType = delta.type;
82
+ if (deltaType === 'text_delta') {
83
+ acc.content += delta.text ?? '';
84
+ write({ choices: [{ delta: { content: delta.text }, index: 0 }] });
85
+ }
86
+ else if (deltaType === 'input_json_delta') {
87
+ const index = parsed?.index ?? 0;
88
+ const tc = acc.toolCalls.get(index);
89
+ const partial = delta.partial_json ?? '';
90
+ if (tc?.function)
91
+ tc.function.arguments += partial;
92
+ write({ choices: [{ delta: { tool_calls: [{ index, function: { arguments: partial } }] }, index: 0 }] });
93
+ }
94
+ else if (deltaType === 'thinking_delta') {
95
+ const chunk = delta.thinking ?? '';
96
+ thinkingChunks.push(chunk);
97
+ thinkingText += chunk;
98
+ acc.content += chunk;
99
+ write({ choices: [{ delta: { reasoning_content: chunk }, index: 0 }] });
100
+ }
101
+ else if (deltaType === 'signature_delta') {
102
+ reasoningSignature += delta.signature ?? '';
103
+ acc.thinkingSignature += delta.signature ?? '';
104
+ }
105
+ continue;
106
+ }
107
+ if (innerType === 'content_block_stop')
108
+ continue;
109
+ if (eventType === 'message_delta' || innerType === 'message_delta') {
110
+ const msgDelta = parsed?.delta;
111
+ const msgUsage = parsed?.usage;
112
+ if (msgUsage)
113
+ anthropicUsage = msgUsage;
114
+ const stopReason = msgDelta?.stop_reason;
115
+ if (stopReason) {
116
+ const finishMap = { end_turn: 'stop', max_tokens: 'length', tool_use: 'tool_calls' };
117
+ const finish = finishMap[stopReason] ?? stopReason;
118
+ const chunk = { choices: [{ delta: {}, finish_reason: finish, index: 0 }] };
119
+ if (Object.keys(anthropicUsage).length > 0) {
120
+ const usage = {
121
+ prompt_tokens: anthropicUsage.input_tokens ?? 0,
122
+ completion_tokens: anthropicUsage.output_tokens ?? 0,
123
+ total_tokens: (anthropicUsage.input_tokens ?? 0) + (anthropicUsage.output_tokens ?? 0),
124
+ };
125
+ const promptDetails = (anthropicUsage.prompt_tokens_details ?? anthropicUsage.prompt_cache_details);
126
+ if (promptDetails?.cached_tokens != null)
127
+ usage.prompt_tokens_details = { cached_tokens: promptDetails.cached_tokens };
128
+ if (anthropicUsage.prompt_cache_miss_tokens != null)
129
+ usage.prompt_cache_miss_tokens = anthropicUsage.prompt_cache_miss_tokens;
130
+ chunk.usage = usage;
131
+ }
132
+ write(chunk);
133
+ }
134
+ continue;
135
+ }
136
+ if (eventType === 'message_stop' || innerType === 'message_stop')
137
+ continue;
138
+ }
139
+ }
140
+ if (acc.thinkingSignature) {
141
+ write({ choices: [{ delta: { reasoning_signature: acc.thinkingSignature }, index: 0 }] });
142
+ }
143
+ res.write('data: [DONE]\n\n');
144
+ res.end();
145
+ logger?.log('request', `流式响应完成 (Anthropic→OpenAI)`, {
146
+ chunks: totalChunks,
147
+ textLength: acc.content.length - thinkingText.length,
148
+ thinkingLength: thinkingText.length,
149
+ thinkingChunks: thinkingChunks.length > 0 ? thinkingChunks : undefined,
150
+ toolCalls: acc.toolCalls.size,
151
+ textPreview: acc.content.slice(0, 200),
152
+ thinkingPreview: thinkingText.slice(0, 200),
153
+ rawLines: rawLines.length > 0 ? rawLines : undefined,
154
+ outLines: outLines.length > 0 ? outLines : undefined,
155
+ }, 'debug');
156
+ if (capture && pairId !== undefined) {
157
+ const sseIn = rawLines.join('\n\n');
158
+ capture.record('response-in', 'anthropic', 'anthropic', 'stream', sseIn, pairId);
159
+ capture.record('response-out', 'anthropic', 'openai', 'stream', outLines.join(''), pairId);
160
+ }
161
+ if (Object.keys(anthropicUsage).length > 0) {
162
+ return {
163
+ input_tokens: (anthropicUsage.input_tokens ?? 0),
164
+ output_tokens: (anthropicUsage.output_tokens ?? 0),
165
+ cache_read_input_tokens: anthropicUsage.cache_read_input_tokens,
166
+ cache_creation_input_tokens: anthropicUsage.cache_creation_input_tokens,
167
+ };
168
+ }
169
+ return null;
170
+ }
171
+ // --- OpenAI SSE → Anthropic SSE ---
172
+ export async function convertOpenAIStreamToAnthropic(reader, res, logger, capture, pairId) {
173
+ const decoder = new TextDecoder();
174
+ let buffer = '';
175
+ let totalText = '';
176
+ let totalChunks = 0;
177
+ let thinkingSignature = '';
178
+ let thinkingBlockStarted = false;
179
+ let thinkingBlockIndex = -1;
180
+ let thinkingText = '';
181
+ let thinkingChunks = [];
182
+ let rawLines = [];
183
+ let outLines = [];
184
+ let lastUsage = {};
185
+ const writeEvent = (eventType, data) => {
186
+ const json = JSON.stringify(data);
187
+ outLines.push(`[${ts()}] event: ${eventType}\ndata: ${json}\n\n`);
188
+ res.write(`event: ${eventType}\ndata: ${json}\n\n`);
189
+ };
190
+ let contentBlockIndex = 0;
191
+ while (true) {
192
+ const { done, value } = await reader.read();
193
+ if (done)
194
+ break;
195
+ buffer += decoder.decode(value, { stream: true });
196
+ const lines = buffer.split('\n');
197
+ buffer = lines.pop() ?? '';
198
+ for (const line of lines) {
199
+ if (!line.startsWith('data: '))
200
+ continue;
201
+ const dataStr = line.slice(6).trim();
202
+ if (dataStr === '[DONE]') {
203
+ writeEvent('message_stop', { type: 'message_stop' });
204
+ res.end();
205
+ logger?.log('request', `流式响应完成 (OpenAI→Anthropic)`, {
206
+ chunks: totalChunks,
207
+ textLength: totalText.length - thinkingText.length,
208
+ thinkingLength: thinkingText.length,
209
+ thinkingChunks: thinkingChunks.length > 0 ? thinkingChunks : undefined,
210
+ rawLines: rawLines.length > 0 ? rawLines : undefined,
211
+ outLines: outLines.length > 0 ? outLines : undefined,
212
+ textPreview: totalText.slice(0, 200),
213
+ thinkingPreview: thinkingText.slice(0, 200),
214
+ }, 'debug');
215
+ if (capture && pairId !== undefined) {
216
+ const sseIn = rawLines.join('\n\n');
217
+ capture.record('response-in', 'openai', 'openai', 'stream', sseIn, pairId);
218
+ capture.record('response-out', 'openai', 'anthropic', 'stream', outLines.join(''), pairId);
219
+ }
220
+ if (Object.keys(lastUsage).length > 0) {
221
+ return {
222
+ input_tokens: (lastUsage.input_tokens ?? 0),
223
+ output_tokens: (lastUsage.output_tokens ?? 0),
224
+ cache_read_input_tokens: lastUsage.cache_read_input_tokens,
225
+ cache_creation_input_tokens: lastUsage.cache_creation_input_tokens,
226
+ };
227
+ }
228
+ return null;
229
+ }
230
+ let parsed;
231
+ try {
232
+ parsed = JSON.parse(dataStr);
233
+ }
234
+ catch {
235
+ continue;
236
+ }
237
+ rawLines.push(`[${ts()}] data: ${dataStr}`);
238
+ const choices = parsed.choices;
239
+ if (!choices || choices.length === 0)
240
+ continue;
241
+ const choice = choices[0];
242
+ const delta = choice.delta;
243
+ const finishReason = choice.finish_reason;
244
+ // On first message: thinking (index=0) + text (index=1) per Anthropic spec
245
+ if (delta?.role === 'assistant') {
246
+ writeEvent('message_start', {
247
+ type: 'message_start',
248
+ message: { id: `msg_${Date.now()}`, type: 'message', role: 'assistant', content: [], model: '', stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } },
249
+ });
250
+ contentBlockIndex = 1;
251
+ thinkingBlockIndex = 0;
252
+ thinkingBlockStarted = true;
253
+ writeEvent('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } });
254
+ writeEvent('content_block_start', { type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } });
255
+ continue;
256
+ }
257
+ // Tool call start
258
+ const toolCalls = delta?.tool_calls;
259
+ if (toolCalls && toolCalls.length > 0) {
260
+ const tc = toolCalls[0];
261
+ if (tc.id && tc.type === 'function') {
262
+ contentBlockIndex++;
263
+ const fn = tc.function;
264
+ writeEvent('content_block_start', { type: 'content_block_start', index: contentBlockIndex, content_block: { type: 'tool_use', id: tc.id, name: fn?.name ?? '', input: {} } });
265
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: contentBlockIndex, delta: { type: 'input_json_delta', partial_json: fn?.arguments ?? '' } });
266
+ }
267
+ else if (tc.function && tc.function.arguments) {
268
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: contentBlockIndex, delta: { type: 'input_json_delta', partial_json: tc.function.arguments } });
269
+ }
270
+ continue;
271
+ }
272
+ // reasoning_signature → signature_delta
273
+ if (delta?.reasoning_signature) {
274
+ thinkingSignature += delta.reasoning_signature;
275
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: delta.reasoning_signature } });
276
+ continue;
277
+ }
278
+ // reasoning_content → thinking_delta
279
+ if (delta?.reasoning_content) {
280
+ const chunk = delta.reasoning_content;
281
+ thinkingChunks.push(chunk);
282
+ thinkingText += chunk;
283
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: chunk } });
284
+ totalText += chunk;
285
+ totalChunks++;
286
+ continue;
287
+ }
288
+ // Regular text delta — close thinking block first per Anthropic spec
289
+ if (delta?.content) {
290
+ if (thinkingBlockStarted) {
291
+ const sig = thinkingSignature || makeSignature(thinkingText);
292
+ if (sig)
293
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: sig } });
294
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: 0 });
295
+ thinkingBlockStarted = false;
296
+ }
297
+ totalText += delta.content;
298
+ totalChunks++;
299
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: delta.content } });
300
+ continue;
301
+ }
302
+ // Finish reason
303
+ if (finishReason) {
304
+ const chunkUsage = parsed.usage;
305
+ if (chunkUsage)
306
+ lastUsage = chunkUsage;
307
+ const reasonMap = { stop: 'end_turn', length: 'max_tokens', tool_calls: 'tool_use' };
308
+ const anthropicReason = reasonMap[finishReason] ?? finishReason;
309
+ if (thinkingBlockStarted) {
310
+ const sig = thinkingSignature || makeSignature(thinkingText);
311
+ if (sig)
312
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: sig } });
313
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: 0 });
314
+ thinkingBlockStarted = false;
315
+ }
316
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: contentBlockIndex });
317
+ const usage = {
318
+ input_tokens: (lastUsage.prompt_tokens ?? lastUsage.input_tokens ?? 0),
319
+ output_tokens: (lastUsage.completion_tokens ?? lastUsage.output_tokens ?? 0),
320
+ };
321
+ const promptDetails = (lastUsage.prompt_tokens_details ?? lastUsage.prompt_cache_details);
322
+ if (promptDetails?.cached_tokens != null)
323
+ usage.cache_read_input_tokens = promptDetails.cached_tokens;
324
+ if (lastUsage.prompt_cache_miss_tokens != null)
325
+ usage.cache_creation_input_tokens = lastUsage.prompt_cache_miss_tokens;
326
+ writeEvent('message_delta', { type: 'message_delta', delta: { stop_reason: anthropicReason, stop_sequence: null }, usage });
327
+ lastUsage = usage;
328
+ continue;
329
+ }
330
+ }
331
+ }
332
+ res.end();
333
+ return null;
334
+ }
335
+ // --- OpenAI Responses SSE → Anthropic SSE ---
336
+ export async function convertOpenAIResponsesStreamToAnthropic(reader, res, logger, capture, pairId) {
337
+ const decoder = new TextDecoder();
338
+ const acc = newAccumulator();
339
+ let buffer = '';
340
+ let totalChunks = 0;
341
+ let currentBlockIndex = 0;
342
+ let currentBlockType = '';
343
+ let thinkingBlockStarted = false;
344
+ let thinkingText = '';
345
+ let thinkingSignature = '';
346
+ let thinkingChunks = [];
347
+ let rawLines = [];
348
+ let outLines = [];
349
+ let lastUsage = null;
350
+ let responsesHasToolCalls = false;
351
+ const writeEvent = (eventType, data) => {
352
+ const json = JSON.stringify(data);
353
+ outLines.push(`[${ts()}] event: ${eventType}\ndata: ${json}\n\n`);
354
+ res.write(`event: ${eventType}\ndata: ${json}\n\n`);
355
+ };
356
+ while (true) {
357
+ const { done, value } = await reader.read();
358
+ if (done)
359
+ break;
360
+ buffer += decoder.decode(value, { stream: true });
361
+ const blocks = buffer.split('\n\n');
362
+ buffer = blocks.pop() ?? '';
363
+ totalChunks += blocks.length;
364
+ for (const block of blocks) {
365
+ if (!block.trim())
366
+ continue;
367
+ const eventLine = block.split('\n').find((l) => l.startsWith('event: '));
368
+ const dataLine = block.split('\n').find((l) => l.startsWith('data: '));
369
+ if (!dataLine)
370
+ continue;
371
+ const eventType = eventLine?.slice(7) ?? '';
372
+ const dataStr = dataLine.slice(6);
373
+ let parsed;
374
+ try {
375
+ parsed = JSON.parse(dataStr);
376
+ }
377
+ catch {
378
+ continue;
379
+ }
380
+ rawLines.push(`[${ts()}] data: ${dataStr}`);
381
+ const innerType = parsed?.type ?? '';
382
+ if (innerType === 'response.created' || innerType === 'response.in_progress')
383
+ continue;
384
+ // output_item.added — message
385
+ if (innerType === 'response.output_item.added') {
386
+ const item = parsed?.item;
387
+ if (item?.type === 'message') {
388
+ currentBlockIndex = 1;
389
+ currentBlockType = 'text';
390
+ writeEvent('message_start', {
391
+ type: 'message_start',
392
+ message: { id: `msg_${Date.now()}`, type: 'message', role: 'assistant', content: [], model: '', stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } },
393
+ });
394
+ thinkingBlockStarted = true;
395
+ writeEvent('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } });
396
+ writeEvent('content_block_start', { type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } });
397
+ }
398
+ else if (item?.type === 'function_call') {
399
+ currentBlockIndex++;
400
+ currentBlockType = 'tool_use';
401
+ responsesHasToolCalls = true;
402
+ acc.toolCalls.set(currentBlockIndex, { id: item.call_id, type: 'function', function: { name: item.name, arguments: '' } });
403
+ writeEvent('content_block_start', {
404
+ type: 'content_block_start', index: currentBlockIndex,
405
+ content_block: { type: 'tool_use', id: item.call_id, name: item.name, input: {} },
406
+ });
407
+ }
408
+ continue;
409
+ }
410
+ if (innerType === 'response.content_part.added') {
411
+ const part = parsed?.part;
412
+ if (part?.type === 'output_text')
413
+ currentBlockType = 'text';
414
+ continue;
415
+ }
416
+ // output_text.delta → text_delta
417
+ if (innerType === 'response.output_text.delta') {
418
+ const delta = parsed?.delta;
419
+ if (delta) {
420
+ if (thinkingBlockStarted) {
421
+ const sig = thinkingSignature || makeSignature(thinkingText);
422
+ if (sig)
423
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: sig } });
424
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: 0 });
425
+ thinkingBlockStarted = false;
426
+ }
427
+ acc.content += delta;
428
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: delta } });
429
+ }
430
+ continue;
431
+ }
432
+ // output_text.done
433
+ if (innerType === 'response.output_text.done') {
434
+ if (thinkingBlockStarted) {
435
+ const sig = thinkingSignature || makeSignature(thinkingText);
436
+ if (sig)
437
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: sig } });
438
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: 0 });
439
+ thinkingBlockStarted = false;
440
+ }
441
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: 1 });
442
+ continue;
443
+ }
444
+ // reasoning_text.delta → thinking_delta
445
+ if (innerType === 'response.reasoning_text.delta') {
446
+ const delta = parsed?.delta;
447
+ if (delta) {
448
+ thinkingChunks.push(delta);
449
+ thinkingText += delta;
450
+ if (!thinkingBlockStarted) {
451
+ writeEvent('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } });
452
+ thinkingBlockStarted = true;
453
+ currentBlockType = 'thinking';
454
+ }
455
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: delta } });
456
+ }
457
+ continue;
458
+ }
459
+ // reasoning_text.done
460
+ if (innerType === 'response.reasoning_text.done') {
461
+ if (thinkingBlockStarted) {
462
+ const sig = thinkingSignature || makeSignature(thinkingText);
463
+ if (sig)
464
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: sig } });
465
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: 0 });
466
+ thinkingBlockStarted = false;
467
+ }
468
+ continue;
469
+ }
470
+ // function_call_arguments.delta
471
+ if (innerType === 'response.function_call_arguments.delta') {
472
+ const delta = parsed?.delta;
473
+ if (delta) {
474
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: currentBlockIndex, delta: { type: 'input_json_delta', partial_json: delta } });
475
+ }
476
+ continue;
477
+ }
478
+ if (innerType === 'response.function_call_arguments.done') {
479
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: currentBlockIndex });
480
+ continue;
481
+ }
482
+ // response.completed
483
+ if (innerType === 'response.completed' || eventType === 'response.completed') {
484
+ const resp = parsed?.response;
485
+ const status = resp?.status ?? 'completed';
486
+ const statusMap = { completed: 'end_turn', incomplete: 'max_tokens' };
487
+ let stopReason = statusMap[status] ?? 'end_turn';
488
+ // If function_calls were emitted, stop_reason should be "tool_use"
489
+ if (responsesHasToolCalls)
490
+ stopReason = 'tool_use';
491
+ const respUsage = resp?.usage;
492
+ const usage = {
493
+ input_tokens: (respUsage?.input_tokens ?? 0),
494
+ output_tokens: (respUsage?.output_tokens ?? 0),
495
+ };
496
+ lastUsage = {
497
+ input_tokens: usage.input_tokens,
498
+ output_tokens: usage.output_tokens,
499
+ };
500
+ if (thinkingBlockStarted) {
501
+ const sig = thinkingSignature || makeSignature(thinkingText);
502
+ if (sig)
503
+ writeEvent('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: sig } });
504
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: 0 });
505
+ thinkingBlockStarted = false;
506
+ }
507
+ writeEvent('content_block_stop', { type: 'content_block_stop', index: currentBlockIndex });
508
+ writeEvent('message_delta', { type: 'message_delta', delta: { stop_reason: stopReason, stop_sequence: null }, usage });
509
+ writeEvent('message_stop', { type: 'message_stop' });
510
+ res.end();
511
+ logger?.log('request', `流式响应完成 (Responses→Anthropic)`, {
512
+ chunks: totalChunks,
513
+ textLength: acc.content.length,
514
+ thinkingLength: thinkingText.length,
515
+ thinkingChunks: thinkingChunks.length > 0 ? thinkingChunks : undefined,
516
+ rawLines: rawLines.length > 0 ? rawLines : undefined,
517
+ outLines: outLines.length > 0 ? outLines : undefined,
518
+ textPreview: acc.content.slice(0, 200),
519
+ thinkingPreview: thinkingText.slice(0, 200),
520
+ }, 'debug');
521
+ if (capture && pairId !== undefined) {
522
+ const sseIn = rawLines.join('\n\n');
523
+ capture.record('response-in', 'openai-responses', 'openai-responses', 'stream', sseIn, pairId);
524
+ capture.record('response-out', 'openai-responses', 'anthropic', 'stream', outLines.join(''), pairId);
525
+ }
526
+ return lastUsage;
527
+ }
528
+ }
529
+ }
530
+ writeEvent('message_stop', { type: 'message_stop' });
531
+ res.end();
532
+ return lastUsage;
533
+ }
534
+ // --- Anthropic SSE → OpenAI Responses SSE ---
535
+ let _respIdCounter = 0;
536
+ function respId() { return `resp_${Date.now().toString(36)}_${(_respIdCounter++).toString(36)}`; }
537
+ let _msgIdCounter = 0;
538
+ function msgId() { return `msg_${Date.now().toString(36)}_${(_msgIdCounter++).toString(36)}`; }
539
+ export async function convertAnthropicStreamToOpenAIResponses(reader, res, logger, capture, pairId) {
540
+ const decoder = new TextDecoder();
541
+ const acc = newAccumulator();
542
+ let buffer = '';
543
+ let totalChunks = 0;
544
+ let currentBlockIndex = 0;
545
+ let currentBlockType = '';
546
+ let fnCallId = '';
547
+ let fnCallName = '';
548
+ let currentRespId = '';
549
+ let currentMsgId = '';
550
+ let completed = false;
551
+ let thinkingText = '';
552
+ let thinkingChunks = [];
553
+ let rawLines = [];
554
+ let outLines = [];
555
+ let anthropicUsage = {};
556
+ const makeUsage = (u) => {
557
+ if (Object.keys(u).length > 0) {
558
+ return {
559
+ input_tokens: (u.input_tokens ?? 0),
560
+ output_tokens: (u.output_tokens ?? 0),
561
+ cache_read_input_tokens: u.cache_read_input_tokens,
562
+ cache_creation_input_tokens: u.cache_creation_input_tokens,
563
+ };
564
+ }
565
+ return null;
566
+ };
567
+ const writeRaw = (data) => {
568
+ outLines.push(`[${ts()}] ${data}`);
569
+ res.write(data);
570
+ };
571
+ const processBlock = (block) => {
572
+ if (!block.trim())
573
+ return false;
574
+ const eventLine = block.split('\n').find((l) => l.startsWith('event: '));
575
+ const dataLine = block.split('\n').find((l) => l.startsWith('data: '));
576
+ if (!dataLine)
577
+ return false;
578
+ const eventType = eventLine?.slice(7) ?? '';
579
+ const dataStr = dataLine.slice(6);
580
+ let parsed;
581
+ try {
582
+ parsed = JSON.parse(dataStr);
583
+ }
584
+ catch {
585
+ return false;
586
+ }
587
+ rawLines.push(`[${ts()}] data: ${dataStr}`);
588
+ const innerType = parsed?.type ?? '';
589
+ if (eventType === 'ping' || innerType === 'ping')
590
+ return false;
591
+ if (eventType === 'message_start' || innerType === 'message_start') {
592
+ currentRespId = respId();
593
+ currentMsgId = msgId();
594
+ writeRaw(`event: response.created\ndata: {"type":"response.created","response":{"id":"${currentRespId}","object":"response","status":"in_progress","output":[]}}\n\n`);
595
+ writeRaw(`event: response.in_progress\ndata: {"type":"response.in_progress","response":{"id":"${currentRespId}","object":"response","status":"in_progress","output":[]}}\n\n`);
596
+ writeRaw(`event: response.output_item.added\ndata: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"${currentMsgId}","status":"in_progress","role":"assistant","content":[]}}\n\n`);
597
+ writeRaw(`event: response.content_part.added\ndata: {"type":"response.content_part.added","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}\n\n`);
598
+ currentBlockIndex = 0;
599
+ currentBlockType = 'text';
600
+ return false;
601
+ }
602
+ if (innerType === 'content_block_start') {
603
+ const cblock = parsed?.content_block;
604
+ if (cblock?.type === 'tool_use') {
605
+ currentBlockIndex++;
606
+ currentBlockType = 'tool_use';
607
+ fnCallId = cblock.id ?? '';
608
+ fnCallName = cblock.name ?? '';
609
+ writeRaw(`event: response.output_item.added\ndata: {"type":"response.output_item.added","output_index":${currentBlockIndex},"item":{"type":"function_call","id":"fc_${fnCallId}","call_id":"${fnCallId}","name":"${fnCallName}","arguments":""}}\n\n`);
610
+ }
611
+ return false;
612
+ }
613
+ if (innerType === 'content_block_delta') {
614
+ const delta = parsed?.delta;
615
+ if (!delta)
616
+ return false;
617
+ const deltaType = delta.type;
618
+ if (deltaType === 'text_delta') {
619
+ const text = delta.text ?? '';
620
+ acc.content += text;
621
+ writeRaw(`event: response.output_text.delta\ndata: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":${JSON.stringify(text)}}\n\n`);
622
+ }
623
+ else if (deltaType === 'input_json_delta') {
624
+ const partialJson = delta.partial_json ?? '';
625
+ writeRaw(`event: response.function_call_arguments.delta\ndata: {"type":"response.function_call_arguments.delta","output_index":${currentBlockIndex},"delta":${JSON.stringify(partialJson)}}\n\n`);
626
+ }
627
+ else if (deltaType === 'thinking_delta') {
628
+ const chunk = delta.thinking ?? '';
629
+ thinkingChunks.push(chunk);
630
+ thinkingText += chunk;
631
+ acc.content += chunk;
632
+ // Don't stream reasoning to Responses client - it doesn't track reasoning for passthrough
633
+ }
634
+ return false;
635
+ }
636
+ if (innerType === 'content_block_stop') {
637
+ if (currentBlockType === 'text') {
638
+ writeRaw(`event: response.output_text.done\ndata: {"type":"response.output_text.done","output_index":0,"content_index":0,"text":${JSON.stringify(acc.content)}}\n\n`);
639
+ }
640
+ else if (currentBlockType === 'tool_use') {
641
+ writeRaw(`event: response.function_call_arguments.done\ndata: {"type":"response.function_call_arguments.done","output_index":${currentBlockIndex},"arguments":""}\n\n`);
642
+ }
643
+ return false;
644
+ }
645
+ if (eventType === 'message_delta' || innerType === 'message_delta') {
646
+ const msgUsage = parsed?.usage;
647
+ if (msgUsage)
648
+ anthropicUsage = msgUsage;
649
+ return false;
650
+ }
651
+ if (eventType === 'message_stop' || innerType === 'message_stop') {
652
+ const respData = { id: currentRespId, object: 'response', status: 'completed', output: [] };
653
+ if (Object.keys(anthropicUsage).length > 0) {
654
+ respData.usage = { input_tokens: anthropicUsage.input_tokens ?? 0, output_tokens: anthropicUsage.output_tokens ?? 0, total_tokens: (anthropicUsage.input_tokens ?? 0) + (anthropicUsage.output_tokens ?? 0) };
655
+ }
656
+ writeRaw('event: response.completed\ndata: ' + JSON.stringify({ type: 'response.completed', response: respData }) + '\n\n');
657
+ res.end();
658
+ logger?.log('request', `流式响应完成 (Anthropic→Responses)`, {
659
+ chunks: totalChunks,
660
+ textLength: acc.content.length - thinkingText.length,
661
+ thinkingLength: thinkingText.length,
662
+ thinkingChunks: thinkingChunks.length > 0 ? thinkingChunks : undefined,
663
+ rawLines: rawLines.length > 0 ? rawLines : undefined,
664
+ outLines: outLines.length > 0 ? outLines : undefined,
665
+ textPreview: acc.content.slice(0, 200),
666
+ thinkingPreview: thinkingText.slice(0, 200),
667
+ }, 'debug');
668
+ if (capture && pairId !== undefined) {
669
+ const sseIn = rawLines.join('\n\n');
670
+ capture.record('response-in', 'anthropic', 'anthropic', 'stream', sseIn, pairId);
671
+ capture.record('response-out', 'anthropic', 'openai-responses', 'stream', outLines.join(''), pairId);
672
+ }
673
+ return true;
674
+ }
675
+ return false;
676
+ };
677
+ while (true) {
678
+ const { done, value } = await reader.read();
679
+ if (done) {
680
+ if (buffer.trim()) {
681
+ const shouldEnd = processBlock(buffer.trim());
682
+ if (shouldEnd) {
683
+ completed = true;
684
+ return makeUsage(anthropicUsage);
685
+ }
686
+ }
687
+ break;
688
+ }
689
+ buffer += decoder.decode(value, { stream: true });
690
+ const blocks = buffer.split('\n\n');
691
+ buffer = blocks.pop() ?? '';
692
+ totalChunks += blocks.length;
693
+ for (const block of blocks) {
694
+ const shouldEnd = processBlock(block);
695
+ if (shouldEnd) {
696
+ completed = true;
697
+ return makeUsage(anthropicUsage);
698
+ }
699
+ }
700
+ }
701
+ if (!completed) {
702
+ if (currentRespId) {
703
+ const respData = { id: currentRespId, object: 'response', status: 'completed', output: [] };
704
+ if (Object.keys(anthropicUsage).length > 0) {
705
+ respData.usage = { input_tokens: anthropicUsage.input_tokens ?? 0, output_tokens: anthropicUsage.output_tokens ?? 0, total_tokens: (anthropicUsage.input_tokens ?? 0) + (anthropicUsage.output_tokens ?? 0) };
706
+ }
707
+ writeRaw('event: response.completed\ndata: ' + JSON.stringify({ type: 'response.completed', response: respData }) + '\n\n');
708
+ }
709
+ res.end();
710
+ }
711
+ return makeUsage(anthropicUsage);
712
+ }
713
+ // --- OpenAI Chat SSE → OpenAI Responses SSE ---
714
+ export async function convertOpenAIStreamToOpenAIResponses(reader, res, logger, capture, pairId) {
715
+ const decoder = new TextDecoder();
716
+ let buffer = '';
717
+ let totalChunks = 0;
718
+ let rawLines = [];
719
+ let outLines = [];
720
+ let lastUsage = {};
721
+ let textContent = '';
722
+ let thinkingText = '';
723
+ let currentRespId = '';
724
+ let currentMsgId = '';
725
+ let messageStarted = false;
726
+ let currentBlockType = 'text';
727
+ let currentBlockIndex = 0;
728
+ let fnCallId = '';
729
+ let fnCallName = '';
730
+ let fnCallArgsAcc = ''; // accumulated args from deltas
731
+ let outputItems = []; // accumulated for response.completed
732
+ const writeRaw = (data) => {
733
+ outLines.push(`[${ts()}] ${data}`);
734
+ res.write(data);
735
+ };
736
+ while (true) {
737
+ const { done, value } = await reader.read();
738
+ if (done)
739
+ break;
740
+ buffer += decoder.decode(value, { stream: true });
741
+ const lines = buffer.split('\n');
742
+ buffer = lines.pop() ?? '';
743
+ for (const line of lines) {
744
+ if (!line.startsWith('data: '))
745
+ continue;
746
+ const dataStr = line.slice(6).trim();
747
+ if (dataStr === '[DONE]') {
748
+ // If output_items not yet emitted (no finish_reason before [DONE]), emit them now
749
+ if (outputItems.length === 0 && messageStarted) {
750
+ const msgContent = [];
751
+ if (thinkingText) {
752
+ // Don't include reasoning in Responses output - Responses clients don't track reasoning for passthrough
753
+ }
754
+ if (textContent) {
755
+ msgContent.push({ type: 'output_text', text: textContent, annotations: [] });
756
+ }
757
+ writeRaw(`event: response.output_item.done\ndata: {"type":"response.output_item.done","output_index":0,"item":{"id":"${currentMsgId}","type":"message","status":"completed","role":"assistant","content":${JSON.stringify(msgContent)}}}\n\n`);
758
+ outputItems.unshift({ type: 'message', id: currentMsgId, status: 'completed', role: 'assistant', content: msgContent });
759
+ }
760
+ // Close any open text block
761
+ if (messageStarted && currentBlockType === 'text') {
762
+ writeRaw(`event: response.output_text.done\ndata: {"type":"response.output_text.done","output_index":0,"content_index":0,"text":${JSON.stringify(textContent)}}\n\n`);
763
+ }
764
+ // Emit completed
765
+ const respData = { id: currentRespId, object: 'response', status: 'completed', output: outputItems.length > 0 ? outputItems : [] };
766
+ if (Object.keys(lastUsage).length > 0) {
767
+ respData.usage = { input_tokens: lastUsage.input_tokens ?? 0, output_tokens: lastUsage.output_tokens ?? 0, total_tokens: (lastUsage.input_tokens ?? 0) + (lastUsage.output_tokens ?? 0) };
768
+ }
769
+ writeRaw('event: response.completed\ndata: ' + JSON.stringify({ type: 'response.completed', response: respData }) + '\n\n');
770
+ res.end();
771
+ logger?.log('request', `流式响应完成 (OpenAI→Responses)`, {
772
+ chunks: totalChunks,
773
+ textLength: textContent.length,
774
+ thinkingLength: thinkingText.length,
775
+ rawLines: rawLines.length > 0 ? rawLines : undefined,
776
+ outLines: outLines.length > 0 ? outLines : undefined,
777
+ textPreview: textContent.slice(0, 200),
778
+ thinkingPreview: thinkingText.slice(0, 200),
779
+ }, 'debug');
780
+ if (capture && pairId !== undefined) {
781
+ const sseIn = rawLines.join('\n\n');
782
+ capture.record('response-in', 'openai', 'openai', 'stream', sseIn, pairId);
783
+ capture.record('response-out', 'openai', 'openai-responses', 'stream', outLines.join(''), pairId);
784
+ }
785
+ if (Object.keys(lastUsage).length > 0) {
786
+ return {
787
+ input_tokens: (lastUsage.input_tokens ?? 0),
788
+ output_tokens: (lastUsage.output_tokens ?? 0),
789
+ };
790
+ }
791
+ return null;
792
+ }
793
+ let parsed;
794
+ try {
795
+ parsed = JSON.parse(dataStr);
796
+ }
797
+ catch {
798
+ continue;
799
+ }
800
+ rawLines.push(`[${ts()}] data: ${dataStr}`);
801
+ totalChunks++;
802
+ const choices = parsed.choices;
803
+ if (!choices || choices.length === 0)
804
+ continue;
805
+ const choice = choices[0];
806
+ const delta = choice.delta;
807
+ const finishReason = choice.finish_reason;
808
+ const chunkUsage = parsed.usage;
809
+ // First message with role → init Responses stream
810
+ if (delta?.role === 'assistant' && !messageStarted) {
811
+ messageStarted = true;
812
+ currentRespId = respId();
813
+ currentMsgId = msgId();
814
+ writeRaw(`event: response.created\ndata: {"type":"response.created","response":{"id":"${currentRespId}","object":"response","status":"in_progress","output":[]}}\n\n`);
815
+ writeRaw(`event: response.in_progress\ndata: {"type":"response.in_progress","response":{"id":"${currentRespId}","object":"response","status":"in_progress","output":[]}}\n\n`);
816
+ writeRaw(`event: response.output_item.added\ndata: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"${currentMsgId}","status":"in_progress","role":"assistant","content":[]}}\n\n`);
817
+ writeRaw(`event: response.content_part.added\ndata: {"type":"response.content_part.added","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}\n\n`);
818
+ currentBlockIndex = 0;
819
+ currentBlockType = 'text';
820
+ continue;
821
+ }
822
+ if (!messageStarted)
823
+ continue;
824
+ // reasoning_content → skip (Responses client doesn't track reasoning for passthrough)
825
+ if (delta?.reasoning_content) {
826
+ // Still track thinkingText for output_item.done stats but don't stream to client
827
+ const chunk = delta.reasoning_content;
828
+ thinkingText += chunk;
829
+ continue;
830
+ }
831
+ // tool_calls start
832
+ if (delta?.tool_calls) {
833
+ const tc = delta.tool_calls[0];
834
+ if (tc.id && tc.type === 'function') {
835
+ currentBlockIndex++;
836
+ currentBlockType = 'tool_use';
837
+ fnCallId = tc.id;
838
+ fnCallName = tc.function?.name ?? '';
839
+ const fnArgs = tc.function?.arguments ?? '';
840
+ fnCallArgsAcc = fnArgs; // Initialize accumulator with initial arguments
841
+ writeRaw(`event: response.output_item.added\ndata: {"type":"response.output_item.added","output_index":${currentBlockIndex},"item":{"type":"function_call","id":"fc_${fnCallId}","call_id":"${fnCallId}","name":"${fnCallName}","arguments":${JSON.stringify(fnArgs)}}}\n\n`);
842
+ }
843
+ else if (tc.function && tc.function.arguments) {
844
+ const partialArgs = tc.function.arguments;
845
+ fnCallArgsAcc += partialArgs;
846
+ writeRaw(`event: response.function_call_arguments.delta\ndata: {"type":"response.function_call_arguments.delta","output_index":${currentBlockIndex},"delta":${JSON.stringify(partialArgs)}}\n\n`);
847
+ }
848
+ continue;
849
+ }
850
+ // text content
851
+ if (delta?.content) {
852
+ const chunk = delta.content;
853
+ textContent += chunk;
854
+ writeRaw(`event: response.output_text.delta\ndata: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":${JSON.stringify(chunk)}}\n\n`);
855
+ continue;
856
+ }
857
+ // Finish reason
858
+ if (finishReason) {
859
+ if (chunkUsage)
860
+ lastUsage = { input_tokens: chunkUsage.prompt_tokens ?? 0, output_tokens: chunkUsage.completion_tokens ?? 0 };
861
+ // Close text block
862
+ writeRaw(`event: response.output_text.done\ndata: {"type":"response.output_text.done","output_index":0,"content_index":0,"text":${JSON.stringify(textContent)}}\n\n`);
863
+ // Close function_call block if any
864
+ if (currentBlockType === 'tool_use') {
865
+ writeRaw(`event: response.function_call_arguments.done\ndata: {"type":"response.function_call_arguments.done","output_index":${currentBlockIndex},"arguments":${JSON.stringify(fnCallArgsAcc)}}\n\n`);
866
+ // Emit response.output_item.done for the function_call
867
+ writeRaw(`event: response.output_item.done\ndata: {"type":"response.output_item.done","output_index":${currentBlockIndex},"item":{"type":"function_call","id":"fc_${fnCallId}","call_id":"${fnCallId}","name":"${fnCallName}","arguments":${JSON.stringify(fnCallArgsAcc)},"status":"completed"}}\n\n`);
868
+ // Record for response.completed output
869
+ outputItems.push({
870
+ type: 'function_call', id: `fc_${fnCallId}`, call_id: fnCallId,
871
+ name: fnCallName, arguments: fnCallArgsAcc, status: 'completed',
872
+ });
873
+ }
874
+ // Emit response.output_item.done for the message
875
+ const msgContent = [];
876
+ // Don't include reasoning in Responses output
877
+ if (textContent) {
878
+ msgContent.push({ type: 'output_text', text: textContent, annotations: [] });
879
+ }
880
+ writeRaw(`event: response.output_item.done\ndata: {"type":"response.output_item.done","output_index":0,"item":{"id":"${currentMsgId}","type":"message","status":"completed","role":"assistant","content":${JSON.stringify(msgContent)}}}\n\n`);
881
+ outputItems.unshift({
882
+ type: 'message', id: currentMsgId, status: 'completed', role: 'assistant', content: msgContent,
883
+ });
884
+ continue;
885
+ }
886
+ }
887
+ }
888
+ // Emit completed if not already
889
+ if (messageStarted) {
890
+ if (outputItems.length === 0) {
891
+ const msgContent = [];
892
+ // Don't include reasoning in Responses output
893
+ if (textContent) {
894
+ msgContent.push({ type: 'output_text', text: textContent, annotations: [] });
895
+ }
896
+ writeRaw(`event: response.output_item.done\ndata: {"type":"response.output_item.done","output_index":0,"item":{"id":"${currentMsgId}","type":"message","status":"completed","role":"assistant","content":${JSON.stringify(msgContent)}}}\n\n`);
897
+ outputItems.unshift({ type: 'message', id: currentMsgId, status: 'completed', role: 'assistant', content: msgContent });
898
+ }
899
+ writeRaw(`event: response.output_text.done\ndata: {"type":"response.output_text.done","output_index":0,"content_index":0,"text":${JSON.stringify(textContent)}}\n\n`);
900
+ const respData = { id: currentRespId, object: 'response', status: 'completed', output: outputItems.length > 0 ? outputItems : [] };
901
+ if (Object.keys(lastUsage).length > 0) {
902
+ respData.usage = { input_tokens: lastUsage.input_tokens ?? 0, output_tokens: lastUsage.output_tokens ?? 0, total_tokens: (lastUsage.input_tokens ?? 0) + (lastUsage.output_tokens ?? 0) };
903
+ }
904
+ writeRaw('event: response.completed\ndata: ' + JSON.stringify({ type: 'response.completed', response: respData }) + '\n\n');
905
+ }
906
+ res.end();
907
+ if (Object.keys(lastUsage).length > 0) {
908
+ return { input_tokens: (lastUsage.input_tokens ?? 0), output_tokens: (lastUsage.output_tokens ?? 0) };
909
+ }
910
+ return null;
911
+ }
912
+ // --- OpenAI Responses SSE → OpenAI Chat SSE ---
913
+ export async function convertOpenAIResponsesStreamToOpenAI(reader, res, logger, capture, pairId) {
914
+ const decoder = new TextDecoder();
915
+ let buffer = '';
916
+ let totalChunks = 0;
917
+ let rawLines = [];
918
+ let outLines = [];
919
+ let lastUsage = {};
920
+ let thinkingText = '';
921
+ let currentFnCallIndex = -1;
922
+ let hasFunctionCalls = false;
923
+ let firstFnCallOutputIndex = -1;
924
+ const write = (data) => {
925
+ const line = JSON.stringify(data);
926
+ outLines.push(`[${ts()}] data: ${line}\n\n`);
927
+ res.write(`data: ${line}\n\n`);
928
+ };
929
+ while (true) {
930
+ const { done, value } = await reader.read();
931
+ if (done)
932
+ break;
933
+ buffer += decoder.decode(value, { stream: true });
934
+ const blocks = buffer.split('\n\n');
935
+ buffer = blocks.pop() ?? '';
936
+ totalChunks += blocks.length;
937
+ for (const block of blocks) {
938
+ if (!block.trim())
939
+ continue;
940
+ const eventLine = block.split('\n').find((l) => l.startsWith('event: '));
941
+ const dataLine = block.split('\n').find((l) => l.startsWith('data: '));
942
+ if (!dataLine)
943
+ continue;
944
+ const eventType = eventLine?.slice(7) ?? '';
945
+ const dataStr = dataLine.slice(6);
946
+ let parsed;
947
+ try {
948
+ parsed = JSON.parse(dataStr);
949
+ }
950
+ catch {
951
+ continue;
952
+ }
953
+ rawLines.push(`[${ts()}] data: ${dataStr}`);
954
+ const innerType = parsed?.type ?? '';
955
+ if (innerType === 'response.created' || innerType === 'response.in_progress')
956
+ continue;
957
+ // output_item.added → role delta + tool_calls start
958
+ if (innerType === 'response.output_item.added') {
959
+ const item = parsed?.item;
960
+ if (item?.type === 'message') {
961
+ write({ choices: [{ delta: { role: 'assistant' }, index: 0 }] });
962
+ }
963
+ else if (item?.type === 'function_call') {
964
+ currentFnCallIndex = (parsed?.output_index ?? 1) - 1;
965
+ if (!hasFunctionCalls) {
966
+ hasFunctionCalls = true;
967
+ firstFnCallOutputIndex = parsed?.output_index ?? 1;
968
+ }
969
+ write({ choices: [{ delta: { tool_calls: [{ index: currentFnCallIndex, id: item?.call_id ?? item?.id, type: 'function', function: { name: item?.name ?? '', arguments: item?.arguments ?? '' } }] }, index: 0 }] });
970
+ }
971
+ continue;
972
+ }
973
+ // output_text.delta → content delta
974
+ if (innerType === 'response.output_text.delta') {
975
+ const delta = parsed?.delta;
976
+ if (delta) {
977
+ write({ choices: [{ delta: { content: delta }, index: 0 }] });
978
+ }
979
+ continue;
980
+ }
981
+ // reasoning_text.delta → reasoning_content delta
982
+ if (innerType === 'response.reasoning_text.delta') {
983
+ const delta = parsed?.delta;
984
+ if (delta) {
985
+ thinkingText += delta;
986
+ write({ choices: [{ delta: { reasoning_content: delta }, index: 0 }] });
987
+ }
988
+ continue;
989
+ }
990
+ // output_text.done - nothing to emit for Chat format
991
+ if (innerType === 'response.output_text.done')
992
+ continue;
993
+ // function_call_arguments.delta
994
+ if (innerType === 'response.function_call_arguments.delta') {
995
+ const delta = parsed?.delta;
996
+ if (delta) {
997
+ write({ choices: [{ delta: { tool_calls: [{ index: currentFnCallIndex >= 0 ? currentFnCallIndex : 0, function: { arguments: delta } }] }, index: 0 }] });
998
+ }
999
+ continue;
1000
+ }
1001
+ if (innerType === 'response.function_call_arguments.done')
1002
+ continue;
1003
+ // response.completed → finish_reason + usage + [DONE]
1004
+ if (innerType === 'response.completed') {
1005
+ const resp = parsed?.response;
1006
+ const status = resp?.status ?? 'completed';
1007
+ const statusMap = { completed: 'stop', incomplete: 'length' };
1008
+ let finishReason = statusMap[status] ?? 'stop';
1009
+ // If function_calls were emitted, finish_reason should be "tool_calls"
1010
+ if (hasFunctionCalls)
1011
+ finishReason = 'tool_calls';
1012
+ const respUsage = resp?.usage;
1013
+ const finalChunk = {
1014
+ choices: [{ delta: {}, finish_reason: finishReason, index: 0 }],
1015
+ };
1016
+ if (respUsage) {
1017
+ lastUsage = {
1018
+ input_tokens: (respUsage.input_tokens ?? 0),
1019
+ output_tokens: (respUsage.output_tokens ?? 0),
1020
+ };
1021
+ finalChunk.usage = {
1022
+ prompt_tokens: respUsage.input_tokens ?? 0,
1023
+ completion_tokens: respUsage.output_tokens ?? 0,
1024
+ total_tokens: (respUsage.input_tokens ?? 0) + (respUsage.output_tokens ?? 0),
1025
+ };
1026
+ }
1027
+ write(finalChunk);
1028
+ res.write('data: [DONE]\n\n');
1029
+ res.end();
1030
+ logger?.log('request', `流式响应完成 (Responses→OpenAI)`, {
1031
+ chunks: totalChunks,
1032
+ thinkingLength: thinkingText.length,
1033
+ rawLines: rawLines.length > 0 ? rawLines : undefined,
1034
+ outLines: outLines.length > 0 ? outLines : undefined,
1035
+ thinkingPreview: thinkingText.slice(0, 200),
1036
+ }, 'debug');
1037
+ if (capture && pairId !== undefined) {
1038
+ const sseIn = rawLines.join('\n\n');
1039
+ capture.record('response-in', 'openai-responses', 'openai-responses', 'stream', sseIn, pairId);
1040
+ capture.record('response-out', 'openai-responses', 'openai', 'stream', outLines.join(''), pairId);
1041
+ }
1042
+ return Object.keys(lastUsage).length > 0 ? { input_tokens: (lastUsage.input_tokens ?? 0), output_tokens: (lastUsage.output_tokens ?? 0) } : null;
1043
+ }
1044
+ }
1045
+ }
1046
+ res.write('data: [DONE]\n\n');
1047
+ res.end();
1048
+ return Object.keys(lastUsage).length > 0 ? { input_tokens: (lastUsage.input_tokens ?? 0), output_tokens: (lastUsage.output_tokens ?? 0) } : null;
1049
+ }
1050
+ //# sourceMappingURL=stream-converter.js.map