@hintergrund/ui 0.2.1 → 0.2.3

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 (42) hide show
  1. package/dist/Builder-H8tY8V9I.js +14172 -0
  2. package/dist/admin.js +11160 -9739
  3. package/dist/{anthropic-UhrJpH25.js → anthropic-messages-C3hIUlsA.js} +1134 -1055
  4. package/dist/azure-openai-responses-t7u41KMr.js +222 -0
  5. package/dist/builder.js +2 -2
  6. package/dist/client-Cd7yMX39.js +7860 -0
  7. package/dist/deferred-tools-BZWMWBYN.js +28 -0
  8. package/dist/error-body-BUPcH4GF.js +71 -0
  9. package/dist/github-copilot-headers-B1RBGoZi.js +21 -0
  10. package/dist/{global-CFcrkAa3.js → global-Bk9T4Af5.js} +17896 -16508
  11. package/dist/google-generative-ai-6ZG79NDC.js +264 -0
  12. package/dist/{google-shared-BmdaIInh.js → google-shared-C6y4fA42.js} +1135 -1104
  13. package/dist/google-vertex-f2myaAmm.js +305 -0
  14. package/dist/headers-D4iLzGaS.js +21 -0
  15. package/dist/json-parse-LZdWp-Nd.js +232 -0
  16. package/dist/login.js +79 -75
  17. package/dist/mistral-conversations-D16H8Mgq.js +513 -0
  18. package/dist/openai-codex-responses-DIHPbnIS.js +947 -0
  19. package/dist/openai-completions-vDHGFsWV.js +741 -0
  20. package/dist/{headers-u7rXGJ9f.js → openai-prompt-cache-BJwqbEDx.js} +7 -6
  21. package/dist/openai-responses-B0rjAJxx.js +184 -0
  22. package/dist/openai-responses-shared-DqdzMfa_.js +477 -0
  23. package/dist/pi-messages-DB2BtH-g.js +251 -0
  24. package/dist/pi-user-agent-CUqx-qiX.js +13 -0
  25. package/dist/provider-env-D2VjEV3S.js +26 -0
  26. package/dist/provider-retry-BsigVlMg.js +67 -0
  27. package/dist/setup.js +275 -188
  28. package/dist/transform-messages-CsKsy6b4.js +398 -0
  29. package/package.json +4 -5
  30. package/dist/Builder-B0XYsyXe.js +0 -163449
  31. package/dist/azure-openai-responses-DAC03Qw1.js +0 -203
  32. package/dist/client-Sh7wNjbG.js +0 -5277
  33. package/dist/github-copilot-headers-DWh_6bE3.js +0 -35
  34. package/dist/google-CVz_TaG6.js +0 -248
  35. package/dist/google-vertex-C6GE41DE.js +0 -285
  36. package/dist/json-parse-DmJ6NiZE.js +0 -93
  37. package/dist/mistral-DqYbzWvv.js +0 -22932
  38. package/dist/openai-codex-responses-ZWuD9ryk.js +0 -700
  39. package/dist/openai-completions-B6B2OwYj.js +0 -535
  40. package/dist/openai-responses-D9Ip2Wgd.js +0 -142
  41. package/dist/openai-responses-shared-eUUJSL4D.js +0 -324
  42. package/dist/transform-messages-CkpQp6fJ.js +0 -132
@@ -1,12 +1,13 @@
1
1
  typeof globalThis.process > "u" && (globalThis.process = { env: {}, platform: "browser", version: "", versions: {}, browser: !0, nextTick: function(e) {
2
2
  return Promise.resolve().then(e);
3
3
  } });
