@supersolutions/super-chat-core 0.4.4 → 0.5.1

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.
@@ -1,17 +1,20 @@
1
1
  import {
2
2
  AgentError,
3
3
  collectAnsweredIds,
4
+ count,
4
5
  dropUnanswered,
5
6
  errorFromResponse,
6
7
  filterNativeTools,
7
8
  foreignFileText,
8
9
  parseSSE,
9
10
  parseSSEJson,
11
+ readObject,
10
12
  repairToolArguments,
13
+ text,
11
14
  toAgentError,
12
15
  withDefaultTimeout,
13
16
  withRetry
14
- } from "./chunk-32DPF33V.js";
17
+ } from "./chunk-7G4U4NTL.js";
15
18
 
16
19
  // src/providers/openai/map-in.ts
17
20
  function dataUrl(mediaType, base64) {
@@ -61,8 +64,8 @@ function toResponsesInput(messages, providerId = "openai") {
61
64
  const items = [];
62
65
  for (const m of messages) {
63
66
  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 }] });
67
+ const text2 = m.parts.filter((p) => p.type === "text").map((p) => p.text).join("\n");
68
+ if (text2) items.push({ type: "message", role: "developer", content: [{ type: "input_text", text: text2 }] });
66
69
  continue;
67
70
  }
68
71
  const role = m.role === "assistant" ? "assistant" : "user";
@@ -231,21 +234,21 @@ function toChatMessages(messages, system, providerId = "openai") {
231
234
  if (system) out.push({ role: "system", content: system });
232
235
  for (const m of messages) {
233
236
  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 });
237
+ const text2 = m.parts.filter((p) => p.type === "text").map((p) => p.text).join("\n");
238
+ if (text2) out.push({ role: "system", content: text2 });
236
239
  continue;
237
240
  }
238
241
  if (m.role === "assistant") {
239
- const text = m.parts.filter((p) => p.type === "text").map((p) => p.text).join("");
242
+ const text2 = m.parts.filter((p) => p.type === "text").map((p) => p.text).join("");
240
243
  const calls = m.parts.filter((p) => p.type === "tool-call").map((p) => ({
241
244
  id: p.callId,
242
245
  type: "function",
243
246
  function: { name: p.name, arguments: typeof p.input === "string" ? p.input : JSON.stringify(p.input ?? {}) }
244
247
  }));
245
- if (text || calls.length) {
248
+ if (text2 || calls.length) {
246
249
  out.push({
247
250
  role: "assistant",
248
- ...text ? { content: text } : { content: null },
251
+ ...text2 ? { content: text2 } : { content: null },
249
252
  ...calls.length ? { tool_calls: calls } : {}
250
253
  });
251
254
  }
@@ -349,35 +352,43 @@ function buildChatRequest(req, opts = {}) {
349
352
 
350
353
  // src/providers/openai/map-out.ts
351
354
  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 } : {}
355
+ if (!u || typeof u !== "object") return {};
356
+ const out = {};
357
+ const set = (key, value) => {
358
+ const n = count(value);
359
+ if (n !== void 0) out[key] = n;
359
360
  };
361
+ set("inputTokens", u.input_tokens);
362
+ set("outputTokens", u.output_tokens);
363
+ set("totalTokens", u.total_tokens);
364
+ set("cachedInputTokens", u.input_tokens_details?.cached_tokens);
365
+ set("reasoningTokens", u.output_tokens_details?.reasoning_tokens);
366
+ return out;
360
367
  }
361
368
  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
+ if (!u || typeof u !== "object") return {};
370
+ const out = {};
371
+ const set = (key, value) => {
372
+ const n = count(value);
373
+ if (n !== void 0) out[key] = n;
369
374
  };
375
+ set("inputTokens", u.prompt_tokens);
376
+ set("outputTokens", u.completion_tokens);
377
+ set("totalTokens", u.total_tokens);
378
+ set("cachedInputTokens", u.prompt_tokens_details?.cached_tokens);
379
+ set("reasoningTokens", u.completion_tokens_details?.reasoning_tokens);
380
+ return out;
370
381
  }
