@hintergrund/ui 0.1.6 → 0.1.7

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.
@@ -0,0 +1,535 @@
1
+ import { O as H } from "./client-Sh7wNjbG.js";
2
+ import { y as F, E as j, z as G, D as $ } from "./Builder-CHLO8Qn6.js";
3
+ import { h as W } from "./headers-u7rXGJ9f.js";
4
+ import { p as q } from "./json-parse-CMq4Lud0.js";
5
+ import { b as J, t as K, s as A } from "./transform-messages-CkpQp6fJ.js";
6
+ import { h as Y, b as V, i as Z, r as Q } from "./github-copilot-headers-DWh_6bE3.js";
7
+ typeof globalThis.process > "u" && (globalThis.process = { env: {}, platform: "browser", version: "", versions: {}, browser: !0, nextTick: function(e) {
8
+ return Promise.resolve().then(e);
9
+ } });
10
+ function X(e) {
11
+ for (const n of e)
12
+ if (n.role === "toolResult" || n.role === "assistant" && n.content.some((t) => t.type === "toolCall"))
13
+ return !0;
14
+ return !1;
15
+ }
16
+ function O(e) {
17
+ return e.type === "text";
18
+ }
19
+ function ee(e) {
20
+ return e.type === "thinking";
21
+ }
22
+ function te(e) {
23
+ return e.type === "toolCall";
24
+ }
25
+ function ne(e) {
26
+ return e.type === "image";
27
+ }
28
+ function B(e) {
29
+ return e || (typeof process < "u" && process.env.PI_CACHE_RETENTION === "long" ? "long" : "short");
30
+ }
31
+ const se = (e, n, t) => {
32
+ const s = new G();
33
+ return (async () => {
34
+ const o = {
35
+ role: "assistant",
36
+ content: [],
37
+ api: e.api,
38
+ provider: e.provider,
39
+ model: e.id,
40
+ usage: {
41
+ input: 0,
42
+ output: 0,
43
+ cacheRead: 0,
44
+ cacheWrite: 0,
45
+ totalTokens: 0,
46
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
47
+ },
48
+ stopReason: "stop",
49
+ timestamp: Date.now()
50
+ };
51
+ try {
52
+ const u = t?.apiKey || F(e.provider) || "", l = E(e), r = B(t?.cacheRetention), i = r === "none" ? void 0 : t?.sessionId, p = oe(e, n, u, t?.headers, i, l);
53
+ let d = re(e, n, t, l, r);
54
+ const y = await t?.onPayload?.(d, e);
55
+ y !== void 0 && (d = y);
56
+ const _ = {
57
+ ...t?.signal ? { signal: t.signal } : {},
58
+ ...t?.timeoutMs !== void 0 ? { timeout: t.timeoutMs } : {},
59
+ ...t?.maxRetries !== void 0 ? { maxRetries: t.maxRetries } : {}
60
+ }, { data: T, response: R } = await p.chat.completions.create(d, _).withResponse();
61
+ await t?.onResponse?.({ status: R.status, headers: W(R.headers) }, e), s.push({ type: "start", partial: o });
62
+ let x = null, c = null;
63
+ const k = /* @__PURE__ */ new Map(), w = /* @__PURE__ */ new Map(), v = o.content, C = (a) => v.indexOf(a), L = (a) => {
64
+ const f = C(a);
65
+ f !== -1 && (a.type === "text" ? s.push({
66
+ type: "text_end",
67
+ contentIndex: f,
68
+ content: a.text,
69
+ partial: o
70
+ }) : a.type === "thinking" ? s.push({
71
+ type: "thinking_end",
72
+ contentIndex: f,
73
+ content: a.thinking,
74
+ partial: o
75
+ }) : a.type === "toolCall" && (a.arguments = q(a.partialArgs), delete a.partialArgs, delete a.streamIndex, s.push({
76
+ type: "toolcall_end",
77
+ contentIndex: f,
78
+ toolCall: a,
79
+ partial: o
80
+ })));
81
+ }, z = () => (x || (x = { type: "text", text: "" }, v.push(x), s.push({ type: "text_start", contentIndex: C(x), partial: o })), x), D = (a) => (c || (c = {
82
+ type: "thinking",
83
+ thinking: "",
84
+ thinkingSignature: a
85
+ }, v.push(c), s.push({ type: "thinking_start", contentIndex: C(c), partial: o })), c), U = (a) => {
86
+ const f = typeof a.index == "number" ? a.index : void 0;
87
+ let h = f !== void 0 ? k.get(f) : void 0;
88
+ return !h && a.id && (h = w.get(a.id)), h || (h = {
89
+ type: "toolCall",
90
+ id: a.id || "",
91
+ name: a.function?.name || "",
92
+ arguments: {},
93
+ partialArgs: "",
94
+ streamIndex: f
95
+ }, f !== void 0 && k.set(f, h), a.id && w.set(a.id, h), v.push(h), s.push({
96
+ type: "toolcall_start",
97
+ contentIndex: C(h),
98
+ partial: o
99
+ })), f !== void 0 && h.streamIndex === void 0 && (h.streamIndex = f, k.set(f, h)), a.id && w.set(a.id, h), h;
100
+ };
101
+ for await (const a of T) {
102
+ if (!a || typeof a != "object")
103
+ continue;
104
+ o.responseId ||= a.id, typeof a.model == "string" && a.model.length > 0 && a.model !== e.id && (o.responseModel ||= a.model), a.usage && (o.usage = P(a.usage, e));
105
+ const f = Array.isArray(a.choices) ? a.choices[0] : void 0;
106
+ if (f) {
107
+ if (!a.usage && f.usage && (o.usage = P(f.usage, e)), f.finish_reason) {
108
+ const h = he(f.finish_reason);
109
+ o.stopReason = h.stopReason, h.errorMessage && (o.errorMessage = h.errorMessage);
110
+ }
111
+ if (f.delta) {
112
+ if (f.delta.content !== null && f.delta.content !== void 0 && f.delta.content.length > 0) {
113
+ const g = z();
114
+ g.text += f.delta.content, s.push({
115
+ type: "text_delta",
116
+ contentIndex: C(g),
117
+ delta: f.delta.content,
118
+ partial: o
119
+ });
120
+ }
121
+ const h = ["reasoning_content", "reasoning", "reasoning_text"], b = f.delta;
122
+ let M = null;
123
+ for (const g of h) {
124
+ const m = b[g];
125
+ if (typeof m == "string" && m.length > 0) {
126
+ M = g;
127
+ break;
128
+ }
129
+ }
130
+ if (M) {
131
+ const g = b[M];
132
+ if (typeof g == "string" && g.length > 0) {
133
+ const m = D(M);
134
+ m.thinking += g, s.push({
135
+ type: "thinking_delta",
136
+ contentIndex: C(m),
137
+ delta: g,
138
+ partial: o
139
+ });
140
+ }
141
+ }
142
+ if (f?.delta?.tool_calls)
143
+ for (const g of f.delta.tool_calls) {
144
+ const m = U(g);
145
+ !m.id && g.id && (m.id = g.id, w.set(g.id, m)), !m.name && g.function?.name && (m.name = g.function.name);
146
+ let I = "";
147
+ g.function?.arguments && (I = g.function.arguments, m.partialArgs = (m.partialArgs ?? "") + g.function.arguments, m.arguments = q(m.partialArgs)), s.push({
148
+ type: "toolcall_delta",
149
+ contentIndex: C(m),
150
+ delta: I,
151
+ partial: o
152
+ });
153
+ }
154
+ const S = f.delta.reasoning_details;
155
+ if (S && Array.isArray(S)) {
156
+ for (const g of S)
157
+ if (g.type === "reasoning.encrypted" && g.id && g.data) {
158
+ const m = o.content.find((I) => I.type === "toolCall" && I.id === g.id);
159
+ m && (m.thoughtSignature = JSON.stringify(g));
160
+ }
161
+ }
162
+ }
163
+ }
164
+ }
165
+ for (const a of v)
166
+ L(a);
167
+ if (t?.signal?.aborted)
168
+ throw new Error("Request was aborted");
169
+ if (o.stopReason === "aborted")
170
+ throw new Error("Request was aborted");
171
+ if (o.stopReason === "error")
172
+ throw new Error(o.errorMessage || "Provider returned an error stop reason");
173
+ s.push({ type: "done", reason: o.stopReason, message: o }), s.end();
174
+ } catch (u) {
175
+ for (const r of o.content)
176
+ delete r.index, delete r.partialArgs, delete r.streamIndex;
177
+ o.stopReason = t?.signal?.aborted ? "aborted" : "error", o.errorMessage = u instanceof Error ? u.message : JSON.stringify(u);
178
+ const l = u?.error?.metadata?.raw;
179
+ l && (o.errorMessage += `
180
+ ${l}`), s.push({ type: "error", reason: o.stopReason, error: o }), s.end();
181
+ }
182
+ })(), s;
183
+ }, Ce = (e, n, t) => {
184
+ const s = t?.apiKey || F(e.provider);
185
+ if (!s)
186
+ throw new Error(`No API key for provider: ${e.provider}`);
187
+ const o = J(e, t, s), u = t?.reasoning ? j(e, t.reasoning) : void 0, l = u === "off" ? void 0 : u, r = t?.toolChoice;
188
+ return se(e, n, {
189
+ ...o,
190
+ reasoningEffort: l,
191
+ toolChoice: r
192
+ });
193
+ };
194
+ function oe(e, n, t, s, o, u = E(e)) {
195
+ if (!t) {
196
+ if (!process.env.OPENAI_API_KEY)
197
+ throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");
198
+ t = process.env.OPENAI_API_KEY;
199
+ }
200
+ const l = { ...e.headers };
201
+ if (e.provider === "github-copilot") {
202
+ const i = Y(n.messages), p = V({
203
+ messages: n.messages,
204
+ hasImages: i
205
+ });
206
+ Object.assign(l, p);
207
+ }
208
+ o && u.sendSessionAffinityHeaders && (l.session_id = o, l["x-client-request-id"] = o, l["x-session-affinity"] = o), s && Object.assign(l, s);
209
+ const r = e.provider === "cloudflare-ai-gateway" ? {
210
+ ...l,
211
+ Authorization: l.Authorization ?? null,
212
+ "cf-aig-authorization": `Bearer ${t}`
213
+ } : l;
214
+ return new H({
215
+ apiKey: t,
216
+ baseURL: Z(e.provider) ? Q(e) : e.baseUrl,
217
+ dangerouslyAllowBrowser: !0,
218
+ defaultHeaders: r
219
+ });
220
+ }
221
+ function re(e, n, t, s = E(e), o = B(t?.cacheRetention)) {
222
+ const u = ge(e, n, s), l = ae(s, o), r = {
223
+ model: e.id,
224
+ messages: u,
225
+ stream: !0,
226
+ prompt_cache_key: e.baseUrl.includes("api.openai.com") && o !== "none" || o === "long" && s.supportsLongCacheRetention ? t?.sessionId : void 0,
227
+ prompt_cache_retention: o === "long" && s.supportsLongCacheRetention ? "24h" : void 0
228
+ };
229
+ if (s.supportsUsageInStreaming !== !1 && (r.stream_options = { include_usage: !0 }), s.supportsStore && (r.store = !1), t?.maxTokens && (s.maxTokensField === "max_tokens" ? r.max_tokens = t.maxTokens : r.max_completion_tokens = t.maxTokens), t?.temperature !== void 0 && (r.temperature = t.temperature), n.tools && n.tools.length > 0 ? (r.tools = de(n.tools, s), s.zaiToolStream && (r.tool_stream = !0)) : X(n.messages) && (r.tools = []), l && ie(u, r.tools, l), t?.toolChoice && (r.tool_choice = t.toolChoice), s.thinkingFormat === "zai" && e.reasoning)
230
+ r.enable_thinking = !!t?.reasoningEffort;
231
+ else if (s.thinkingFormat === "qwen" && e.reasoning)
232
+ r.enable_thinking = !!t?.reasoningEffort;
233
+ else if (s.thinkingFormat === "qwen-chat-template" && e.reasoning)
234
+ r.chat_template_kwargs = {
235
+ enable_thinking: !!t?.reasoningEffort,
236
+ preserve_thinking: !0
237
+ };
238
+ else if (s.thinkingFormat === "deepseek" && e.reasoning)
239
+ r.thinking = { type: t?.reasoningEffort ? "enabled" : "disabled" }, t?.reasoningEffort && (r.reasoning_effort = e.thinkingLevelMap?.[t.reasoningEffort] ?? t.reasoningEffort);
240
+ else if (s.thinkingFormat === "openrouter" && e.reasoning) {
241
+ const i = r;
242
+ t?.reasoningEffort ? i.reasoning = {
243
+ effort: e.thinkingLevelMap?.[t.reasoningEffort] ?? t.reasoningEffort
244
+ } : e.thinkingLevelMap?.off !== null && (i.reasoning = { effort: e.thinkingLevelMap?.off ?? "none" });
245
+ } else if (t?.reasoningEffort && e.reasoning && s.supportsReasoningEffort)
246
+ r.reasoning_effort = e.thinkingLevelMap?.[t.reasoningEffort] ?? t.reasoningEffort;
247
+ else if (!t?.reasoningEffort && e.reasoning && s.supportsReasoningEffort) {
248
+ const i = e.thinkingLevelMap?.off;
249
+ typeof i == "string" && (r.reasoning_effort = i);
250
+ }
251
+ if (e.baseUrl.includes("openrouter.ai") && e.compat?.openRouterRouting && (r.provider = e.compat.openRouterRouting), e.baseUrl.includes("ai-gateway.vercel.sh") && e.compat?.vercelGatewayRouting) {
252
+ const i = e.compat.vercelGatewayRouting;
253
+ if (i.only || i.order) {
254
+ const p = {};
255
+ i.only && (p.only = i.only), i.order && (p.order = i.order), r.providerOptions = { gateway: p };
256
+ }
257
+ }
258
+ return r;
259
+ }
260
+ function ae(e, n) {
261
+ if (e.cacheControlFormat !== "anthropic" || n === "none")
262
+ return;
263
+ const t = n === "long" && e.supportsLongCacheRetention ? "1h" : void 0;
264
+ return { type: "ephemeral", ...t ? { ttl: t } : {} };
265
+ }
266
+ function ie(e, n, t) {
267
+ le(e, t), ue(n, t), ce(e, t);
268
+ }
269
+ function le(e, n) {
270
+ for (const t of e)
271
+ if (t.role === "system" || t.role === "developer") {
272
+ fe(t, n);
273
+ return;
274
+ }
275
+ }
276
+ function ce(e, n) {
277
+ for (let t = e.length - 1; t >= 0; t--) {
278
+ const s = e[t];
279
+ if ((s.role === "user" || s.role === "assistant") && pe(s, n))
280
+ return;
281
+ }
282
+ }
283
+ function ue(e, n) {
284
+ if (!e || e.length === 0)
285
+ return;
286
+ const t = e[e.length - 1];
287
+ t.cache_control = n;
288
+ }
289
+ function fe(e, n) {
290
+ return N(e, n);
291
+ }
292
+ function pe(e, n) {
293
+ return e.role === "user" || e.role === "assistant" ? N(e, n) : !1;
294
+ }
295
+ function N(e, n) {
296
+ const t = e.content;
297
+ if (typeof t == "string")
298
+ return t.length === 0 ? !1 : (e.content = [
299
+ {
300
+ type: "text",
301
+ text: t,
302
+ cache_control: n
303
+ }
304
+ ], !0);
305
+ if (!Array.isArray(t))
306
+ return !1;
307
+ for (let s = t.length - 1; s >= 0; s--) {
308
+ const o = t[s];
309
+ if (o?.type === "text") {
310
+ const u = o;
311
+ return u.cache_control = n, !0;
312
+ }
313
+ }
314
+ return !1;
315
+ }
316
+ function ge(e, n, t) {
317
+ const s = [], o = (r) => {
318
+ if (r.includes("|")) {
319
+ const [i] = r.split("|");
320
+ return i.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
321
+ }
322
+ return e.provider === "openai" && r.length > 40 ? r.slice(0, 40) : r;
323
+ }, u = K(n.messages, e, (r) => o(r));
324
+ if (n.systemPrompt) {
325
+ const i = e.reasoning && t.supportsDeveloperRole ? "developer" : "system";
326
+ s.push({ role: i, content: A(n.systemPrompt) });
327
+ }
328
+ let l = null;
329
+ for (let r = 0; r < u.length; r++) {
330
+ const i = u[r];
331
+ if (t.requiresAssistantAfterToolResult && l === "toolResult" && i.role === "user" && s.push({
332
+ role: "assistant",
333
+ content: "I have processed the tool results."
334
+ }), i.role === "user")
335
+ if (typeof i.content == "string")
336
+ s.push({
337
+ role: "user",
338
+ content: A(i.content)
339
+ });
340
+ else {
341
+ const p = i.content.map((d) => d.type === "text" ? {
342
+ type: "text",
343
+ text: A(d.text)
344
+ } : {
345
+ type: "image_url",
346
+ image_url: {
347
+ url: `data:${d.mimeType};base64,${d.data}`
348
+ }
349
+ });
350
+ if (p.length === 0)
351
+ continue;
352
+ s.push({
353
+ role: "user",
354
+ content: p
355
+ });
356
+ }
357
+ else if (i.role === "assistant") {
358
+ const p = {
359
+ role: "assistant",
360
+ content: t.requiresAssistantAfterToolResult ? "" : null
361
+ }, d = i.content.filter(O).filter((c) => c.text.trim().length > 0).map((c) => ({
362
+ type: "text",
363
+ text: A(c.text)
364
+ })), y = d.map((c) => c.text).join(""), _ = i.content.filter(ee).filter((c) => c.thinking.trim().length > 0);
365
+ if (_.length > 0)
366
+ if (t.requiresThinkingAsText) {
367
+ const c = _.map((k) => A(k.thinking)).join(`
368
+
369
+ `);
370
+ p.content = [{ type: "text", text: c }, ...d];
371
+ } else {
372
+ y.length > 0 && (p.content = y);
373
+ const c = _[0].thinkingSignature;
374
+ c && c.length > 0 && (p[c] = _.map((k) => k.thinking).join(`
375
+ `));
376
+ }
377
+ else y.length > 0 && (p.content = y);
378
+ const T = i.content.filter(te);
379
+ if (T.length > 0) {
380
+ p.tool_calls = T.map((k) => ({
381
+ id: k.id,
382
+ type: "function",
383
+ function: {
384
+ name: k.name,
385
+ arguments: JSON.stringify(k.arguments)
386
+ }
387
+ }));
388
+ const c = T.filter((k) => k.thoughtSignature).map((k) => {
389
+ try {
390
+ return JSON.parse(k.thoughtSignature);
391
+ } catch {
392
+ return null;
393
+ }
394
+ }).filter(Boolean);
395
+ c.length > 0 && (p.reasoning_details = c);
396
+ }
397
+ t.requiresReasoningContentOnAssistantMessages && e.reasoning && p.reasoning_content === void 0 && (p.reasoning_content = "");
398
+ const R = p.content;
399
+ if (!(R != null && R.length > 0) && !p.tool_calls)
400
+ continue;
401
+ s.push(p);
402
+ } else if (i.role === "toolResult") {
403
+ const p = [];
404
+ let d = r;
405
+ for (; d < u.length && u[d].role === "toolResult"; d++) {
406
+ const y = u[d], _ = y.content.filter(O).map((c) => c.text).join(`
407
+ `), T = y.content.some((c) => c.type === "image"), R = _.length > 0, x = {
408
+ role: "tool",
409
+ content: A(R ? _ : "(see attached image)"),
410
+ tool_call_id: y.toolCallId
411
+ };
412
+ if (t.requiresToolResultName && y.toolName && (x.name = y.toolName), s.push(x), T && e.input.includes("image"))
413
+ for (const c of y.content)
414
+ ne(c) && p.push({
415
+ type: "image_url",
416
+ image_url: {
417
+ url: `data:${c.mimeType};base64,${c.data}`
418
+ }
419
+ });
420
+ }
421
+ r = d - 1, p.length > 0 ? (t.requiresAssistantAfterToolResult && s.push({
422
+ role: "assistant",
423
+ content: "I have processed the tool results."
424
+ }), s.push({
425
+ role: "user",
426
+ content: [
427
+ {
428
+ type: "text",
429
+ text: "Attached image(s) from tool result:"
430
+ },
431
+ ...p
432
+ ]
433
+ }), l = "user") : l = "toolResult";
434
+ continue;
435
+ }
436
+ l = i.role;
437
+ }
438
+ return s;
439
+ }
440
+ function de(e, n) {
441
+ return e.map((t) => ({
442
+ type: "function",
443
+ function: {
444
+ name: t.name,
445
+ description: t.description,
446
+ parameters: t.parameters,
447
+ // TypeBox already generates JSON Schema
448
+ // Only include strict if provider supports it. Some reject unknown fields.
449
+ ...n.supportsStrictMode !== !1 && { strict: !1 }
450
+ }
451
+ }));
452
+ }
453
+ function P(e, n) {
454
+ const t = e.prompt_tokens || 0, s = e.prompt_tokens_details?.cached_tokens ?? e.prompt_cache_hit_tokens ?? 0, o = e.prompt_tokens_details?.cache_write_tokens || 0, u = o > 0 ? Math.max(0, s - o) : s, l = Math.max(0, t - u - o), r = e.completion_tokens || 0, i = {
455
+ input: l,
456
+ output: r,
457
+ cacheRead: u,
458
+ cacheWrite: o,
459
+ totalTokens: l + r + u + o,
460
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
461
+ };
462
+ return $(n, i), i;
463
+ }
464
+ function he(e) {
465
+ if (e === null)
466
+ return { stopReason: "stop" };
467
+ switch (e) {
468
+ case "stop":
469
+ case "end":
470
+ return { stopReason: "stop" };
471
+ case "length":
472
+ return { stopReason: "length" };
473
+ case "function_call":
474
+ case "tool_calls":
475
+ return { stopReason: "toolUse" };
476
+ case "content_filter":
477
+ return { stopReason: "error", errorMessage: "Provider finish_reason: content_filter" };
478
+ case "network_error":
479
+ return { stopReason: "error", errorMessage: "Provider finish_reason: network_error" };
480
+ default:
481
+ return {
482
+ stopReason: "error",
483
+ errorMessage: `Provider finish_reason: ${e}`
484
+ };
485
+ }
486
+ }
487
+ function me(e) {
488
+ const n = e.provider, t = e.baseUrl, s = n === "zai" || t.includes("api.z.ai"), o = n === "moonshotai" || n === "moonshotai-cn" || t.includes("api.moonshot."), u = n === "cloudflare-workers-ai" || t.includes("api.cloudflare.com"), l = n === "cloudflare-ai-gateway" || t.includes("gateway.ai.cloudflare.com"), r = n === "cerebras" || t.includes("cerebras.ai") || n === "xai" || t.includes("api.x.ai") || t.includes("chutes.ai") || t.includes("deepseek.com") || s || o || n === "opencode" || t.includes("opencode.ai") || u || l, i = t.includes("chutes.ai") || o || l, p = n === "xai" || t.includes("api.x.ai"), d = n === "deepseek" || t.includes("deepseek.com"), y = n === "openrouter" && e.id.startsWith("anthropic/") ? "anthropic" : void 0;
489
+ return {
490
+ supportsStore: !r,
491
+ supportsDeveloperRole: !r,
492
+ supportsReasoningEffort: !p && !s && !o && !l,
493
+ supportsUsageInStreaming: !0,
494
+ maxTokensField: i ? "max_tokens" : "max_completion_tokens",
495
+ requiresToolResultName: !1,
496
+ requiresAssistantAfterToolResult: !1,
497
+ requiresThinkingAsText: !1,
498
+ requiresReasoningContentOnAssistantMessages: d,
499
+ thinkingFormat: d ? "deepseek" : s ? "zai" : n === "openrouter" || t.includes("openrouter.ai") ? "openrouter" : "openai",
500
+ openRouterRouting: {},
501
+ vercelGatewayRouting: {},
502
+ zaiToolStream: !1,
503
+ supportsStrictMode: !o && !l,
504
+ cacheControlFormat: y,
505
+ sendSessionAffinityHeaders: !1,
506
+ supportsLongCacheRetention: !(u || l)
507
+ };
508
+ }
509
+ function E(e) {
510
+ const n = me(e);
511
+ return e.compat ? {
512
+ supportsStore: e.compat.supportsStore ?? n.supportsStore,
513
+ supportsDeveloperRole: e.compat.supportsDeveloperRole ?? n.supportsDeveloperRole,
514
+ supportsReasoningEffort: e.compat.supportsReasoningEffort ?? n.supportsReasoningEffort,
515
+ supportsUsageInStreaming: e.compat.supportsUsageInStreaming ?? n.supportsUsageInStreaming,
516
+ maxTokensField: e.compat.maxTokensField ?? n.maxTokensField,
517
+ requiresToolResultName: e.compat.requiresToolResultName ?? n.requiresToolResultName,
518
+ requiresAssistantAfterToolResult: e.compat.requiresAssistantAfterToolResult ?? n.requiresAssistantAfterToolResult,
519
+ requiresThinkingAsText: e.compat.requiresThinkingAsText ?? n.requiresThinkingAsText,
520
+ requiresReasoningContentOnAssistantMessages: e.compat.requiresReasoningContentOnAssistantMessages ?? n.requiresReasoningContentOnAssistantMessages,
521
+ thinkingFormat: e.compat.thinkingFormat ?? n.thinkingFormat,
522
+ openRouterRouting: e.compat.openRouterRouting ?? {},
523
+ vercelGatewayRouting: e.compat.vercelGatewayRouting ?? n.vercelGatewayRouting,
524
+ zaiToolStream: e.compat.zaiToolStream ?? n.zaiToolStream,
525
+ supportsStrictMode: e.compat.supportsStrictMode ?? n.supportsStrictMode,
526
+ cacheControlFormat: e.compat.cacheControlFormat ?? n.cacheControlFormat,
527
+ sendSessionAffinityHeaders: e.compat.sendSessionAffinityHeaders ?? n.sendSessionAffinityHeaders,
528
+ supportsLongCacheRetention: e.compat.supportsLongCacheRetention ?? n.supportsLongCacheRetention
529
+ } : n;
530
+ }
531
+ export {
532
+ ge as convertMessages,
533
+ se as streamOpenAICompletions,
534
+ Ce as streamSimpleOpenAICompletions
535
+ };
@@ -0,0 +1,142 @@
1
+ import { O as w } from "./client-Sh7wNjbG.js";
2
+ import { y as d, E as y, z as E } from "./Builder-CHLO8Qn6.js";
3
+ import { h as b } from "./headers-u7rXGJ9f.js";
4
+ import { h as I, b as A, i as _, r as P } from "./github-copilot-headers-DWh_6bE3.js";
5
+ import { p as T, c as O, a as S } from "./openai-responses-shared-DGYGIZPG.js";
6
+ import { b as C } from "./transform-messages-CkpQp6fJ.js";
7
+ typeof globalThis.process > "u" && (globalThis.process = { env: {}, platform: "browser", version: "", versions: {}, browser: !0, nextTick: function(e) {
8
+ return Promise.resolve().then(e);
9
+ } });
10
+ const k = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]);
11
+ function h(e) {
12
+ return e || (typeof process < "u" && process.env.PI_CACHE_RETENTION === "long" ? "long" : "short");
13
+ }
14
+ function l(e) {
15
+ return {
16
+ sendSessionIdHeader: e.compat?.sendSessionIdHeader ?? !0,
17
+ supportsLongCacheRetention: e.compat?.supportsLongCacheRetention ?? !0
18
+ };
19
+ }
20
+ function L(e, a) {
21
+ return a === "long" && e.supportsLongCacheRetention ? "24h" : void 0;
22
+ }
23
+ const M = (e, a, r) => {
24
+ const t = new E();
25
+ return (async () => {
26
+ const s = {
27
+ role: "assistant",
28
+ content: [],
29
+ api: e.api,
30
+ provider: e.provider,
31
+ model: e.id,
32
+ usage: {
33
+ input: 0,
34
+ output: 0,
35
+ cacheRead: 0,
36
+ cacheWrite: 0,
37
+ totalTokens: 0,
38
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
39
+ },
40
+ stopReason: "stop",
41
+ timestamp: Date.now()
42
+ };
43
+ try {
44
+ const o = r?.apiKey || d(e.provider) || "", i = h(r?.cacheRetention) === "none" ? void 0 : r?.sessionId, u = x(e, a, o, r?.headers, i);
45
+ let c = N(e, a, r);
46
+ const p = await r?.onPayload?.(c, e);
47
+ p !== void 0 && (c = p);
48
+ const g = {
49
+ ...r?.signal ? { signal: r.signal } : {},
50
+ ...r?.timeoutMs !== void 0 ? { timeout: r.timeoutMs } : {},
51
+ ...r?.maxRetries !== void 0 ? { maxRetries: r.maxRetries } : {}
52
+ }, { data: m, response: f } = await u.responses.create(c, g).withResponse();
53
+ if (await r?.onResponse?.({ status: f.status, headers: b(f.headers) }, e), t.push({ type: "start", partial: s }), await T(m, s, t, e, {
54
+ serviceTier: r?.serviceTier,
55
+ applyServiceTierPricing: (v, R) => K(v, R, e)
56
+ }), r?.signal?.aborted)
57
+ throw new Error("Request was aborted");
58
+ if (s.stopReason === "aborted" || s.stopReason === "error")
59
+ throw new Error("An unknown error occurred");
60
+ t.push({ type: "done", reason: s.stopReason, message: s }), t.end();
61
+ } catch (o) {
62
+ for (const n of s.content)
63
+ delete n.index, delete n.partialJson;
64
+ s.stopReason = r?.signal?.aborted ? "aborted" : "error", s.errorMessage = o instanceof Error ? o.message : JSON.stringify(o), t.push({ type: "error", reason: s.stopReason, error: s }), t.end();
65
+ }
66
+ })(), t;
67
+ }, Y = (e, a, r) => {
68
+ const t = r?.apiKey || d(e.provider);
69
+ if (!t)
70
+ throw new Error(`No API key for provider: ${e.provider}`);
71
+ const s = C(e, r, t), o = r?.reasoning ? y(e, r.reasoning) : void 0;
72
+ return M(e, a, {
73
+ ...s,
74
+ reasoningEffort: o === "off" ? void 0 : o
75
+ });
76
+ };
77
+ function x(e, a, r, t, s) {
78
+ if (!r) {
79
+ if (!process.env.OPENAI_API_KEY)
80
+ throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");
81
+ r = process.env.OPENAI_API_KEY;
82
+ }
83
+ const o = l(e), n = { ...e.headers };
84
+ if (e.provider === "github-copilot") {
85
+ const u = I(a.messages), c = A({
86
+ messages: a.messages,
87
+ hasImages: u
88
+ });
89
+ Object.assign(n, c);
90
+ }
91
+ s && (o.sendSessionIdHeader && (n.session_id = s), n["x-client-request-id"] = s), t && Object.assign(n, t);
92
+ const i = e.provider === "cloudflare-ai-gateway" ? {
93
+ ...n,
94
+ Authorization: n.Authorization ?? null,
95
+ "cf-aig-authorization": `Bearer ${r}`
96
+ } : n;
97
+ return new w({
98
+ apiKey: r,
99
+ baseURL: _(e.provider) ? P(e) : e.baseUrl,
100
+ dangerouslyAllowBrowser: !0,
101
+ defaultHeaders: i
102
+ });
103
+ }
104
+ function N(e, a, r) {
105
+ const t = O(e, a, k), s = h(r?.cacheRetention), o = l(e), n = {
106
+ model: e.id,
107
+ input: t,
108
+ stream: !0,
109
+ prompt_cache_key: s === "none" ? void 0 : r?.sessionId,
110
+ prompt_cache_retention: L(o, s),
111
+ store: !1
112
+ };
113
+ if (r?.maxTokens && (n.max_output_tokens = r?.maxTokens), r?.temperature !== void 0 && (n.temperature = r?.temperature), r?.serviceTier !== void 0 && (n.service_tier = r.serviceTier), a.tools && a.tools.length > 0 && (n.tools = S(a.tools)), e.reasoning)
114
+ if (r?.reasoningEffort || r?.reasoningSummary) {
115
+ const i = r?.reasoningEffort ? e.thinkingLevelMap?.[r.reasoningEffort] ?? r.reasoningEffort : "medium";
116
+ n.reasoning = {
117
+ effort: i,
118
+ summary: r?.reasoningSummary || "auto"
119
+ }, n.include = ["reasoning.encrypted_content"];
120
+ } else e.provider !== "github-copilot" && e.thinkingLevelMap?.off !== null && (n.reasoning = {
121
+ effort: e.thinkingLevelMap?.off ?? "none"
122
+ });
123
+ return n;
124
+ }
125
+ function H(e, a) {
126
+ switch (a) {
127
+ case "flex":
128
+ return 0.5;
129
+ case "priority":
130
+ return e.id === "gpt-5.5" ? 2.5 : 2;
131
+ default:
132
+ return 1;
133
+ }
134
+ }
135
+ function K(e, a, r) {
136
+ const t = H(r, a);
137
+ t !== 1 && (e.cost.input *= t, e.cost.output *= t, e.cost.cacheRead *= t, e.cost.cacheWrite *= t, e.cost.total = e.cost.input + e.cost.output + e.cost.cacheRead + e.cost.cacheWrite);
138
+ }
139
+ export {
140
+ M as streamOpenAIResponses,
141
+ Y as streamSimpleOpenAIResponses
142
+ };