@sriinnu/fiche 0.18.0-bootstrap.0 → 0.19.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 (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +289 -0
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +115 -3
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,893 @@
1
+ /** Anthropic Messages wire compatibility for GPT models served by OpenAI Responses. */
2
+ function invalidRequest(message) {
3
+ const error = new Error(message);
4
+ error.name = 'MessagesBridgeInvalidRequest';
5
+ throw error;
6
+ }
7
+ function object(value) {
8
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
9
+ ? value
10
+ : undefined;
11
+ }
12
+ function textFromBlocks(value) {
13
+ if (value === undefined)
14
+ return '';
15
+ if (typeof value === 'string')
16
+ return value;
17
+ if (!Array.isArray(value))
18
+ invalidRequest('system must be a string or an array of text blocks');
19
+ return value.map((part) => {
20
+ const p = object(part);
21
+ if (p?.type !== 'text' || typeof p.text !== 'string') {
22
+ invalidRequest(`Unsupported system content block: ${String(p?.type ?? 'invalid')}`);
23
+ }
24
+ return p.text;
25
+ }).join('\n');
26
+ }
27
+ function imageUrl(source) {
28
+ const s = object(source);
29
+ if (s?.type === 'base64' && typeof s.media_type === 'string' && typeof s.data === 'string') {
30
+ return `data:${s.media_type};base64,${s.data}`;
31
+ }
32
+ if (s?.type === 'url' && typeof s.url === 'string' && /^https?:\/\//.test(s.url))
33
+ return s.url;
34
+ return undefined;
35
+ }
36
+ /** Mirrors isGpt5Family in src/core/openai.ts: only the GPT-5 family accepts
37
+ * detail:'original'; every other upstream (Workers AI, GPT-4o, …) validates
38
+ * detail against 'auto'|'low'|'high' and 400s on 'original'. */
39
+ function imageDetailFor(model) {
40
+ return typeof model === 'string' && /^gpt-5/i.test(model) ? 'original' : 'high';
41
+ }
42
+ function inputParts(content, location = 'message', role = 'user', imageDetail = 'high') {
43
+ // Responses requires assistant-role message text to be `output_text`;
44
+ // `input_text` is only valid for user/system. Emitting input_text under
45
+ // role:"assistant" (any replayed assistant turn) is a 400.
46
+ const textType = role === 'assistant' ? 'output_text' : 'input_text';
47
+ if (typeof content === 'string')
48
+ return [{ type: textType, text: content }];
49
+ if (!Array.isArray(content))
50
+ invalidRequest(`${location} content must be a string or an array`);
51
+ const out = [];
52
+ for (const raw of content) {
53
+ const part = object(raw);
54
+ if (part?.type === 'text' && typeof part.text === 'string') {
55
+ out.push({ type: textType, text: part.text });
56
+ }
57
+ else if (part?.type === 'image') {
58
+ const image_url = imageUrl(part.source);
59
+ if (!image_url)
60
+ invalidRequest(`Unsupported ${location} image source`);
61
+ out.push({ type: 'input_image', image_url, detail: imageDetail });
62
+ }
63
+ else {
64
+ invalidRequest(`Unsupported ${location} content block: ${String(part?.type ?? 'invalid')}`);
65
+ }
66
+ }
67
+ return out;
68
+ }
69
+ function functionOutput(content, isError, imageDetail = 'high') {
70
+ if (typeof content === 'string') {
71
+ return isError
72
+ ? [{ type: 'input_text', text: '[Tool execution failed]' }, { type: 'input_text', text: content }]
73
+ : content;
74
+ }
75
+ if (!Array.isArray(content)) {
76
+ const rendered = JSON.stringify(content ?? '');
77
+ return isError
78
+ ? [{ type: 'input_text', text: '[Tool execution failed]' }, { type: 'input_text', text: rendered }]
79
+ : rendered;
80
+ }
81
+ const pieces = [];
82
+ if (isError)
83
+ pieces.push({ type: 'input_text', text: '[Tool execution failed]' });
84
+ for (const raw of content) {
85
+ const part = object(raw);
86
+ if (part?.type === 'text' && typeof part.text === 'string') {
87
+ pieces.push({ type: 'input_text', text: part.text });
88
+ }
89
+ else if (part?.type === 'image') {
90
+ const image_url = imageUrl(part.source);
91
+ if (!image_url)
92
+ invalidRequest('Unsupported tool_result image source');
93
+ pieces.push({ type: 'input_image', image_url, detail: imageDetail });
94
+ }
95
+ else {
96
+ invalidRequest(`Unsupported tool_result content block: ${String(part?.type ?? 'invalid')}`);
97
+ }
98
+ }
99
+ if (pieces.length === 1 && pieces[0]?.type === 'input_text' && !isError) {
100
+ return String(pieces[0].text ?? '');
101
+ }
102
+ return pieces;
103
+ }
104
+ function reasoningEffort(value) {
105
+ const thinking = object(value);
106
+ if (thinking?.type !== 'enabled')
107
+ return undefined;
108
+ const budget = typeof thinking.budget_tokens === 'number' ? thinking.budget_tokens : 0;
109
+ if (budget >= 32000)
110
+ return 'high';
111
+ if (budget >= 8000)
112
+ return 'medium';
113
+ return 'low';
114
+ }
115
+ function supportsReasoningEffort(model) {
116
+ return typeof model === 'string' && /^(?:(?:openai\/)?(?:gpt-[56]|o[134](?:-|$)|codex))/i.test(model.trim());
117
+ }
118
+ function mapToolChoice(value) {
119
+ const choice = object(value);
120
+ if (!choice || typeof choice.type !== 'string')
121
+ return value;
122
+ if (choice.type === 'auto' || choice.type === 'none')
123
+ return choice.type;
124
+ if (choice.type === 'any')
125
+ return 'required';
126
+ if (choice.type === 'tool' && typeof choice.name === 'string') {
127
+ return { type: 'function', name: choice.name };
128
+ }
129
+ return value;
130
+ }
131
+ /** Convert a Claude Code Messages request into an OpenAI Responses request. */
132
+ export function anthropicMessagesToOpenAIResponses(body) {
133
+ const req = JSON.parse(new TextDecoder().decode(body));
134
+ const imageDetail = imageDetailFor(req.model);
135
+ const input = [];
136
+ if (Array.isArray(req.messages)) {
137
+ for (const rawMessage of req.messages) {
138
+ const message = object(rawMessage);
139
+ if (!message
140
+ || (message.role !== 'user' && message.role !== 'assistant' && message.role !== 'system')) {
141
+ invalidRequest('Each message must have a user, assistant, or system role');
142
+ }
143
+ // Newer Claude Code builds inject system-role messages mid-conversation
144
+ // (e.g. system reminders); map them to Responses system input items.
145
+ if (message.role === 'system') {
146
+ const text = textFromBlocks(message.content);
147
+ if (text)
148
+ input.push({ role: 'system', content: [{ type: 'input_text', text }] });
149
+ continue;
150
+ }
151
+ const content = message.content;
152
+ if (!Array.isArray(content)) {
153
+ const ordinary = inputParts(content, `${String(message.role)} message`, String(message.role), imageDetail);
154
+ if (ordinary.length)
155
+ input.push({ role: message.role, content: ordinary });
156
+ continue;
157
+ }
158
+ let ordinary = [];
159
+ const flushOrdinary = () => {
160
+ if (ordinary.length)
161
+ input.push({ role: message.role, content: ordinary });
162
+ ordinary = [];
163
+ };
164
+ for (const rawPart of content) {
165
+ const part = object(rawPart);
166
+ if (message.role === 'assistant' && part?.type === 'tool_use'
167
+ && typeof part.id === 'string' && typeof part.name === 'string') {
168
+ flushOrdinary();
169
+ input.push({
170
+ type: 'function_call',
171
+ call_id: part.id,
172
+ name: part.name,
173
+ arguments: JSON.stringify(part.input ?? {}),
174
+ });
175
+ }
176
+ else if (message.role === 'user' && part?.type === 'tool_result'
177
+ && typeof part.tool_use_id === 'string') {
178
+ flushOrdinary();
179
+ input.push({
180
+ type: 'function_call_output',
181
+ call_id: part.tool_use_id,
182
+ output: functionOutput(part.content, part.is_error === true, imageDetail),
183
+ });
184
+ }
185
+ else if (message.role === 'assistant'
186
+ && (part?.type === 'thinking' || part?.type === 'redacted_thinking')) {
187
+ continue;
188
+ }
189
+ else {
190
+ ordinary.push(...inputParts([rawPart], `${String(message.role)} message`, String(message.role), imageDetail));
191
+ }
192
+ }
193
+ flushOrdinary();
194
+ }
195
+ }
196
+ else
197
+ invalidRequest('messages must be an array');
198
+ const out = { model: req.model, input };
199
+ const instructions = textFromBlocks(req.system);
200
+ if (instructions)
201
+ out.instructions = instructions;
202
+ if (typeof req.max_tokens === 'number')
203
+ out.max_output_tokens = req.max_tokens;
204
+ for (const key of ['stream', 'temperature', 'top_p', 'metadata']) {
205
+ if (req[key] !== undefined)
206
+ out[key] = req[key];
207
+ }
208
+ const effort = reasoningEffort(req.thinking);
209
+ if (effort !== undefined && supportsReasoningEffort(req.model)) {
210
+ out.reasoning = { effort };
211
+ delete out.temperature;
212
+ delete out.top_p;
213
+ }
214
+ if (Array.isArray(req.stop_sequences))
215
+ out.stop = req.stop_sequences;
216
+ if (req.tool_choice !== undefined)
217
+ out.tool_choice = mapToolChoice(req.tool_choice);
218
+ const toolChoice = object(req.tool_choice);
219
+ out.parallel_tool_calls = toolChoice?.disable_parallel_tool_use !== true;
220
+ if (Array.isArray(req.tools)) {
221
+ out.tools = req.tools.flatMap((raw) => {
222
+ const tool = object(raw);
223
+ if (!tool || typeof tool.name !== 'string')
224
+ return [];
225
+ return [{
226
+ type: 'function',
227
+ name: tool.name,
228
+ ...(typeof tool.description === 'string' ? { description: tool.description } : {}),
229
+ parameters: tool.input_schema ?? { type: 'object', properties: {} },
230
+ }];
231
+ });
232
+ }
233
+ return new TextEncoder().encode(JSON.stringify(out));
234
+ }
235
+ function anthropicUsage(raw) {
236
+ const usage = object(raw) ?? {};
237
+ const details = object(usage.input_tokens_details);
238
+ const totalInput = typeof usage.input_tokens === 'number' ? usage.input_tokens : 0;
239
+ const cached = typeof details?.cached_tokens === 'number' ? details.cached_tokens : 0;
240
+ return {
241
+ input_tokens: Math.max(0, totalInput - cached),
242
+ output_tokens: typeof usage.output_tokens === 'number' ? usage.output_tokens : 0,
243
+ cache_creation_input_tokens: 0,
244
+ cache_read_input_tokens: cached,
245
+ };
246
+ }
247
+ function parseArguments(value, allowRawFallback = false) {
248
+ // Empty string = a no-argument tool call; treat as {} rather than throwing.
249
+ // Mirrors the Chat bridge (messages-chat-bridge.ts) and the streaming path,
250
+ // which both yield input:{} for empty args. Without this, JSON.parse('')
251
+ // throws and fails the whole turn on a benign no-arg tool call.
252
+ if (typeof value !== 'string' || value.trim() === '')
253
+ return {};
254
+ try {
255
+ return JSON.parse(value);
256
+ }
257
+ catch {
258
+ if (allowRawFallback)
259
+ return { _raw: value };
260
+ throw new Error('OpenAI returned malformed function-call arguments');
261
+ }
262
+ }
263
+ function stopReason(response, hasToolUse, sawRefusal = false) {
264
+ const raw = typeof response.stop_reason === 'string'
265
+ ? response.stop_reason
266
+ : object(response.incomplete_details)?.reason;
267
+ if (raw === 'max_output_tokens' || raw === 'max_tokens')
268
+ return 'max_tokens';
269
+ if (raw === 'content_filter' || raw === 'refusal')
270
+ return 'refusal';
271
+ if (response.status === 'incomplete')
272
+ return 'max_tokens';
273
+ if (hasToolUse)
274
+ return 'tool_use';
275
+ if (sawRefusal)
276
+ return 'refusal';
277
+ if ((raw === 'stop' || raw === 'completed') && typeof response.stop_sequence === 'string') {
278
+ return 'stop_sequence';
279
+ }
280
+ if (raw === 'stop_sequence' || raw === 'pause_turn')
281
+ return raw;
282
+ return 'end_turn';
283
+ }
284
+ function reasoningSummary(item) {
285
+ if (!Array.isArray(item.summary))
286
+ return '';
287
+ return item.summary.flatMap((raw) => {
288
+ const part = object(raw);
289
+ return typeof part?.text === 'string' ? [part.text] : [];
290
+ }).join('');
291
+ }
292
+ /** Convert one completed Responses JSON object into Anthropic Messages JSON. */
293
+ export function openAIResponseToAnthropicMessage(response, fallbackModel) {
294
+ const r = object(response) ?? {};
295
+ const truncated = r.status === 'incomplete' ||
296
+ r.stop_reason === 'max_tokens' ||
297
+ object(r.incomplete_details)?.reason === 'max_output_tokens';
298
+ const content = [];
299
+ let hasToolUse = false;
300
+ let sawRefusal = false;
301
+ let pendingReasoningSummary = '';
302
+ if (Array.isArray(r.output)) {
303
+ for (const rawItem of r.output) {
304
+ const item = object(rawItem);
305
+ if (item?.type === 'message' && Array.isArray(item.content)) {
306
+ for (const rawPart of item.content) {
307
+ const part = object(rawPart);
308
+ if ((part?.type === 'output_text' || part?.type === 'refusal') && typeof part.text === 'string') {
309
+ content.push({ type: 'text', text: part.text });
310
+ if (part.type === 'refusal')
311
+ sawRefusal = true;
312
+ }
313
+ else if (part?.type === 'refusal' && typeof part.refusal === 'string') {
314
+ content.push({ type: 'text', text: part.refusal });
315
+ sawRefusal = true;
316
+ }
317
+ }
318
+ }
319
+ else if (item?.type === 'function_call' && typeof item.name === 'string') {
320
+ hasToolUse = true;
321
+ content.push({
322
+ type: 'tool_use',
323
+ id: typeof item.call_id === 'string' ? item.call_id : String(item.id ?? ''),
324
+ name: item.name,
325
+ input: parseArguments(item.arguments, truncated),
326
+ });
327
+ }
328
+ else if (item?.type === 'reasoning') {
329
+ pendingReasoningSummary += reasoningSummary(item);
330
+ }
331
+ }
332
+ }
333
+ if (content.length === 0 && pendingReasoningSummary) {
334
+ content.push({ type: 'text', text: pendingReasoningSummary });
335
+ }
336
+ const id = typeof r.id === 'string' ? r.id.replace(/^resp_/, 'msg_') : 'msg_fiche';
337
+ return {
338
+ id,
339
+ type: 'message',
340
+ role: 'assistant',
341
+ model: typeof r.model === 'string' ? r.model : fallbackModel,
342
+ content,
343
+ stop_reason: stopReason(r, hasToolUse, sawRefusal),
344
+ stop_sequence: typeof r.stop_sequence === 'string' ? r.stop_sequence : null,
345
+ usage: anthropicUsage(r.usage),
346
+ };
347
+ }
348
+ function sse(event, data) {
349
+ return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
350
+ }
351
+ function streamEvent(event, value, state) {
352
+ let out = '';
353
+ const response = object(value.response);
354
+ const ensureStart = () => {
355
+ if (state.started)
356
+ return;
357
+ if (response) {
358
+ if (typeof response.id === 'string')
359
+ state.id = response.id.replace(/^resp_/, 'msg_');
360
+ if (typeof response.model === 'string')
361
+ state.model = response.model;
362
+ if (response.usage)
363
+ state.usage = anthropicUsage(response.usage);
364
+ }
365
+ state.started = true;
366
+ out += sse('message_start', {
367
+ type: 'message_start',
368
+ message: { id: state.id, type: 'message', role: 'assistant', model: state.model,
369
+ content: [], stop_reason: null, stop_sequence: null, usage: state.usage },
370
+ });
371
+ };
372
+ const openText = () => {
373
+ ensureStart();
374
+ if (state.textOpen)
375
+ return;
376
+ state.textIndex = state.nextIndex++;
377
+ state.textOpen = true;
378
+ out += sse('content_block_start', {
379
+ type: 'content_block_start', index: state.textIndex, content_block: { type: 'text', text: '' },
380
+ });
381
+ };
382
+ const closeText = () => {
383
+ if (!state.textOpen || state.textIndex === undefined)
384
+ return;
385
+ out += sse('content_block_stop', { type: 'content_block_stop', index: state.textIndex });
386
+ state.textOpen = false;
387
+ };
388
+ const alias = (call, key) => {
389
+ if (key)
390
+ state.callAliases.set(key, call);
391
+ };
392
+ const hydrateCall = (call, item, root) => {
393
+ if (typeof item.id === 'string')
394
+ call.itemId = item.id;
395
+ if (typeof item.call_id === 'string')
396
+ call.callId = item.call_id;
397
+ if (typeof item.name === 'string' && item.name)
398
+ call.name = item.name;
399
+ const oi = typeof root.output_index === 'number' ? root.output_index
400
+ : typeof item.output_index === 'number' ? item.output_index : undefined;
401
+ if (oi !== undefined)
402
+ call.outputIndex = oi;
403
+ alias(call, call.itemId ? `item:${call.itemId}` : undefined);
404
+ alias(call, call.callId ? `call:${call.callId}` : undefined);
405
+ alias(call, call.outputIndex !== undefined ? `output:${call.outputIndex}` : undefined);
406
+ };
407
+ const resolveCall = (root, item) => {
408
+ const itemId = typeof root.item_id === 'string' ? root.item_id
409
+ : typeof item?.id === 'string' ? item.id : undefined;
410
+ const callId = typeof root.call_id === 'string' ? root.call_id
411
+ : typeof item?.call_id === 'string' ? item.call_id : undefined;
412
+ const oi = typeof root.output_index === 'number' ? root.output_index
413
+ : typeof item?.output_index === 'number' ? item.output_index : undefined;
414
+ return (itemId ? state.callAliases.get(`item:${itemId}`) : undefined)
415
+ ?? (oi !== undefined ? state.callAliases.get(`output:${oi}`) : undefined)
416
+ ?? (callId ? state.callAliases.get(`call:${callId}`) : undefined);
417
+ };
418
+ const hasCallIdentity = (root) => typeof root.item_id === 'string'
419
+ || typeof root.call_id === 'string'
420
+ || typeof root.output_index === 'number';
421
+ const makeCall = (item, root) => {
422
+ const call = { arguments: '', started: false, stopped: false };
423
+ hydrateCall(call, item, root);
424
+ state.calls.add(call);
425
+ state.lastCall = call;
426
+ return call;
427
+ };
428
+ const startCall = (call) => {
429
+ if (call.started || !call.name)
430
+ return;
431
+ ensureStart();
432
+ closeText();
433
+ state.sawTool = true;
434
+ call.index = state.nextIndex++;
435
+ call.started = true;
436
+ out += sse('content_block_start', {
437
+ type: 'content_block_start', index: call.index,
438
+ content_block: { type: 'tool_use', id: call.callId ?? call.itemId ?? '', name: call.name, input: {} },
439
+ });
440
+ if (call.arguments)
441
+ out += sse('content_block_delta', {
442
+ type: 'content_block_delta', index: call.index,
443
+ delta: { type: 'input_json_delta', partial_json: call.arguments },
444
+ });
445
+ };
446
+ const stopCall = (call) => {
447
+ startCall(call);
448
+ if (!call.started || call.stopped || call.index === undefined)
449
+ return;
450
+ out += sse('content_block_stop', { type: 'content_block_stop', index: call.index });
451
+ call.stopped = true;
452
+ };
453
+ const reconcileArguments = (call, complete) => {
454
+ if (typeof complete !== 'string' || complete.length === 0)
455
+ return true;
456
+ if (!call.arguments) {
457
+ call.arguments = complete;
458
+ if (call.started && call.index !== undefined)
459
+ out += sse('content_block_delta', {
460
+ type: 'content_block_delta', index: call.index,
461
+ delta: { type: 'input_json_delta', partial_json: complete },
462
+ });
463
+ return true;
464
+ }
465
+ if (complete === call.arguments)
466
+ return true;
467
+ if (complete.startsWith(call.arguments)) {
468
+ const suffix = complete.slice(call.arguments.length);
469
+ call.arguments = complete;
470
+ if (suffix && call.started && call.index !== undefined)
471
+ out += sse('content_block_delta', {
472
+ type: 'content_block_delta', index: call.index,
473
+ delta: { type: 'input_json_delta', partial_json: suffix },
474
+ });
475
+ return true;
476
+ }
477
+ ensureStart();
478
+ closeText();
479
+ out += sse('error', {
480
+ type: 'error',
481
+ error: { type: 'api_error', message: 'OpenAI returned inconsistent streamed function-call arguments' },
482
+ });
483
+ state.terminated = true;
484
+ return false;
485
+ };
486
+ const terminalOutput = (terminal) => {
487
+ if (!Array.isArray(terminal.output))
488
+ return;
489
+ for (let i = 0; i < terminal.output.length; i++) {
490
+ const item = object(terminal.output[i]);
491
+ if (item?.type === 'reasoning' && !state.receivedReasoningSummaryDelta) {
492
+ state.pendingReasoningSummary += reasoningSummary(item);
493
+ }
494
+ else if (item?.type === 'function_call') {
495
+ const root = { output_index: i };
496
+ const call = resolveCall(root, item) ?? makeCall(item, root);
497
+ hydrateCall(call, item, root);
498
+ if (reconcileArguments(call, item.arguments)) {
499
+ startCall(call);
500
+ }
501
+ }
502
+ }
503
+ let hadMessage = false;
504
+ for (let i = 0; i < terminal.output.length; i++) {
505
+ const item = object(terminal.output[i]);
506
+ if (item?.type === 'message' && Array.isArray(item.content)) {
507
+ hadMessage = true;
508
+ emitReasoningSummary();
509
+ const recovered = item.content.flatMap((raw) => {
510
+ const part = object(raw);
511
+ return (part?.type === 'output_text' || part?.type === 'refusal') && typeof part.text === 'string'
512
+ ? [part.text] : [];
513
+ }).join('');
514
+ if (recovered && !state.sawTextDelta) {
515
+ openText();
516
+ state.sawTextDelta = true;
517
+ const idx = state.textIndex;
518
+ if (idx !== undefined) {
519
+ out += sse('content_block_delta', {
520
+ type: 'content_block_delta', index: idx,
521
+ delta: { type: 'text_delta', text: recovered },
522
+ });
523
+ }
524
+ }
525
+ }
526
+ }
527
+ if (!hadMessage)
528
+ emitReasoningSummary();
529
+ };
530
+ /** Emit accumulated reasoning summary as Anthropic text delta if no visible text/tools/refusals were emitted. */
531
+ const emitReasoningSummary = () => {
532
+ if (state.sawTool || state.sawRefusal || state.sawTextDelta || !state.pendingReasoningSummary)
533
+ return;
534
+ openText();
535
+ const idx = state.textIndex;
536
+ if (idx !== undefined) {
537
+ out += sse('content_block_delta', {
538
+ type: 'content_block_delta', index: idx,
539
+ delta: { type: 'text_delta', text: state.pendingReasoningSummary },
540
+ });
541
+ }
542
+ state.pendingReasoningSummary = '';
543
+ };
544
+ if (event === 'response.created' || event === 'response.in_progress')
545
+ ensureStart();
546
+ else if (event === 'response.output_text.delta' && typeof value.delta === 'string') {
547
+ openText();
548
+ state.sawTextDelta = true;
549
+ state.pendingReasoningSummary = '';
550
+ const idx = state.textIndex;
551
+ if (idx !== undefined) {
552
+ out += sse('content_block_delta', {
553
+ type: 'content_block_delta', index: idx, delta: { type: 'text_delta', text: value.delta },
554
+ });
555
+ }
556
+ }
557
+ else if (event === 'response.output_item.added') {
558
+ const item = object(value.item);
559
+ if (item?.type === 'function_call') {
560
+ const call = resolveCall(value, item) ?? makeCall(item, value);
561
+ hydrateCall(call, item, value);
562
+ startCall(call);
563
+ }
564
+ }
565
+ else if (event === 'response.function_call_arguments.delta' && typeof value.delta === 'string') {
566
+ const call = resolveCall(value) ?? (!hasCallIdentity(value) ? state.lastCall : undefined);
567
+ if (call) {
568
+ call.arguments += value.delta;
569
+ if (call.started && call.index !== undefined)
570
+ out += sse('content_block_delta', {
571
+ type: 'content_block_delta', index: call.index,
572
+ delta: { type: 'input_json_delta', partial_json: value.delta },
573
+ });
574
+ }
575
+ }
576
+ else if (event === 'response.output_item.done') {
577
+ const item = object(value.item);
578
+ if (item?.type === 'message' && Array.isArray(item.content)) {
579
+ terminalOutput({ output: [item] });
580
+ if (state.sawTextDelta)
581
+ closeText();
582
+ }
583
+ else if (item?.type === 'function_call') {
584
+ const call = resolveCall(value, item) ?? makeCall(item, value);
585
+ hydrateCall(call, item, value);
586
+ if (!reconcileArguments(call, item.arguments))
587
+ return out;
588
+ stopCall(call);
589
+ }
590
+ }
591
+ else if (event === 'response.output_text.done') {
592
+ closeText();
593
+ }
594
+ else if (event === 'response.refusal.delta' && typeof value.delta === 'string') {
595
+ openText();
596
+ state.sawRefusal = true;
597
+ state.sawTextDelta = true;
598
+ const idx = state.textIndex;
599
+ if (idx !== undefined) {
600
+ out += sse('content_block_delta', {
601
+ type: 'content_block_delta', index: idx, delta: { type: 'text_delta', text: value.delta },
602
+ });
603
+ }
604
+ }
605
+ else if (event === 'response.reasoning_summary_text.delta' && typeof value.delta === 'string') {
606
+ state.receivedReasoningSummaryDelta = true;
607
+ state.pendingReasoningSummary += value.delta;
608
+ }
609
+ else if (event === 'response.completed' || event === 'response.incomplete') {
610
+ ensureStart();
611
+ if (response)
612
+ terminalOutput(response);
613
+ emitReasoningSummary();
614
+ closeText();
615
+ for (const call of state.calls)
616
+ stopCall(call);
617
+ if (response?.usage)
618
+ state.usage = anthropicUsage(response.usage);
619
+ const reason = stopReason(response ?? {}, state.sawTool, state.sawRefusal);
620
+ out += sse('message_delta', {
621
+ type: 'message_delta', delta: {
622
+ stop_reason: reason,
623
+ stop_sequence: typeof response?.stop_sequence === 'string' ? response.stop_sequence : null,
624
+ }, usage: state.usage,
625
+ });
626
+ out += sse('message_stop', { type: 'message_stop' });
627
+ state.terminated = true;
628
+ }
629
+ else if (event === 'error' || event === 'response.failed') {
630
+ ensureStart();
631
+ closeText();
632
+ for (const call of state.calls)
633
+ stopCall(call);
634
+ const failure = object(value.error) ?? object(response?.error) ?? value;
635
+ const rawType = typeof failure.type === 'string' ? failure.type : 'api_error';
636
+ const code = typeof failure.code === 'string' ? failure.code : '';
637
+ const errorType = code === 'cyber_policy' || rawType === 'invalid_request'
638
+ ? 'invalid_request_error' : rawType;
639
+ const message = typeof failure.message === 'string' ? failure.message : code || errorType;
640
+ out += sse('error', { type: 'error', error: { type: errorType, message } });
641
+ state.terminated = true;
642
+ }
643
+ return out;
644
+ }
645
+ /** Incrementally translate Responses SSE without buffering model output. */
646
+ const MAX_SSE_BUFFER_CHARS = 4 * 1024 * 1024;
647
+ const MAX_BUFFERED_RESPONSE_BYTES = 16 * 1024 * 1024;
648
+ const SSE_PEEK_RE = /^(?:event:|data:|id:|retry:|:)/;
649
+ function concatUint8Arrays(chunks, total) {
650
+ const out = new Uint8Array(total);
651
+ let offset = 0;
652
+ for (const c of chunks) {
653
+ out.set(c, offset);
654
+ offset += c.byteLength;
655
+ }
656
+ return out;
657
+ }
658
+ function streamWithPrependedChunks(firstChunks, reader) {
659
+ let idx = 0;
660
+ return new ReadableStream({
661
+ async pull(controller) {
662
+ if (idx < firstChunks.length) {
663
+ controller.enqueue(firstChunks[idx++]);
664
+ return;
665
+ }
666
+ const next = await reader.read();
667
+ if (next.done)
668
+ controller.close();
669
+ else
670
+ controller.enqueue(next.value);
671
+ },
672
+ async cancel(reason) {
673
+ await reader.cancel(reason);
674
+ },
675
+ });
676
+ }
677
+ async function readRemainingBytes(firstChunks, reader) {
678
+ const chunks = [...firstChunks];
679
+ let total = 0;
680
+ for (const c of chunks)
681
+ total += c.byteLength;
682
+ if (total > MAX_BUFFERED_RESPONSE_BYTES) {
683
+ await reader.cancel().catch(() => { });
684
+ throw new Error('Upstream response exceeded maximum buffered size');
685
+ }
686
+ for (;;) {
687
+ const next = await reader.read();
688
+ if (next.done)
689
+ break;
690
+ total += next.value.byteLength;
691
+ if (total > MAX_BUFFERED_RESPONSE_BYTES) {
692
+ await reader.cancel().catch(() => { });
693
+ throw new Error('Upstream response exceeded maximum buffered size');
694
+ }
695
+ chunks.push(next.value);
696
+ }
697
+ return concatUint8Arrays(chunks, total);
698
+ }
699
+ export function openAIResponsesStreamToAnthropic(body, fallbackModel) {
700
+ const decoder = new TextDecoder();
701
+ const encoder = new TextEncoder();
702
+ let buffer = '';
703
+ let pendingCR = false;
704
+ const state = {
705
+ started: false, terminated: false, id: 'msg_fiche', model: fallbackModel, nextIndex: 0,
706
+ textOpen: false, sawTextDelta: false, sawTool: false, sawRefusal: false,
707
+ pendingReasoningSummary: '', receivedReasoningSummaryDelta: false,
708
+ calls: new Set(), callAliases: new Map(), usage: anthropicUsage(undefined),
709
+ };
710
+ const process = (chunk, controller, final = false) => {
711
+ if (state.terminated)
712
+ return;
713
+ let normalized = chunk;
714
+ if (pendingCR) {
715
+ normalized = '\r' + normalized;
716
+ pendingCR = false;
717
+ }
718
+ if (!final && normalized.endsWith('\r')) {
719
+ normalized = normalized.slice(0, -1);
720
+ pendingCR = true;
721
+ }
722
+ buffer += normalized.replace(/\r\n|\r/g, '\n');
723
+ let start = 0;
724
+ let end;
725
+ while ((end = buffer.indexOf('\n\n', start)) >= 0) {
726
+ const block = buffer.slice(start, end);
727
+ start = end + 2;
728
+ let event = '';
729
+ const data = [];
730
+ for (const line of block.split('\n')) {
731
+ if (line.startsWith('event:'))
732
+ event = line.slice(6).trim();
733
+ else if (line.startsWith('data:'))
734
+ data.push(line.slice(5).trimStart());
735
+ }
736
+ if (data.length === 0)
737
+ continue;
738
+ const payload = data.join('\n');
739
+ if (payload === '[DONE]')
740
+ continue;
741
+ if (state.terminated)
742
+ continue;
743
+ try {
744
+ const parsed = JSON.parse(payload);
745
+ const resolvedEvent = event || (typeof parsed.type === 'string' ? parsed.type : '');
746
+ if (!resolvedEvent)
747
+ continue;
748
+ const rendered = streamEvent(resolvedEvent, parsed, state);
749
+ if (rendered)
750
+ controller.enqueue(encoder.encode(rendered));
751
+ }
752
+ catch {
753
+ controller.enqueue(encoder.encode(sse('error', {
754
+ type: 'error', error: { type: 'api_error', message: 'OpenAI returned a malformed streaming event' },
755
+ })));
756
+ state.terminated = true;
757
+ buffer = '';
758
+ controller.terminate();
759
+ return;
760
+ }
761
+ }
762
+ buffer = start > 0 ? buffer.slice(start) : buffer;
763
+ if (!state.terminated && buffer.length > MAX_SSE_BUFFER_CHARS) {
764
+ controller.enqueue(encoder.encode(sse('error', {
765
+ type: 'error', error: { type: 'api_error', message: 'OpenAI stream event exceeded maximum size' },
766
+ })));
767
+ state.terminated = true;
768
+ buffer = '';
769
+ controller.terminate();
770
+ }
771
+ };
772
+ return body.pipeThrough(new TransformStream({
773
+ transform(chunk, controller) {
774
+ // Append before normalizing so a CRLF split across transport chunks is
775
+ // still recognized as one newline.
776
+ process(decoder.decode(chunk, { stream: true }), controller);
777
+ },
778
+ flush(controller) {
779
+ process(decoder.decode() + (pendingCR ? '\r' : '') + '\n\n', controller, true);
780
+ pendingCR = false;
781
+ if (state.started && !state.terminated) {
782
+ controller.enqueue(encoder.encode(sse('error', {
783
+ type: 'error', error: { type: 'api_error', message: 'OpenAI Responses stream ended before a terminal event' },
784
+ })));
785
+ }
786
+ },
787
+ }));
788
+ }
789
+ /** Translate a successful Responses HTTP response to the Messages wire format. */
790
+ export async function openAIResponsesToAnthropicResponse(response, fallbackModel) {
791
+ const headers = new Headers(response.headers);
792
+ headers.delete('content-length');
793
+ const contentType = (headers.get('content-type') ?? '').toLowerCase();
794
+ if (!response.ok) {
795
+ let source = {};
796
+ let fallbackMessage = response.statusText || `OpenAI request failed with status ${response.status}`;
797
+ if (response.body) {
798
+ if (contentType.includes('json')) {
799
+ const raw = object(await response.json()) ?? {};
800
+ source = object(raw.error) ?? raw;
801
+ }
802
+ else {
803
+ const text = (await response.text()).trim();
804
+ if (text)
805
+ fallbackMessage = text.slice(0, 4096);
806
+ }
807
+ }
808
+ const rawType = typeof source.type === 'string' ? source.type : 'api_error';
809
+ const code = typeof source.code === 'string' ? source.code : '';
810
+ const type = code === 'cyber_policy' || rawType === 'invalid_request'
811
+ ? 'invalid_request_error' : rawType;
812
+ const message = typeof source.message === 'string' ? source.message : code || fallbackMessage;
813
+ headers.set('content-type', 'application/json');
814
+ return new Response(JSON.stringify({ type: 'error', error: { type, message } }), {
815
+ status: response.status, statusText: response.statusText, headers,
816
+ });
817
+ }
818
+ if (!response.body)
819
+ return response;
820
+ if (contentType.includes('text/event-stream')) {
821
+ headers.set('content-type', 'text/event-stream; charset=utf-8');
822
+ return new Response(openAIResponsesStreamToAnthropic(response.body, fallbackModel), {
823
+ status: response.status, statusText: response.statusText, headers,
824
+ });
825
+ }
826
+ if (!contentType.includes('json')) {
827
+ const reader = response.body.getReader();
828
+ const peekDecoder = new TextDecoder();
829
+ const pendingChunks = [];
830
+ let pendingBytes = 0;
831
+ let peekText = '';
832
+ for (;;) {
833
+ const next = await reader.read();
834
+ if (next.done) {
835
+ const trimmed = peekText.trimStart();
836
+ if (SSE_PEEK_RE.test(trimmed)) {
837
+ headers.set('content-type', 'text/event-stream; charset=utf-8');
838
+ const replay = streamWithPrependedChunks(pendingChunks, reader);
839
+ return new Response(openAIResponsesStreamToAnthropic(replay, fallbackModel), {
840
+ status: response.status, statusText: response.statusText, headers,
841
+ });
842
+ }
843
+ if (pendingBytes === 0) {
844
+ headers.set('content-type', 'application/json');
845
+ return new Response(JSON.stringify(openAIResponseToAnthropicMessage({}, fallbackModel)), {
846
+ status: response.status, statusText: response.statusText, headers,
847
+ });
848
+ }
849
+ const bytes = concatUint8Arrays(pendingChunks, pendingBytes);
850
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
851
+ const converted = openAIResponseToAnthropicMessage(parsed, fallbackModel);
852
+ headers.set('content-type', 'application/json');
853
+ return new Response(JSON.stringify(converted), {
854
+ status: response.status, statusText: response.statusText, headers,
855
+ });
856
+ }
857
+ if (next.value.byteLength === 0)
858
+ continue;
859
+ pendingChunks.push(next.value);
860
+ pendingBytes += next.value.byteLength;
861
+ if (pendingBytes > MAX_BUFFERED_RESPONSE_BYTES) {
862
+ await reader.cancel().catch(() => { });
863
+ throw new Error('Upstream response exceeded maximum buffered size');
864
+ }
865
+ peekText += peekDecoder.decode(next.value, { stream: true });
866
+ const trimmed = peekText.trimStart();
867
+ if (trimmed.length === 0)
868
+ continue;
869
+ if (trimmed.length < 16 && !trimmed.includes('\n'))
870
+ continue;
871
+ if (SSE_PEEK_RE.test(trimmed)) {
872
+ headers.set('content-type', 'text/event-stream; charset=utf-8');
873
+ const replay = streamWithPrependedChunks(pendingChunks, reader);
874
+ return new Response(openAIResponsesStreamToAnthropic(replay, fallbackModel), {
875
+ status: response.status, statusText: response.statusText, headers,
876
+ });
877
+ }
878
+ const bytes = await readRemainingBytes(pendingChunks, reader);
879
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
880
+ const converted = openAIResponseToAnthropicMessage(parsed, fallbackModel);
881
+ headers.set('content-type', 'application/json');
882
+ return new Response(JSON.stringify(converted), {
883
+ status: response.status, statusText: response.statusText, headers,
884
+ });
885
+ }
886
+ }
887
+ const converted = openAIResponseToAnthropicMessage(await response.json(), fallbackModel);
888
+ headers.set('content-type', 'application/json');
889
+ return new Response(JSON.stringify(converted), {
890
+ status: response.status, statusText: response.statusText, headers,
891
+ });
892
+ }
893
+ //# sourceMappingURL=messages-responses-bridge.js.map