@supersolutions/super-chat-core 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1080 @@
1
+ import {
2
+ AgentError,
3
+ collectAnsweredIds,
4
+ dropUnanswered,
5
+ errorFromResponse,
6
+ filterNativeTools,
7
+ foreignFileText,
8
+ parseSSE,
9
+ parseSSEJson,
10
+ repairToolArguments,
11
+ toAgentError,
12
+ withDefaultTimeout,
13
+ withRetry
14
+ } from "./chunk-32DPF33V.js";
15
+
16
+ // src/providers/openai/map-in.ts
17
+ function dataUrl(mediaType, base64) {
18
+ return `data:${mediaType};base64,${base64}`;
19
+ }
20
+ var ownFile = (source, providerId) => source.provider === providerId;
21
+ var stringifyOutput = (output) => typeof output === "string" ? output : JSON.stringify(output ?? null);
22
+ function toResponsesContent(part, role, providerId) {
23
+ switch (part.type) {
24
+ case "text":
25
+ return role === "assistant" ? { type: "output_text", text: part.text } : { type: "input_text", text: part.text };
26
+ case "image": {
27
+ const s = part.source;
28
+ if (s.kind === "url") return { type: "input_image", image_url: s.url, ...part.detail ? { detail: part.detail } : {} };
29
+ if (s.kind === "base64") {
30
+ return {
31
+ type: "input_image",
32
+ image_url: dataUrl(part.mediaType ?? "image/png", s.data),
33
+ ...part.detail ? { detail: part.detail } : {}
34
+ };
35
+ }
36
+ if (!ownFile(s, providerId)) return { type: "input_text", text: foreignFileText("image", void 0, s) };
37
+ return { type: "input_image", file_id: s.id, ...part.detail ? { detail: part.detail } : {} };
38
+ }
39
+ case "file": {
40
+ const s = part.source;
41
+ if (s.kind === "providerFile") {
42
+ if (!ownFile(s, providerId)) return { type: "input_text", text: foreignFileText("file", part.filename, s) };
43
+ return { type: "input_file", file_id: s.id };
44
+ }
45
+ if (s.kind === "base64") {
46
+ return {
47
+ type: "input_file",
48
+ file_data: dataUrl(part.mediaType, s.data),
49
+ filename: part.filename ?? "attachment"
50
+ };
51
+ }
52
+ return { type: "input_text", text: `[file] ${part.filename ?? s.url} (${s.url})` };
53
+ }
54
+ case "audio":
55
+ return part.transcript ? { type: "input_text", text: part.transcript } : null;
56
+ default:
57
+ return null;
58
+ }
59
+ }
60
+ function toResponsesInput(messages, providerId = "openai") {
61
+ const items = [];
62
+ for (const m of messages) {
63
+ if (m.role === "system") {
64
+ const text = m.parts.filter((p) => p.type === "text").map((p) => p.text).join("\n");
65
+ if (text) items.push({ type: "message", role: "developer", content: [{ type: "input_text", text }] });
66
+ continue;
67
+ }
68
+ const role = m.role === "assistant" ? "assistant" : "user";
69
+ const content = [];
70
+ for (const part of m.parts) {
71
+ if (part.type === "tool-call") {
72
+ if (content.length) {
73
+ items.push({ type: "message", role, content: [...content] });
74
+ content.length = 0;
75
+ }
76
+ items.push({
77
+ type: "function_call",
78
+ call_id: part.callId,
79
+ name: part.name,
80
+ arguments: typeof part.input === "string" ? part.input : JSON.stringify(part.input ?? {})
81
+ });
82
+ continue;
83
+ }
84
+ if (part.type === "tool-result") {
85
+ if (content.length) {
86
+ items.push({ type: "message", role, content: [...content] });
87
+ content.length = 0;
88
+ }
89
+ items.push({ type: "function_call_output", call_id: part.callId, output: stringifyOutput(part.output) });
90
+ continue;
91
+ }
92
+ if (part.type === "reasoning") {
93
+ if (part.signature) {
94
+ items.push({
95
+ type: "reasoning",
96
+ id: part.signature,
97
+ summary: part.text ? [{ type: "summary_text", text: part.text }] : []
98
+ });
99
+ }
100
+ continue;
101
+ }
102
+ const mapped = toResponsesContent(part, role, providerId);
103
+ if (mapped) content.push(mapped);
104
+ }
105
+ if (content.length) items.push({ type: "message", role, content });
106
+ }
107
+ return dropOrphanToolCalls(items);
108
+ }
109
+ function dropOrphanToolCalls(items) {
110
+ const answered = collectAnsweredIds(items, (i) => i.type === "function_call_output" ? i.call_id : void 0);
111
+ return dropUnanswered(items, answered, (i) => i.type === "function_call" ? i.call_id : void 0);
112
+ }
113
+ function toResponsesTools(tools) {
114
+ return tools.map((t) => ({
115
+ type: "function",
116
+ name: t.name,
117
+ description: t.description,
118
+ parameters: t.parameters,
119
+ ...t.strict ? { strict: true } : {}
120
+ }));
121
+ }
122
+ function buildResponsesRequest(req, opts = {}) {
123
+ const systemFromMessages = req.messages.filter((m) => m.role === "system").flatMap((m) => m.parts.filter((p) => p.type === "text").map((p) => p.text)).join("\n\n");
124
+ const instructions = [req.system, systemFromMessages].filter(Boolean).join("\n\n") || void 0;
125
+ const messages = req.previousResponseId ? tailAfterLastAssistant(req.messages) : req.messages;
126
+ const out = {
127
+ model: req.model,
128
+ input: toResponsesInput(messages.filter((m) => m.role !== "system"), opts.providerId)
129
+ };
130
+ if (instructions && !req.previousResponseId) out.instructions = instructions;
131
+ const nativeTools = filterNativeTools(req.providerTools?.[opts.providerId ?? "openai"]);
132
+ if (req.tools?.length || nativeTools.length) {
133
+ out.tools = [...req.tools?.length ? toResponsesTools(req.tools) : [], ...nativeTools];
134
+ if (req.tools?.length) out.tool_choice = toResponsesToolChoice(req);
135
+ if (opts.parallelToolCalls !== false) out.parallel_tool_calls = true;
136
+ }
137
+ if (req.maxOutputTokens != null) out.max_output_tokens = req.maxOutputTokens;
138
+ if (req.temperature != null) out.temperature = req.temperature;
139
+ if (req.topP != null) out.top_p = req.topP;
140
+ if (req.responseFormat) out.text = { format: toResponsesFormat(req.responseFormat) };
141
+ if (req.reasoning) {
142
+ out.reasoning = {
143
+ ...req.reasoning.effort ? { effort: req.reasoning.effort } : {},
144
+ ...req.reasoning.summary && req.reasoning.summary !== "none" ? { summary: req.reasoning.summary } : {}
145
+ };
146
+ }
147
+ if (req.previousResponseId) out.previous_response_id = req.previousResponseId;
148
+ if (req.metadata) out.metadata = req.metadata;
149
+ if (opts.stream) out.stream = true;
150
+ if (req.background) {
151
+ out.background = true;
152
+ out.store = true;
153
+ } else if (req.store != null) {
154
+ out.store = req.store;
155
+ }
156
+ mergeProviderOptions(out, req, opts.providerId);
157
+ return out;
158
+ }
159
+ function mergeProviderOptions(out, req, providerId = "openai") {
160
+ const extra = req.providerOptions?.[providerId];
161
+ if (extra) Object.assign(out, extra);
162
+ }
163
+ function tailAfterLastAssistant(messages) {
164
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
165
+ if (messages[i]?.role === "assistant") return messages.slice(i + 1);
166
+ }
167
+ return [...messages];
168
+ }
169
+ function toResponsesToolChoice(req) {
170
+ if (req.activeTools?.length === 1 && req.tools && req.tools.length > 1) {
171
+ return { type: "function", name: req.activeTools[0] };
172
+ }
173
+ if (req.activeTools?.length === 0) return "none";
174
+ switch (req.toolChoice?.type) {
175
+ case "none":
176
+ return "none";
177
+ case "required":
178
+ return "required";
179
+ case "tool":
180
+ return { type: "function", name: req.toolChoice.name };
181
+ default:
182
+ return "auto";
183
+ }
184
+ }
185
+ function toResponsesFormat(f) {
186
+ if (f.type === "json") return { type: "json_object" };
187
+ if (f.type === "json_schema") {
188
+ return { type: "json_schema", name: f.name, schema: f.schema, strict: f.strict ?? true };
189
+ }
190
+ return { type: "text" };
191
+ }
192
+ function toChatContent(part, providerId) {
193
+ switch (part.type) {
194
+ case "text":
195
+ return { type: "text", text: part.text };
196
+ case "image": {
197
+ const s = part.source;
198
+ const url = s.kind === "url" ? s.url : s.kind === "base64" ? dataUrl(part.mediaType ?? "image/png", s.data) : null;
199
+ if (!url) {
200
+ const pf = s;
201
+ if (!ownFile(pf, providerId)) return { type: "text", text: foreignFileText("image", void 0, pf) };
202
+ return { type: "file", file: { file_id: pf.id } };
203
+ }
204
+ return { type: "image_url", image_url: { url, ...part.detail ? { detail: part.detail } : {} } };
205
+ }
206
+ case "file": {
207
+ const s = part.source;
208
+ if (s.kind === "providerFile") {
209
+ if (!ownFile(s, providerId)) return { type: "text", text: foreignFileText("file", part.filename, s) };
210
+ return { type: "file", file: { file_id: s.id } };
211
+ }
212
+ if (s.kind === "base64") {
213
+ return { type: "file", file: { filename: part.filename ?? "attachment", file_data: dataUrl(part.mediaType, s.data) } };
214
+ }
215
+ return { type: "text", text: `[file] ${part.filename ?? s.url} (${s.url})` };
216
+ }
217
+ case "audio": {
218
+ const s = part.source;
219
+ if (s.kind === "base64") {
220
+ const format = part.mediaType.includes("mp3") ? "mp3" : "wav";
221
+ return { type: "input_audio", input_audio: { data: s.data, format } };
222
+ }
223
+ return part.transcript ? { type: "text", text: part.transcript } : null;
224
+ }
225
+ default:
226
+ return null;
227
+ }
228
+ }
229
+ function toChatMessages(messages, system, providerId = "openai") {
230
+ const out = [];
231
+ if (system) out.push({ role: "system", content: system });
232
+ for (const m of messages) {
233
+ if (m.role === "system") {
234
+ const text = m.parts.filter((p) => p.type === "text").map((p) => p.text).join("\n");
235
+ if (text) out.push({ role: "system", content: text });
236
+ continue;
237
+ }
238
+ if (m.role === "assistant") {
239
+ const text = m.parts.filter((p) => p.type === "text").map((p) => p.text).join("");
240
+ const calls = m.parts.filter((p) => p.type === "tool-call").map((p) => ({
241
+ id: p.callId,
242
+ type: "function",
243
+ function: { name: p.name, arguments: typeof p.input === "string" ? p.input : JSON.stringify(p.input ?? {}) }
244
+ }));
245
+ if (text || calls.length) {
246
+ out.push({
247
+ role: "assistant",
248
+ ...text ? { content: text } : { content: null },
249
+ ...calls.length ? { tool_calls: calls } : {}
250
+ });
251
+ }
252
+ for (const p of m.parts) {
253
+ if (p.type === "tool-result") {
254
+ out.push({ role: "tool", tool_call_id: p.callId, content: stringifyOutput(p.output) });
255
+ }
256
+ }
257
+ continue;
258
+ }
259
+ const toolResults = m.parts.filter((p) => p.type === "tool-result");
260
+ for (const p of toolResults) {
261
+ out.push({ role: "tool", tool_call_id: p.callId, content: stringifyOutput(p.output) });
262
+ }
263
+ const content = m.parts.map((p) => toChatContent(p, providerId)).filter((c) => c !== null);
264
+ if (content.length) {
265
+ const only = content.length === 1 && content[0]?.type === "text" ? content[0].text : null;
266
+ out.push({ role: "user", content: only ?? content });
267
+ }
268
+ }
269
+ return dropOrphanChatToolCalls(out);
270
+ }
271
+ function dropOrphanChatToolCalls(messages) {
272
+ const answered = collectAnsweredIds(messages, (m) => m.role === "tool" ? m.tool_call_id : void 0);
273
+ return messages.map((m) => {
274
+ if (m.role !== "assistant" || !m.tool_calls?.length) return m;
275
+ const kept = dropUnanswered(m.tool_calls, answered, (c) => c.id);
276
+ if (kept.length === m.tool_calls.length) return m;
277
+ if (kept.length === 0) {
278
+ const { tool_calls: _dropped, ...rest } = m;
279
+ return rest.content ? rest : null;
280
+ }
281
+ return { ...m, tool_calls: kept };
282
+ }).filter((m) => m !== null);
283
+ }
284
+ function toChatTools(tools) {
285
+ return tools.map((t) => ({
286
+ type: "function",
287
+ function: {
288
+ name: t.name,
289
+ description: t.description,
290
+ parameters: t.parameters,
291
+ ...t.strict ? { strict: true } : {}
292
+ }
293
+ }));
294
+ }
295
+ function buildChatRequest(req, opts = {}) {
296
+ const out = {
297
+ model: req.model,
298
+ messages: toChatMessages(req.messages, req.system, opts.providerId)
299
+ };
300
+ const nativeChatTools = filterNativeTools(req.providerTools?.[opts.providerId ?? "openai"]);
301
+ if (req.tools?.length || nativeChatTools.length) {
302
+ const activeNames = req.activeTools ? new Set(req.activeTools) : void 0;
303
+ const active = activeNames ? (req.tools ?? []).filter((t) => activeNames.has(t.name)) : req.tools ?? [];
304
+ if (active.length || nativeChatTools.length) {
305
+ out.tools = [...active.length ? toChatTools(active) : [], ...nativeChatTools];
306
+ if (opts.parallelToolCalls !== false) out.parallel_tool_calls = true;
307
+ switch (req.toolChoice?.type) {
308
+ case "none":
309
+ out.tool_choice = "none";
310
+ break;
311
+ case "required":
312
+ out.tool_choice = "required";
313
+ break;
314
+ case "tool":
315
+ out.tool_choice = { type: "function", function: { name: req.toolChoice.name } };
316
+ break;
317
+ default:
318
+ out.tool_choice = "auto";
319
+ }
320
+ }
321
+ }
322
+ if (req.maxOutputTokens != null) out.max_completion_tokens = req.maxOutputTokens;
323
+ if (req.temperature != null) out.temperature = req.temperature;
324
+ if (req.topP != null) out.top_p = req.topP;
325
+ if (req.stopSequences?.length) out.stop = req.stopSequences;
326
+ if (req.reasoning?.effort) out.reasoning_effort = req.reasoning.effort;
327
+ if (req.metadata) out.metadata = req.metadata;
328
+ if (req.store != null) out.store = req.store;
329
+ if (req.responseFormat) {
330
+ if (req.responseFormat.type === "json") out.response_format = { type: "json_object" };
331
+ else if (req.responseFormat.type === "json_schema") {
332
+ out.response_format = {
333
+ type: "json_schema",
334
+ json_schema: {
335
+ name: req.responseFormat.name,
336
+ schema: req.responseFormat.schema,
337
+ strict: req.responseFormat.strict ?? true
338
+ }
339
+ };
340
+ } else out.response_format = { type: "text" };
341
+ }
342
+ if (opts.stream) {
343
+ out.stream = true;
344
+ out.stream_options = { include_usage: true };
345
+ }
346
+ mergeProviderOptions(out, req, opts.providerId);
347
+ return out;
348
+ }
349
+
350
+ // src/providers/openai/map-out.ts
351
+ function usageFromResponses(u) {
352
+ if (!u) return {};
353
+ return {
354
+ ...u.input_tokens != null ? { inputTokens: u.input_tokens } : {},
355
+ ...u.output_tokens != null ? { outputTokens: u.output_tokens } : {},
356
+ ...u.total_tokens != null ? { totalTokens: u.total_tokens } : {},
357
+ ...u.input_tokens_details?.cached_tokens != null ? { cachedInputTokens: u.input_tokens_details.cached_tokens } : {},
358
+ ...u.output_tokens_details?.reasoning_tokens != null ? { reasoningTokens: u.output_tokens_details.reasoning_tokens } : {}
359
+ };
360
+ }
361
+ function usageFromChat(u) {
362
+ if (!u) return {};
363
+ return {
364
+ ...u.prompt_tokens != null ? { inputTokens: u.prompt_tokens } : {},
365
+ ...u.completion_tokens != null ? { outputTokens: u.completion_tokens } : {},
366
+ ...u.total_tokens != null ? { totalTokens: u.total_tokens } : {},
367
+ ...u.prompt_tokens_details?.cached_tokens != null ? { cachedInputTokens: u.prompt_tokens_details.cached_tokens } : {},
368
+ ...u.completion_tokens_details?.reasoning_tokens != null ? { reasoningTokens: u.completion_tokens_details.reasoning_tokens } : {}
369
+ };
370
+ }
371
+ function finishFromResponses(r) {
372
+ switch (r.status) {
373
+ case "completed":
374
+ return r.output.some((o) => o.type === "function_call") ? "tool-calls" : "stop";
375
+ case "cancelled":
376
+ return "cancelled";
377
+ case "failed":
378
+ return "error";
379
+ case "incomplete": {
380
+ const reason = r.incomplete_details?.reason ?? "";
381
+ if (/max_output_tokens|max_tokens|length/i.test(reason)) return "length";
382
+ if (/content_filter|refusal|safety/i.test(reason)) return "content-filter";
383
+ return "unknown";
384
+ }
385
+ default:
386
+ return "unknown";
387
+ }
388
+ }
389
+ function finishFromChat(raw) {
390
+ switch (raw) {
391
+ case "stop":
392
+ return "stop";
393
+ case "length":
394
+ return "length";
395
+ case "tool_calls":
396
+ case "function_call":
397
+ return "tool-calls";
398
+ case "content_filter":
399
+ return "content-filter";
400
+ default:
401
+ return raw ? "unknown" : "stop";
402
+ }
403
+ }
404
+ function partsFromResponses(r) {
405
+ const parts = [];
406
+ for (const item of r.output ?? []) {
407
+ if (item.type === "message") {
408
+ for (const c of item.content ?? []) {
409
+ if (c.type === "output_text" && c.text) parts.push({ type: "text", text: c.text });
410
+ else if (c.type === "refusal" && c.refusal) parts.push({ type: "text", text: c.refusal });
411
+ }
412
+ continue;
413
+ }
414
+ if (item.type === "function_call") {
415
+ const call = item;
416
+ const { value, repaired } = repairToolArguments(call.arguments);
417
+ parts.push({
418
+ type: "tool-call",
419
+ callId: call.call_id,
420
+ name: call.name,
421
+ input: value,
422
+ status: "pending",
423
+ ...repaired ? { repaired: true } : {}
424
+ });
425
+ continue;
426
+ }
427
+ if (item.type === "reasoning") {
428
+ const rz = item;
429
+ const text = (rz.summary ?? []).map((s) => s.text).join("\n");
430
+ parts.push({ type: "reasoning", text, signature: rz.id });
431
+ continue;
432
+ }
433
+ const record = item;
434
+ parts.push({
435
+ type: "artifact",
436
+ id: record.id ?? `${record.type}_${parts.length}`,
437
+ kind: `provider-tool:${record.type}`,
438
+ data: record
439
+ });
440
+ }
441
+ return parts;
442
+ }
443
+ function partsFromChat(r) {
444
+ const choice = r.choices?.[0];
445
+ if (!choice) return [];
446
+ const parts = [];
447
+ const msg = choice.message;
448
+ if (msg.refusal) parts.push({ type: "text", text: msg.refusal });
449
+ if (msg.reasoning_content) parts.push({ type: "reasoning", text: msg.reasoning_content });
450
+ if (msg.content) parts.push({ type: "text", text: msg.content });
451
+ for (const call of msg.tool_calls ?? []) {
452
+ const { value, repaired } = repairToolArguments(call.function.arguments);
453
+ parts.push({
454
+ type: "tool-call",
455
+ callId: call.id,
456
+ name: call.function.name,
457
+ input: value,
458
+ status: "pending",
459
+ ...repaired ? { repaired: true } : {}
460
+ });
461
+ }
462
+ return parts;
463
+ }
464
+
465
+ // src/providers/openai/stream.ts
466
+ async function* streamResponses(body, opts = {}) {
467
+ const callsByItemId = /* @__PURE__ */ new Map();
468
+ let started = false;
469
+ for await (const { data } of parseSSEJson(body)) {
470
+ if (typeof data.sequence_number === "number") opts.onCursor?.(data.sequence_number);
471
+ switch (data.type) {
472
+ case "response.created":
473
+ case "response.in_progress": {
474
+ if (started) break;
475
+ started = true;
476
+ yield { type: "start", responseId: data.response?.id, modelId: data.response?.model ?? "" };
477
+ break;
478
+ }
479
+ case "response.output_item.added": {
480
+ const item = data.item;
481
+ if (item?.type === "function_call") {
482
+ const fc = item;
483
+ const key = fc.id ?? fc.call_id;
484
+ callsByItemId.set(key, { callId: fc.call_id, name: fc.name, args: "" });
485
+ yield { type: "tool-call-start", callId: fc.call_id, name: fc.name };
486
+ }
487
+ break;
488
+ }
489
+ case "response.output_text.delta": {
490
+ if (data.delta) yield { type: "text-delta", delta: data.delta };
491
+ break;
492
+ }
493
+ case "response.reasoning_summary_text.delta": {
494
+ if (data.delta) {
495
+ yield { type: "reasoning-delta", delta: data.delta, ...data.item_id ? { signature: data.item_id } : {} };
496
+ }
497
+ break;
498
+ }
499
+ case "response.function_call_arguments.delta": {
500
+ const key = data.item_id ?? "";
501
+ const pending = callsByItemId.get(key);
502
+ if (pending && data.delta) {
503
+ pending.args += data.delta;
504
+ yield { type: "tool-call-delta", callId: pending.callId, argsDelta: data.delta };
505
+ }
506
+ break;
507
+ }
508
+ case "response.function_call_arguments.done": {
509
+ const key = data.item_id ?? "";
510
+ const pending = callsByItemId.get(key);
511
+ if (pending) {
512
+ const raw = data.arguments ?? pending.args;
513
+ const { value, repaired } = repairToolArguments(raw);
514
+ yield { type: "tool-call-end", callId: pending.callId, name: pending.name, input: value, repaired };
515
+ callsByItemId.delete(key);
516
+ }
517
+ break;
518
+ }
519
+ case "response.completed":
520
+ case "response.incomplete":
521
+ case "response.failed": {
522
+ const r = data.response;
523
+ if (!r) break;
524
+ for (const [key, pending] of callsByItemId) {
525
+ const { value, repaired } = repairToolArguments(pending.args);
526
+ yield { type: "tool-call-end", callId: pending.callId, name: pending.name, input: value, repaired };
527
+ callsByItemId.delete(key);
528
+ }
529
+ const usage = usageFromResponses(r.usage);
530
+ yield { type: "usage", usage };
531
+ yield { type: "finish", finishReason: finishFromResponses(r), responseId: r.id, usage };
532
+ return;
533
+ }
534
+ case "error": {
535
+ yield { type: "error", error: { message: data.message ?? "Stream error", code: data.code } };
536
+ return;
537
+ }
538
+ default:
539
+ break;
540
+ }
541
+ }
542
+ }
543
+ async function* streamChat(body) {
544
+ const pending = /* @__PURE__ */ new Map();
545
+ let started = false;
546
+ let finish = null;
547
+ let lastUsage = null;
548
+ for await (const { data } of parseSSEJson(body)) {
549
+ if (!started) {
550
+ started = true;
551
+ yield { type: "start", responseId: data.id, modelId: data.model };
552
+ }
553
+ if (data.usage) lastUsage = usageFromChat(data.usage);
554
+ const choice = data.choices?.[0];
555
+ if (!choice) continue;
556
+ const delta = choice.delta ?? {};
557
+ if (delta.reasoning_content) yield { type: "reasoning-delta", delta: delta.reasoning_content };
558
+ if (delta.content) yield { type: "text-delta", delta: delta.content };
559
+ for (const call of delta.tool_calls ?? []) {
560
+ const index = call.index ?? 0;
561
+ let entry = pending.get(index);
562
+ if (!entry) {
563
+ entry = { callId: call.id ?? `call_${index}`, name: "", args: "", announced: false };
564
+ pending.set(index, entry);
565
+ }
566
+ if (call.id) entry.callId = call.id;
567
+ if (call.function?.name) entry.name += call.function.name;
568
+ if (!entry.announced && entry.name && entry.callId) {
569
+ entry.announced = true;
570
+ yield { type: "tool-call-start", callId: entry.callId, name: entry.name };
571
+ }
572
+ if (call.function?.arguments) {
573
+ entry.args += call.function.arguments;
574
+ if (entry.announced) yield { type: "tool-call-delta", callId: entry.callId, argsDelta: call.function.arguments };
575
+ }
576
+ }
577
+ if (choice.finish_reason) {
578
+ finish = { type: "finish", finishReason: finishFromChat(choice.finish_reason), responseId: data.id };
579
+ }
580
+ }
581
+ for (const entry of pending.values()) {
582
+ const { value, repaired } = repairToolArguments(entry.args);
583
+ if (!entry.announced) yield { type: "tool-call-start", callId: entry.callId, name: entry.name };
584
+ yield { type: "tool-call-end", callId: entry.callId, name: entry.name, input: value, repaired };
585
+ }
586
+ if (lastUsage) yield { type: "usage", usage: lastUsage };
587
+ yield finish ? { ...finish, ...lastUsage ? { usage: lastUsage } : {} } : { type: "finish", finishReason: pending.size ? "tool-calls" : "stop", ...lastUsage ? { usage: lastUsage } : {} };
588
+ }
589
+ async function finalResponseFromStream(body) {
590
+ for await (const msg of parseSSE(body)) {
591
+ if (!msg.data || msg.data === "[DONE]") continue;
592
+ try {
593
+ const evt = JSON.parse(msg.data);
594
+ if ((evt.type === "response.completed" || evt.type === "response.failed" || evt.type === "response.incomplete") && evt.response) {
595
+ return evt.response;
596
+ }
597
+ } catch {
598
+ continue;
599
+ }
600
+ }
601
+ return null;
602
+ }
603
+
604
+ // src/providers/openai/models.ts
605
+ var OPENAI_MODELS = [
606
+ { id: "gpt-5.2", label: "GPT-5.2", contextWindow: 4e5, maxOutputTokens: 128e3 },
607
+ { id: "gpt-5.2-mini", label: "GPT-5.2 mini", contextWindow: 4e5, maxOutputTokens: 128e3 },
608
+ { id: "gpt-5.1", label: "GPT-5.1", contextWindow: 4e5, maxOutputTokens: 128e3 },
609
+ { id: "gpt-4.1", label: "GPT-4.1", contextWindow: 1047576, maxOutputTokens: 32768 },
610
+ { id: "gpt-4.1-mini", label: "GPT-4.1 mini", contextWindow: 1047576, maxOutputTokens: 32768 },
611
+ { id: "gpt-4o", label: "GPT-4o", contextWindow: 128e3, maxOutputTokens: 16384 },
612
+ { id: "gpt-4o-mini", label: "GPT-4o mini", contextWindow: 128e3, maxOutputTokens: 16384 },
613
+ { id: "o4-mini", label: "o4-mini", contextWindow: 2e5, maxOutputTokens: 1e5 }
614
+ ];
615
+ function modelCapabilities(modelId) {
616
+ const id = modelId.toLowerCase();
617
+ if (/^(o\d|gpt-5)/.test(id)) return { reasoning: true };
618
+ if (/gpt-4o|gpt-4\.1/.test(id)) return { reasoning: false };
619
+ return void 0;
620
+ }
621
+ function isReasoningModel(modelId) {
622
+ return /^(o\d|gpt-5)/.test(modelId.toLowerCase());
623
+ }
624
+ function sanitizeForModel(req, modelId) {
625
+ if (!isReasoningModel(modelId)) return req;
626
+ const { temperature: _t, topP: _p, ...rest } = req;
627
+ return rest;
628
+ }
629
+
630
+ // src/providers/openai/adapter.ts
631
+ var RESPONSES_CAPS = {
632
+ streaming: true,
633
+ backgroundJobs: true,
634
+ resumableStreams: true,
635
+ tools: true,
636
+ parallelToolCalls: true,
637
+ images: true,
638
+ files: true,
639
+ audio: false,
640
+ reasoning: true,
641
+ strictJsonSchema: true,
642
+ serverSideHistory: true,
643
+ fileUpload: true
644
+ };
645
+ var CHAT_CAPS = {
646
+ ...RESPONSES_CAPS,
647
+ backgroundJobs: false,
648
+ resumableStreams: false,
649
+ audio: true,
650
+ serverSideHistory: false,
651
+ // Most OpenAI-compatible routers implement /chat/completions but not /files.
652
+ // Override via `capabilities` for the ones that do.
653
+ fileUpload: false
654
+ };
655
+ function createOpenAIProvider(config) {
656
+ const dialect = config.dialect ?? "responses";
657
+ const id = config.id ?? "openai";
658
+ const capabilities = {
659
+ ...dialect === "responses" ? RESPONSES_CAPS : CHAT_CAPS,
660
+ ...config.capabilities
661
+ };
662
+ async function call(path, init, opts) {
663
+ const signal = withDefaultTimeout(opts?.signal);
664
+ return withRetry(
665
+ async () => {
666
+ const res = await config.transport.fetch({
667
+ provider: id,
668
+ path,
669
+ method: init.method,
670
+ body: init.body,
671
+ stream: init.stream,
672
+ query: init.query,
673
+ headers: opts?.headers,
674
+ signal
675
+ });
676
+ if (!res.ok) throw await errorFromResponse(res, id);
677
+ return res;
678
+ },
679
+ { policy: config.retry, signal, provider: id }
680
+ );
681
+ }
682
+ function guardRequest(req) {
683
+ if (req.background && !capabilities.backgroundJobs) {
684
+ throw new AgentError(
685
+ "not-supported",
686
+ `Provider "${id}" (${dialect} dialect) has no background mode. Use streaming, or switch to the Responses dialect.`,
687
+ { provider: id }
688
+ );
689
+ }
690
+ if (req.tools?.length && !capabilities.tools) {
691
+ throw new AgentError("not-supported", `Provider "${id}" does not support tools.`, { provider: id });
692
+ }
693
+ if (!capabilities.images || !capabilities.files || !capabilities.audio) {
694
+ let hasImage = false;
695
+ let hasFile = false;
696
+ let hasAudio = false;
697
+ req.messages.some(
698
+ (m) => m.parts.some((p) => {
699
+ if (p.type === "image") hasImage = true;
700
+ else if (p.type === "file") hasFile = true;
701
+ else if (p.type === "audio") hasAudio = true;
702
+ return hasImage && hasFile && hasAudio;
703
+ })
704
+ );
705
+ if (!capabilities.images && hasImage) {
706
+ throw new AgentError("not-supported", `Provider "${id}" does not accept image parts.`, { provider: id });
707
+ }
708
+ if (!capabilities.files && hasFile) {
709
+ throw new AgentError("not-supported", `Provider "${id}" does not accept file parts.`, { provider: id });
710
+ }
711
+ if (!capabilities.audio && hasAudio) {
712
+ throw new AgentError("not-supported", `Provider "${id}" does not accept audio parts.`, { provider: id });
713
+ }
714
+ }
715
+ }
716
+ function applyCapabilities(req) {
717
+ if (capabilities.strictJsonSchema || !req.tools?.some((t) => t.strict)) return req;
718
+ return { ...req, tools: req.tools.map(({ strict: _strict, ...t }) => t) };
719
+ }
720
+ const buildOpts = (stream) => ({
721
+ ...stream ? { stream: true } : {},
722
+ providerId: id,
723
+ parallelToolCalls: capabilities.parallelToolCalls
724
+ });
725
+ function resultFromResponses(r) {
726
+ return {
727
+ parts: partsFromResponses(r),
728
+ finishReason: finishFromResponses(r),
729
+ usage: usageFromResponses(r.usage),
730
+ responseId: r.id,
731
+ modelId: r.model,
732
+ raw: r
733
+ };
734
+ }
735
+ const provider = {
736
+ id,
737
+ label: config.label ?? (dialect === "responses" ? "OpenAI" : "OpenAI-compatible"),
738
+ capabilities,
739
+ transport: config.transport,
740
+ async generate(rawReq, opts) {
741
+ guardRequest(rawReq);
742
+ const req = applyCapabilities(rawReq);
743
+ if (dialect === "responses") {
744
+ const res2 = await call("/responses", { method: "POST", body: buildResponsesRequest(req, buildOpts()) }, opts);
745
+ const json2 = await res2.json();
746
+ if (json2.status === "failed" && json2.error) {
747
+ throw new AgentError("unknown", json2.error.message, { provider: id, detail: json2.error });
748
+ }
749
+ return resultFromResponses(json2);
750
+ }
751
+ const res = await call("/chat/completions", { method: "POST", body: buildChatRequest(req, buildOpts()) }, opts);
752
+ const json = await res.json();
753
+ return {
754
+ parts: partsFromChat(json),
755
+ finishReason: finishFromChat(json.choices?.[0]?.finish_reason),
756
+ usage: usageFromChat(json.usage),
757
+ responseId: json.id,
758
+ modelId: json.model,
759
+ raw: json
760
+ };
761
+ },
762
+ async *stream(rawReq, opts) {
763
+ guardRequest(rawReq);
764
+ const req = applyCapabilities(rawReq);
765
+ try {
766
+ if (dialect === "responses") {
767
+ const res2 = await call(
768
+ "/responses",
769
+ { method: "POST", body: buildResponsesRequest(req, buildOpts(true)), stream: true },
770
+ opts
771
+ );
772
+ if (!res2.body) throw new AgentError("network", "Response had no body to stream.", { provider: id });
773
+ yield* streamResponses(res2.body);
774
+ return;
775
+ }
776
+ const res = await call(
777
+ "/chat/completions",
778
+ { method: "POST", body: buildChatRequest(req, buildOpts(true)), stream: true },
779
+ opts
780
+ );
781
+ if (!res.body) throw new AgentError("network", "Response had no body to stream.", { provider: id });
782
+ yield* streamChat(res.body);
783
+ } catch (e) {
784
+ yield { type: "error", error: toAgentError(e, id) };
785
+ }
786
+ },
787
+ async startJob(rawReq, opts) {
788
+ if (!capabilities.backgroundJobs) {
789
+ throw new AgentError("not-supported", `Provider "${id}" has no background mode.`, { provider: id });
790
+ }
791
+ const req = applyCapabilities(rawReq);
792
+ const body = buildResponsesRequest({ ...req, background: true }, buildOpts());
793
+ const res = await call("/responses", { method: "POST", body }, opts);
794
+ const json = await res.json();
795
+ return { provider: id, id: json.id, model: json.model || req.model, createdAt: Date.now() };
796
+ },
797
+ async pollJob(handle, opts) {
798
+ const res = await call(`/responses/${encodeURIComponent(handle.id)}`, { method: "GET" }, opts);
799
+ const json = await res.json();
800
+ if (json.status === "failed") {
801
+ return {
802
+ handle,
803
+ status: "failed",
804
+ error: { message: json.error?.message ?? "Background response failed.", code: json.error?.code }
805
+ };
806
+ }
807
+ if (json.status === "completed" || json.status === "incomplete") {
808
+ return { handle, status: json.status, result: resultFromResponses(json) };
809
+ }
810
+ return { handle, status: json.status };
811
+ },
812
+ async cancelJob(handle, opts) {
813
+ const res = await call(`/responses/${encodeURIComponent(handle.id)}/cancel`, { method: "POST" }, opts);
814
+ const json = await res.json();
815
+ return { handle, status: json.status === "cancelled" ? "cancelled" : json.status };
816
+ },
817
+ async *streamJob(handle, opts) {
818
+ let cursor = handle.cursor;
819
+ try {
820
+ const res = await call(
821
+ `/responses/${encodeURIComponent(handle.id)}`,
822
+ {
823
+ method: "GET",
824
+ stream: true,
825
+ query: { stream: true, ...cursor != null ? { starting_after: cursor } : {} }
826
+ },
827
+ opts
828
+ );
829
+ if (!res.body) throw new AgentError("network", "Job stream had no body.", { provider: id });
830
+ yield* streamResponses(res.body, {
831
+ onCursor: (seq) => {
832
+ cursor = seq;
833
+ handle.cursor = seq;
834
+ }
835
+ });
836
+ } catch (e) {
837
+ yield { type: "error", error: toAgentError(e, id) };
838
+ }
839
+ },
840
+ async uploadFile(req, opts) {
841
+ if (!capabilities.fileUpload) {
842
+ throw new AgentError("not-supported", `Provider "${id}" has no file upload endpoint.`, { provider: id });
843
+ }
844
+ const data = req.data instanceof Uint8Array ? req.data : req.data instanceof ArrayBuffer ? new Uint8Array(req.data) : new Uint8Array(await req.data.arrayBuffer());
845
+ const res = await call(
846
+ "/files",
847
+ {
848
+ method: "POST",
849
+ body: {
850
+ kind: "multipart",
851
+ fields: { purpose: req.purpose ?? "user_data" },
852
+ files: [
853
+ {
854
+ field: "file",
855
+ filename: req.filename,
856
+ ...req.mediaType ? { mediaType: req.mediaType } : {},
857
+ data
858
+ }
859
+ ]
860
+ }
861
+ },
862
+ opts
863
+ );
864
+ const json = await res.json();
865
+ return {
866
+ kind: "providerFile",
867
+ id: json.id,
868
+ provider: id,
869
+ filename: json.filename ?? req.filename,
870
+ ...json.bytes != null ? { sizeBytes: json.bytes } : {},
871
+ ...json.created_at != null ? { createdAt: json.created_at * 1e3 } : {}
872
+ };
873
+ },
874
+ async deleteFile(fileId, opts) {
875
+ await call(`/files/${encodeURIComponent(fileId)}`, { method: "DELETE" }, opts);
876
+ },
877
+ async listModels(opts) {
878
+ if (config.models) return config.models;
879
+ try {
880
+ const res = await call("/models", { method: "GET" }, opts);
881
+ const json = await res.json();
882
+ const remote = (json.data ?? []).map((m) => ({
883
+ id: m.id,
884
+ ...modelCapabilities(m.id) ? { supports: modelCapabilities(m.id) } : {}
885
+ }));
886
+ return remote.length ? remote : OPENAI_MODELS;
887
+ } catch {
888
+ return OPENAI_MODELS;
889
+ }
890
+ }
891
+ };
892
+ return provider;
893
+ }
894
+
895
+ // src/runtime/jobs.ts
896
+ async function awaitJob(provider, handle, opts = {}) {
897
+ if (!provider.pollJob) {
898
+ throw new AgentError("not-supported", `Provider "${provider.id}" cannot poll jobs.`, { provider: provider.id });
899
+ }
900
+ const start = Date.now();
901
+ const maxInterval = opts.maxIntervalMs ?? 5e3;
902
+ let interval = opts.initialIntervalMs ?? 1e3;
903
+ for (; ; ) {
904
+ if (opts.signal?.aborted) throw new AgentError("cancelled", "Job wait was cancelled.", { provider: provider.id });
905
+ const snapshot = await provider.pollJob(handle, { signal: opts.signal });
906
+ opts.onStatus?.(snapshot);
907
+ if (snapshot.status !== "queued" && snapshot.status !== "in_progress") return snapshot;
908
+ if (opts.timeoutMs && Date.now() - start > opts.timeoutMs) {
909
+ throw new AgentError("timeout", `Background job ${handle.id} did not finish within ${opts.timeoutMs}ms.`, {
910
+ provider: provider.id
911
+ });
912
+ }
913
+ await pollWait(interval, opts.signal);
914
+ interval = Math.min(interval * 1.5, maxInterval);
915
+ }
916
+ }
917
+ function pollWait(ms, signal) {
918
+ return new Promise((resolve, reject) => {
919
+ if (signal?.aborted) {
920
+ reject(new AgentError("cancelled", "Job wait was cancelled."));
921
+ return;
922
+ }
923
+ const onAbort = () => {
924
+ clearTimeout(t);
925
+ reject(new AgentError("cancelled", "Job wait was cancelled."));
926
+ };
927
+ const t = setTimeout(() => {
928
+ signal?.removeEventListener("abort", onAbort);
929
+ resolve();
930
+ }, ms);
931
+ signal?.addEventListener("abort", onAbort, { once: true });
932
+ });
933
+ }
934
+ function createMemoryJobStore() {
935
+ const jobs = /* @__PURE__ */ new Map();
936
+ return {
937
+ async list() {
938
+ return [...jobs.values()].sort((a, b) => b.createdAt - a.createdAt);
939
+ },
940
+ async get(id) {
941
+ return jobs.get(id);
942
+ },
943
+ async put(job) {
944
+ jobs.set(job.handle.id, job);
945
+ },
946
+ async remove(id) {
947
+ jobs.delete(id);
948
+ }
949
+ };
950
+ }
951
+ function createLocalJobStore(prefix = "superchat:jobs") {
952
+ const indexKey = `${prefix}:index`;
953
+ const jobKey = (id) => `${prefix}:${id}`;
954
+ const readIndex = () => {
955
+ try {
956
+ const raw = globalThis.localStorage?.getItem(indexKey) ?? null;
957
+ const parsed = raw ? JSON.parse(raw) : [];
958
+ return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : [];
959
+ } catch {
960
+ return [];
961
+ }
962
+ };
963
+ const writeIndex = (ids) => {
964
+ try {
965
+ globalThis.localStorage?.setItem(indexKey, JSON.stringify(ids));
966
+ } catch {
967
+ }
968
+ };
969
+ const readJob = (id) => {
970
+ try {
971
+ const raw = globalThis.localStorage?.getItem(jobKey(id)) ?? null;
972
+ return raw ? JSON.parse(raw) : void 0;
973
+ } catch {
974
+ return void 0;
975
+ }
976
+ };
977
+ return {
978
+ async list() {
979
+ const jobs = readIndex().map((id) => readJob(id)).filter((j) => j != null);
980
+ return jobs.sort((a, b) => b.createdAt - a.createdAt);
981
+ },
982
+ async get(id) {
983
+ return readJob(id);
984
+ },
985
+ async put(job) {
986
+ const id = job.handle.id;
987
+ try {
988
+ globalThis.localStorage?.setItem(jobKey(id), JSON.stringify(job));
989
+ } catch {
990
+ return;
991
+ }
992
+ const index = readIndex();
993
+ if (!index.includes(id)) writeIndex([...index, id]);
994
+ },
995
+ async remove(id) {
996
+ try {
997
+ globalThis.localStorage?.removeItem(jobKey(id));
998
+ } catch {
999
+ }
1000
+ const index = readIndex();
1001
+ if (index.includes(id)) writeIndex(index.filter((x) => x !== id));
1002
+ }
1003
+ };
1004
+ }
1005
+ var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "incomplete"]);
1006
+ var isTerminal = (status) => TERMINAL.has(status);
1007
+ async function reap(store, opts = {}) {
1008
+ const maxAge = opts.maxAgeMs ?? 30 * 6e4;
1009
+ const now = Date.now();
1010
+ const kept = [];
1011
+ for (const job of await store.list()) {
1012
+ if (isTerminal(job.status) || now - job.createdAt > maxAge) {
1013
+ await store.remove(job.handle.id);
1014
+ continue;
1015
+ }
1016
+ kept.push(job);
1017
+ }
1018
+ return kept;
1019
+ }
1020
+ async function resumeJobs(store, providers, opts = {}) {
1021
+ const out = [];
1022
+ for (const job of await reap(store)) {
1023
+ const provider = providers[job.handle.provider];
1024
+ if (!provider?.pollJob) {
1025
+ await store.remove(job.handle.id);
1026
+ continue;
1027
+ }
1028
+ try {
1029
+ const snapshot = await provider.pollJob(job.handle, { signal: opts.signal });
1030
+ const updated = { ...job, status: snapshot.status, updatedAt: Date.now() };
1031
+ if (isTerminal(snapshot.status)) await store.remove(job.handle.id);
1032
+ else await store.put(updated);
1033
+ out.push({ job: updated, snapshot });
1034
+ } catch (e) {
1035
+ const updated = { ...job, status: "failed", updatedAt: Date.now() };
1036
+ await store.remove(job.handle.id);
1037
+ out.push({
1038
+ job: updated,
1039
+ snapshot: {
1040
+ handle: job.handle,
1041
+ status: "failed",
1042
+ error: {
1043
+ message: e instanceof Error && /404|not found/i.test(e.message) ? "This background job expired before it could be read back." : e instanceof Error ? e.message : "Could not resume job."
1044
+ }
1045
+ }
1046
+ });
1047
+ }
1048
+ }
1049
+ return out;
1050
+ }
1051
+
1052
+ export {
1053
+ toResponsesInput,
1054
+ dropOrphanToolCalls,
1055
+ buildResponsesRequest,
1056
+ toChatMessages,
1057
+ dropOrphanChatToolCalls,
1058
+ buildChatRequest,
1059
+ usageFromResponses,
1060
+ usageFromChat,
1061
+ finishFromResponses,
1062
+ finishFromChat,
1063
+ partsFromResponses,
1064
+ partsFromChat,
1065
+ streamResponses,
1066
+ streamChat,
1067
+ finalResponseFromStream,
1068
+ OPENAI_MODELS,
1069
+ modelCapabilities,
1070
+ isReasoningModel,
1071
+ sanitizeForModel,
1072
+ createOpenAIProvider,
1073
+ awaitJob,
1074
+ createMemoryJobStore,
1075
+ createLocalJobStore,
1076
+ isTerminal,
1077
+ reap,
1078
+ resumeJobs
1079
+ };
1080
+ //# sourceMappingURL=chunk-MHGENDQX.js.map