371
382
  function finishFromResponses(r) {
372
383
  switch (r.status) {
373
384
  case "completed":
374
- return r.output.some((o) => o.type === "function_call") ? "tool-calls" : "stop";
385
+ return (Array.isArray(r.output) ? r.output : []).some((o) => typeof o === "object" && o !== null && o.type === "function_call") ? "tool-calls" : "stop";
375
386
  case "cancelled":
376
387
  return "cancelled";
377
388
  case "failed":
378
389
  return "error";
379
390
  case "incomplete": {
380
- const reason = r.incomplete_details?.reason ?? "";
391
+ const reason = text(r.incomplete_details?.reason) ?? "";
381
392
  if (/max_output_tokens|max_tokens|length/i.test(reason)) return "length";
382
393
  if (/content_filter|refusal|safety/i.test(reason)) return "content-filter";
383
394
  return "unknown";
@@ -403,21 +414,29 @@ function finishFromChat(raw) {
403
414
  }
404
415
  function partsFromResponses(r) {
405
416
  const parts = [];
406
- for (const item of r.output ?? []) {
417
+ for (const item of Array.isArray(r?.output) ? r.output : []) {
418
+ if (item === null || typeof item !== "object") continue;
407
419
  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 });
420
+ const content = item.content;
421
+ for (const c of Array.isArray(content) ? content : []) {
422
+ if (c === null || typeof c !== "object") continue;
423
+ const t = text(c.text);
424
+ const refusal = text(c.refusal);
425
+ if (c.type === "output_text" && t) parts.push({ type: "text", text: t });
426
+ else if (c.type === "refusal" && refusal) parts.push({ type: "text", text: refusal });
411
427
  }
412
428
  continue;
413
429
  }
414
430
  if (item.type === "function_call") {
415
431
  const call = item;
432
+ const callId = text(call.call_id);
433
+ const name = text(call.name);
434
+ if (!callId || !name) throw new AgentError("unknown", "The model sent a tool call without an id or a name.", { provider: "openai" });
416
435
  const { value, repaired } = repairToolArguments(call.arguments);
417
436
  parts.push({
418
437
  type: "tool-call",
419
- callId: call.call_id,
420
- name: call.name,
438
+ callId,
439
+ name,
421
440
  input: value,
422
441
  status: "pending",
423
442
  ...repaired ? { repaired: true } : {}
@@ -426,14 +445,14 @@ function partsFromResponses(r) {
426
445
  }
427
446
  if (item.type === "reasoning") {
428
447
  const rz = item;
429
- const text = (rz.summary ?? []).map((s) => s.text).join("\n");
430
- parts.push({ type: "reasoning", text, signature: rz.id });
448
+ const summary = (Array.isArray(rz.summary) ? rz.summary : []).map((s) => text(s?.text) ?? "").join("\n");
449
+ parts.push({ type: "reasoning", text: summary, signature: text(rz.id) ?? "" });
431
450
  continue;
432
451
  }
433
452
  const record = item;
434
453
  parts.push({
435
454
  type: "artifact",
436
- id: record.id ?? `${record.type}_${parts.length}`,
455
+ id: text(record.id) ?? `${record.type}_${parts.length}`,
437
456
  kind: `provider-tool:${record.type}`,
438
457
  data: record
439
458
  });
@@ -441,19 +460,26 @@ function partsFromResponses(r) {
441
460
  return parts;
442
461
  }
443
462
  function partsFromChat(r) {
444
- const choice = r.choices?.[0];
445
- if (!choice) return [];
463
+ const choice = Array.isArray(r?.choices) ? r.choices[0] : void 0;
464
+ if (!choice || typeof choice !== "object" || choice.message === null || typeof choice.message !== "object") return [];
446
465
  const parts = [];
447
466
  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);
467
+ const refusal = text(msg.refusal);
468
+ if (refusal) parts.push({ type: "text", text: refusal });
469
+ const reasoning = text(msg.reasoning_content);
470
+ if (reasoning) parts.push({ type: "reasoning", text: reasoning });
471
+ const content = text(msg.content);
472
+ if (content) parts.push({ type: "text", text: content });
473
+ for (const call of Array.isArray(msg.tool_calls) ? msg.tool_calls : []) {
474
+ if (call === null || typeof call !== "object") continue;
475
+ const callId = text(call.id);
476
+ const name = text(call.function?.name);
477
+ if (!callId || !name) throw new AgentError("unknown", "The model sent a tool call without an id or a name.", { provider: "openai" });
478
+ const { value, repaired } = repairToolArguments(call.function?.arguments);
453
479
  parts.push({
454
480
  type: "tool-call",
455
- callId: call.id,
456
- name: call.function.name,
481
+ callId,
482
+ name,
457
483
  input: value,
458
484
  status: "pending",
459
485
  ...repaired ? { repaired: true } : {}
@@ -463,53 +489,64 @@ function partsFromChat(r) {
463
489
  }
464
490
 
465
491
  // src/providers/openai/stream.ts
492
+ var malformed = (message) => ({ type: "error", error: { message, code: "invalid_upstream_event" } });
466
493
  async function* streamResponses(body, opts = {}) {
467
494
  const callsByItemId = /* @__PURE__ */ new Map();
468
495
  let started = false;
469
496
  for await (const { data } of parseSSEJson(body)) {
497
+ if (data === null || typeof data !== "object") continue;
470
498
  if (typeof data.sequence_number === "number") opts.onCursor?.(data.sequence_number);
471
499
  switch (data.type) {
472
500
  case "response.created":
473
501
  case "response.in_progress": {
474
502
  if (started) break;
475
503
  started = true;
476
- yield { type: "start", responseId: data.response?.id, modelId: data.response?.model ?? "" };
504
+ yield { type: "start", responseId: text(data.response?.id), modelId: text(data.response?.model) ?? "" };
477
505
  break;
478
506
  }
479
507
  case "response.output_item.added": {
480
508
  const item = data.item;
481
509
  if (item?.type === "function_call") {
482
510
  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 };
511
+ const callId = text(fc.call_id);
512
+ const name = text(fc.name);
513
+ if (!callId || !name) {
514
+ yield malformed("The model sent a tool call without an id or a name.");
515
+ return;
516
+ }
517
+ callsByItemId.set(text(fc.id) || callId, { callId, name, args: "" });
518
+ yield { type: "tool-call-start", callId, name };
486
519
  }
487
520
  break;
488
521
  }
489
522
  case "response.output_text.delta": {
490
- if (data.delta) yield { type: "text-delta", delta: data.delta };
523
+ const delta = text(data.delta);
524
+ if (delta) yield { type: "text-delta", delta };
491
525
  break;
492
526
  }
493
527
  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 } : {} };
528
+ const delta = text(data.delta);
529
+ if (delta) {
530
+ const signature = text(data.item_id);
531
+ yield { type: "reasoning-delta", delta, ...signature ? { signature } : {} };
496
532
  }
497
533
  break;
498
534
  }
499
535
  case "response.function_call_arguments.delta": {
500
- const key = data.item_id ?? "";
536
+ const key = text(data.item_id) ?? "";
501
537
  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 };
538
+ const delta = text(data.delta);
539
+ if (pending && delta) {
540
+ pending.args += delta;
541
+ yield { type: "tool-call-delta", callId: pending.callId, argsDelta: delta };
505
542
  }
506
543
  break;
507
544
  }
508
545
  case "response.function_call_arguments.done": {
509
- const key = data.item_id ?? "";
546
+ const key = text(data.item_id) ?? "";
510
547
  const pending = callsByItemId.get(key);
511
548
  if (pending) {
512
- const raw = data.arguments ?? pending.args;
549
+ const raw = text(data.arguments) ?? pending.args;
513
550
  const { value, repaired } = repairToolArguments(raw);
514
551
  yield { type: "tool-call-end", callId: pending.callId, name: pending.name, input: value, repaired };
515
552
  callsByItemId.delete(key);
@@ -528,57 +565,91 @@ async function* streamResponses(body, opts = {}) {
528
565
  }
529
566
  const usage = usageFromResponses(r.usage);
530
567
  yield { type: "usage", usage };
531
- yield { type: "finish", finishReason: finishFromResponses(r), responseId: r.id, usage };
568
+ yield { type: "finish", finishReason: finishFromResponses(r), responseId: text(r.id), usage };
532
569
  return;
533
570
  }
534
571
  case "error": {
535
- yield { type: "error", error: { message: data.message ?? "Stream error", code: data.code } };
572
+ yield { type: "error", error: { message: text(data.message) ?? "Stream error", code: text(data.code) } };
536
573
  return;
537
574
  }
538
575
  default:
539
576
  break;
540
577
  }
541
578
  }
579
+ throw new AgentError("network", "The model's stream ended before it finished.", { provider: "openai" });
580
+ }
581
+ async function* chatChunks(body, onDone) {
582
+ for await (const msg of parseSSE(body)) {
583
+ if (msg.data === "[DONE]") {
584
+ onDone();
585
+ return;
586
+ }
587
+ if (!msg.data) continue;
588
+ try {
589
+ yield { event: msg.event, data: JSON.parse(msg.data) };
590
+ } catch {
591
+ }
592
+ }
542
593
  }
543
594
  async function* streamChat(body) {
544
595
  const pending = /* @__PURE__ */ new Map();
545
596
  let started = false;
597
+ let responseId;
546
598
  let finish = null;
547
599
  let lastUsage = null;
548
- for await (const { data } of parseSSEJson(body)) {
600
+ let sawDone = false;
601
+ for await (const { data } of chatChunks(body, () => sawDone = true)) {
602
+ if (data === null || typeof data !== "object") continue;
549
603
  if (!started) {
550
604
  started = true;
551
- yield { type: "start", responseId: data.id, modelId: data.model };
605
+ const id = text(data.id);
606
+ responseId = id;
607
+ yield { type: "start", responseId: id, modelId: text(data.model) ?? "" };
552
608
  }
553
609
  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;
610
+ const choice = Array.isArray(data.choices) ? data.choices[0] : void 0;
611
+ if (!choice || typeof choice !== "object") continue;
612
+ const delta = choice.delta !== null && typeof choice.delta === "object" && !Array.isArray(choice.delta) ? choice.delta : {};
613
+ const reasoning = text(delta.reasoning_content);
614
+ if (reasoning) yield { type: "reasoning-delta", delta: reasoning };
615
+ const content = text(delta.content);
616
+ if (content) yield { type: "text-delta", delta: content };
617
+ for (const call of Array.isArray(delta.tool_calls) ? delta.tool_calls : []) {
618
+ if (call === null || typeof call !== "object") continue;
619
+ const index = typeof call.index === "number" && Number.isSafeInteger(call.index) ? call.index : 0;
561
620
  let entry = pending.get(index);
562
621
  if (!entry) {
563
- entry = { callId: call.id ?? `call_${index}`, name: "", args: "", announced: false };
622
+ entry = { callId: text(call.id) || `call_${index}`, name: "", args: "", announced: false };
564
623
  pending.set(index, entry);
565
624
  }
566
- if (call.id) entry.callId = call.id;
567
- if (call.function?.name) entry.name += call.function.name;
625
+ const callId = text(call.id);
626
+ if (callId) entry.callId = callId;
627
+ const fn = call.function !== null && typeof call.function === "object" ? call.function : void 0;
628
+ const fragmentName = text(fn?.name);
629
+ if (fragmentName) entry.name += fragmentName;
568
630
  if (!entry.announced && entry.name && entry.callId) {
569
631
  entry.announced = true;
570
632
  yield { type: "tool-call-start", callId: entry.callId, name: entry.name };
571
633
  }
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 };
634
+ const fragmentArgs = text(fn?.arguments);
635
+ if (fragmentArgs) {
636
+ entry.args += fragmentArgs;
637
+ if (entry.announced) yield { type: "tool-call-delta", callId: entry.callId, argsDelta: fragmentArgs };
575
638
  }
576
639
  }
577
- if (choice.finish_reason) {
578
- finish = { type: "finish", finishReason: finishFromChat(choice.finish_reason), responseId: data.id };
640
+ const reason = text(choice.finish_reason);
641
+ if (reason) {
642
+ finish = { type: "finish", finishReason: finishFromChat(reason), ...responseId !== void 0 ? { responseId } : {} };
579
643
  }
580
644
  }
645
+ if (!finish && !sawDone) {
646
+ throw new AgentError("network", "The model's stream ended before it finished.", { provider: "openai" });
647
+ }
581
648
  for (const entry of pending.values()) {
649
+ if (!entry.name) {
650
+ yield malformed("The model sent a tool call without a name.");
651
+ return;
652
+ }
582
653
  const { value, repaired } = repairToolArguments(entry.args);
583
654
  if (!entry.announced) yield { type: "tool-call-start", callId: entry.callId, name: entry.name };
584
655
  yield { type: "tool-call-end", callId: entry.callId, name: entry.name, input: value, repaired };
@@ -722,13 +793,13 @@ function createOpenAIProvider(config) {
722
793
  providerId: id,
723
794
  parallelToolCalls: capabilities.parallelToolCalls
724
795
  });
725
- function resultFromResponses(r) {
796
+ function resultFromResponses(r, fallbackModel) {
726
797
  return {
727
798
  parts: partsFromResponses(r),
728
799
  finishReason: finishFromResponses(r),
729
800
  usage: usageFromResponses(r.usage),
730
- responseId: r.id,
731
- modelId: r.model,
801
+ responseId: text(r.id),
802
+ modelId: text(r.model) ?? fallbackModel,
732
803
  raw: r
733
804
  };
734
805
  }
@@ -742,20 +813,23 @@ function createOpenAIProvider(config) {
742
813
  const req = applyCapabilities(rawReq);
743
814
  if (dialect === "responses") {
744
815
  const res2 = await call("/responses", { method: "POST", body: buildResponsesRequest(req, buildOpts()) }, opts);
745
- const json2 = await res2.json();
816
+ const json2 = await readObject(res2, id);
746
817
  if (json2.status === "failed" && json2.error) {
747
- throw new AgentError("unknown", json2.error.message, { provider: id, detail: json2.error });
818
+ const message = text(json2.error.message);
819
+ throw new AgentError("unknown", message ?? "The provider reported that the response failed.", { provider: id, detail: json2.error });
748
820
  }
749
- return resultFromResponses(json2);
821
+ return resultFromResponses(json2, req.model);
750
822
  }
751
823
  const res = await call("/chat/completions", { method: "POST", body: buildChatRequest(req, buildOpts()) }, opts);
752
- const json = await res.json();
824
+ const json = await readObject(res, id);
825
+ const firstChoice = Array.isArray(json.choices) ? json.choices[0] : void 0;
826
+ const finish = typeof firstChoice === "object" && firstChoice !== null ? firstChoice.finish_reason : void 0;
753
827
  return {
754
828
  parts: partsFromChat(json),
755
- finishReason: finishFromChat(json.choices?.[0]?.finish_reason),
829
+ finishReason: finishFromChat(text(finish)),
756
830
  usage: usageFromChat(json.usage),
757
- responseId: json.id,
758
- modelId: json.model,
831
+ responseId: text(json.id),
832
+ modelId: text(json.model) ?? req.model,
759
833
  raw: json
760
834
  };
761
835
  },
@@ -791,27 +865,30 @@ function createOpenAIProvider(config) {
791
865
  const req = applyCapabilities(rawReq);
792
866
  const body = buildResponsesRequest({ ...req, background: true }, buildOpts());
793
867
  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() };
868
+ const json = await readObject(res, id);
869
+ const jobId = text(json.id);
870
+ if (!jobId) throw new AgentError("unknown", `Provider "${id}" started a background response without an id.`, { provider: id });
871
+ return { provider: id, id: jobId, model: text(json.model) || req.model, createdAt: Date.now() };
796
872
  },
797
873
  async pollJob(handle, opts) {
798
874
  const res = await call(`/responses/${encodeURIComponent(handle.id)}`, { method: "GET" }, opts);
799
- const json = await res.json();
875
+ const json = await readObject(res, id);
800
876
  if (json.status === "failed") {
877
+ const error = typeof json.error === "object" && json.error !== null ? json.error : {};
801
878
  return {
802
879
  handle,
803
880
  status: "failed",
804
- error: { message: json.error?.message ?? "Background response failed.", code: json.error?.code }
881
+ error: { message: text(error.message) ?? "Background response failed.", code: text(error.code) }
805
882
  };
806
883
  }
807
884
  if (json.status === "completed" || json.status === "incomplete") {
808
- return { handle, status: json.status, result: resultFromResponses(json) };
885
+ return { handle, status: json.status, result: resultFromResponses(json, handle.model) };
809
886
  }
810
887
  return { handle, status: json.status };
811
888
  },
812
889
  async cancelJob(handle, opts) {
813
890
  const res = await call(`/responses/${encodeURIComponent(handle.id)}/cancel`, { method: "POST" }, opts);
814
- const json = await res.json();
891
+ const json = await readObject(res, id);
815
892
  return { handle, status: json.status === "cancelled" ? "cancelled" : json.status };
816
893
  },
817
894
  async *streamJob(handle, opts) {
@@ -861,14 +938,18 @@ function createOpenAIProvider(config) {
861
938
  },
862
939
  opts
863
940
  );
864
- const json = await res.json();
941
+ const json = await readObject(res, id);
942
+ const fileId = text(json.id);
943
+ if (!fileId) throw new AgentError("unknown", `Provider "${id}" stored the file but sent no file id.`, { provider: id });
944
+ const bytes = count(json.bytes);
945
+ const createdAt = count(json.created_at);
865
946
  return {
866
947
  kind: "providerFile",
867
- id: json.id,
948
+ id: fileId,
868
949
  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 } : {}
950
+ filename: text(json.filename) ?? req.filename,
951
+ ...bytes != null ? { sizeBytes: bytes } : {},
952
+ ...createdAt != null ? { createdAt: createdAt * 1e3 } : {}
872
953
  };
873
954
  },
874
955
  async deleteFile(fileId, opts) {
@@ -878,10 +959,14 @@ function createOpenAIProvider(config) {
878
959
  if (config.models) return config.models;
879
960
  try {
880
961
  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) } : {}
962
+ const json = await readObject(res, id);
963
+ const ids = (Array.isArray(json.data) ? json.data : []).flatMap((m) => {
964
+ const mid = typeof m === "object" && m !== null ? text(m.id) : void 0;
965
+ return mid ? [mid] : [];
966
+ });
967
+ const remote = ids.map((mid) => ({
968
+ id: mid,
969
+ ...modelCapabilities(mid) ? { supports: modelCapabilities(mid) } : {}
885
970
  }));
886
971
  return remote.length ? remote : OPENAI_MODELS;
887
972
  } catch {
@@ -969,7 +1054,9 @@ function createLocalJobStore(prefix = "superchat:jobs") {
969
1054
  const readJob = (id) => {
970
1055
  try {
971
1056
  const raw = globalThis.localStorage?.getItem(jobKey(id)) ?? null;
972
- return raw ? JSON.parse(raw) : void 0;
1057
+ const job = raw ? JSON.parse(raw) : void 0;
1058
+ const usable = job && typeof job === "object" && job.handle && typeof job.handle.id === "string" && typeof job.status === "string" && typeof job.createdAt === "number";
1059
+ return usable ? job : void 0;
973
1060
  } catch {
974
1061
  return void 0;
975
1062
  }
@@ -1077,4 +1164,4 @@ export {
1077
1164
  reap,
1078
1165
  resumeJobs
1079
1166
  };
1080
- //# sourceMappingURL=chunk-MHGENDQX.js.map
1167
+ //# sourceMappingURL=chunk-WFU4HXUG.js.map