4
- function n(e) {
5
- const r = {};
6
- for (const [o, s] of e.entries())
7
- r[o] = s;
8
- return r;
4
+ const n = 64;
5
+ function o(e) {
6
+ if (e === void 0)
7
+ return;
8
+ const r = Array.from(e);
9
+ return r.length <= n ? e : r.slice(0, n).join("");
9
10
  }
10
11
  export {
11
- n as h
12
+ o as c
12
13
  };
@@ -0,0 +1,184 @@
1
+ import { O as P } from "./client-Cd7yMX39.js";
2
+ import { d as w, e as E } from "./Builder-H8tY8V9I.js";
3
+ import { s as I } from "./deferred-tools-BZWMWBYN.js";
4
+ import { f as b, n as S } from "./error-body-BUPcH4GF.js";
5
+ import { h as M } from "./headers-D4iLzGaS.js";
6
+ import { g as C } from "./provider-env-D2VjEV3S.js";
7
+ import { r as _ } from "./provider-retry-BsigVlMg.js";
8
+ import { c as g, b as x } from "./transform-messages-CsKsy6b4.js";
9
+ import { h as k, b as L } from "./github-copilot-headers-B1RBGoZi.js";
10
+ import { c as G } from "./openai-prompt-cache-BJwqbEDx.js";
11
+ import { p as D, c as N, a as K } from "./openai-responses-shared-DqdzMfa_.js";
12
+ typeof globalThis.process > "u" && (globalThis.process = { env: {}, platform: "browser", version: "", versions: {}, browser: !0, nextTick: function(e) {
13
+ return Promise.resolve().then(e);
14
+ } });
15
+ const F = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]), U = 16;
16
+ function h(e, s) {
17
+ if (!e)
18
+ return !1;
19
+ const r = s.toLowerCase();
20
+ for (const [t, o] of Object.entries(e))
21
+ if (t.toLowerCase() === r && o !== null && o.trim().length > 0)
22
+ return !0;
23
+ return !1;
24
+ }
25
+ function R(e, s, r) {
26
+ if (s)
27
+ return s;
28
+ if (h(r, "authorization") || h(r, "cf-aig-authorization"))
29
+ return "unused";
30
+ throw new Error(`No API key for provider: ${e}`);
31
+ }
32
+ function j(e) {
33
+ return e.provider === "openrouter" || e.baseUrl.includes("openrouter.ai") ? "openrouter" : "openai";
34
+ }
35
+ function T(e, s) {
36
+ return e || (C("PI_CACHE_RETENTION", s) === "long" ? "long" : "short");
37
+ }
38
+ function l(e) {
39
+ return {
40
+ supportsDeveloperRole: e.compat?.supportsDeveloperRole ?? !0,
41
+ sessionAffinityFormat: e.compat?.sessionAffinityFormat ?? j(e),
42
+ supportsLongCacheRetention: e.compat?.supportsLongCacheRetention ?? !0,
43
+ supportsStrictMode: e.compat?.supportsStrictMode ?? !1,
44
+ supportsOpenAIGrammarTools: e.compat?.supportsOpenAIGrammarTools ?? !1,
45
+ supportsAdditionalTools: e.compat?.supportsAdditionalTools ?? !1,
46
+ supportsToolSearch: e.compat?.supportsToolSearch ?? !1,
47
+ supportsExplicitPromptCacheMode: e.compat?.supportsExplicitPromptCacheMode ?? !1
48
+ };
49
+ }
50
+ function q(e, s) {
51
+ return s === "long" && e.supportsLongCacheRetention ? "24h" : void 0;
52
+ }
53
+ function H(e) {
54
+ return b(S(e), "OpenAI API error");
55
+ }
56
+ const W = (e, s, r) => {
57
+ const t = new w();
58
+ return (async () => {
59
+ const o = {
60
+ role: "assistant",
61
+ content: [],
62
+ api: e.api,
63
+ provider: e.provider,
64
+ model: e.id,
65
+ usage: {
66
+ input: 0,
67
+ output: 0,
68
+ cacheRead: 0,
69
+ cacheWrite: 0,
70
+ totalTokens: 0,
71
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
72
+ },
73
+ stopReason: "pending",
74
+ timestamp: Date.now()
75
+ };
76
+ try {
77
+ const a = R(e.provider, r?.apiKey, r?.headers), c = T(r?.cacheRetention, r?.env) === "none" ? void 0 : r?.sessionId, p = l(e), u = g(s.tools, p.supportsOpenAIGrammarTools), n = z(e, s, a, r?.headers, r?.fetch, c);
78
+ let f = V(e, s, r, p, u);
79
+ const d = await r?.onPayload?.(f, e);
80
+ d !== void 0 && (f = d);
81
+ const v = {
82
+ ...r?.signal ? { signal: r.signal } : {},
83
+ ...r?.timeoutMs !== void 0 ? { timeout: r.timeoutMs } : {},
84
+ maxRetries: 0
85
+ }, { data: y, response: m } = await _(() => n.responses.create(f, v).withResponse(), {
86
+ maxRetries: r?.maxRetries,
87
+ maxRetryDelayMs: r?.maxRetryDelayMs,
88
+ signal: r?.signal
89
+ });
90
+ if (await r?.onResponse?.({ status: m.status, headers: M(m.headers) }, e), t.push({ type: "start", partial: o }), await D(y, o, t, e, {
91
+ serviceTier: r?.serviceTier,
92
+ grammarToolInputProperties: u,
93
+ applyServiceTierPricing: (A, O) => J(A, O, e)
94
+ }), r?.signal?.aborted)
95
+ throw new Error("Request was aborted");
96
+ if (o.stopReason === "pending")
97
+ throw new Error("OpenAI Responses stream ended without a stop reason");
98
+ if (o.stopReason === "aborted" || o.stopReason === "error")
99
+ throw new Error(o.errorMessage || "An unknown error occurred");
100
+ t.push({ type: "done", reason: o.stopReason, message: o }), t.end();
101
+ } catch (a) {
102
+ for (const i of o.content)
103
+ delete i.index, delete i.partialJson, delete i.customInput;
104
+ o.stopReason = r?.signal?.aborted ? "aborted" : "error", o.errorMessage = H(a), t.push({ type: "error", reason: o.stopReason, error: o }), t.end();
105
+ }
106
+ })(), t;
107
+ }, ae = (e, s, r) => {
108
+ R(e.provider, r?.apiKey, r?.headers);
109
+ const t = x(e, s, r, r?.apiKey), o = r?.reasoning ? E(e, r.reasoning) : void 0;
110
+ return W(e, s, {
111
+ ...t,
112
+ reasoningEffort: o === "off" ? void 0 : o
113
+ });
114
+ };
115
+ function z(e, s, r, t, o, a) {
116
+ const i = l(e), c = { ...e.headers };
117
+ if (e.provider === "github-copilot") {
118
+ const p = k(s.messages), u = L({
119
+ messages: s.messages,
120
+ hasImages: p
121
+ });
122
+ Object.assign(c, u);
123
+ }
124
+ return a && (i.sessionAffinityFormat === "openrouter" ? c["x-session-id"] = a : (i.sessionAffinityFormat === "openai" && (c.session_id = a), c["x-client-request-id"] = a)), t && Object.assign(c, t), new P({
125
+ apiKey: r,
126
+ baseURL: e.baseUrl,
127
+ dangerouslyAllowBrowser: !0,
128
+ fetch: o,
129
+ defaultHeaders: c
130
+ });
131
+ }
132
+ function V(e, s, r, t = l(e), o = g(s.tools, t.supportsOpenAIGrammarTools)) {
133
+ const a = t.supportsAdditionalTools ? "additional-tools" : t.supportsToolSearch ? "tool-search" : void 0, i = I(s, a !== void 0), c = N(e, s, F, {
134
+ grammarToolInputProperties: o,
135
+ deferredTools: i.deferred,
136
+ deferredToolsMode: a,
137
+ toolOptions: {
138
+ supportsStrictMode: t.supportsStrictMode,
139
+ supportsOpenAIGrammarTools: t.supportsOpenAIGrammarTools
140
+ }
141
+ }), p = T(r?.cacheRetention, r?.env), u = p === "none" && t.supportsExplicitPromptCacheMode, n = {
142
+ model: e.id,
143
+ input: c,
144
+ stream: !0,
145
+ prompt_cache_key: p === "none" ? void 0 : G(r?.sessionId),
146
+ prompt_cache_retention: q(t, p),
147
+ prompt_cache_options: u ? { mode: "explicit" } : void 0,
148
+ store: !1
149
+ };
150
+ if (r?.maxTokens && (n.max_output_tokens = Math.max(r.maxTokens, U)), r?.temperature !== void 0 && (n.temperature = r?.temperature), r?.serviceTier !== void 0 && (n.service_tier = r.serviceTier), i.immediate.length > 0 && (n.tools = K(i.immediate, {
151
+ supportsStrictMode: t.supportsStrictMode,
152
+ supportsOpenAIGrammarTools: t.supportsOpenAIGrammarTools
153
+ })), r?.toolChoice !== void 0 && (n.tool_choice = r.toolChoice), e.reasoning) {
154
+ if (r?.reasoningEffort || r?.reasoningSummary) {
155
+ const f = r?.reasoningEffort ? e.thinkingLevelMap?.[r.reasoningEffort] ?? r.reasoningEffort : "medium";
156
+ n.reasoning = {
157
+ effort: f,
158
+ summary: r?.reasoningSummary || "auto"
159
+ }, n.include = ["reasoning.encrypted_content"];
160
+ } else e.provider !== "github-copilot" && e.thinkingLevelMap?.off !== null && (n.reasoning = {
161
+ effort: e.thinkingLevelMap?.off ?? "none"
162
+ });
163
+ e.provider === "xai" && (n.include = ["reasoning.encrypted_content"]);
164
+ }
165
+ return r?.samplingParams && Object.assign(n, r.samplingParams), n;
166
+ }
167
+ function B(e, s) {
168
+ switch (s) {
169
+ case "flex":
170
+ return 0.5;
171
+ case "priority":
172
+ return e.id === "gpt-5.5" ? 2.5 : 2;
173
+ default:
174
+ return 1;
175
+ }
176
+ }
177
+ function J(e, s, r) {
178
+ const t = B(r, s);
179
+ 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);
180
+ }
181
+ export {
182
+ W as stream,
183
+ ae as streamSimple
184
+ };
@@ -0,0 +1,477 @@
1
+ import { f as P } from "./Builder-H8tY8V9I.js";
2
+ import { s as R } from "./hash-DFlR084x.js";
3
+ import { p as C } from "./json-parse-LZdWp-Nd.js";
4
+ import { t as O, s as k, g as z, r as N, d as j, e as W, a as A } from "./transform-messages-CsKsy6b4.js";
5
+ typeof globalThis.process > "u" && (globalThis.process = { env: {}, platform: "browser", version: "", versions: {}, browser: !0, nextTick: function(a) {
6
+ return Promise.resolve().then(a);
7
+ } });
8
+ function B(a, n) {
9
+ const i = { v: 1, id: a };
10
+ return n && (i.phase = n), JSON.stringify(i);
11
+ }
12
+ function D(a) {
13
+ if (a) {
14
+ if (a.startsWith("{"))
15
+ try {
16
+ const n = JSON.parse(a);
17
+ if (n.v === 1 && typeof n.id == "string")
18
+ return n.phase === "commentary" || n.phase === "final_answer" ? { id: n.id, phase: n.phase } : { id: n.id };
19
+ } catch {
20
+ }
21
+ return { id: a };
22
+ }
23
+ }
24
+ function E(a, n) {
25
+ const i = n.filter((l) => l.type === "text").map((l) => l.text).join(`
26
+ `), u = n.filter((l) => l.type === "image"), p = i.length > 0;
27
+ if (u.length === 0 || !a.input.includes("image"))
28
+ return k(p ? i : u.length > 0 ? "(see attached image)" : "(no tool output)");
29
+ const m = [];
30
+ p && m.push({ type: "input_text", text: k(i) });
31
+ for (const l of u)
32
+ m.push({
33
+ type: "input_image",
34
+ detail: "auto",
35
+ image_url: `data:${l.mimeType};base64,${l.data}`
36
+ });
37
+ return m;
38
+ }
39
+ function H(a, n, i, u) {
40
+ const p = [], m = /* @__PURE__ */ new Set(), l = (c) => {
41
+ const d = c.replace(/[^a-zA-Z0-9_-]/g, "_");
42
+ return (d.length > 64 ? d.slice(0, 64) : d).replace(/_+$/, "");
43
+ }, T = (c) => {
44
+ const d = `fc_${R(c)}`;
45
+ return d.length > 64 ? d.slice(0, 64) : d;
46
+ }, x = (c, d, g) => {
47
+ if (!i.has(a.provider) || !c.includes("|"))
48
+ return l(c);
49
+ const [t, e] = c.split("|"), o = l(t);
50
+ let f = g.provider !== a.provider || g.api !== a.api ? T(e) : l(e);
51
+ return f.startsWith("fc_") || (f = l(`fc_${f}`)), `${o}|${f}`;
52
+ }, _ = O(n.messages, a, x);
53
+ if ((u?.includeSystemPrompt ?? !0) && n.systemPrompt) {
54
+ const c = a.compat, d = a.reasoning && c?.supportsDeveloperRole !== !1 ? "developer" : "system";
55
+ p.push({
56
+ role: d,
57
+ content: k(n.systemPrompt)
58
+ });
59
+ }
60
+ let b = 0;
61
+ for (const c of _) {
62
+ if (c.role === "user")
63
+ if (typeof c.content == "string")
64
+ p.push({
65
+ role: "user",
66
+ content: [{ type: "input_text", text: k(c.content) }]
67
+ });
68
+ else {
69
+ const d = c.content.map((g) => g.type === "text" ? {
70
+ type: "input_text",
71
+ text: k(g.text)
72
+ } : {
73
+ type: "input_image",
74
+ detail: "auto",
75
+ image_url: `data:${g.mimeType};base64,${g.data}`
76
+ });
77
+ if (d.length === 0)
78
+ continue;
79
+ p.push({
80
+ role: "user",
81
+ content: d
82
+ });
83
+ }
84
+ else if (c.role === "assistant") {
85
+ const d = [], g = c, t = g.provider === a.provider && g.api === a.api, e = t && g.model === a.id, o = t && g.model !== a.id;
86
+ let s = 0;
87
+ for (const f of c.content)
88
+ if (f.type === "thinking") {
89
+ if (f.thinkingSignature) {
90
+ const r = JSON.parse(f.thinkingSignature);
91
+ d.push(r);
92
+ }
93
+ } else if (f.type === "text") {
94
+ const r = f, y = D(r.textSignature), S = s === 0 ? `msg_pi_${b}` : `msg_pi_${b}_${s}`;
95
+ s++;
96
+ let h = y?.id;
97
+ h ? h.length > 64 && (h = `msg_${R(h)}`) : h = S, d.push({
98
+ type: "message",
99
+ role: "assistant",
100
+ content: [{ type: "output_text", text: k(r.text), annotations: [] }],
101
+ status: "completed",
102
+ id: h,
103
+ phase: y?.phase
104
+ });
105
+ } else if (f.type === "toolCall") {
106
+ const r = f, [y, S] = r.id.split("|"), h = u?.grammarToolInputProperties?.get(r.name);
107
+ let v = S;
108
+ (o && v?.startsWith("fc_") || h === void 0 && !v?.startsWith("fc_")) && (v = void 0);
109
+ const w = e || u?.deferredTools?.has(r.name) === !0;
110
+ h !== void 0 ? d.push({
111
+ type: "custom_tool_call",
112
+ id: v,
113
+ call_id: y,
114
+ name: r.name,
115
+ input: k(z(r.name, r.arguments, h)),
116
+ ...w && r.namespace !== void 0 ? { namespace: r.namespace } : {}
117
+ }) : d.push({
118
+ type: "function_call",
119
+ id: v,
120
+ call_id: y,
121
+ name: r.name,
122
+ arguments: JSON.stringify(r.arguments),
123
+ ...w && r.namespace !== void 0 ? { namespace: r.namespace } : {}
124
+ });
125
+ }
126
+ if (d.length === 0)
127
+ continue;
128
+ p.push(...d);
129
+ } else if (c.role === "toolResult") {
130
+ const [d] = c.toolCallId.split("|"), g = E(a, c.content);
131
+ u?.grammarToolInputProperties?.has(c.toolName) ? p.push({
132
+ type: "custom_tool_call_output",
133
+ call_id: d,
134
+ output: g
135
+ }) : p.push({
136
+ type: "function_call_output",
137
+ call_id: d,
138
+ output: g
139
+ });
140
+ const t = [];
141
+ for (const e of c.addedToolNames ?? []) {
142
+ const o = u?.deferredTools?.get(e);
143
+ !o || m.has(e) || (m.add(e), t.push(o));
144
+ }
145
+ if (t.length > 0 && u?.deferredToolsMode === "additional-tools")
146
+ p.push({
147
+ type: "additional_tools",
148
+ role: "developer",
149
+ tools: J(t, u.toolOptions)
150
+ });
151
+ else if (t.length > 0 && u?.deferredToolsMode === "tool-search") {
152
+ const e = t.map((s) => s.name), o = `pi_tool_load_${R(`${c.toolCallId}:${e.join(",")}`)}`;
153
+ p.push({
154
+ type: "tool_search_call",
155
+ call_id: o,
156
+ execution: "client",
157
+ status: "completed",
158
+ arguments: { query: e.join(" "), limit: e.length }
159
+ }), p.push({
160
+ type: "tool_search_output",
161
+ call_id: o,
162
+ execution: "client",
163
+ status: "completed",
164
+ tools: J(t, {
165
+ ...u.toolOptions,
166
+ deferLoading: !0
167
+ })
168
+ });
169
+ }
170
+ }
171
+ b++;
172
+ }
173
+ return p;
174
+ }
175
+ function J(a, n) {
176
+ const i = n?.strict === void 0 ? !1 : n.strict, u = n?.supportsStrictMode ?? !0, p = n?.supportsOpenAIGrammarTools ?? !1;
177
+ return a.map((m) => {
178
+ const l = N(m, p);
179
+ if (l)
180
+ return {
181
+ type: "custom",
182
+ name: m.name,
183
+ description: m.description,
184
+ format: {
185
+ type: "grammar",
186
+ syntax: l.format,
187
+ definition: l.definition
188
+ },
189
+ ...n?.deferLoading ? { defer_loading: !0 } : {}
190
+ };
191
+ const x = j(m, u) ?? i, _ = {
192
+ type: "function",
193
+ name: m.name,
194
+ description: m.description,
195
+ parameters: W(m, x === !0),
196
+ ...n?.deferLoading ? { defer_loading: !0 } : {}
197
+ };
198
+ return u && (_.strict = x), _;
199
+ });
200
+ }
201
+ function M(a) {
202
+ const n = a.customInput?.property;
203
+ if (n === void 0)
204
+ return "";
205
+ const i = a.arguments[n];
206
+ return typeof i == "string" ? i : "";
207
+ }
208
+ function $(a, n, i) {
209
+ const u = a.customInput;
210
+ if (!u)
211
+ return;
212
+ const p = A(u.jsonBuffer, u.property, n, i);
213
+ return a.arguments = { [u.property]: n }, p;
214
+ }
215
+ async function V(a, n, i, u, p) {
216
+ let m = !1;
217
+ const l = /* @__PURE__ */ new Map(), T = /* @__PURE__ */ new Map(), x = (t) => {
218
+ t.type === "message" && t.phase === "final_answer" && (n.stopReason = "stop");
219
+ }, _ = (t, e) => {
220
+ const o = l.get(t);
221
+ return o?.type === e ? o : void 0;
222
+ }, I = (t, e) => {
223
+ e !== void 0 && i.push({
224
+ type: "toolcall_delta",
225
+ contentIndex: t.contentIndex,
226
+ delta: e,
227
+ partial: n
228
+ });
229
+ }, b = (t, e) => {
230
+ if (e.type === "reasoning") {
231
+ const o = { type: "thinking", thinking: "" };
232
+ n.content.push(o);
233
+ const s = {
234
+ type: "thinking",
235
+ block: o,
236
+ contentIndex: n.content.length - 1
237
+ };
238
+ return l.set(t, s), i.push({ type: "thinking_start", contentIndex: s.contentIndex, partial: n }), s;
239
+ }
240
+ if (e.type === "message") {
241
+ x(e);
242
+ const o = { type: "text", text: "" };
243
+ n.content.push(o);
244
+ const s = { type: "text", block: o, contentIndex: n.content.length - 1 };
245
+ return l.set(t, s), i.push({ type: "text_start", contentIndex: s.contentIndex, partial: n }), s;
246
+ }
247
+ if (e.type === "function_call") {
248
+ const o = {
249
+ type: "toolCall",
250
+ id: `${e.call_id}|${e.id}`,
251
+ name: e.name,
252
+ arguments: {},
253
+ ...e.namespace !== void 0 ? { namespace: e.namespace } : {},
254
+ partialJson: e.arguments || ""
255
+ };
256
+ n.content.push(o);
257
+ const s = {
258
+ type: "toolCall",
259
+ block: o,
260
+ contentIndex: n.content.length - 1
261
+ };
262
+ return l.set(t, s), i.push({ type: "toolcall_start", contentIndex: s.contentIndex, partial: n }), s;
263
+ }
264
+ if (e.type === "custom_tool_call") {
265
+ const o = p?.grammarToolInputProperties?.get(e.name) ?? "input", s = e.input || "", f = {
266
+ type: "toolCall",
267
+ id: `${e.call_id}|${e.id}`,
268
+ name: e.name,
269
+ arguments: { [o]: s },
270
+ ...e.namespace !== void 0 ? { namespace: e.namespace } : {},
271
+ customInput: {
272
+ property: o,
273
+ jsonBuffer: { input: "", started: !1, closed: !1 }
274
+ }
275
+ };
276
+ n.content.push(f);
277
+ const r = {
278
+ type: "toolCall",
279
+ block: f,
280
+ contentIndex: n.content.length - 1
281
+ };
282
+ return l.set(t, r), i.push({ type: "toolcall_start", contentIndex: r.contentIndex, partial: n }), r;
283
+ }
284
+ }, c = (t, e) => l.get(t) ?? b(t, e), d = (t) => {
285
+ for (const e of t) {
286
+ if (e.type !== "reasoning" || !e.encrypted_content)
287
+ continue;
288
+ const o = T.get(e.id);
289
+ if (!o?.thinkingSignature)
290
+ continue;
291
+ const s = JSON.parse(o.thinkingSignature);
292
+ s.encrypted_content || (o.thinkingSignature = JSON.stringify({
293
+ ...s,
294
+ encrypted_content: e.encrypted_content
295
+ }));
296
+ }
297
+ }, g = (t) => {
298
+ if (m = !0, d(t.output ?? []), t?.id && (n.responseId = t.id), t?.usage) {
299
+ const r = t.usage.input_tokens_details, y = r?.cached_tokens || 0, S = r?.cache_write_tokens || 0;
300
+ n.usage = {
301
+ // OpenAI includes cached and cache-write tokens in input_tokens, so subtract both.
302
+ input: Math.max(0, (t.usage.input_tokens || 0) - y - S),
303
+ output: t.usage.output_tokens || 0,
304
+ cacheRead: y,
305
+ cacheWrite: S,
306
+ reasoning: t.usage.output_tokens_details?.reasoning_tokens || 0,
307
+ totalTokens: t.usage.total_tokens || 0,
308
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
309
+ };
310
+ }
311
+ if (P(u, n.usage), p?.applyServiceTierPricing) {
312
+ const r = p.resolveServiceTier ? p.resolveServiceTier(t?.service_tier, p.serviceTier) : t?.service_tier ?? p.serviceTier;
313
+ p.applyServiceTierPricing(n.usage, r);
314
+ }
315
+ const e = t?.status, o = t?.incomplete_details, s = typeof o?.reason == "string" ? o.reason : void 0;
316
+ n.rawStopReason = s ? `${e}.${s}` : e;
317
+ const f = G(e, s);
318
+ n.stopReason = f.stopReason, n.errorMessage = f.errorMessage, n.content.some((r) => r.type === "toolCall") && n.stopReason === "stop" && (n.stopReason = "toolUse");
319
+ };
320
+ for await (const t of a)
321
+ if (t.type === "response.created")
322
+ n.responseId = t.response.id;
323
+ else if (t.type === "response.output_item.added")
324
+ b(t.output_index, t.item);
325
+ else if (t.type === "response.reasoning_summary_text.delta") {
326
+ const e = _(t.output_index, "thinking");
327
+ if (!e)
328
+ continue;
329
+ e.block.thinking += t.delta, i.push({
330
+ type: "thinking_delta",
331
+ contentIndex: e.contentIndex,
332
+ delta: t.delta,
333
+ partial: n
334
+ });
335
+ } else if (t.type === "response.reasoning_summary_part.done") {
336
+ const e = _(t.output_index, "thinking");
337
+ if (!e)
338
+ continue;
339
+ e.block.thinking += `
340
+
341
+ `, i.push({
342
+ type: "thinking_delta",
343
+ contentIndex: e.contentIndex,
344
+ delta: `
345
+
346
+ `,
347
+ partial: n
348
+ });
349
+ } else if (t.type === "response.reasoning_text.delta") {
350
+ const e = _(t.output_index, "thinking");
351
+ if (!e)
352
+ continue;
353
+ e.block.thinking += t.delta, i.push({
354
+ type: "thinking_delta",
355
+ contentIndex: e.contentIndex,
356
+ delta: t.delta,
357
+ partial: n
358
+ });
359
+ } else if (t.type === "response.output_text.delta") {
360
+ const e = _(t.output_index, "text");
361
+ if (!e)
362
+ continue;
363
+ e.block.text += t.delta, i.push({
364
+ type: "text_delta",
365
+ contentIndex: e.contentIndex,
366
+ delta: t.delta,
367
+ partial: n
368
+ });
369
+ } else if (t.type === "response.refusal.delta") {
370
+ const e = _(t.output_index, "text");
371
+ if (!e)
372
+ continue;
373
+ e.block.text += t.delta, i.push({
374
+ type: "text_delta",
375
+ contentIndex: e.contentIndex,
376
+ delta: t.delta,
377
+ partial: n
378
+ });
379
+ } else if (t.type === "response.function_call_arguments.delta") {
380
+ const e = _(t.output_index, "toolCall");
381
+ if (!e || e.block.partialJson === void 0)
382
+ continue;
383
+ e.block.partialJson += t.delta, e.block.arguments = C(e.block.partialJson), I(e, t.delta);
384
+ } else if (t.type === "response.function_call_arguments.done") {
385
+ const e = _(t.output_index, "toolCall");
386
+ if (!e || e.block.partialJson === void 0)
387
+ continue;
388
+ const o = e.block.partialJson;
389
+ if (e.block.partialJson = t.arguments, e.block.arguments = C(e.block.partialJson), t.arguments.startsWith(o)) {
390
+ const s = t.arguments.slice(o.length);
391
+ s.length > 0 && I(e, s);
392
+ }
393
+ } else if (t.type === "response.custom_tool_call_input.delta") {
394
+ const e = _(t.output_index, "toolCall");
395
+ if (!e || !e.block.customInput)
396
+ continue;
397
+ I(e, $(e.block, M(e.block) + t.delta, !1));
398
+ } else if (t.type === "response.custom_tool_call_input.done") {
399
+ const e = _(t.output_index, "toolCall");
400
+ if (!e || !e.block.customInput)
401
+ continue;
402
+ I(e, $(e.block, t.input, !0));
403
+ } else if (t.type === "response.output_item.done") {
404
+ const e = t.item;
405
+ x(e);
406
+ const o = c(t.output_index, e);
407
+ if (e.type === "reasoning" && o?.type === "thinking") {
408
+ const s = e.summary?.map((r) => r.text).join(`
409
+
410
+ `) || "", f = e.content?.map((r) => r.text).join(`
411
+
412
+ `) || "";
413
+ o.block.thinking = s || f || o.block.thinking, o.block.thinkingSignature = JSON.stringify(e), T.set(e.id, o.block), i.push({
414
+ type: "thinking_end",
415
+ contentIndex: o.contentIndex,
416
+ content: o.block.thinking,
417
+ partial: n
418
+ }), l.delete(t.output_index);
419
+ } else e.type === "message" && o?.type === "text" ? (o.block.text = e.content?.map((s) => s.type === "output_text" ? s.text : s.refusal).join("") || "", o.block.textSignature = B(e.id, e.phase ?? void 0), i.push({
420
+ type: "text_end",
421
+ contentIndex: o.contentIndex,
422
+ content: o.block.text,
423
+ partial: n
424
+ }), l.delete(t.output_index)) : e.type === "function_call" && o?.type === "toolCall" && o.block.partialJson !== void 0 ? (o.block.arguments = C(e.arguments || o.block.partialJson || "{}"), e.namespace !== void 0 && (o.block.namespace = e.namespace), delete o.block.partialJson, i.push({
425
+ type: "toolcall_end",
426
+ contentIndex: o.contentIndex,
427
+ toolCall: o.block,
428
+ partial: n
429
+ }), l.delete(t.output_index)) : e.type === "custom_tool_call" && o?.type === "toolCall" && o.block.customInput && (I(o, $(o.block, e.input ?? M(o.block), !0)), e.namespace !== void 0 && (o.block.namespace = e.namespace), delete o.block.customInput, i.push({
430
+ type: "toolcall_end",
431
+ contentIndex: o.contentIndex,
432
+ toolCall: o.block,
433
+ partial: n
434
+ }), l.delete(t.output_index));
435
+ } else if (t.type === "response.completed" || t.type === "response.incomplete")
436
+ g(t.response);
437
+ else {
438
+ if (t.type === "error")
439
+ throw new Error(`Error Code ${t.code}: ${t.message}` || "Unknown error");
440
+ if (t.type === "response.failed") {
441
+ m = !0, n.rawStopReason = t.response?.status;
442
+ const e = t.response?.error, o = t.response?.incomplete_details, s = e ? `${e.code || "unknown"}: ${e.message || "no message"}` : o?.reason ? `incomplete: ${o.reason}` : "Unknown error (no error details in response)";
443
+ throw new Error(s);
444
+ }
445
+ }
446
+ if (!m)
447
+ throw new Error("OpenAI Responses stream ended before a terminal response event");
448
+ }
449
+ function G(a, n) {
450
+ if (!a)
451
+ return { stopReason: "stop" };
452
+ switch (a) {
453
+ case "completed":
454
+ return { stopReason: "stop" };
455
+ case "incomplete":
456
+ return n === "max_output_tokens" ? { stopReason: "length" } : {
457
+ stopReason: "error",
458
+ errorMessage: n ? `Response incomplete: ${n}` : "Response incomplete without a provider reason"
459
+ };
460
+ case "failed":
461
+ case "cancelled":
462
+ return { stopReason: "error" };
463
+ // These two are wonky ...
464
+ case "in_progress":
465
+ case "queued":
466
+ return { stopReason: "stop" };
467
+ default: {
468
+ const i = a;
469
+ throw new Error(`Unhandled stop reason: ${i}`);
470
+ }
471
+ }
472
+ }
473
+ export {
474
+ J as a,
475
+ H as c,
476
+ V as p
477
+ };