@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,747 @@
1
+ /**
2
+ * Anthropic Messages wire compatibility for OpenAI Chat Completions upstreams.
3
+ *
4
+ * Lets Claude Code (which only speaks the Anthropic /v1/messages schema) drive
5
+ * Kimi through Cloudflare's OpenAI-compatible Chat Completions endpoint. This
6
+ * module is pure wire translation and contains no credentials.
7
+ *
8
+ * Mirrors messages-responses-bridge.ts, but targets /v1/chat/completions rather
9
+ * than the Responses API.
10
+ */
11
+ function invalidRequest(message) {
12
+ const error = new Error(message);
13
+ error.name = 'MessagesBridgeInvalidRequest';
14
+ throw error;
15
+ }
16
+ function object(value) {
17
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
18
+ ? value
19
+ : undefined;
20
+ }
21
+ function textFromBlocks(value) {
22
+ if (value === undefined)
23
+ return '';
24
+ if (typeof value === 'string')
25
+ return value;
26
+ if (!Array.isArray(value))
27
+ invalidRequest('system must be a string or an array of text blocks');
28
+ return value.map((part) => {
29
+ const p = object(part);
30
+ if (p?.type !== 'text' || typeof p.text !== 'string') {
31
+ invalidRequest(`Unsupported system content block: ${String(p?.type ?? 'invalid')}`);
32
+ }
33
+ return p.text;
34
+ }).join('\n');
35
+ }
36
+ function imageUrl(source) {
37
+ const s = object(source);
38
+ if (s?.type === 'base64' && typeof s.media_type === 'string' && typeof s.data === 'string') {
39
+ return `data:${s.media_type};base64,${s.data}`;
40
+ }
41
+ if (s?.type === 'url' && typeof s.url === 'string' && /^https?:\/\//.test(s.url))
42
+ return s.url;
43
+ return undefined;
44
+ }
45
+ /** Build Chat Completions content parts from an Anthropic content array/string. */
46
+ function contentParts(content, location) {
47
+ if (typeof content === 'string')
48
+ return 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: 'text', text: part.text });
56
+ }
57
+ else if (part?.type === 'image') {
58
+ const url = imageUrl(part.source);
59
+ if (!url)
60
+ invalidRequest(`Unsupported ${location} image source`);
61
+ out.push({ type: 'image_url', image_url: { url } });
62
+ }
63
+ else {
64
+ invalidRequest(`Unsupported ${location} content block: ${String(part?.type ?? 'invalid')}`);
65
+ }
66
+ }
67
+ // Collapse a lone text part to a plain string — the shape most providers prefer.
68
+ if (out.length === 1 && out[0]?.type === 'text')
69
+ return String(out[0].text ?? '');
70
+ return out;
71
+ }
72
+ /** Split a tool_result into text for the Chat `tool` message and visual parts
73
+ * that must be sent in a following multimodal `user` message. */
74
+ function toolResultContent(content, isError) {
75
+ const prefix = isError ? '[Tool execution failed]\n' : '';
76
+ if (typeof content === 'string')
77
+ return { text: prefix + content, images: [] };
78
+ if (!Array.isArray(content)) {
79
+ return { text: prefix + JSON.stringify(content ?? ''), images: [] };
80
+ }
81
+ const pieces = [];
82
+ const images = [];
83
+ for (const raw of content) {
84
+ const part = object(raw);
85
+ if (part?.type === 'text' && typeof part.text === 'string')
86
+ pieces.push(part.text);
87
+ else if (part?.type === 'image') {
88
+ const url = imageUrl(part.source);
89
+ if (!url)
90
+ invalidRequest('Unsupported tool_result image source');
91
+ images.push({ type: 'image_url', image_url: { url } });
92
+ }
93
+ else
94
+ pieces.push(JSON.stringify(raw ?? ''));
95
+ }
96
+ return { text: prefix + pieces.join('\n'), images };
97
+ }
98
+ /** Map Anthropic extended-thinking config to an OpenAI `reasoning_effort` bucket.
99
+ * Claude Code sends `thinking: { type: 'enabled', budget_tokens: N }`; OpenAI-
100
+ * compatible reasoning models (Kimi, etc.) take a coarse low/medium/high knob.
101
+ * We use the universal three values — Kimi also accepts `max`, but staying in
102
+ * the standard set keeps this provider-agnostic. */
103
+ function reasoningEffort(value) {
104
+ const thinking = object(value);
105
+ if (thinking?.type !== 'enabled')
106
+ return undefined;
107
+ const budget = typeof thinking.budget_tokens === 'number' ? thinking.budget_tokens : 0;
108
+ if (budget >= 32000)
109
+ return 'high';
110
+ if (budget >= 8000)
111
+ return 'medium';
112
+ return 'low';
113
+ }
114
+ function mapToolChoice(value) {
115
+ const choice = object(value);
116
+ if (!choice || typeof choice.type !== 'string')
117
+ return undefined;
118
+ if (choice.type === 'auto' || choice.type === 'none')
119
+ return choice.type;
120
+ if (choice.type === 'any')
121
+ return 'required';
122
+ if (choice.type === 'tool' && typeof choice.name === 'string') {
123
+ return { type: 'function', function: { name: choice.name } };
124
+ }
125
+ return undefined;
126
+ }
127
+ /** Convert a Claude Code Messages request into an OpenAI Chat Completions request. */
128
+ export function anthropicMessagesToOpenAIChat(body, modelOverride) {
129
+ const req = JSON.parse(new TextDecoder().decode(body));
130
+ const messages = [];
131
+ const instructions = textFromBlocks(req.system);
132
+ if (instructions)
133
+ messages.push({ role: 'system', content: instructions });
134
+ if (!Array.isArray(req.messages))
135
+ invalidRequest('messages must be an array');
136
+ for (const rawMessage of req.messages) {
137
+ const message = object(rawMessage);
138
+ if (!message
139
+ || (message.role !== 'user' && message.role !== 'assistant' && message.role !== 'system')) {
140
+ invalidRequest('Each message must have a user, assistant, or system role');
141
+ }
142
+ // Newer Claude Code builds inject system-role messages mid-conversation
143
+ // (e.g. system reminders); map them to Chat Completions system messages.
144
+ if (message.role === 'system') {
145
+ const text = textFromBlocks(message.content);
146
+ if (text)
147
+ messages.push({ role: 'system', content: text });
148
+ continue;
149
+ }
150
+ const role = message.role;
151
+ const content = message.content;
152
+ if (!Array.isArray(content)) {
153
+ const parts = contentParts(content, `${role} message`);
154
+ if (typeof parts === 'string' ? parts.length : parts.length) {
155
+ messages.push({ role, content: parts });
156
+ }
157
+ continue;
158
+ }
159
+ if (role === 'assistant') {
160
+ // Assistant turn: gather text/image into content, tool_use into tool_calls.
161
+ const ordinary = [];
162
+ const toolCalls = [];
163
+ for (const rawPart of content) {
164
+ const part = object(rawPart);
165
+ if (part?.type === 'tool_use' && typeof part.id === 'string' && typeof part.name === 'string') {
166
+ toolCalls.push({
167
+ id: part.id,
168
+ type: 'function',
169
+ function: { name: part.name, arguments: JSON.stringify(part.input ?? {}) },
170
+ });
171
+ }
172
+ else if (part?.type === 'text' && typeof part.text === 'string') {
173
+ ordinary.push({ type: 'text', text: part.text });
174
+ }
175
+ else if (part?.type === 'image') {
176
+ const url = imageUrl(part.source);
177
+ if (!url)
178
+ invalidRequest('Unsupported assistant image source');
179
+ ordinary.push({ type: 'image_url', image_url: { url } });
180
+ }
181
+ else if (part?.type === 'thinking' || part?.type === 'redacted_thinking') {
182
+ // Chat Completions has no portable representation for Anthropic's
183
+ // signed thinking history. Keep the visible answer and tool calls.
184
+ continue;
185
+ }
186
+ else {
187
+ invalidRequest(`Unsupported assistant content block: ${String(part?.type ?? 'invalid')}`);
188
+ }
189
+ }
190
+ const msg = { role: 'assistant' };
191
+ const text = ordinary.filter((p) => p.type === 'text').map((p) => String(p.text ?? '')).join('');
192
+ const hasImage = ordinary.some((p) => p.type === 'image_url');
193
+ msg.content = hasImage ? ordinary : (text || (toolCalls.length ? null : ''));
194
+ if (toolCalls.length)
195
+ msg.tool_calls = toolCalls;
196
+ messages.push(msg);
197
+ continue;
198
+ }
199
+ // User turn: emit every tool response contiguously after the assistant
200
+ // tool_calls. Chat `tool` content is text-only, so returned images move to
201
+ // the following multimodal user message with any ordinary user content.
202
+ const ordinary = [];
203
+ const toolMessages = [];
204
+ const toolImages = [];
205
+ for (const rawPart of content) {
206
+ const part = object(rawPart);
207
+ if (part?.type === 'tool_result' && typeof part.tool_use_id === 'string') {
208
+ const result = toolResultContent(part.content, part.is_error === true);
209
+ toolMessages.push({
210
+ role: 'tool',
211
+ tool_call_id: part.tool_use_id,
212
+ content: result.text,
213
+ });
214
+ toolImages.push(...result.images);
215
+ }
216
+ else if (part?.type === 'text' && typeof part.text === 'string') {
217
+ ordinary.push({ type: 'text', text: part.text });
218
+ }
219
+ else if (part?.type === 'image') {
220
+ const url = imageUrl(part.source);
221
+ if (!url)
222
+ invalidRequest('Unsupported user image source');
223
+ ordinary.push({ type: 'image_url', image_url: { url } });
224
+ }
225
+ else {
226
+ invalidRequest(`Unsupported user content block: ${String(part?.type ?? 'invalid')}`);
227
+ }
228
+ }
229
+ messages.push(...toolMessages);
230
+ const userParts = [...toolImages, ...ordinary];
231
+ if (userParts.length) {
232
+ const sole = userParts.length === 1 ? userParts[0] : undefined;
233
+ messages.push({
234
+ role: 'user',
235
+ content: sole?.type === 'text' ? String(sole.text ?? '') : userParts,
236
+ });
237
+ }
238
+ }
239
+ // A blank override is treated as absent (consistent with the env-parsing
240
+ // boundary), so the client-sent model id falls through.
241
+ const out = { model: modelOverride || req.model, messages };
242
+ if (typeof req.max_tokens === 'number')
243
+ out.max_tokens = req.max_tokens;
244
+ // top_k is in both Anthropic's schema and the Cloudflare Workers AI chat
245
+ // schema (though not vanilla OpenAI's); forward it — unknown-field-tolerant
246
+ // upstreams ignore it, and CF actually honors it.
247
+ for (const key of ['stream', 'temperature', 'top_p', 'top_k', 'metadata']) {
248
+ if (req[key] !== undefined)
249
+ out[key] = req[key];
250
+ }
251
+ // OpenAI-compatible endpoints only report token usage on a streamed response
252
+ // when include_usage is set. Anthropic's schema has no equivalent, so request
253
+ // it ourselves — otherwise Claude Code sees zero usage for streaming turns.
254
+ if (req.stream === true)
255
+ out.stream_options = { include_usage: true };
256
+ const effort = reasoningEffort(req.thinking);
257
+ if (effort !== undefined)
258
+ out.reasoning_effort = effort;
259
+ if (Array.isArray(req.stop_sequences))
260
+ out.stop = req.stop_sequences;
261
+ const toolChoice = mapToolChoice(req.tool_choice);
262
+ if (toolChoice !== undefined)
263
+ out.tool_choice = toolChoice;
264
+ if (Array.isArray(req.tools)) {
265
+ const tools = req.tools.flatMap((raw) => {
266
+ const tool = object(raw);
267
+ if (!tool || typeof tool.name !== 'string')
268
+ return [];
269
+ return [{
270
+ type: 'function',
271
+ function: {
272
+ name: tool.name,
273
+ ...(typeof tool.description === 'string' ? { description: tool.description } : {}),
274
+ parameters: tool.input_schema ?? { type: 'object', properties: {} },
275
+ },
276
+ }];
277
+ });
278
+ if (tools.length)
279
+ out.tools = tools;
280
+ }
281
+ return new TextEncoder().encode(JSON.stringify(out));
282
+ }
283
+ function anthropicUsage(raw) {
284
+ const usage = object(raw) ?? {};
285
+ const details = object(usage.prompt_tokens_details);
286
+ const total = typeof usage.prompt_tokens === 'number' ? usage.prompt_tokens : 0;
287
+ const cached = typeof details?.cached_tokens === 'number' ? details.cached_tokens : 0;
288
+ return {
289
+ input_tokens: Math.max(0, total - cached),
290
+ output_tokens: typeof usage.completion_tokens === 'number' ? usage.completion_tokens : 0,
291
+ cache_creation_input_tokens: 0,
292
+ cache_read_input_tokens: cached,
293
+ };
294
+ }
295
+ function parseArguments(value, allowRawFallback = false) {
296
+ if (typeof value !== 'string' || value.trim() === '')
297
+ return {};
298
+ try {
299
+ return JSON.parse(value);
300
+ }
301
+ catch {
302
+ if (allowRawFallback)
303
+ return { _raw: value };
304
+ throw new Error('OpenAI returned malformed function-call arguments');
305
+ }
306
+ }
307
+ function stopReason(finish, hasToolUse) {
308
+ if (finish === 'length')
309
+ return 'max_tokens';
310
+ if (finish === 'content_filter')
311
+ return 'refusal';
312
+ if (hasToolUse)
313
+ return 'tool_use';
314
+ switch (finish) {
315
+ case 'tool_calls':
316
+ case 'function_call': return 'tool_use';
317
+ case 'stop': return 'end_turn';
318
+ default: return 'end_turn';
319
+ }
320
+ }
321
+ /** Convert one completed Chat Completions JSON object into Anthropic Messages JSON. */
322
+ export function openAIChatToAnthropicMessage(response, fallbackModel) {
323
+ const r = object(response) ?? {};
324
+ const choice = Array.isArray(r.choices) ? object(r.choices[0]) : undefined;
325
+ const truncated = choice?.finish_reason === 'length';
326
+ const message = object(choice?.message) ?? {};
327
+ const content = [];
328
+ let hasToolUse = false;
329
+ if (typeof message.content === 'string' && message.content.length) {
330
+ content.push({ type: 'text', text: message.content });
331
+ }
332
+ else if (Array.isArray(message.content)) {
333
+ for (const raw of message.content) {
334
+ const part = object(raw);
335
+ if (part?.type === 'text' && typeof part.text === 'string') {
336
+ content.push({ type: 'text', text: part.text });
337
+ }
338
+ }
339
+ }
340
+ if (Array.isArray(message.tool_calls)) {
341
+ for (const raw of message.tool_calls) {
342
+ const call = object(raw);
343
+ const fn = object(call?.function);
344
+ if (!fn || typeof fn.name !== 'string')
345
+ continue;
346
+ hasToolUse = true;
347
+ content.push({
348
+ type: 'tool_use',
349
+ id: typeof call?.id === 'string' ? call.id : `call_${content.length}`,
350
+ name: fn.name,
351
+ input: parseArguments(fn.arguments, truncated),
352
+ });
353
+ }
354
+ }
355
+ if (content.length === 0)
356
+ content.push({ type: 'text', text: '' });
357
+ const id = typeof r.id === 'string' ? r.id.replace(/^chatcmpl[-_]/, 'msg_') : 'msg_fiche';
358
+ return {
359
+ id,
360
+ type: 'message',
361
+ role: 'assistant',
362
+ model: typeof r.model === 'string' ? r.model : fallbackModel,
363
+ content,
364
+ stop_reason: stopReason(choice?.finish_reason, hasToolUse),
365
+ stop_sequence: null,
366
+ usage: anthropicUsage(r.usage),
367
+ };
368
+ }
369
+ function sse(event, data) {
370
+ return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
371
+ }
372
+ function chatStreamEvent(chunk, state) {
373
+ let out = '';
374
+ const ensureStart = () => {
375
+ if (state.started)
376
+ return;
377
+ if (typeof chunk.id === 'string')
378
+ state.id = chunk.id.replace(/^chatcmpl[-_]/, 'msg_');
379
+ if (typeof chunk.model === 'string')
380
+ state.model = chunk.model;
381
+ state.started = true;
382
+ out += sse('message_start', {
383
+ type: 'message_start',
384
+ message: {
385
+ id: state.id, type: 'message', role: 'assistant', model: state.model,
386
+ content: [], stop_reason: null, stop_sequence: null, usage: anthropicUsage(undefined),
387
+ },
388
+ });
389
+ };
390
+ const openText = () => {
391
+ ensureStart();
392
+ if (state.textOpen)
393
+ return;
394
+ state.textIndex = state.nextIndex++;
395
+ state.textOpen = true;
396
+ out += sse('content_block_start', {
397
+ type: 'content_block_start', index: state.textIndex, content_block: { type: 'text', text: '' },
398
+ });
399
+ };
400
+ const closeText = () => {
401
+ if (!state.textOpen || state.textIndex === undefined)
402
+ return;
403
+ out += sse('content_block_stop', { type: 'content_block_stop', index: state.textIndex });
404
+ state.textOpen = false;
405
+ };
406
+ if (chunk.usage)
407
+ state.usage = anthropicUsage(chunk.usage);
408
+ const choice = Array.isArray(chunk.choices) ? object(chunk.choices[0]) : undefined;
409
+ if (!choice) {
410
+ ensureStart();
411
+ return out;
412
+ }
413
+ if (choice.finish_reason != null)
414
+ state.finish = choice.finish_reason;
415
+ const delta = object(choice.delta) ?? {};
416
+ if (typeof delta.content === 'string' && delta.content.length) {
417
+ openText();
418
+ out += sse('content_block_delta', {
419
+ type: 'content_block_delta', index: state.textIndex,
420
+ delta: { type: 'text_delta', text: delta.content },
421
+ });
422
+ }
423
+ if (Array.isArray(delta.tool_calls)) {
424
+ for (const raw of delta.tool_calls) {
425
+ const tc = object(raw);
426
+ if (!tc)
427
+ continue;
428
+ const fn = object(tc.function) ?? {};
429
+ // Some OpenAI-compatible providers omit `index` on tool-call deltas.
430
+ // A new call is signaled by an id/name; an args-only fragment continues
431
+ // the most recent call. Keying index-less continuations by calls.size
432
+ // would split them into spurious new tool_use blocks.
433
+ let key;
434
+ if (typeof tc.index === 'number') {
435
+ key = tc.index;
436
+ }
437
+ else if (typeof tc.id === 'string' || typeof fn.name === 'string' || state.calls.size === 0) {
438
+ key = state.calls.size; // opens a new call
439
+ }
440
+ else {
441
+ key = state.lastToolKey ?? 0; // args-only continuation
442
+ }
443
+ state.lastToolKey = key;
444
+ let call = state.calls.get(key);
445
+ if (!call) {
446
+ closeText();
447
+ ensureStart();
448
+ call = { index: state.nextIndex++, started: true };
449
+ state.calls.set(key, call);
450
+ state.sawTool = true;
451
+ out += sse('content_block_start', {
452
+ type: 'content_block_start', index: call.index,
453
+ content_block: {
454
+ type: 'tool_use',
455
+ id: typeof tc.id === 'string' ? tc.id : `call_${key}`,
456
+ name: typeof fn.name === 'string' ? fn.name : '',
457
+ input: {},
458
+ },
459
+ });
460
+ }
461
+ if (typeof fn.arguments === 'string' && fn.arguments.length) {
462
+ out += sse('content_block_delta', {
463
+ type: 'content_block_delta', index: call.index,
464
+ delta: { type: 'input_json_delta', partial_json: fn.arguments },
465
+ });
466
+ }
467
+ }
468
+ }
469
+ return out;
470
+ }
471
+ function finalizeStream(state) {
472
+ let out = '';
473
+ if (!state.started) {
474
+ out += sse('message_start', {
475
+ type: 'message_start',
476
+ message: {
477
+ id: state.id, type: 'message', role: 'assistant', model: state.model,
478
+ content: [], stop_reason: null, stop_sequence: null, usage: anthropicUsage(undefined),
479
+ },
480
+ });
481
+ state.started = true;
482
+ }
483
+ if (state.textOpen && state.textIndex !== undefined) {
484
+ out += sse('content_block_stop', { type: 'content_block_stop', index: state.textIndex });
485
+ state.textOpen = false;
486
+ }
487
+ for (const call of state.calls.values()) {
488
+ out += sse('content_block_stop', { type: 'content_block_stop', index: call.index });
489
+ }
490
+ out += sse('message_delta', {
491
+ type: 'message_delta',
492
+ delta: { stop_reason: stopReason(state.finish, state.sawTool), stop_sequence: null },
493
+ usage: state.usage ?? anthropicUsage(undefined),
494
+ });
495
+ out += sse('message_stop', { type: 'message_stop' });
496
+ return out;
497
+ }
498
+ /** Incrementally translate Chat Completions SSE without buffering model output. */
499
+ const MAX_SSE_BUFFER_CHARS = 4 * 1024 * 1024;
500
+ const MAX_BUFFERED_RESPONSE_BYTES = 16 * 1024 * 1024;
501
+ const SSE_PEEK_RE = /^(?:event:|data:|id:|retry:|:)/;
502
+ function concatUint8Arrays(chunks, total) {
503
+ const out = new Uint8Array(total);
504
+ let offset = 0;
505
+ for (const c of chunks) {
506
+ out.set(c, offset);
507
+ offset += c.byteLength;
508
+ }
509
+ return out;
510
+ }
511
+ function streamWithPrependedChunks(firstChunks, reader) {
512
+ let idx = 0;
513
+ return new ReadableStream({
514
+ async pull(controller) {
515
+ if (idx < firstChunks.length) {
516
+ controller.enqueue(firstChunks[idx++]);
517
+ return;
518
+ }
519
+ const next = await reader.read();
520
+ if (next.done)
521
+ controller.close();
522
+ else
523
+ controller.enqueue(next.value);
524
+ },
525
+ async cancel(reason) {
526
+ await reader.cancel(reason);
527
+ },
528
+ });
529
+ }
530
+ async function readRemainingBytes(firstChunks, reader) {
531
+ const chunks = [...firstChunks];
532
+ let total = 0;
533
+ for (const c of chunks)
534
+ total += c.byteLength;
535
+ if (total > MAX_BUFFERED_RESPONSE_BYTES) {
536
+ await reader.cancel().catch(() => { });
537
+ throw new Error('Upstream response exceeded maximum buffered size');
538
+ }
539
+ for (;;) {
540
+ const next = await reader.read();
541
+ if (next.done)
542
+ break;
543
+ total += next.value.byteLength;
544
+ if (total > MAX_BUFFERED_RESPONSE_BYTES) {
545
+ await reader.cancel().catch(() => { });
546
+ throw new Error('Upstream response exceeded maximum buffered size');
547
+ }
548
+ chunks.push(next.value);
549
+ }
550
+ return concatUint8Arrays(chunks, total);
551
+ }
552
+ export function openAIChatStreamToAnthropic(body, fallbackModel) {
553
+ const decoder = new TextDecoder();
554
+ const encoder = new TextEncoder();
555
+ let buffer = '';
556
+ let pendingCR = false;
557
+ let done = false;
558
+ const state = {
559
+ started: false, terminated: false, id: 'msg_fiche', model: fallbackModel,
560
+ nextIndex: 0, textOpen: false, sawTool: false, calls: new Map(),
561
+ };
562
+ const process = (chunk, controller, final = false) => {
563
+ if (state.terminated)
564
+ return;
565
+ let normalized = chunk;
566
+ if (pendingCR) {
567
+ normalized = '\r' + normalized;
568
+ pendingCR = false;
569
+ }
570
+ if (!final && normalized.endsWith('\r')) {
571
+ normalized = normalized.slice(0, -1);
572
+ pendingCR = true;
573
+ }
574
+ buffer += normalized.replace(/\r\n|\r/g, '\n');
575
+ let start = 0;
576
+ let end;
577
+ while ((end = buffer.indexOf('\n\n', start)) >= 0) {
578
+ const block = buffer.slice(start, end);
579
+ start = end + 2;
580
+ const data = [];
581
+ for (const line of block.split('\n')) {
582
+ if (line.startsWith('data:'))
583
+ data.push(line.slice(5).trimStart());
584
+ }
585
+ if (data.length === 0)
586
+ continue;
587
+ const payload = data.join('\n');
588
+ if (payload === '[DONE]') {
589
+ done = true;
590
+ continue;
591
+ }
592
+ if (state.terminated)
593
+ continue;
594
+ try {
595
+ const rendered = chatStreamEvent(JSON.parse(payload), state);
596
+ if (rendered)
597
+ controller.enqueue(encoder.encode(rendered));
598
+ }
599
+ catch {
600
+ controller.enqueue(encoder.encode(sse('error', {
601
+ type: 'error', error: { type: 'api_error', message: 'OpenAI returned a malformed streaming event' },
602
+ })));
603
+ state.terminated = true;
604
+ buffer = '';
605
+ controller.terminate();
606
+ return;
607
+ }
608
+ }
609
+ buffer = start > 0 ? buffer.slice(start) : buffer;
610
+ if (!state.terminated && buffer.length > MAX_SSE_BUFFER_CHARS) {
611
+ controller.enqueue(encoder.encode(sse('error', {
612
+ type: 'error', error: { type: 'api_error', message: 'OpenAI stream event exceeded maximum size' },
613
+ })));
614
+ state.terminated = true;
615
+ buffer = '';
616
+ controller.terminate();
617
+ }
618
+ };
619
+ return body.pipeThrough(new TransformStream({
620
+ transform(chunk, controller) {
621
+ process(decoder.decode(chunk, { stream: true }), controller);
622
+ },
623
+ flush(controller) {
624
+ process(decoder.decode() + (pendingCR ? '\r' : '') + '\n\n', controller, true);
625
+ pendingCR = false;
626
+ if (!state.terminated) {
627
+ controller.enqueue(encoder.encode(finalizeStream(state)));
628
+ }
629
+ void done;
630
+ },
631
+ }));
632
+ }
633
+ /** Translate a Chat Completions HTTP response to the Messages wire format. */
634
+ export async function openAIChatToAnthropicResponse(response, fallbackModel) {
635
+ const headers = new Headers(response.headers);
636
+ headers.delete('content-length');
637
+ const contentType = (headers.get('content-type') ?? '').toLowerCase();
638
+ if (!response.ok) {
639
+ let source = {};
640
+ let fallbackMessage = response.statusText || `OpenAI request failed with status ${response.status}`;
641
+ if (response.body) {
642
+ if (contentType.includes('json')) {
643
+ const raw = object(await response.json()) ?? {};
644
+ source = object(raw.error) ?? raw;
645
+ }
646
+ else {
647
+ const text = (await response.text()).trim();
648
+ if (text)
649
+ fallbackMessage = text.slice(0, 4096);
650
+ }
651
+ }
652
+ const rawType = typeof source.type === 'string' ? source.type : 'api_error';
653
+ const code = typeof source.code === 'string' ? source.code : '';
654
+ const type = rawType === 'invalid_request_error' || rawType === 'invalid_request'
655
+ ? 'invalid_request_error' : rawType;
656
+ const message = typeof source.message === 'string' ? source.message : code || fallbackMessage;
657
+ headers.set('content-type', 'application/json');
658
+ return new Response(JSON.stringify({ type: 'error', error: { type, message } }), {
659
+ status: response.status, statusText: response.statusText, headers,
660
+ });
661
+ }
662
+ if (!response.body)
663
+ return response;
664
+ if (contentType.includes('text/event-stream')) {
665
+ headers.set('content-type', 'text/event-stream; charset=utf-8');
666
+ return new Response(openAIChatStreamToAnthropic(response.body, fallbackModel), {
667
+ status: response.status, statusText: response.statusText, headers,
668
+ });
669
+ }
670
+ if (!contentType.includes('json')) {
671
+ const reader = response.body.getReader();
672
+ const peekDecoder = new TextDecoder();
673
+ const pendingChunks = [];
674
+ let pendingBytes = 0;
675
+ let peekText = '';
676
+ for (;;) {
677
+ const next = await reader.read();
678
+ if (next.done) {
679
+ const trimmed = peekText.trimStart();
680
+ if (SSE_PEEK_RE.test(trimmed)) {
681
+ headers.set('content-type', 'text/event-stream; charset=utf-8');
682
+ const replay = streamWithPrependedChunks(pendingChunks, reader);
683
+ return new Response(openAIChatStreamToAnthropic(replay, fallbackModel), {
684
+ status: response.status, statusText: response.statusText, headers,
685
+ });
686
+ }
687
+ if (pendingBytes === 0) {
688
+ headers.set('content-type', 'application/json');
689
+ return new Response(JSON.stringify(openAIChatToAnthropicMessage({}, fallbackModel)), {
690
+ status: response.status, statusText: response.statusText, headers,
691
+ });
692
+ }
693
+ const bytes = concatUint8Arrays(pendingChunks, pendingBytes);
694
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
695
+ const converted = openAIChatToAnthropicMessage(parsed, fallbackModel);
696
+ headers.set('content-type', 'application/json');
697
+ return new Response(JSON.stringify(converted), {
698
+ status: response.status, statusText: response.statusText, headers,
699
+ });
700
+ }
701
+ if (next.value.byteLength === 0)
702
+ continue;
703
+ pendingChunks.push(next.value);
704
+ pendingBytes += next.value.byteLength;
705
+ if (pendingBytes > MAX_BUFFERED_RESPONSE_BYTES) {
706
+ await reader.cancel().catch(() => { });
707
+ throw new Error('Upstream response exceeded maximum buffered size');
708
+ }
709
+ peekText += peekDecoder.decode(next.value, { stream: true });
710
+ const trimmed = peekText.trimStart();
711
+ if (trimmed.length === 0)
712
+ continue;
713
+ if (trimmed.length < 16 && !trimmed.includes('\n'))
714
+ continue;
715
+ if (SSE_PEEK_RE.test(trimmed)) {
716
+ headers.set('content-type', 'text/event-stream; charset=utf-8');
717
+ const replay = streamWithPrependedChunks(pendingChunks, reader);
718
+ return new Response(openAIChatStreamToAnthropic(replay, fallbackModel), {
719
+ status: response.status, statusText: response.statusText, headers,
720
+ });
721
+ }
722
+ const bytes = await readRemainingBytes(pendingChunks, reader);
723
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
724
+ const converted = openAIChatToAnthropicMessage(parsed, fallbackModel);
725
+ headers.set('content-type', 'application/json');
726
+ return new Response(JSON.stringify(converted), {
727
+ status: response.status, statusText: response.statusText, headers,
728
+ });
729
+ }
730
+ }
731
+ const converted = openAIChatToAnthropicMessage(await response.json(), fallbackModel);
732
+ headers.set('content-type', 'application/json');
733
+ return new Response(JSON.stringify(converted), {
734
+ status: response.status, statusText: response.statusText, headers,
735
+ });
736
+ }
737
+ /** Build the chat-completions endpoint URL from a user-supplied base. Accepts a
738
+ * bare host, a `/v1` base, or the full `/chat/completions` URL. */
739
+ export function chatCompletionsUrl(base) {
740
+ const b = base.replace(/\/+$/, '');
741
+ if (/\/chat\/completions$/.test(b))
742
+ return b;
743
+ if (/\/v\d+$/.test(b))
744
+ return `${b}/chat/completions`;
745
+ return `${b}/v1/chat/completions`;
746
+ }
747
+ //# sourceMappingURL=messages-chat-bridge.js.map