@probelabs/probe 0.6.0-rc334 → 0.6.0-rc335

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.
package/cjs/index.cjs CHANGED
@@ -18326,6 +18326,218 @@ var init_v3 = __esm({
18326
18326
  }
18327
18327
  });
18328
18328
 
18329
+ // node_modules/eventsource-parser/dist/index.js
18330
+ function noop(_arg) {
18331
+ }
18332
+ function createParser(config2) {
18333
+ if (typeof config2 == "function")
18334
+ throw new TypeError(
18335
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
18336
+ );
18337
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config2, pendingFragments = [];
18338
+ let pendingFragmentsLength = 0, isFirstChunk = true, id, data2 = "", dataLines = 0, eventType, terminated = false;
18339
+ function feed(chunk) {
18340
+ if (terminated)
18341
+ throw new Error(
18342
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
18343
+ );
18344
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
18345
+ const trailing2 = processLines(chunk);
18346
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
18347
+ return;
18348
+ }
18349
+ if (chunk.indexOf(`
18350
+ `) === -1 && chunk.indexOf("\r") === -1) {
18351
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
18352
+ return;
18353
+ }
18354
+ pendingFragments.push(chunk);
18355
+ const input = pendingFragments.join("");
18356
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
18357
+ const trailing = processLines(input);
18358
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
18359
+ }
18360
+ function checkBufferSize() {
18361
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data2.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data2 = "", dataLines = 0, eventType = void 0, onError(
18362
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
18363
+ type: "max-buffer-size-exceeded"
18364
+ })
18365
+ )));
18366
+ }
18367
+ function processLines(chunk) {
18368
+ let searchIndex = 0;
18369
+ if (chunk.indexOf("\r") === -1) {
18370
+ let lfIndex = chunk.indexOf(`
18371
+ `, searchIndex);
18372
+ for (; lfIndex !== -1; ) {
18373
+ if (searchIndex === lfIndex) {
18374
+ dataLines > 0 && onEvent({ id, event: eventType, data: data2 }), id = void 0, data2 = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
18375
+ `, searchIndex);
18376
+ continue;
18377
+ }
18378
+ const firstCharCode = chunk.charCodeAt(searchIndex);
18379
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
18380
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
18381
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
18382
+ onEvent({ id, event: eventType, data: value }), id = void 0, data2 = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
18383
+ `, searchIndex);
18384
+ continue;
18385
+ }
18386
+ data2 = dataLines === 0 ? value : `${data2}
18387
+ ${value}`, dataLines++;
18388
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
18389
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
18390
+ lfIndex
18391
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
18392
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
18393
+ `, searchIndex);
18394
+ }
18395
+ return chunk.slice(searchIndex);
18396
+ }
18397
+ for (; searchIndex < chunk.length; ) {
18398
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
18399
+ `, searchIndex);
18400
+ let lineEnd = -1;
18401
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
18402
+ break;
18403
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
18404
+ }
18405
+ return chunk.slice(searchIndex);
18406
+ }
18407
+ function parseLine(chunk, start, end) {
18408
+ if (start === end) {
18409
+ dispatchEvent();
18410
+ return;
18411
+ }
18412
+ const firstCharCode = chunk.charCodeAt(start);
18413
+ if (isDataPrefix(chunk, start, firstCharCode)) {
18414
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
18415
+ data2 = dataLines === 0 ? value2 : `${data2}
18416
+ ${value2}`, dataLines++;
18417
+ return;
18418
+ }
18419
+ if (isEventPrefix(chunk, start, firstCharCode)) {
18420
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
18421
+ return;
18422
+ }
18423
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
18424
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
18425
+ value2.includes("\0") || (id = value2);
18426
+ return;
18427
+ }
18428
+ if (firstCharCode === 58) {
18429
+ if (onComment) {
18430
+ const line2 = chunk.slice(start, end);
18431
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
18432
+ }
18433
+ return;
18434
+ }
18435
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
18436
+ if (fieldSeparatorIndex === -1) {
18437
+ processField(line, "", line);
18438
+ return;
18439
+ }
18440
+ const field = line.slice(0, fieldSeparatorIndex), offset2 = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset2);
18441
+ processField(field, value, line);
18442
+ }
18443
+ function processField(field, value, line) {
18444
+ switch (field) {
18445
+ case "event":
18446
+ eventType = value || void 0;
18447
+ break;
18448
+ case "data":
18449
+ data2 = dataLines === 0 ? value : `${data2}
18450
+ ${value}`, dataLines++;
18451
+ break;
18452
+ case "id":
18453
+ value.includes("\0") || (id = value);
18454
+ break;
18455
+ case "retry":
18456
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
18457
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
18458
+ type: "invalid-retry",
18459
+ value,
18460
+ line
18461
+ })
18462
+ );
18463
+ break;
18464
+ default:
18465
+ onError(
18466
+ new ParseError(
18467
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
18468
+ { type: "unknown-field", field, value, line }
18469
+ )
18470
+ );
18471
+ break;
18472
+ }
18473
+ }
18474
+ function dispatchEvent() {
18475
+ dataLines > 0 && onEvent({
18476
+ id,
18477
+ event: eventType,
18478
+ data: data2
18479
+ }), id = void 0, data2 = "", dataLines = 0, eventType = void 0;
18480
+ }
18481
+ function reset2(options = {}) {
18482
+ if (options.consume && pendingFragments.length > 0) {
18483
+ const incompleteLine = pendingFragments.join("");
18484
+ parseLine(incompleteLine, 0, incompleteLine.length);
18485
+ }
18486
+ isFirstChunk = true, id = void 0, data2 = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
18487
+ }
18488
+ return { feed, reset: reset2 };
18489
+ }
18490
+ function isDataPrefix(chunk, i, firstCharCode) {
18491
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
18492
+ }
18493
+ function isEventPrefix(chunk, i, firstCharCode) {
18494
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
18495
+ }
18496
+ var ParseError, LF, CR, SPACE;
18497
+ var init_dist2 = __esm({
18498
+ "node_modules/eventsource-parser/dist/index.js"() {
18499
+ ParseError = class extends Error {
18500
+ constructor(message, options) {
18501
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
18502
+ }
18503
+ };
18504
+ LF = 10;
18505
+ CR = 13;
18506
+ SPACE = 32;
18507
+ }
18508
+ });
18509
+
18510
+ // node_modules/eventsource-parser/dist/stream.js
18511
+ var EventSourceParserStream;
18512
+ var init_stream = __esm({
18513
+ "node_modules/eventsource-parser/dist/stream.js"() {
18514
+ init_dist2();
18515
+ EventSourceParserStream = class extends TransformStream {
18516
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
18517
+ let parser;
18518
+ super({
18519
+ start(controller) {
18520
+ parser = createParser({
18521
+ onEvent: (event) => {
18522
+ controller.enqueue(event);
18523
+ },
18524
+ onError(error40) {
18525
+ typeof onError == "function" && onError(error40), (onError === "terminate" || error40.type === "max-buffer-size-exceeded") && controller.error(error40);
18526
+ },
18527
+ onRetry,
18528
+ onComment,
18529
+ maxBufferSize
18530
+ });
18531
+ },
18532
+ transform(chunk) {
18533
+ parser.feed(chunk);
18534
+ }
18535
+ });
18536
+ }
18537
+ };
18538
+ }
18539
+ });
18540
+
18329
18541
  // node_modules/@ai-sdk/provider-utils/dist/index.mjs
18330
18542
  function combineHeaders(...headers) {
18331
18543
  return headers.reduce(
@@ -18339,6 +18551,11 @@ function combineHeaders(...headers) {
18339
18551
  function extractResponseHeaders(response) {
18340
18552
  return Object.fromEntries([...response.headers]);
18341
18553
  }
18554
+ function convertBase64ToUint8Array(base64String) {
18555
+ const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
18556
+ const latin1string = atob2(base64Url);
18557
+ return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
18558
+ }
18342
18559
  function convertUint8ArrayToBase64(array2) {
18343
18560
  let latin1string = "";
18344
18561
  for (let i = 0; i < array2.length; i++) {
@@ -18349,6 +18566,28 @@ function convertUint8ArrayToBase64(array2) {
18349
18566
  function convertToBase64(value) {
18350
18567
  return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
18351
18568
  }
18569
+ function convertToFormData(input, options = {}) {
18570
+ const { useArrayBrackets = true } = options;
18571
+ const formData = new FormData();
18572
+ for (const [key, value] of Object.entries(input)) {
18573
+ if (value == null) {
18574
+ continue;
18575
+ }
18576
+ if (Array.isArray(value)) {
18577
+ if (value.length === 1) {
18578
+ formData.append(key, value[0]);
18579
+ continue;
18580
+ }
18581
+ const arrayKey = useArrayBrackets ? `${key}[]` : key;
18582
+ for (const item of value) {
18583
+ formData.append(arrayKey, item);
18584
+ }
18585
+ continue;
18586
+ }
18587
+ formData.append(key, value);
18588
+ }
18589
+ return formData;
18590
+ }
18352
18591
  async function cancelResponseBody(response) {
18353
18592
  var _a22;
18354
18593
  try {
@@ -18356,6 +18595,202 @@ async function cancelResponseBody(response) {
18356
18595
  } catch (e) {
18357
18596
  }
18358
18597
  }
18598
+ function isBrowserRuntime(globalThisAny = globalThis) {
18599
+ return globalThisAny.window != null;
18600
+ }
18601
+ function validateDownloadUrl(url2) {
18602
+ let parsed;
18603
+ try {
18604
+ parsed = new URL(url2);
18605
+ } catch (e) {
18606
+ throw new DownloadError({
18607
+ url: url2,
18608
+ message: `Invalid URL: ${url2}`
18609
+ });
18610
+ }
18611
+ if (parsed.protocol === "data:") {
18612
+ return;
18613
+ }
18614
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
18615
+ throw new DownloadError({
18616
+ url: url2,
18617
+ message: `URL scheme must be http, https, or data, got ${parsed.protocol}`
18618
+ });
18619
+ }
18620
+ const hostname2 = parsed.hostname.toLowerCase().replace(/\.+$/, "");
18621
+ if (!hostname2) {
18622
+ throw new DownloadError({
18623
+ url: url2,
18624
+ message: `URL must have a hostname`
18625
+ });
18626
+ }
18627
+ if (hostname2 === "localhost" || hostname2.endsWith(".local") || hostname2.endsWith(".localhost")) {
18628
+ throw new DownloadError({
18629
+ url: url2,
18630
+ message: `URL with hostname ${hostname2} is not allowed`
18631
+ });
18632
+ }
18633
+ if (hostname2.startsWith("[") && hostname2.endsWith("]")) {
18634
+ const ipv63 = hostname2.slice(1, -1);
18635
+ if (isPrivateIPv6(ipv63)) {
18636
+ throw new DownloadError({
18637
+ url: url2,
18638
+ message: `URL with IPv6 address ${hostname2} is not allowed`
18639
+ });
18640
+ }
18641
+ return;
18642
+ }
18643
+ if (isIPv4(hostname2)) {
18644
+ if (isPrivateIPv4(hostname2)) {
18645
+ throw new DownloadError({
18646
+ url: url2,
18647
+ message: `URL with IP address ${hostname2} is not allowed`
18648
+ });
18649
+ }
18650
+ return;
18651
+ }
18652
+ }
18653
+ function validateDownloadAddress({
18654
+ address,
18655
+ family,
18656
+ hostname: hostname2
18657
+ }) {
18658
+ const isUnsafe = family === 4 ? !isIPv4(address) || isPrivateIPv4(address) : family === 6 ? isPrivateIPv6(address) : true;
18659
+ if (isUnsafe) {
18660
+ throw new DownloadError({
18661
+ url: hostname2,
18662
+ message: `Hostname ${hostname2} resolved to disallowed IP address ${address}`
18663
+ });
18664
+ }
18665
+ }
18666
+ function isIPv4(hostname2) {
18667
+ const parts = hostname2.split(".");
18668
+ if (parts.length !== 4) return false;
18669
+ return parts.every((part) => {
18670
+ const num = Number(part);
18671
+ return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
18672
+ });
18673
+ }
18674
+ function isPrivateIPv4(ip) {
18675
+ const parts = ip.split(".").map(Number);
18676
+ const [a, b, c] = parts;
18677
+ if (a === 0) return true;
18678
+ if (a === 10) return true;
18679
+ if (a === 100 && b >= 64 && b <= 127) return true;
18680
+ if (a === 127) return true;
18681
+ if (a === 169 && b === 254) return true;
18682
+ if (a === 172 && b >= 16 && b <= 31) return true;
18683
+ if (a === 192 && b === 0 && c === 0) return true;
18684
+ if (a === 192 && b === 168) return true;
18685
+ if (a === 198 && (b === 18 || b === 19)) return true;
18686
+ if (a >= 240) return true;
18687
+ return false;
18688
+ }
18689
+ function parseIPv6(ip) {
18690
+ let address = ip.toLowerCase();
18691
+ const zoneIndex = address.indexOf("%");
18692
+ if (zoneIndex !== -1) {
18693
+ address = address.slice(0, zoneIndex);
18694
+ }
18695
+ const halves = address.split("::");
18696
+ if (halves.length > 2) return null;
18697
+ const toGroups = (segment) => {
18698
+ if (segment === "") return [];
18699
+ const groups = [];
18700
+ const parts = segment.split(":");
18701
+ for (let i = 0; i < parts.length; i++) {
18702
+ const part = parts[i];
18703
+ if (part.includes(".")) {
18704
+ if (i !== parts.length - 1 || !isIPv4(part)) return null;
18705
+ const [a, b, c, d] = part.split(".").map(Number);
18706
+ groups.push(a << 8 | b, c << 8 | d);
18707
+ continue;
18708
+ }
18709
+ if (!/^[0-9a-f]{1,4}$/.test(part)) return null;
18710
+ groups.push(parseInt(part, 16));
18711
+ }
18712
+ return groups;
18713
+ };
18714
+ const head2 = toGroups(halves[0]);
18715
+ if (head2 === null) return null;
18716
+ if (halves.length === 2) {
18717
+ const tail = toGroups(halves[1]);
18718
+ if (tail === null) return null;
18719
+ const fill = 8 - head2.length - tail.length;
18720
+ if (fill < 0) return null;
18721
+ return [...head2, ...new Array(fill).fill(0), ...tail];
18722
+ }
18723
+ return head2.length === 8 ? head2 : null;
18724
+ }
18725
+ function isPrivateIPv6(ip) {
18726
+ const groups = parseIPv6(ip);
18727
+ if (groups === null) return true;
18728
+ const topZero = (count) => groups.slice(0, count).every((group) => group === 0);
18729
+ if (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;
18730
+ if ((groups[0] & 65024) === 64512) return true;
18731
+ if ((groups[0] & 65472) === 65152) return true;
18732
+ if ((groups[0] & 65472) === 65216) return true;
18733
+ if ((groups[0] & 65280) === 65280) return true;
18734
+ const embedsIPv4 = (
18735
+ // ::/96 — IPv4-compatible (deprecated)
18736
+ topZero(6) || // ::ffff:0:0/96 — IPv4-mapped (ffff in group 5)
18737
+ topZero(5) && groups[5] === 65535 || // ::ffff:0:0/96 — IPv4-translated form (ffff in group 4, group 5 zero)
18738
+ topZero(4) && groups[4] === 65535 && groups[5] === 0 || // 64:ff9b::/96 — NAT64 well-known prefix
18739
+ groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || // 64:ff9b:1::/48 — NAT64 local-use prefix
18740
+ groups[0] === 100 && groups[1] === 65435 && groups[2] === 1
18741
+ );
18742
+ if (embedsIPv4) {
18743
+ const a = groups[6] >> 8 & 255;
18744
+ const b = groups[6] & 255;
18745
+ const c = groups[7] >> 8 & 255;
18746
+ const d = groups[7] & 255;
18747
+ return isPrivateIPv4(`${a}.${b}.${c}.${d}`);
18748
+ }
18749
+ return false;
18750
+ }
18751
+ function createSafeLookup(lookup) {
18752
+ return ((hostname2, options, callback) => {
18753
+ lookup(hostname2, { ...options, all: true }, (error40, addresses) => {
18754
+ if (error40) {
18755
+ callback(error40);
18756
+ return;
18757
+ }
18758
+ try {
18759
+ const [firstAddress] = addresses;
18760
+ if (firstAddress == null) {
18761
+ throw new Error(`Hostname ${hostname2} did not resolve to an address`);
18762
+ }
18763
+ for (const { address, family } of addresses) {
18764
+ validateDownloadAddress({ address, family, hostname: hostname2 });
18765
+ }
18766
+ if (options.all === true) {
18767
+ callback(null, addresses);
18768
+ } else {
18769
+ callback(
18770
+ null,
18771
+ firstAddress.address,
18772
+ firstAddress.family
18773
+ );
18774
+ }
18775
+ } catch (error210) {
18776
+ callback(
18777
+ error210 instanceof Error ? error210 : new Error(String(error210))
18778
+ );
18779
+ }
18780
+ });
18781
+ });
18782
+ }
18783
+ function isNodeRuntime() {
18784
+ var _a22, _b22;
18785
+ const runtimeProcess = globalThis.process;
18786
+ return ((_a22 = runtimeProcess == null ? void 0 : runtimeProcess.release) == null ? void 0 : _a22.name) === "node" && ((_b22 = runtimeProcess.versions) == null ? void 0 : _b22.bun) == null;
18787
+ }
18788
+ async function getDefaultDownloadFetch() {
18789
+ if (!isNodeRuntime() || !initialGlobalFetchIsNodeDefault || globalThis.fetch !== initialGlobalFetch) {
18790
+ return globalThis.fetch;
18791
+ }
18792
+ return safeNodeFetchPromise != null ? safeNodeFetchPromise : safeNodeFetchPromise = createSafeNodeFetch();
18793
+ }
18359
18794
  function isNodeDefaultFetch(fetch2) {
18360
18795
  if (typeof fetch2 !== "function") {
18361
18796
  return false;
@@ -18363,6 +18798,92 @@ function isNodeDefaultFetch(fetch2) {
18363
18798
  const source = Function.prototype.toString.call(fetch2);
18364
18799
  return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
18365
18800
  }
18801
+ async function createSafeNodeFetch() {
18802
+ const [{ createRequire: createRequire2 }, { lookup }] = await Promise.all([
18803
+ loadNodeModule("node:module"),
18804
+ loadNodeModule("node:dns")
18805
+ ]);
18806
+ const { Agent, fetch: fetch2 } = createRequire2(getCurrentModulePath())(
18807
+ "undici"
18808
+ );
18809
+ const dispatcher = new Agent({
18810
+ connect: {
18811
+ lookup: createSafeLookup(lookup)
18812
+ }
18813
+ });
18814
+ return ((input, init) => fetch2(
18815
+ input,
18816
+ {
18817
+ ...init,
18818
+ dispatcher
18819
+ }
18820
+ ));
18821
+ }
18822
+ async function loadNodeModule(id) {
18823
+ var _a22;
18824
+ const processWithBuiltins = globalThis.process;
18825
+ const builtinModule = (_a22 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a22.call(processWithBuiltins, id);
18826
+ if (builtinModule == null) {
18827
+ throw new Error(`Node.js built-in module ${id} is unavailable`);
18828
+ }
18829
+ return builtinModule;
18830
+ }
18831
+ function getCurrentModulePath() {
18832
+ const originalPrepareStackTrace = Error.prepareStackTrace;
18833
+ try {
18834
+ Error.prepareStackTrace = (_error, callSites) => callSites;
18835
+ const error40 = new Error("Capture current module path");
18836
+ Error.captureStackTrace(error40, getCurrentModulePath);
18837
+ const [caller] = error40.stack;
18838
+ const fileName = caller == null ? void 0 : caller.getFileName();
18839
+ if (fileName == null) {
18840
+ throw new Error("Unable to determine the current module path");
18841
+ }
18842
+ return fileName;
18843
+ } finally {
18844
+ Error.prepareStackTrace = originalPrepareStackTrace;
18845
+ }
18846
+ }
18847
+ async function fetchWithValidatedRedirects({
18848
+ url: url2,
18849
+ headers,
18850
+ abortSignal,
18851
+ maxRedirects = MAX_DOWNLOAD_REDIRECTS
18852
+ }) {
18853
+ const baseInit = { signal: abortSignal };
18854
+ if (headers !== void 0) {
18855
+ baseInit.headers = headers;
18856
+ }
18857
+ let currentUrl = url2;
18858
+ for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
18859
+ validateDownloadUrl(currentUrl);
18860
+ const fetch2 = await getDefaultDownloadFetch();
18861
+ const response = await fetch2(currentUrl, {
18862
+ ...baseInit,
18863
+ redirect: "manual"
18864
+ });
18865
+ if (response.type === "opaqueredirect") {
18866
+ if (!isBrowserRuntime()) {
18867
+ throw new DownloadError({
18868
+ url: url2,
18869
+ message: `Redirect from ${currentUrl} could not be validated and was blocked`
18870
+ });
18871
+ }
18872
+ return await fetch2(currentUrl, { ...baseInit, redirect: "follow" });
18873
+ }
18874
+ const location = response.headers.get("location");
18875
+ if (response.status >= 300 && response.status < 400 && location) {
18876
+ await cancelResponseBody(response);
18877
+ currentUrl = new URL(location, currentUrl).toString();
18878
+ continue;
18879
+ }
18880
+ return response;
18881
+ }
18882
+ throw new DownloadError({
18883
+ url: url2,
18884
+ message: `Too many redirects (max ${maxRedirects})`
18885
+ });
18886
+ }
18366
18887
  async function readResponseWithSizeLimit({
18367
18888
  response,
18368
18889
  url: url2,
@@ -18417,6 +18938,35 @@ async function readResponseWithSizeLimit({
18417
18938
  }
18418
18939
  return result;
18419
18940
  }
18941
+ async function downloadBlob(url2, options) {
18942
+ var _a22, _b22;
18943
+ try {
18944
+ const response = await fetchWithValidatedRedirects({
18945
+ url: url2,
18946
+ abortSignal: options == null ? void 0 : options.abortSignal
18947
+ });
18948
+ if (!response.ok) {
18949
+ await cancelResponseBody(response);
18950
+ throw new DownloadError({
18951
+ url: url2,
18952
+ statusCode: response.status,
18953
+ statusText: response.statusText
18954
+ });
18955
+ }
18956
+ const data2 = await readResponseWithSizeLimit({
18957
+ response,
18958
+ url: url2,
18959
+ maxBytes: (_a22 = options == null ? void 0 : options.maxBytes) != null ? _a22 : DEFAULT_MAX_DOWNLOAD_SIZE
18960
+ });
18961
+ const contentType = (_b22 = response.headers.get("content-type")) != null ? _b22 : void 0;
18962
+ return new Blob([data2], contentType ? { type: contentType } : void 0);
18963
+ } catch (error40) {
18964
+ if (DownloadError.isInstance(error40)) {
18965
+ throw error40;
18966
+ }
18967
+ throw new DownloadError({ url: url2, cause: error40 });
18968
+ }
18969
+ }
18420
18970
  function isAbortError(error40) {
18421
18971
  return (error40 instanceof Error || error40 instanceof DOMException) && (error40.name === "AbortError" || error40.name === "ResponseAborted" || // Next.js
18422
18972
  error40.name === "TimeoutError");
@@ -19636,6 +20186,21 @@ async function safeParseJSON({
19636
20186
  };
19637
20187
  }
19638
20188
  }
20189
+ function parseJsonEventStream({
20190
+ stream: stream2,
20191
+ schema
20192
+ }) {
20193
+ return stream2.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
20194
+ new TransformStream({
20195
+ async transform({ data: data2 }, controller) {
20196
+ if (data2 === "[DONE]") {
20197
+ return;
20198
+ }
20199
+ controller.enqueue(await safeParseJSON({ text: data2, schema }));
20200
+ }
20201
+ })
20202
+ );
20203
+ }
19639
20204
  async function parseProviderOptions({
19640
20205
  provider,
19641
20206
  providerOptions,
@@ -19663,6 +20228,62 @@ async function resolve(value) {
19663
20228
  }
19664
20229
  return Promise.resolve(value);
19665
20230
  }
20231
+ function wrapResponseBodyStream({
20232
+ stream: stream2,
20233
+ url: url2,
20234
+ requestBodyValues,
20235
+ statusCode,
20236
+ responseHeaders
20237
+ }) {
20238
+ const reader = stream2.getReader();
20239
+ let readerReleased = false;
20240
+ const releaseReader = () => {
20241
+ if (!readerReleased) {
20242
+ reader.releaseLock();
20243
+ readerReleased = true;
20244
+ }
20245
+ };
20246
+ return new ReadableStream({
20247
+ async pull(controller) {
20248
+ try {
20249
+ const { done, value } = await reader.read();
20250
+ if (done) {
20251
+ releaseReader();
20252
+ controller.close();
20253
+ } else {
20254
+ controller.enqueue(value);
20255
+ }
20256
+ } catch (error40) {
20257
+ releaseReader();
20258
+ if (isAbortError(error40)) {
20259
+ controller.error(error40);
20260
+ return;
20261
+ }
20262
+ controller.error(
20263
+ handleFetchError({
20264
+ error: new APICallError({
20265
+ message: "Failed to process successful response",
20266
+ cause: error40,
20267
+ statusCode,
20268
+ url: url2,
20269
+ responseHeaders,
20270
+ requestBodyValues
20271
+ }),
20272
+ url: url2,
20273
+ requestBodyValues
20274
+ })
20275
+ );
20276
+ }
20277
+ },
20278
+ async cancel(reason) {
20279
+ try {
20280
+ await reader.cancel(reason);
20281
+ } finally {
20282
+ releaseReader();
20283
+ }
20284
+ }
20285
+ });
20286
+ }
19666
20287
  async function readResponseBodyAsText({
19667
20288
  response,
19668
20289
  url: url2
@@ -19681,8 +20302,8 @@ function stripFileExtension(filename) {
19681
20302
  function withoutTrailingSlash(url2) {
19682
20303
  return url2 == null ? void 0 : url2.replace(/\/$/, "");
19683
20304
  }
19684
- var btoa2, atob2, name14, marker15, symbol16, _a15, _b15, DownloadError, initialGlobalFetch, initialGlobalFetchIsNodeDefault, DEFAULT_MAX_DOWNLOAD_SIZE, createIdGenerator, generateId, FETCH_FAILED_ERROR_MESSAGES, RETRYABLE_NETWORK_ERROR_CODES, VERSION, DEFAULT_SCHEMA_PREFIX, DEFAULT_SCHEMA_SUFFIX, DEFAULT_GENERIC_SUFFIX, suspectProtoRx, suspectConstructorRx, ignoreOverride, defaultOptions, getDefaultOptions, parseCatchDef, integerDateParser, isJsonSchema7AllOfType, emojiRegex2, zodPatterns, ALPHA_NUMERIC, primitiveMappings, asAnyOf, parseOptionalDef, parsePipelineDef, parseReadonlyDef, selectParser, getRelativePath, get$ref, addMeta, getRefs, zod3ToJsonSchema, schemaSymbol, getOriginalFetch2, postJsonToApi, postToApi, textDecoder, createJsonErrorResponseHandler, createJsonResponseHandler;
19685
- var init_dist2 = __esm({
20305
+ var btoa2, atob2, name14, marker15, symbol16, _a15, _b15, DownloadError, safeNodeFetchPromise, initialGlobalFetch, initialGlobalFetchIsNodeDefault, MAX_DOWNLOAD_REDIRECTS, DEFAULT_MAX_DOWNLOAD_SIZE, createIdGenerator, generateId, FETCH_FAILED_ERROR_MESSAGES, RETRYABLE_NETWORK_ERROR_CODES, VERSION, DEFAULT_SCHEMA_PREFIX, DEFAULT_SCHEMA_SUFFIX, DEFAULT_GENERIC_SUFFIX, suspectProtoRx, suspectConstructorRx, ignoreOverride, defaultOptions, getDefaultOptions, parseCatchDef, integerDateParser, isJsonSchema7AllOfType, emojiRegex2, zodPatterns, ALPHA_NUMERIC, primitiveMappings, asAnyOf, parseOptionalDef, parsePipelineDef, parseReadonlyDef, selectParser, getRelativePath, get$ref, addMeta, getRefs, zod3ToJsonSchema, schemaSymbol, getOriginalFetch2, postJsonToApi, postFormDataToApi, postToApi, textDecoder, createJsonErrorResponseHandler, createEventSourceResponseHandler, createJsonResponseHandler;
20306
+ var init_dist3 = __esm({
19686
20307
  "node_modules/@ai-sdk/provider-utils/dist/index.mjs"() {
19687
20308
  init_dist();
19688
20309
  init_dist();
@@ -19695,6 +20316,7 @@ var init_dist2 = __esm({
19695
20316
  init_v3();
19696
20317
  init_v3();
19697
20318
  init_v3();
20319
+ init_stream();
19698
20320
  init_dist();
19699
20321
  init_dist();
19700
20322
  init_dist();
@@ -19722,6 +20344,7 @@ var init_dist2 = __esm({
19722
20344
  };
19723
20345
  initialGlobalFetch = globalThis.fetch;
19724
20346
  initialGlobalFetchIsNodeDefault = isNodeDefaultFetch(initialGlobalFetch);
20347
+ MAX_DOWNLOAD_REDIRECTS = 10;
19725
20348
  DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
19726
20349
  createIdGenerator = ({
19727
20350
  prefix,
@@ -20130,6 +20753,26 @@ var init_dist2 = __esm({
20130
20753
  abortSignal,
20131
20754
  fetch: fetch2
20132
20755
  });
20756
+ postFormDataToApi = async ({
20757
+ url: url2,
20758
+ headers,
20759
+ formData,
20760
+ failedResponseHandler,
20761
+ successfulResponseHandler,
20762
+ abortSignal,
20763
+ fetch: fetch2
20764
+ }) => postToApi({
20765
+ url: url2,
20766
+ headers,
20767
+ body: {
20768
+ content: formData,
20769
+ values: Object.fromEntries(formData.entries())
20770
+ },
20771
+ failedResponseHandler,
20772
+ successfulResponseHandler,
20773
+ abortSignal,
20774
+ fetch: fetch2
20775
+ });
20133
20776
  postToApi = async ({
20134
20777
  url: url2,
20135
20778
  headers = {},
@@ -20254,6 +20897,25 @@ var init_dist2 = __esm({
20254
20897
  };
20255
20898
  }
20256
20899
  };
20900
+ createEventSourceResponseHandler = (chunkSchema) => async ({ response, url: url2, requestBodyValues }) => {
20901
+ const responseHeaders = extractResponseHeaders(response);
20902
+ if (response.body == null) {
20903
+ throw new EmptyResponseBodyError({});
20904
+ }
20905
+ return {
20906
+ responseHeaders,
20907
+ value: parseJsonEventStream({
20908
+ stream: wrapResponseBodyStream({
20909
+ stream: response.body,
20910
+ url: url2,
20911
+ requestBodyValues,
20912
+ statusCode: response.status,
20913
+ responseHeaders
20914
+ }),
20915
+ schema: chunkSchema
20916
+ })
20917
+ };
20918
+ };
20257
20919
  createJsonResponseHandler = (responseSchema) => async ({ response, url: url2, requestBodyValues }) => {
20258
20920
  const responseBody = await readResponseBodyAsText({ response, url: url2 });
20259
20921
  const parsedResult = await safeParseJSON({
@@ -20281,6 +20943,1758 @@ var init_dist2 = __esm({
20281
20943
  }
20282
20944
  });
20283
20945
 
20946
+ // node_modules/@ai-sdk/openai-compatible/dist/index.mjs
20947
+ function toCamelCase(str) {
20948
+ return str.replace(/[_-]([a-z])/g, (g) => g[1].toUpperCase());
20949
+ }
20950
+ function resolveProviderOptionsKey(rawName, providerOptions) {
20951
+ const camelName = toCamelCase(rawName);
20952
+ if (camelName !== rawName && (providerOptions == null ? void 0 : providerOptions[camelName]) != null) {
20953
+ return camelName;
20954
+ }
20955
+ return rawName;
20956
+ }
20957
+ function convertOpenAICompatibleChatUsage(usage) {
20958
+ var _a17, _b16, _c, _d, _e, _f;
20959
+ if (usage == null) {
20960
+ return {
20961
+ inputTokens: {
20962
+ total: void 0,
20963
+ noCache: void 0,
20964
+ cacheRead: void 0,
20965
+ cacheWrite: void 0
20966
+ },
20967
+ outputTokens: {
20968
+ total: void 0,
20969
+ text: void 0,
20970
+ reasoning: void 0
20971
+ },
20972
+ raw: void 0
20973
+ };
20974
+ }
20975
+ const promptTokens = (_a17 = usage.prompt_tokens) != null ? _a17 : 0;
20976
+ const completionTokens = (_b16 = usage.completion_tokens) != null ? _b16 : 0;
20977
+ const cacheReadTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0;
20978
+ const reasoningTokens = (_f = (_e = usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0;
20979
+ return {
20980
+ inputTokens: {
20981
+ total: promptTokens,
20982
+ noCache: promptTokens - cacheReadTokens,
20983
+ cacheRead: cacheReadTokens,
20984
+ cacheWrite: void 0
20985
+ },
20986
+ outputTokens: {
20987
+ total: completionTokens,
20988
+ text: Math.max(0, completionTokens - reasoningTokens),
20989
+ reasoning: reasoningTokens
20990
+ },
20991
+ raw: usage
20992
+ };
20993
+ }
20994
+ function getOpenAIMetadata(message) {
20995
+ var _a17, _b16;
20996
+ return (_b16 = (_a17 = message == null ? void 0 : message.providerOptions) == null ? void 0 : _a17.openaiCompatible) != null ? _b16 : {};
20997
+ }
20998
+ function getAudioFormat(mediaType) {
20999
+ switch (mediaType) {
21000
+ case "audio/wav":
21001
+ return "wav";
21002
+ case "audio/mp3":
21003
+ case "audio/mpeg":
21004
+ return "mp3";
21005
+ default:
21006
+ return null;
21007
+ }
21008
+ }
21009
+ function convertToOpenAICompatibleChatMessages(prompt) {
21010
+ var _a17, _b16, _c;
21011
+ const messages = [];
21012
+ for (const { role, content, ...message } of prompt) {
21013
+ const metadata = getOpenAIMetadata({ ...message });
21014
+ switch (role) {
21015
+ case "system": {
21016
+ messages.push({ role: "system", content, ...metadata });
21017
+ break;
21018
+ }
21019
+ case "user": {
21020
+ if (content.length === 1 && content[0].type === "text") {
21021
+ messages.push({
21022
+ role: "user",
21023
+ content: content[0].text,
21024
+ ...getOpenAIMetadata(content[0])
21025
+ });
21026
+ break;
21027
+ }
21028
+ messages.push({
21029
+ role: "user",
21030
+ content: content.map((part) => {
21031
+ var _a22;
21032
+ const partMetadata = getOpenAIMetadata(part);
21033
+ switch (part.type) {
21034
+ case "text": {
21035
+ return { type: "text", text: part.text, ...partMetadata };
21036
+ }
21037
+ case "file": {
21038
+ if (part.mediaType.startsWith("image/")) {
21039
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
21040
+ return {
21041
+ type: "image_url",
21042
+ image_url: {
21043
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`
21044
+ },
21045
+ ...partMetadata
21046
+ };
21047
+ }
21048
+ if (part.mediaType.startsWith("audio/")) {
21049
+ if (part.data instanceof URL) {
21050
+ throw new UnsupportedFunctionalityError({
21051
+ functionality: "audio file parts with URLs"
21052
+ });
21053
+ }
21054
+ const format2 = getAudioFormat(part.mediaType);
21055
+ if (format2 === null) {
21056
+ throw new UnsupportedFunctionalityError({
21057
+ functionality: `audio media type ${part.mediaType}`
21058
+ });
21059
+ }
21060
+ return {
21061
+ type: "input_audio",
21062
+ input_audio: {
21063
+ data: convertToBase64(part.data),
21064
+ format: format2
21065
+ },
21066
+ ...partMetadata
21067
+ };
21068
+ }
21069
+ if (part.mediaType === "application/pdf") {
21070
+ if (part.data instanceof URL) {
21071
+ throw new UnsupportedFunctionalityError({
21072
+ functionality: "PDF file parts with URLs"
21073
+ });
21074
+ }
21075
+ return {
21076
+ type: "file",
21077
+ file: {
21078
+ filename: (_a22 = part.filename) != null ? _a22 : "document.pdf",
21079
+ file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`
21080
+ },
21081
+ ...partMetadata
21082
+ };
21083
+ }
21084
+ if (part.mediaType.startsWith("text/")) {
21085
+ const textContent = part.data instanceof URL ? part.data.toString() : typeof part.data === "string" ? new TextDecoder().decode(
21086
+ convertBase64ToUint8Array(part.data)
21087
+ ) : new TextDecoder().decode(part.data);
21088
+ return {
21089
+ type: "text",
21090
+ text: textContent,
21091
+ ...partMetadata
21092
+ };
21093
+ }
21094
+ throw new UnsupportedFunctionalityError({
21095
+ functionality: `file part media type ${part.mediaType}`
21096
+ });
21097
+ }
21098
+ }
21099
+ }),
21100
+ ...metadata
21101
+ });
21102
+ break;
21103
+ }
21104
+ case "assistant": {
21105
+ let text = "";
21106
+ let reasoning = "";
21107
+ const toolCalls = [];
21108
+ for (const part of content) {
21109
+ const partMetadata = getOpenAIMetadata(part);
21110
+ switch (part.type) {
21111
+ case "text": {
21112
+ text += part.text;
21113
+ break;
21114
+ }
21115
+ case "reasoning": {
21116
+ reasoning += part.text;
21117
+ break;
21118
+ }
21119
+ case "tool-call": {
21120
+ const thoughtSignature = (_b16 = (_a17 = part.providerOptions) == null ? void 0 : _a17.google) == null ? void 0 : _b16.thoughtSignature;
21121
+ toolCalls.push({
21122
+ id: part.toolCallId,
21123
+ type: "function",
21124
+ function: {
21125
+ name: part.toolName,
21126
+ arguments: JSON.stringify(part.input)
21127
+ },
21128
+ ...partMetadata,
21129
+ // Include extra_content for Google Gemini thought signatures
21130
+ ...thoughtSignature ? {
21131
+ extra_content: {
21132
+ google: {
21133
+ thought_signature: String(thoughtSignature)
21134
+ }
21135
+ }
21136
+ } : {}
21137
+ });
21138
+ break;
21139
+ }
21140
+ }
21141
+ }
21142
+ messages.push({
21143
+ role: "assistant",
21144
+ content: toolCalls.length > 0 ? text || null : text,
21145
+ ...reasoning.length > 0 ? { reasoning_content: reasoning } : {},
21146
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
21147
+ ...metadata
21148
+ });
21149
+ break;
21150
+ }
21151
+ case "tool": {
21152
+ for (const toolResponse of content) {
21153
+ if (toolResponse.type === "tool-approval-response") {
21154
+ continue;
21155
+ }
21156
+ const output = toolResponse.output;
21157
+ let contentValue;
21158
+ switch (output.type) {
21159
+ case "text":
21160
+ case "error-text":
21161
+ contentValue = output.value;
21162
+ break;
21163
+ case "execution-denied":
21164
+ contentValue = (_c = output.reason) != null ? _c : "Tool call execution denied.";
21165
+ break;
21166
+ case "content":
21167
+ case "json":
21168
+ case "error-json":
21169
+ contentValue = JSON.stringify(output.value);
21170
+ break;
21171
+ }
21172
+ const toolResponseMetadata = getOpenAIMetadata(toolResponse);
21173
+ messages.push({
21174
+ role: "tool",
21175
+ tool_call_id: toolResponse.toolCallId,
21176
+ content: contentValue,
21177
+ ...toolResponseMetadata
21178
+ });
21179
+ }
21180
+ break;
21181
+ }
21182
+ default: {
21183
+ const _exhaustiveCheck = role;
21184
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
21185
+ }
21186
+ }
21187
+ }
21188
+ return messages;
21189
+ }
21190
+ function getResponseMetadata({
21191
+ id,
21192
+ model,
21193
+ created
21194
+ }) {
21195
+ return {
21196
+ id: id != null ? id : void 0,
21197
+ modelId: model != null ? model : void 0,
21198
+ timestamp: created != null ? new Date(created * 1e3) : void 0
21199
+ };
21200
+ }
21201
+ function mapOpenAICompatibleFinishReason(finishReason) {
21202
+ switch (finishReason) {
21203
+ case "stop":
21204
+ return "stop";
21205
+ case "length":
21206
+ return "length";
21207
+ case "content_filter":
21208
+ return "content-filter";
21209
+ case "function_call":
21210
+ case "tool_calls":
21211
+ return "tool-calls";
21212
+ default:
21213
+ return "other";
21214
+ }
21215
+ }
21216
+ function prepareTools({
21217
+ tools: tools2,
21218
+ toolChoice
21219
+ }) {
21220
+ tools2 = (tools2 == null ? void 0 : tools2.length) ? tools2 : void 0;
21221
+ const toolWarnings = [];
21222
+ if (tools2 == null) {
21223
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
21224
+ }
21225
+ const openaiCompatTools = [];
21226
+ for (const tool6 of tools2) {
21227
+ if (tool6.type === "provider") {
21228
+ toolWarnings.push({
21229
+ type: "unsupported",
21230
+ feature: `provider-defined tool ${tool6.id}`
21231
+ });
21232
+ } else {
21233
+ openaiCompatTools.push({
21234
+ type: "function",
21235
+ function: {
21236
+ name: tool6.name,
21237
+ description: tool6.description,
21238
+ parameters: tool6.inputSchema,
21239
+ ...tool6.strict != null ? { strict: tool6.strict } : {}
21240
+ }
21241
+ });
21242
+ }
21243
+ }
21244
+ if (toolChoice == null) {
21245
+ return { tools: openaiCompatTools, toolChoice: void 0, toolWarnings };
21246
+ }
21247
+ const type = toolChoice.type;
21248
+ switch (type) {
21249
+ case "auto":
21250
+ case "none":
21251
+ case "required":
21252
+ return { tools: openaiCompatTools, toolChoice: type, toolWarnings };
21253
+ case "tool":
21254
+ return {
21255
+ tools: openaiCompatTools,
21256
+ toolChoice: {
21257
+ type: "function",
21258
+ function: { name: toolChoice.toolName }
21259
+ },
21260
+ toolWarnings
21261
+ };
21262
+ default: {
21263
+ const _exhaustiveCheck = type;
21264
+ throw new UnsupportedFunctionalityError({
21265
+ functionality: `tool choice type: ${_exhaustiveCheck}`
21266
+ });
21267
+ }
21268
+ }
21269
+ }
21270
+ function convertOpenAICompatibleContent(content) {
21271
+ if (content == null) {
21272
+ return [];
21273
+ }
21274
+ if (typeof content === "string") {
21275
+ return content.length > 0 ? [{ type: "text", text: content }] : [];
21276
+ }
21277
+ const result = [];
21278
+ for (const part of content) {
21279
+ if (part.type === "text" && typeof part.text === "string") {
21280
+ if (part.text.length > 0) {
21281
+ result.push({ type: "text", text: part.text });
21282
+ }
21283
+ } else if (part.type === "thinking" && Array.isArray(part.thinking)) {
21284
+ const reasoningText = part.thinking.filter(
21285
+ (chunk) => chunk != null && typeof chunk === "object" && "type" in chunk && chunk.type === "text" && "text" in chunk && typeof chunk.text === "string"
21286
+ ).map((chunk) => chunk.text).join("");
21287
+ if (reasoningText.length > 0) {
21288
+ result.push({ type: "reasoning", text: reasoningText });
21289
+ }
21290
+ }
21291
+ }
21292
+ return result;
21293
+ }
21294
+ function convertOpenAICompatibleCompletionUsage(usage) {
21295
+ var _a17, _b16;
21296
+ if (usage == null) {
21297
+ return {
21298
+ inputTokens: {
21299
+ total: void 0,
21300
+ noCache: void 0,
21301
+ cacheRead: void 0,
21302
+ cacheWrite: void 0
21303
+ },
21304
+ outputTokens: {
21305
+ total: void 0,
21306
+ text: void 0,
21307
+ reasoning: void 0
21308
+ },
21309
+ raw: void 0
21310
+ };
21311
+ }
21312
+ const promptTokens = (_a17 = usage.prompt_tokens) != null ? _a17 : 0;
21313
+ const completionTokens = (_b16 = usage.completion_tokens) != null ? _b16 : 0;
21314
+ return {
21315
+ inputTokens: {
21316
+ total: promptTokens,
21317
+ noCache: promptTokens,
21318
+ cacheRead: void 0,
21319
+ cacheWrite: void 0
21320
+ },
21321
+ outputTokens: {
21322
+ total: completionTokens,
21323
+ text: completionTokens,
21324
+ reasoning: void 0
21325
+ },
21326
+ raw: usage
21327
+ };
21328
+ }
21329
+ function convertToOpenAICompatibleCompletionPrompt({
21330
+ prompt,
21331
+ user = "user",
21332
+ assistant = "assistant"
21333
+ }) {
21334
+ let text = "";
21335
+ if (prompt[0].role === "system") {
21336
+ text += `${prompt[0].content}
21337
+
21338
+ `;
21339
+ prompt = prompt.slice(1);
21340
+ }
21341
+ for (const { role, content } of prompt) {
21342
+ switch (role) {
21343
+ case "system": {
21344
+ throw new InvalidPromptError({
21345
+ message: "Unexpected system message in prompt: ${content}",
21346
+ prompt
21347
+ });
21348
+ }
21349
+ case "user": {
21350
+ const userMessage = content.map((part) => {
21351
+ switch (part.type) {
21352
+ case "text": {
21353
+ return part.text;
21354
+ }
21355
+ }
21356
+ }).filter(Boolean).join("");
21357
+ text += `${user}:
21358
+ ${userMessage}
21359
+
21360
+ `;
21361
+ break;
21362
+ }
21363
+ case "assistant": {
21364
+ const assistantMessage = content.map((part) => {
21365
+ switch (part.type) {
21366
+ case "text": {
21367
+ return part.text;
21368
+ }
21369
+ case "tool-call": {
21370
+ throw new UnsupportedFunctionalityError({
21371
+ functionality: "tool-call messages"
21372
+ });
21373
+ }
21374
+ }
21375
+ }).join("");
21376
+ text += `${assistant}:
21377
+ ${assistantMessage}
21378
+
21379
+ `;
21380
+ break;
21381
+ }
21382
+ case "tool": {
21383
+ throw new UnsupportedFunctionalityError({
21384
+ functionality: "tool messages"
21385
+ });
21386
+ }
21387
+ default: {
21388
+ const _exhaustiveCheck = role;
21389
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
21390
+ }
21391
+ }
21392
+ }
21393
+ text += `${assistant}:
21394
+ `;
21395
+ return {
21396
+ prompt: text,
21397
+ stopSequences: [`
21398
+ ${user}:`]
21399
+ };
21400
+ }
21401
+ function getResponseMetadata2({
21402
+ id,
21403
+ model,
21404
+ created
21405
+ }) {
21406
+ return {
21407
+ id: id != null ? id : void 0,
21408
+ modelId: model != null ? model : void 0,
21409
+ timestamp: created != null ? new Date(created * 1e3) : void 0
21410
+ };
21411
+ }
21412
+ function mapOpenAICompatibleFinishReason2(finishReason) {
21413
+ switch (finishReason) {
21414
+ case "stop":
21415
+ return "stop";
21416
+ case "length":
21417
+ return "length";
21418
+ case "content_filter":
21419
+ return "content-filter";
21420
+ case "function_call":
21421
+ case "tool_calls":
21422
+ return "tool-calls";
21423
+ default:
21424
+ return "other";
21425
+ }
21426
+ }
21427
+ async function fileToBlob(file2) {
21428
+ if (file2.type === "url") {
21429
+ return downloadBlob(file2.url);
21430
+ }
21431
+ const data2 = file2.data instanceof Uint8Array ? file2.data : convertBase64ToUint8Array(file2.data);
21432
+ return new Blob([data2], { type: file2.mediaType });
21433
+ }
21434
+ function createOpenAICompatible(options) {
21435
+ const baseURL = withoutTrailingSlash(options.baseURL);
21436
+ const providerName = options.name;
21437
+ const headers = {
21438
+ ...options.apiKey && { Authorization: `Bearer ${options.apiKey}` },
21439
+ ...options.headers
21440
+ };
21441
+ const getHeaders = () => withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION2}`);
21442
+ const getCommonModelConfig = (modelType) => ({
21443
+ provider: `${providerName}.${modelType}`,
21444
+ url: ({ path: path9 }) => {
21445
+ const url2 = new URL(`${baseURL}${path9}`);
21446
+ if (options.queryParams) {
21447
+ url2.search = new URLSearchParams(options.queryParams).toString();
21448
+ }
21449
+ return url2.toString();
21450
+ },
21451
+ headers: getHeaders,
21452
+ fetch: options.fetch
21453
+ });
21454
+ const createLanguageModel2 = (modelId) => createChatModel(modelId);
21455
+ const createChatModel = (modelId) => new OpenAICompatibleChatLanguageModel(modelId, {
21456
+ ...getCommonModelConfig("chat"),
21457
+ includeUsage: options.includeUsage,
21458
+ supportsStructuredOutputs: options.supportsStructuredOutputs,
21459
+ supportedUrls: options.supportedUrls,
21460
+ transformRequestBody: options.transformRequestBody,
21461
+ metadataExtractor: options.metadataExtractor,
21462
+ convertUsage: options.convertUsage
21463
+ });
21464
+ const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(modelId, {
21465
+ ...getCommonModelConfig("completion"),
21466
+ includeUsage: options.includeUsage
21467
+ });
21468
+ const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(modelId, {
21469
+ ...getCommonModelConfig("embedding")
21470
+ });
21471
+ const createImageModel = (modelId) => new OpenAICompatibleImageModel(modelId, getCommonModelConfig("image"));
21472
+ const provider = (modelId) => createLanguageModel2(modelId);
21473
+ provider.specificationVersion = "v3";
21474
+ provider.languageModel = createLanguageModel2;
21475
+ provider.chatModel = createChatModel;
21476
+ provider.completionModel = createCompletionModel;
21477
+ provider.embeddingModel = createEmbeddingModel;
21478
+ provider.textEmbeddingModel = createEmbeddingModel;
21479
+ provider.imageModel = createImageModel;
21480
+ return provider;
21481
+ }
21482
+ var openaiCompatibleErrorDataSchema, defaultOpenAICompatibleErrorStructure, openaiCompatibleLanguageModelChatOptions, OpenAICompatibleChatLanguageModel, openaiCompatibleTokenUsageSchema, openAICompatibleContentSchema, OpenAICompatibleChatResponseSchema, chunkBaseSchema, createOpenAICompatibleChatChunkSchema, openaiCompatibleLanguageModelCompletionOptions, OpenAICompatibleCompletionLanguageModel, usageSchema, openaiCompatibleCompletionResponseSchema, createOpenAICompatibleCompletionChunkSchema, openaiCompatibleEmbeddingModelOptions, OpenAICompatibleEmbeddingModel, openaiTextEmbeddingResponseSchema, OpenAICompatibleImageModel, openaiCompatibleImageResponseSchema, VERSION2;
21483
+ var init_dist4 = __esm({
21484
+ "node_modules/@ai-sdk/openai-compatible/dist/index.mjs"() {
21485
+ init_dist();
21486
+ init_dist3();
21487
+ init_v4();
21488
+ init_v4();
21489
+ init_dist();
21490
+ init_dist3();
21491
+ init_v4();
21492
+ init_dist();
21493
+ init_dist3();
21494
+ init_v4();
21495
+ init_dist();
21496
+ init_v4();
21497
+ init_dist();
21498
+ init_dist3();
21499
+ init_v4();
21500
+ init_v4();
21501
+ init_dist3();
21502
+ init_v4();
21503
+ init_dist3();
21504
+ openaiCompatibleErrorDataSchema = external_exports.object({
21505
+ error: external_exports.object({
21506
+ message: external_exports.string(),
21507
+ // The additional information below is handled loosely to support
21508
+ // OpenAI-compatible providers that have slightly different error
21509
+ // responses:
21510
+ type: external_exports.string().nullish(),
21511
+ param: external_exports.any().nullish(),
21512
+ code: external_exports.union([external_exports.string(), external_exports.number()]).nullish()
21513
+ })
21514
+ });
21515
+ defaultOpenAICompatibleErrorStructure = {
21516
+ errorSchema: openaiCompatibleErrorDataSchema,
21517
+ errorToMessage: (data2) => data2.error.message
21518
+ };
21519
+ openaiCompatibleLanguageModelChatOptions = external_exports.object({
21520
+ /**
21521
+ * A unique identifier representing your end-user, which can help the provider to
21522
+ * monitor and detect abuse.
21523
+ */
21524
+ user: external_exports.string().optional(),
21525
+ /**
21526
+ * Reasoning effort for reasoning models. Defaults to `medium`.
21527
+ */
21528
+ reasoningEffort: external_exports.string().optional(),
21529
+ /**
21530
+ * Controls the verbosity of the generated text. Defaults to `medium`.
21531
+ */
21532
+ textVerbosity: external_exports.string().optional(),
21533
+ /**
21534
+ * Whether to use strict JSON schema validation.
21535
+ * When true, the model uses constrained decoding to guarantee schema compliance.
21536
+ * Only used when the provider supports structured outputs and a schema is provided.
21537
+ *
21538
+ * @default true
21539
+ */
21540
+ strictJsonSchema: external_exports.boolean().optional()
21541
+ });
21542
+ OpenAICompatibleChatLanguageModel = class {
21543
+ // type inferred via constructor
21544
+ constructor(modelId, config2) {
21545
+ this.specificationVersion = "v3";
21546
+ var _a17, _b16;
21547
+ this.modelId = modelId;
21548
+ this.config = config2;
21549
+ const errorStructure = (_a17 = config2.errorStructure) != null ? _a17 : defaultOpenAICompatibleErrorStructure;
21550
+ this.chunkSchema = createOpenAICompatibleChatChunkSchema(
21551
+ errorStructure.errorSchema
21552
+ );
21553
+ this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
21554
+ this.supportsStructuredOutputs = (_b16 = config2.supportsStructuredOutputs) != null ? _b16 : false;
21555
+ }
21556
+ get provider() {
21557
+ return this.config.provider;
21558
+ }
21559
+ get providerOptionsName() {
21560
+ return this.config.provider.split(".")[0].trim();
21561
+ }
21562
+ get supportedUrls() {
21563
+ var _a17, _b16, _c;
21564
+ return (_c = (_b16 = (_a17 = this.config).supportedUrls) == null ? void 0 : _b16.call(_a17)) != null ? _c : {};
21565
+ }
21566
+ transformRequestBody(args) {
21567
+ var _a17, _b16, _c;
21568
+ return (_c = (_b16 = (_a17 = this.config).transformRequestBody) == null ? void 0 : _b16.call(_a17, args)) != null ? _c : args;
21569
+ }
21570
+ convertUsage(usage) {
21571
+ var _a17, _b16, _c;
21572
+ return (_c = (_b16 = (_a17 = this.config).convertUsage) == null ? void 0 : _b16.call(_a17, usage)) != null ? _c : convertOpenAICompatibleChatUsage(usage);
21573
+ }
21574
+ async getArgs({
21575
+ prompt,
21576
+ maxOutputTokens,
21577
+ temperature,
21578
+ topP,
21579
+ topK,
21580
+ frequencyPenalty,
21581
+ presencePenalty,
21582
+ providerOptions,
21583
+ stopSequences,
21584
+ responseFormat,
21585
+ seed,
21586
+ toolChoice,
21587
+ tools: tools2
21588
+ }) {
21589
+ var _a17, _b16, _c, _d, _e;
21590
+ const warnings = [];
21591
+ const deprecatedOptions = await parseProviderOptions({
21592
+ provider: "openai-compatible",
21593
+ providerOptions,
21594
+ schema: openaiCompatibleLanguageModelChatOptions
21595
+ });
21596
+ if (deprecatedOptions != null) {
21597
+ warnings.push({
21598
+ type: "other",
21599
+ message: `The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead.`
21600
+ });
21601
+ }
21602
+ const compatibleOptions = Object.assign(
21603
+ deprecatedOptions != null ? deprecatedOptions : {},
21604
+ (_a17 = await parseProviderOptions({
21605
+ provider: "openaiCompatible",
21606
+ providerOptions,
21607
+ schema: openaiCompatibleLanguageModelChatOptions
21608
+ })) != null ? _a17 : {},
21609
+ (_b16 = await parseProviderOptions({
21610
+ provider: this.providerOptionsName,
21611
+ providerOptions,
21612
+ schema: openaiCompatibleLanguageModelChatOptions
21613
+ })) != null ? _b16 : {},
21614
+ (_c = await parseProviderOptions({
21615
+ provider: toCamelCase(this.providerOptionsName),
21616
+ providerOptions,
21617
+ schema: openaiCompatibleLanguageModelChatOptions
21618
+ })) != null ? _c : {}
21619
+ );
21620
+ const strictJsonSchema = (_d = compatibleOptions == null ? void 0 : compatibleOptions.strictJsonSchema) != null ? _d : true;
21621
+ if (topK != null) {
21622
+ warnings.push({ type: "unsupported", feature: "topK" });
21623
+ }
21624
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) {
21625
+ warnings.push({
21626
+ type: "unsupported",
21627
+ feature: "responseFormat",
21628
+ details: "JSON response format schema is only supported with structuredOutputs"
21629
+ });
21630
+ }
21631
+ const {
21632
+ tools: openaiTools,
21633
+ toolChoice: openaiToolChoice,
21634
+ toolWarnings
21635
+ } = prepareTools({
21636
+ tools: tools2,
21637
+ toolChoice
21638
+ });
21639
+ const metadataKey = resolveProviderOptionsKey(
21640
+ this.providerOptionsName,
21641
+ providerOptions
21642
+ );
21643
+ return {
21644
+ metadataKey,
21645
+ args: {
21646
+ // model id:
21647
+ model: this.modelId,
21648
+ // model specific settings:
21649
+ user: compatibleOptions.user,
21650
+ // standardized settings:
21651
+ max_tokens: maxOutputTokens,
21652
+ temperature,
21653
+ top_p: topP,
21654
+ frequency_penalty: frequencyPenalty,
21655
+ presence_penalty: presencePenalty,
21656
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? this.supportsStructuredOutputs === true && responseFormat.schema != null ? {
21657
+ type: "json_schema",
21658
+ json_schema: {
21659
+ schema: responseFormat.schema,
21660
+ strict: strictJsonSchema,
21661
+ name: (_e = responseFormat.name) != null ? _e : "response",
21662
+ description: responseFormat.description
21663
+ }
21664
+ } : { type: "json_object" } : void 0,
21665
+ stop: stopSequences,
21666
+ seed,
21667
+ ...Object.fromEntries(
21668
+ Object.entries({
21669
+ ...providerOptions == null ? void 0 : providerOptions[this.providerOptionsName],
21670
+ ...providerOptions == null ? void 0 : providerOptions[toCamelCase(this.providerOptionsName)]
21671
+ }).filter(
21672
+ ([key]) => !Object.keys(
21673
+ openaiCompatibleLanguageModelChatOptions.shape
21674
+ ).includes(key)
21675
+ )
21676
+ ),
21677
+ reasoning_effort: compatibleOptions.reasoningEffort,
21678
+ verbosity: compatibleOptions.textVerbosity,
21679
+ // messages:
21680
+ messages: convertToOpenAICompatibleChatMessages(prompt),
21681
+ // tools:
21682
+ tools: openaiTools,
21683
+ tool_choice: openaiToolChoice
21684
+ },
21685
+ warnings: [...warnings, ...toolWarnings]
21686
+ };
21687
+ }
21688
+ async doGenerate(options) {
21689
+ var _a17, _b16, _c, _d, _e, _f, _g, _h;
21690
+ const { args, warnings, metadataKey } = await this.getArgs({ ...options });
21691
+ const transformedBody = this.transformRequestBody(args);
21692
+ const body = JSON.stringify(transformedBody);
21693
+ const {
21694
+ responseHeaders,
21695
+ value: responseBody,
21696
+ rawValue: rawResponse
21697
+ } = await postJsonToApi({
21698
+ url: this.config.url({
21699
+ path: "/chat/completions",
21700
+ modelId: this.modelId
21701
+ }),
21702
+ headers: combineHeaders(this.config.headers(), options.headers),
21703
+ body: transformedBody,
21704
+ failedResponseHandler: this.failedResponseHandler,
21705
+ successfulResponseHandler: createJsonResponseHandler(
21706
+ OpenAICompatibleChatResponseSchema
21707
+ ),
21708
+ abortSignal: options.abortSignal,
21709
+ fetch: this.config.fetch
21710
+ });
21711
+ const choice = responseBody.choices[0];
21712
+ const content = [];
21713
+ content.push(...convertOpenAICompatibleContent(choice.message.content));
21714
+ const reasoning = (_a17 = choice.message.reasoning_content) != null ? _a17 : choice.message.reasoning;
21715
+ if (reasoning != null && reasoning.length > 0) {
21716
+ content.push({
21717
+ type: "reasoning",
21718
+ text: reasoning
21719
+ });
21720
+ }
21721
+ if (choice.message.tool_calls != null) {
21722
+ for (const toolCall of choice.message.tool_calls) {
21723
+ const thoughtSignature = (_c = (_b16 = toolCall.extra_content) == null ? void 0 : _b16.google) == null ? void 0 : _c.thought_signature;
21724
+ content.push({
21725
+ type: "tool-call",
21726
+ toolCallId: (_d = toolCall.id) != null ? _d : generateId(),
21727
+ toolName: toolCall.function.name,
21728
+ input: toolCall.function.arguments,
21729
+ ...thoughtSignature ? {
21730
+ providerMetadata: {
21731
+ [metadataKey]: { thoughtSignature }
21732
+ }
21733
+ } : {}
21734
+ });
21735
+ }
21736
+ }
21737
+ const providerMetadata = {
21738
+ [metadataKey]: {},
21739
+ ...await ((_f = (_e = this.config.metadataExtractor) == null ? void 0 : _e.extractMetadata) == null ? void 0 : _f.call(_e, {
21740
+ parsedBody: rawResponse
21741
+ }))
21742
+ };
21743
+ const completionTokenDetails = (_g = responseBody.usage) == null ? void 0 : _g.completion_tokens_details;
21744
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) {
21745
+ providerMetadata[metadataKey].acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens;
21746
+ }
21747
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) {
21748
+ providerMetadata[metadataKey].rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens;
21749
+ }
21750
+ return {
21751
+ content,
21752
+ finishReason: {
21753
+ unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
21754
+ raw: (_h = choice.finish_reason) != null ? _h : void 0
21755
+ },
21756
+ usage: this.convertUsage(responseBody.usage),
21757
+ providerMetadata,
21758
+ request: { body },
21759
+ response: {
21760
+ ...getResponseMetadata(responseBody),
21761
+ headers: responseHeaders,
21762
+ body: rawResponse
21763
+ },
21764
+ warnings
21765
+ };
21766
+ }
21767
+ async doStream(options) {
21768
+ var _a17;
21769
+ const { args, warnings, metadataKey } = await this.getArgs({ ...options });
21770
+ const body = this.transformRequestBody({
21771
+ ...args,
21772
+ stream: true,
21773
+ // only include stream_options when in strict compatibility mode:
21774
+ stream_options: this.config.includeUsage ? { include_usage: true } : void 0
21775
+ });
21776
+ const metadataExtractor = (_a17 = this.config.metadataExtractor) == null ? void 0 : _a17.createStreamExtractor();
21777
+ const { responseHeaders, value: response } = await postJsonToApi({
21778
+ url: this.config.url({
21779
+ path: "/chat/completions",
21780
+ modelId: this.modelId
21781
+ }),
21782
+ headers: combineHeaders(this.config.headers(), options.headers),
21783
+ body,
21784
+ failedResponseHandler: this.failedResponseHandler,
21785
+ successfulResponseHandler: createEventSourceResponseHandler(
21786
+ this.chunkSchema
21787
+ ),
21788
+ abortSignal: options.abortSignal,
21789
+ fetch: this.config.fetch
21790
+ });
21791
+ const toolCalls = [];
21792
+ const pendingToolCalls = /* @__PURE__ */ new Map();
21793
+ let finishReason;
21794
+ let usage = void 0;
21795
+ let isFirstChunk = true;
21796
+ const providerOptionsName = metadataKey;
21797
+ let isActiveReasoning = false;
21798
+ let isActiveText = false;
21799
+ const convertUsage = (usage2) => this.convertUsage(usage2);
21800
+ return {
21801
+ stream: response.pipeThrough(
21802
+ new TransformStream({
21803
+ start(controller) {
21804
+ controller.enqueue({ type: "stream-start", warnings });
21805
+ },
21806
+ transform(chunk, controller) {
21807
+ var _a22, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
21808
+ if (options.includeRawChunks) {
21809
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
21810
+ }
21811
+ if (!chunk.success) {
21812
+ finishReason = { unified: "error", raw: void 0 };
21813
+ controller.enqueue({ type: "error", error: chunk.error });
21814
+ return;
21815
+ }
21816
+ metadataExtractor == null ? void 0 : metadataExtractor.processChunk(chunk.rawValue);
21817
+ if ("error" in chunk.value) {
21818
+ finishReason = { unified: "error", raw: void 0 };
21819
+ controller.enqueue({
21820
+ type: "error",
21821
+ error: chunk.value.error
21822
+ });
21823
+ return;
21824
+ }
21825
+ const value = chunk.value;
21826
+ if (isFirstChunk) {
21827
+ isFirstChunk = false;
21828
+ controller.enqueue({
21829
+ type: "response-metadata",
21830
+ ...getResponseMetadata(value)
21831
+ });
21832
+ }
21833
+ if (value.usage != null) {
21834
+ usage = value.usage;
21835
+ }
21836
+ const choice = value.choices[0];
21837
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
21838
+ finishReason = {
21839
+ unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
21840
+ raw: (_a22 = choice.finish_reason) != null ? _a22 : void 0
21841
+ };
21842
+ }
21843
+ if ((choice == null ? void 0 : choice.delta) == null) {
21844
+ return;
21845
+ }
21846
+ const delta = choice.delta;
21847
+ const enqueueReasoningDelta = (reasoningDelta) => {
21848
+ if (isActiveText) {
21849
+ controller.enqueue({ type: "text-end", id: "txt-0" });
21850
+ isActiveText = false;
21851
+ }
21852
+ if (!isActiveReasoning) {
21853
+ controller.enqueue({
21854
+ type: "reasoning-start",
21855
+ id: "reasoning-0"
21856
+ });
21857
+ isActiveReasoning = true;
21858
+ }
21859
+ controller.enqueue({
21860
+ type: "reasoning-delta",
21861
+ id: "reasoning-0",
21862
+ delta: reasoningDelta
21863
+ });
21864
+ };
21865
+ const enqueueTextDelta = (textDelta) => {
21866
+ if (isActiveReasoning) {
21867
+ controller.enqueue({
21868
+ type: "reasoning-end",
21869
+ id: "reasoning-0"
21870
+ });
21871
+ isActiveReasoning = false;
21872
+ }
21873
+ if (!isActiveText) {
21874
+ controller.enqueue({ type: "text-start", id: "txt-0" });
21875
+ isActiveText = true;
21876
+ }
21877
+ controller.enqueue({
21878
+ type: "text-delta",
21879
+ id: "txt-0",
21880
+ delta: textDelta
21881
+ });
21882
+ };
21883
+ const reasoningContent = (_b16 = delta.reasoning_content) != null ? _b16 : delta.reasoning;
21884
+ if (reasoningContent) {
21885
+ enqueueReasoningDelta(reasoningContent);
21886
+ }
21887
+ for (const contentPart of convertOpenAICompatibleContent(
21888
+ delta.content
21889
+ )) {
21890
+ if (contentPart.type === "reasoning") {
21891
+ enqueueReasoningDelta(contentPart.text);
21892
+ } else {
21893
+ enqueueTextDelta(contentPart.text);
21894
+ }
21895
+ }
21896
+ if (delta.tool_calls != null) {
21897
+ if (isActiveReasoning) {
21898
+ controller.enqueue({
21899
+ type: "reasoning-end",
21900
+ id: "reasoning-0"
21901
+ });
21902
+ isActiveReasoning = false;
21903
+ }
21904
+ for (const toolCallDelta of delta.tool_calls) {
21905
+ const index = (_c = toolCallDelta.index) != null ? _c : toolCalls.length;
21906
+ if (toolCalls[index] == null) {
21907
+ if (toolCallDelta.index != null) {
21908
+ let pending = pendingToolCalls.get(index);
21909
+ if (pending == null) {
21910
+ pending = {
21911
+ id: (_d = toolCallDelta.id) != null ? _d : null,
21912
+ bufferedArguments: "",
21913
+ thoughtSignature: (_g = (_f = (_e = toolCallDelta.extra_content) == null ? void 0 : _e.google) == null ? void 0 : _f.thought_signature) != null ? _g : void 0
21914
+ };
21915
+ pendingToolCalls.set(index, pending);
21916
+ } else {
21917
+ if (pending.id == null && toolCallDelta.id != null) {
21918
+ pending.id = toolCallDelta.id;
21919
+ }
21920
+ if (pending.thoughtSignature == null && ((_i = (_h = toolCallDelta.extra_content) == null ? void 0 : _h.google) == null ? void 0 : _i.thought_signature) != null) {
21921
+ pending.thoughtSignature = toolCallDelta.extra_content.google.thought_signature;
21922
+ }
21923
+ }
21924
+ const argumentsDelta = (_j = toolCallDelta.function) == null ? void 0 : _j.arguments;
21925
+ if (argumentsDelta != null) {
21926
+ pending.bufferedArguments += argumentsDelta;
21927
+ }
21928
+ const name15 = (_k = toolCallDelta.function) == null ? void 0 : _k.name;
21929
+ if (name15 == null) {
21930
+ continue;
21931
+ }
21932
+ pendingToolCalls.delete(index);
21933
+ if (pending.id == null) {
21934
+ throw new InvalidResponseDataError({
21935
+ data: toolCallDelta,
21936
+ message: `Expected 'id' to be a string.`
21937
+ });
21938
+ }
21939
+ controller.enqueue({
21940
+ type: "tool-input-start",
21941
+ id: pending.id,
21942
+ toolName: name15
21943
+ });
21944
+ toolCalls[index] = {
21945
+ id: pending.id,
21946
+ type: "function",
21947
+ function: {
21948
+ name: name15,
21949
+ arguments: pending.bufferedArguments
21950
+ },
21951
+ hasFinished: false,
21952
+ thoughtSignature: pending.thoughtSignature
21953
+ };
21954
+ } else {
21955
+ if (toolCallDelta.id == null) {
21956
+ throw new InvalidResponseDataError({
21957
+ data: toolCallDelta,
21958
+ message: `Expected 'id' to be a string.`
21959
+ });
21960
+ }
21961
+ if (((_l = toolCallDelta.function) == null ? void 0 : _l.name) == null) {
21962
+ throw new InvalidResponseDataError({
21963
+ data: toolCallDelta,
21964
+ message: `Expected 'function.name' to be a string.`
21965
+ });
21966
+ }
21967
+ controller.enqueue({
21968
+ type: "tool-input-start",
21969
+ id: toolCallDelta.id,
21970
+ toolName: toolCallDelta.function.name
21971
+ });
21972
+ toolCalls[index] = {
21973
+ id: toolCallDelta.id,
21974
+ type: "function",
21975
+ function: {
21976
+ name: toolCallDelta.function.name,
21977
+ arguments: (_m = toolCallDelta.function.arguments) != null ? _m : ""
21978
+ },
21979
+ hasFinished: false,
21980
+ thoughtSignature: (_p = (_o = (_n = toolCallDelta.extra_content) == null ? void 0 : _n.google) == null ? void 0 : _o.thought_signature) != null ? _p : void 0
21981
+ };
21982
+ }
21983
+ const toolCall2 = toolCalls[index];
21984
+ if (((_q = toolCall2.function) == null ? void 0 : _q.name) != null && ((_r = toolCall2.function) == null ? void 0 : _r.arguments) != null) {
21985
+ if (toolCall2.function.arguments.length > 0) {
21986
+ controller.enqueue({
21987
+ type: "tool-input-delta",
21988
+ id: toolCall2.id,
21989
+ delta: toolCall2.function.arguments
21990
+ });
21991
+ }
21992
+ }
21993
+ continue;
21994
+ }
21995
+ const toolCall = toolCalls[index];
21996
+ if (toolCall.hasFinished) {
21997
+ continue;
21998
+ }
21999
+ if (((_s = toolCallDelta.function) == null ? void 0 : _s.arguments) != null) {
22000
+ toolCall.function.arguments += (_u = (_t = toolCallDelta.function) == null ? void 0 : _t.arguments) != null ? _u : "";
22001
+ }
22002
+ controller.enqueue({
22003
+ type: "tool-input-delta",
22004
+ id: toolCall.id,
22005
+ delta: (_v = toolCallDelta.function.arguments) != null ? _v : ""
22006
+ });
22007
+ }
22008
+ }
22009
+ },
22010
+ flush(controller) {
22011
+ var _a22, _b16, _c, _d, _e;
22012
+ if (isActiveReasoning) {
22013
+ controller.enqueue({ type: "reasoning-end", id: "reasoning-0" });
22014
+ }
22015
+ if (isActiveText) {
22016
+ controller.enqueue({ type: "text-end", id: "txt-0" });
22017
+ }
22018
+ for (const [index, pending] of pendingToolCalls) {
22019
+ throw new InvalidResponseDataError({
22020
+ data: {
22021
+ index,
22022
+ id: pending.id,
22023
+ function: { arguments: pending.bufferedArguments }
22024
+ },
22025
+ message: `Expected 'function.name' to be a string.`
22026
+ });
22027
+ }
22028
+ for (const toolCall of toolCalls.filter(
22029
+ (toolCall2) => !toolCall2.hasFinished
22030
+ )) {
22031
+ controller.enqueue({
22032
+ type: "tool-input-end",
22033
+ id: toolCall.id
22034
+ });
22035
+ controller.enqueue({
22036
+ type: "tool-call",
22037
+ toolCallId: (_a22 = toolCall.id) != null ? _a22 : generateId(),
22038
+ toolName: toolCall.function.name,
22039
+ input: toolCall.function.arguments,
22040
+ ...toolCall.thoughtSignature ? {
22041
+ providerMetadata: {
22042
+ [providerOptionsName]: {
22043
+ thoughtSignature: toolCall.thoughtSignature
22044
+ }
22045
+ }
22046
+ } : {}
22047
+ });
22048
+ }
22049
+ if (finishReason == null) {
22050
+ finishReason = { unified: "error", raw: void 0 };
22051
+ controller.enqueue({
22052
+ type: "error",
22053
+ error: new InvalidResponseDataError({
22054
+ data: void 0,
22055
+ message: "Response stream ended without a finish reason."
22056
+ })
22057
+ });
22058
+ }
22059
+ const providerMetadata = {
22060
+ [providerOptionsName]: {},
22061
+ ...metadataExtractor == null ? void 0 : metadataExtractor.buildMetadata()
22062
+ };
22063
+ if (((_b16 = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _b16.accepted_prediction_tokens) != null) {
22064
+ providerMetadata[providerOptionsName].acceptedPredictionTokens = (_c = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _c.accepted_prediction_tokens;
22065
+ }
22066
+ if (((_d = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _d.rejected_prediction_tokens) != null) {
22067
+ providerMetadata[providerOptionsName].rejectedPredictionTokens = (_e = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _e.rejected_prediction_tokens;
22068
+ }
22069
+ controller.enqueue({
22070
+ type: "finish",
22071
+ finishReason,
22072
+ usage: convertUsage(usage),
22073
+ providerMetadata
22074
+ });
22075
+ }
22076
+ })
22077
+ ),
22078
+ request: { body },
22079
+ response: { headers: responseHeaders }
22080
+ };
22081
+ }
22082
+ };
22083
+ openaiCompatibleTokenUsageSchema = external_exports.looseObject({
22084
+ prompt_tokens: external_exports.number().nullish(),
22085
+ completion_tokens: external_exports.number().nullish(),
22086
+ total_tokens: external_exports.number().nullish(),
22087
+ prompt_tokens_details: external_exports.looseObject({
22088
+ cached_tokens: external_exports.number().nullish()
22089
+ }).nullish(),
22090
+ completion_tokens_details: external_exports.looseObject({
22091
+ reasoning_tokens: external_exports.number().nullish(),
22092
+ accepted_prediction_tokens: external_exports.number().nullish(),
22093
+ rejected_prediction_tokens: external_exports.number().nullish()
22094
+ }).nullish()
22095
+ }).nullish();
22096
+ openAICompatibleContentSchema = external_exports.union([
22097
+ external_exports.string(),
22098
+ external_exports.array(
22099
+ external_exports.looseObject({
22100
+ type: external_exports.string()
22101
+ })
22102
+ )
22103
+ ]).nullish();
22104
+ OpenAICompatibleChatResponseSchema = external_exports.looseObject({
22105
+ id: external_exports.string().nullish(),
22106
+ created: external_exports.number().nullish(),
22107
+ model: external_exports.string().nullish(),
22108
+ choices: external_exports.array(
22109
+ external_exports.object({
22110
+ message: external_exports.object({
22111
+ role: external_exports.literal("assistant").nullish(),
22112
+ content: openAICompatibleContentSchema,
22113
+ reasoning_content: external_exports.string().nullish(),
22114
+ reasoning: external_exports.string().nullish(),
22115
+ tool_calls: external_exports.array(
22116
+ external_exports.object({
22117
+ id: external_exports.string().nullish(),
22118
+ function: external_exports.object({
22119
+ name: external_exports.string(),
22120
+ arguments: external_exports.string()
22121
+ }),
22122
+ // Support for Google Gemini thought signatures via OpenAI compatibility
22123
+ extra_content: external_exports.object({
22124
+ google: external_exports.object({
22125
+ thought_signature: external_exports.string().nullish()
22126
+ }).nullish()
22127
+ }).nullish()
22128
+ })
22129
+ ).nullish()
22130
+ }),
22131
+ finish_reason: external_exports.string().nullish()
22132
+ })
22133
+ ),
22134
+ usage: openaiCompatibleTokenUsageSchema
22135
+ });
22136
+ chunkBaseSchema = external_exports.looseObject({
22137
+ id: external_exports.string().nullish(),
22138
+ created: external_exports.number().nullish(),
22139
+ model: external_exports.string().nullish(),
22140
+ choices: external_exports.array(
22141
+ external_exports.object({
22142
+ delta: external_exports.object({
22143
+ role: external_exports.enum(["assistant", ""]).nullish(),
22144
+ content: openAICompatibleContentSchema,
22145
+ // Most openai-compatible models set `reasoning_content`, but some
22146
+ // providers serving `gpt-oss` set `reasoning`. See #7866
22147
+ reasoning_content: external_exports.string().nullish(),
22148
+ reasoning: external_exports.string().nullish(),
22149
+ tool_calls: external_exports.array(
22150
+ external_exports.object({
22151
+ index: external_exports.number().nullish(),
22152
+ //google does not send index
22153
+ id: external_exports.string().nullish(),
22154
+ function: external_exports.object({
22155
+ name: external_exports.string().nullish(),
22156
+ arguments: external_exports.string().nullish()
22157
+ }),
22158
+ // Support for Google Gemini thought signatures via OpenAI compatibility
22159
+ extra_content: external_exports.object({
22160
+ google: external_exports.object({
22161
+ thought_signature: external_exports.string().nullish()
22162
+ }).nullish()
22163
+ }).nullish()
22164
+ })
22165
+ ).nullish()
22166
+ }).nullish(),
22167
+ finish_reason: external_exports.string().nullish()
22168
+ })
22169
+ ),
22170
+ usage: openaiCompatibleTokenUsageSchema
22171
+ });
22172
+ createOpenAICompatibleChatChunkSchema = (errorSchema) => external_exports.union([chunkBaseSchema, errorSchema]);
22173
+ openaiCompatibleLanguageModelCompletionOptions = external_exports.object({
22174
+ /**
22175
+ * Echo back the prompt in addition to the completion.
22176
+ */
22177
+ echo: external_exports.boolean().optional(),
22178
+ /**
22179
+ * Modify the likelihood of specified tokens appearing in the completion.
22180
+ *
22181
+ * Accepts a JSON object that maps tokens (specified by their token ID in
22182
+ * the GPT tokenizer) to an associated bias value from -100 to 100.
22183
+ */
22184
+ logitBias: external_exports.record(external_exports.string(), external_exports.number()).optional(),
22185
+ /**
22186
+ * The suffix that comes after a completion of inserted text.
22187
+ */
22188
+ suffix: external_exports.string().optional(),
22189
+ /**
22190
+ * A unique identifier representing your end-user, which can help providers to
22191
+ * monitor and detect abuse.
22192
+ */
22193
+ user: external_exports.string().optional()
22194
+ });
22195
+ OpenAICompatibleCompletionLanguageModel = class {
22196
+ // type inferred via constructor
22197
+ constructor(modelId, config2) {
22198
+ this.specificationVersion = "v3";
22199
+ var _a17;
22200
+ this.modelId = modelId;
22201
+ this.config = config2;
22202
+ const errorStructure = (_a17 = config2.errorStructure) != null ? _a17 : defaultOpenAICompatibleErrorStructure;
22203
+ this.chunkSchema = createOpenAICompatibleCompletionChunkSchema(
22204
+ errorStructure.errorSchema
22205
+ );
22206
+ this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
22207
+ }
22208
+ get provider() {
22209
+ return this.config.provider;
22210
+ }
22211
+ get providerOptionsName() {
22212
+ return this.config.provider.split(".")[0].trim();
22213
+ }
22214
+ get supportedUrls() {
22215
+ var _a17, _b16, _c;
22216
+ return (_c = (_b16 = (_a17 = this.config).supportedUrls) == null ? void 0 : _b16.call(_a17)) != null ? _c : {};
22217
+ }
22218
+ async getArgs({
22219
+ prompt,
22220
+ maxOutputTokens,
22221
+ temperature,
22222
+ topP,
22223
+ topK,
22224
+ frequencyPenalty,
22225
+ presencePenalty,
22226
+ stopSequences: userStopSequences,
22227
+ responseFormat,
22228
+ seed,
22229
+ providerOptions,
22230
+ tools: tools2,
22231
+ toolChoice
22232
+ }) {
22233
+ var _a17, _b16;
22234
+ const warnings = [];
22235
+ const completionOptions = Object.assign(
22236
+ (_a17 = await parseProviderOptions({
22237
+ provider: this.providerOptionsName,
22238
+ providerOptions,
22239
+ schema: openaiCompatibleLanguageModelCompletionOptions
22240
+ })) != null ? _a17 : {},
22241
+ (_b16 = await parseProviderOptions({
22242
+ provider: toCamelCase(this.providerOptionsName),
22243
+ providerOptions,
22244
+ schema: openaiCompatibleLanguageModelCompletionOptions
22245
+ })) != null ? _b16 : {}
22246
+ );
22247
+ if (topK != null) {
22248
+ warnings.push({ type: "unsupported", feature: "topK" });
22249
+ }
22250
+ if (tools2 == null ? void 0 : tools2.length) {
22251
+ warnings.push({ type: "unsupported", feature: "tools" });
22252
+ }
22253
+ if (toolChoice != null) {
22254
+ warnings.push({ type: "unsupported", feature: "toolChoice" });
22255
+ }
22256
+ if (responseFormat != null && responseFormat.type !== "text") {
22257
+ warnings.push({
22258
+ type: "unsupported",
22259
+ feature: "responseFormat",
22260
+ details: "JSON response format is not supported."
22261
+ });
22262
+ }
22263
+ const { prompt: completionPrompt, stopSequences } = convertToOpenAICompatibleCompletionPrompt({ prompt });
22264
+ const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
22265
+ return {
22266
+ args: {
22267
+ // model id:
22268
+ model: this.modelId,
22269
+ // model specific settings:
22270
+ echo: completionOptions.echo,
22271
+ logit_bias: completionOptions.logitBias,
22272
+ suffix: completionOptions.suffix,
22273
+ user: completionOptions.user,
22274
+ // standardized settings:
22275
+ max_tokens: maxOutputTokens,
22276
+ temperature,
22277
+ top_p: topP,
22278
+ frequency_penalty: frequencyPenalty,
22279
+ presence_penalty: presencePenalty,
22280
+ seed,
22281
+ ...providerOptions == null ? void 0 : providerOptions[this.providerOptionsName],
22282
+ ...providerOptions == null ? void 0 : providerOptions[toCamelCase(this.providerOptionsName)],
22283
+ // prompt:
22284
+ prompt: completionPrompt,
22285
+ // stop sequences:
22286
+ stop: stop.length > 0 ? stop : void 0
22287
+ },
22288
+ warnings
22289
+ };
22290
+ }
22291
+ async doGenerate(options) {
22292
+ const { args, warnings } = await this.getArgs(options);
22293
+ const {
22294
+ responseHeaders,
22295
+ value: response,
22296
+ rawValue: rawResponse
22297
+ } = await postJsonToApi({
22298
+ url: this.config.url({
22299
+ path: "/completions",
22300
+ modelId: this.modelId
22301
+ }),
22302
+ headers: combineHeaders(this.config.headers(), options.headers),
22303
+ body: args,
22304
+ failedResponseHandler: this.failedResponseHandler,
22305
+ successfulResponseHandler: createJsonResponseHandler(
22306
+ openaiCompatibleCompletionResponseSchema
22307
+ ),
22308
+ abortSignal: options.abortSignal,
22309
+ fetch: this.config.fetch
22310
+ });
22311
+ const choice = response.choices[0];
22312
+ const content = [];
22313
+ if (choice.text != null && choice.text.length > 0) {
22314
+ content.push({ type: "text", text: choice.text });
22315
+ }
22316
+ return {
22317
+ content,
22318
+ usage: convertOpenAICompatibleCompletionUsage(response.usage),
22319
+ finishReason: {
22320
+ unified: mapOpenAICompatibleFinishReason2(choice.finish_reason),
22321
+ raw: choice.finish_reason
22322
+ },
22323
+ request: { body: args },
22324
+ response: {
22325
+ ...getResponseMetadata2(response),
22326
+ headers: responseHeaders,
22327
+ body: rawResponse
22328
+ },
22329
+ warnings
22330
+ };
22331
+ }
22332
+ async doStream(options) {
22333
+ const { args, warnings } = await this.getArgs(options);
22334
+ const body = {
22335
+ ...args,
22336
+ stream: true,
22337
+ // only include stream_options when in strict compatibility mode:
22338
+ stream_options: this.config.includeUsage ? { include_usage: true } : void 0
22339
+ };
22340
+ const { responseHeaders, value: response } = await postJsonToApi({
22341
+ url: this.config.url({
22342
+ path: "/completions",
22343
+ modelId: this.modelId
22344
+ }),
22345
+ headers: combineHeaders(this.config.headers(), options.headers),
22346
+ body,
22347
+ failedResponseHandler: this.failedResponseHandler,
22348
+ successfulResponseHandler: createEventSourceResponseHandler(
22349
+ this.chunkSchema
22350
+ ),
22351
+ abortSignal: options.abortSignal,
22352
+ fetch: this.config.fetch
22353
+ });
22354
+ let finishReason = {
22355
+ unified: "other",
22356
+ raw: void 0
22357
+ };
22358
+ let usage = void 0;
22359
+ let isFirstChunk = true;
22360
+ return {
22361
+ stream: response.pipeThrough(
22362
+ new TransformStream({
22363
+ start(controller) {
22364
+ controller.enqueue({ type: "stream-start", warnings });
22365
+ },
22366
+ transform(chunk, controller) {
22367
+ var _a17;
22368
+ if (options.includeRawChunks) {
22369
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
22370
+ }
22371
+ if (!chunk.success) {
22372
+ finishReason = { unified: "error", raw: void 0 };
22373
+ controller.enqueue({ type: "error", error: chunk.error });
22374
+ return;
22375
+ }
22376
+ const value = chunk.value;
22377
+ if ("error" in value) {
22378
+ finishReason = { unified: "error", raw: void 0 };
22379
+ controller.enqueue({ type: "error", error: value.error });
22380
+ return;
22381
+ }
22382
+ if (isFirstChunk) {
22383
+ isFirstChunk = false;
22384
+ controller.enqueue({
22385
+ type: "response-metadata",
22386
+ ...getResponseMetadata2(value)
22387
+ });
22388
+ controller.enqueue({
22389
+ type: "text-start",
22390
+ id: "0"
22391
+ });
22392
+ }
22393
+ if (value.usage != null) {
22394
+ usage = value.usage;
22395
+ }
22396
+ const choice = value.choices[0];
22397
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
22398
+ finishReason = {
22399
+ unified: mapOpenAICompatibleFinishReason2(choice.finish_reason),
22400
+ raw: (_a17 = choice.finish_reason) != null ? _a17 : void 0
22401
+ };
22402
+ }
22403
+ if ((choice == null ? void 0 : choice.text) != null) {
22404
+ controller.enqueue({
22405
+ type: "text-delta",
22406
+ id: "0",
22407
+ delta: choice.text
22408
+ });
22409
+ }
22410
+ },
22411
+ flush(controller) {
22412
+ if (!isFirstChunk) {
22413
+ controller.enqueue({ type: "text-end", id: "0" });
22414
+ }
22415
+ controller.enqueue({
22416
+ type: "finish",
22417
+ finishReason,
22418
+ usage: convertOpenAICompatibleCompletionUsage(usage)
22419
+ });
22420
+ }
22421
+ })
22422
+ ),
22423
+ request: { body },
22424
+ response: { headers: responseHeaders }
22425
+ };
22426
+ }
22427
+ };
22428
+ usageSchema = external_exports.looseObject({
22429
+ prompt_tokens: external_exports.number(),
22430
+ completion_tokens: external_exports.number(),
22431
+ total_tokens: external_exports.number()
22432
+ });
22433
+ openaiCompatibleCompletionResponseSchema = external_exports.object({
22434
+ id: external_exports.string().nullish(),
22435
+ created: external_exports.number().nullish(),
22436
+ model: external_exports.string().nullish(),
22437
+ choices: external_exports.array(
22438
+ external_exports.object({
22439
+ text: external_exports.string(),
22440
+ finish_reason: external_exports.string()
22441
+ })
22442
+ ),
22443
+ usage: usageSchema.nullish()
22444
+ });
22445
+ createOpenAICompatibleCompletionChunkSchema = (errorSchema) => external_exports.union([
22446
+ external_exports.object({
22447
+ id: external_exports.string().nullish(),
22448
+ created: external_exports.number().nullish(),
22449
+ model: external_exports.string().nullish(),
22450
+ choices: external_exports.array(
22451
+ external_exports.object({
22452
+ text: external_exports.string(),
22453
+ finish_reason: external_exports.string().nullish(),
22454
+ index: external_exports.number()
22455
+ })
22456
+ ),
22457
+ usage: usageSchema.nullish()
22458
+ }),
22459
+ errorSchema
22460
+ ]);
22461
+ openaiCompatibleEmbeddingModelOptions = external_exports.object({
22462
+ /**
22463
+ * The number of dimensions the resulting output embeddings should have.
22464
+ * Only supported in text-embedding-3 and later models.
22465
+ */
22466
+ dimensions: external_exports.number().optional(),
22467
+ /**
22468
+ * A unique identifier representing your end-user, which can help providers to
22469
+ * monitor and detect abuse.
22470
+ */
22471
+ user: external_exports.string().optional()
22472
+ });
22473
+ OpenAICompatibleEmbeddingModel = class {
22474
+ constructor(modelId, config2) {
22475
+ this.specificationVersion = "v3";
22476
+ this.modelId = modelId;
22477
+ this.config = config2;
22478
+ }
22479
+ get provider() {
22480
+ return this.config.provider;
22481
+ }
22482
+ get maxEmbeddingsPerCall() {
22483
+ var _a17;
22484
+ return (_a17 = this.config.maxEmbeddingsPerCall) != null ? _a17 : 2048;
22485
+ }
22486
+ get supportsParallelCalls() {
22487
+ var _a17;
22488
+ return (_a17 = this.config.supportsParallelCalls) != null ? _a17 : true;
22489
+ }
22490
+ get providerOptionsName() {
22491
+ return this.config.provider.split(".")[0].trim();
22492
+ }
22493
+ async doEmbed({
22494
+ values: values2,
22495
+ headers,
22496
+ abortSignal,
22497
+ providerOptions
22498
+ }) {
22499
+ var _a17, _b16, _c;
22500
+ const warnings = [];
22501
+ const deprecatedOptions = await parseProviderOptions({
22502
+ provider: "openai-compatible",
22503
+ providerOptions,
22504
+ schema: openaiCompatibleEmbeddingModelOptions
22505
+ });
22506
+ if (deprecatedOptions != null) {
22507
+ warnings.push({
22508
+ type: "other",
22509
+ message: `The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead.`
22510
+ });
22511
+ }
22512
+ const compatibleOptions = Object.assign(
22513
+ deprecatedOptions != null ? deprecatedOptions : {},
22514
+ (_a17 = await parseProviderOptions({
22515
+ provider: "openaiCompatible",
22516
+ providerOptions,
22517
+ schema: openaiCompatibleEmbeddingModelOptions
22518
+ })) != null ? _a17 : {},
22519
+ (_b16 = await parseProviderOptions({
22520
+ provider: this.providerOptionsName,
22521
+ providerOptions,
22522
+ schema: openaiCompatibleEmbeddingModelOptions
22523
+ })) != null ? _b16 : {}
22524
+ );
22525
+ if (values2.length > this.maxEmbeddingsPerCall) {
22526
+ throw new TooManyEmbeddingValuesForCallError({
22527
+ provider: this.provider,
22528
+ modelId: this.modelId,
22529
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
22530
+ values: values2
22531
+ });
22532
+ }
22533
+ const {
22534
+ responseHeaders,
22535
+ value: response,
22536
+ rawValue
22537
+ } = await postJsonToApi({
22538
+ url: this.config.url({
22539
+ path: "/embeddings",
22540
+ modelId: this.modelId
22541
+ }),
22542
+ headers: combineHeaders(this.config.headers(), headers),
22543
+ body: {
22544
+ model: this.modelId,
22545
+ input: values2,
22546
+ encoding_format: "float",
22547
+ dimensions: compatibleOptions.dimensions,
22548
+ user: compatibleOptions.user
22549
+ },
22550
+ failedResponseHandler: createJsonErrorResponseHandler(
22551
+ (_c = this.config.errorStructure) != null ? _c : defaultOpenAICompatibleErrorStructure
22552
+ ),
22553
+ successfulResponseHandler: createJsonResponseHandler(
22554
+ openaiTextEmbeddingResponseSchema
22555
+ ),
22556
+ abortSignal,
22557
+ fetch: this.config.fetch
22558
+ });
22559
+ return {
22560
+ warnings,
22561
+ embeddings: response.data.map((item) => item.embedding),
22562
+ usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
22563
+ providerMetadata: response.providerMetadata,
22564
+ response: { headers: responseHeaders, body: rawValue }
22565
+ };
22566
+ }
22567
+ };
22568
+ openaiTextEmbeddingResponseSchema = external_exports.object({
22569
+ data: external_exports.array(external_exports.object({ embedding: external_exports.array(external_exports.number()) })),
22570
+ usage: external_exports.object({ prompt_tokens: external_exports.number() }).nullish(),
22571
+ providerMetadata: external_exports.record(external_exports.string(), external_exports.record(external_exports.string(), external_exports.any())).optional()
22572
+ });
22573
+ OpenAICompatibleImageModel = class {
22574
+ constructor(modelId, config2) {
22575
+ this.modelId = modelId;
22576
+ this.config = config2;
22577
+ this.specificationVersion = "v3";
22578
+ this.maxImagesPerCall = 10;
22579
+ }
22580
+ get provider() {
22581
+ return this.config.provider;
22582
+ }
22583
+ /**
22584
+ * The provider options key used to extract provider-specific options.
22585
+ */
22586
+ get providerOptionsKey() {
22587
+ return this.config.provider.split(".")[0].trim();
22588
+ }
22589
+ // TODO: deprecate non-camelCase keys and remove in future major version
22590
+ getArgs(providerOptions) {
22591
+ return {
22592
+ ...providerOptions[this.providerOptionsKey],
22593
+ ...providerOptions[toCamelCase(this.providerOptionsKey)]
22594
+ };
22595
+ }
22596
+ async doGenerate({
22597
+ prompt,
22598
+ n,
22599
+ size,
22600
+ aspectRatio,
22601
+ seed,
22602
+ providerOptions,
22603
+ headers,
22604
+ abortSignal,
22605
+ files,
22606
+ mask
22607
+ }) {
22608
+ var _a17, _b16, _c, _d, _e;
22609
+ const warnings = [];
22610
+ if (aspectRatio != null) {
22611
+ warnings.push({
22612
+ type: "unsupported",
22613
+ feature: "aspectRatio",
22614
+ details: "This model does not support aspect ratio. Use `size` instead."
22615
+ });
22616
+ }
22617
+ if (seed != null) {
22618
+ warnings.push({ type: "unsupported", feature: "seed" });
22619
+ }
22620
+ const currentDate = (_c = (_b16 = (_a17 = this.config._internal) == null ? void 0 : _a17.currentDate) == null ? void 0 : _b16.call(_a17)) != null ? _c : /* @__PURE__ */ new Date();
22621
+ const args = this.getArgs(providerOptions);
22622
+ if (files != null && files.length > 0) {
22623
+ const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi({
22624
+ url: this.config.url({
22625
+ path: "/images/edits",
22626
+ modelId: this.modelId
22627
+ }),
22628
+ headers: combineHeaders(this.config.headers(), headers),
22629
+ formData: convertToFormData({
22630
+ model: this.modelId,
22631
+ prompt,
22632
+ image: await Promise.all(files.map((file2) => fileToBlob(file2))),
22633
+ mask: mask != null ? await fileToBlob(mask) : void 0,
22634
+ n,
22635
+ size,
22636
+ ...args
22637
+ }),
22638
+ failedResponseHandler: createJsonErrorResponseHandler(
22639
+ (_d = this.config.errorStructure) != null ? _d : defaultOpenAICompatibleErrorStructure
22640
+ ),
22641
+ successfulResponseHandler: createJsonResponseHandler(
22642
+ openaiCompatibleImageResponseSchema
22643
+ ),
22644
+ abortSignal,
22645
+ fetch: this.config.fetch
22646
+ });
22647
+ return {
22648
+ images: response2.data.map((item) => item.b64_json),
22649
+ warnings,
22650
+ response: {
22651
+ timestamp: currentDate,
22652
+ modelId: this.modelId,
22653
+ headers: responseHeaders2
22654
+ }
22655
+ };
22656
+ }
22657
+ const { value: response, responseHeaders } = await postJsonToApi({
22658
+ url: this.config.url({
22659
+ path: "/images/generations",
22660
+ modelId: this.modelId
22661
+ }),
22662
+ headers: combineHeaders(this.config.headers(), headers),
22663
+ body: {
22664
+ model: this.modelId,
22665
+ prompt,
22666
+ n,
22667
+ size,
22668
+ ...args,
22669
+ response_format: "b64_json"
22670
+ },
22671
+ failedResponseHandler: createJsonErrorResponseHandler(
22672
+ (_e = this.config.errorStructure) != null ? _e : defaultOpenAICompatibleErrorStructure
22673
+ ),
22674
+ successfulResponseHandler: createJsonResponseHandler(
22675
+ openaiCompatibleImageResponseSchema
22676
+ ),
22677
+ abortSignal,
22678
+ fetch: this.config.fetch
22679
+ });
22680
+ return {
22681
+ images: response.data.map((item) => item.b64_json),
22682
+ warnings,
22683
+ response: {
22684
+ timestamp: currentDate,
22685
+ modelId: this.modelId,
22686
+ headers: responseHeaders
22687
+ }
22688
+ };
22689
+ }
22690
+ };
22691
+ openaiCompatibleImageResponseSchema = external_exports.object({
22692
+ data: external_exports.array(external_exports.object({ b64_json: external_exports.string() }))
22693
+ });
22694
+ VERSION2 = true ? "2.0.74" : "0.0.0-test";
22695
+ }
22696
+ });
22697
+
20284
22698
  // node_modules/@smithy/core/dist-es/submodules/serde/is-array-buffer/is-array-buffer.js
20285
22699
  var isArrayBuffer;
20286
22700
  var init_is_array_buffer = __esm({
@@ -24918,16 +27332,17 @@ var init_aws4fetch_esm = __esm({
24918
27332
 
24919
27333
  // node_modules/@ai-sdk/amazon-bedrock/dist/index.mjs
24920
27334
  function supportsStrictTools(modelId) {
24921
- return !rejectsNewerSchemaFields(modelId);
27335
+ return !matchesModel(modelId, MODELS_WITHOUT_STRICT_TOOL_SUPPORT);
24922
27336
  }
24923
27337
  function supportsNativeStructuredOutput(modelId) {
24924
- return !rejectsNewerSchemaFields(modelId);
24925
- }
24926
- function rejectsNewerSchemaFields(modelId) {
24927
- return MODELS_REJECTING_NEWER_SCHEMA_FIELDS.some(
24928
- (model) => modelId.includes(model)
27338
+ return !matchesModel(
27339
+ modelId,
27340
+ MODELS_WITHOUT_RELIABLE_NATIVE_STRUCTURED_OUTPUT
24929
27341
  );
24930
27342
  }
27343
+ function matchesModel(modelId, models) {
27344
+ return models.some((model) => modelId.includes(model));
27345
+ }
24931
27346
  function createBedrockEventStreamDecoder(body, processEvent) {
24932
27347
  const codec = new import_eventstream_codec.EventStreamCodec(import_util_utf8.toUtf8, import_util_utf8.fromUtf8);
24933
27348
  let buffer = new Uint8Array(0);
@@ -24972,7 +27387,7 @@ function createBedrockEventStreamDecoder(body, processEvent) {
24972
27387
  })
24973
27388
  );
24974
27389
  }
24975
- async function prepareTools({
27390
+ async function prepareTools2({
24976
27391
  tools: tools2,
24977
27392
  toolChoice,
24978
27393
  modelId,
@@ -25625,6 +28040,9 @@ function mapBedrockFinishReason(finishReason, isJsonResponseFromTool) {
25625
28040
  return "other";
25626
28041
  }
25627
28042
  }
28043
+ function isJsonResponseToolName(name15) {
28044
+ return name15 === "json" || name15 === "json<|channel|>commentary";
28045
+ }
25628
28046
  function isCohereEmbeddingModel(modelId) {
25629
28047
  return modelId.includes("cohere.embed-");
25630
28048
  }
@@ -25656,7 +28074,7 @@ function createSigV4FetchFunction(getCredentials, fetch2, service = "bedrock") {
25656
28074
  );
25657
28075
  const headersWithUserAgent = withUserAgentSuffix(
25658
28076
  originalHeaders,
25659
- `ai-sdk/amazon-bedrock/${VERSION2}`,
28077
+ `ai-sdk/amazon-bedrock/${VERSION3}`,
25660
28078
  getRuntimeEnvironmentUserAgent()
25661
28079
  );
25662
28080
  let effectiveBody = (_a17 = init == null ? void 0 : init.body) != null ? _a17 : void 0;
@@ -25714,7 +28132,7 @@ function createApiKeyFetchFunction(apiKey, fetch2) {
25714
28132
  const originalHeaders = normalizeHeaders(init == null ? void 0 : init.headers);
25715
28133
  const headersWithUserAgent = withUserAgentSuffix(
25716
28134
  originalHeaders,
25717
- `ai-sdk/amazon-bedrock/${VERSION2}`,
28135
+ `ai-sdk/amazon-bedrock/${VERSION3}`,
25718
28136
  getRuntimeEnvironmentUserAgent()
25719
28137
  );
25720
28138
  const finalHeaders = combineHeaders(headersWithUserAgent, {
@@ -25796,7 +28214,7 @@ Original error: ${errorMessage}`
25796
28214
  const getHeaders = () => {
25797
28215
  var _a17;
25798
28216
  const baseHeaders = (_a17 = options.headers) != null ? _a17 : {};
25799
- return withUserAgentSuffix(baseHeaders, `ai-sdk/amazon-bedrock/${VERSION2}`);
28217
+ return withUserAgentSuffix(baseHeaders, `ai-sdk/amazon-bedrock/${VERSION3}`);
25800
28218
  };
25801
28219
  const getBedrockRuntimeBaseUrl = () => {
25802
28220
  var _a17, _b16;
@@ -25869,38 +28287,38 @@ Original error: ${errorMessage}`
25869
28287
  provider.tools = import_internal.anthropicTools;
25870
28288
  return provider;
25871
28289
  }
25872
- var import_internal, import_internal2, import_eventstream_codec, import_util_utf8, import_internal3, BEDROCK_STOP_REASONS, BEDROCK_IMAGE_MIME_TYPES, BEDROCK_DOCUMENT_MIME_TYPES, bedrockFilePartProviderOptions, amazonBedrockLanguageModelOptions, MODELS_REJECTING_NEWER_SCHEMA_FIELDS, BedrockErrorSchema, createBedrockEventStreamResponseHandler, bedrockReasoningMetadataSchema, anthropicProviderOptions, BedrockChatLanguageModel, JsonObjectTextExtractor, BedrockStopReasonSchema, BedrockAdditionalModelResponseFieldsSchema, BedrockToolUseSchema, BedrockReasoningTextSchema, BedrockRedactedReasoningSchema, AmazonBedrockCacheDetailSchema, BedrockResponseSchema, BedrockStreamSchema, amazonBedrockEmbeddingModelOptionsSchema, BedrockEmbeddingModel, BedrockEmbeddingResponseSchema, modelMaxImagesPerCall, BedrockImageModel, bedrockImageResponseSchema, VERSION2, bedrockRerankingResponseSchema, amazonBedrockRerankingModelOptionsSchema, BedrockRerankingModel, bedrock;
25873
- var init_dist3 = __esm({
28290
+ var import_internal, import_internal2, import_eventstream_codec, import_util_utf8, import_internal3, BEDROCK_STOP_REASONS, BEDROCK_IMAGE_MIME_TYPES, BEDROCK_DOCUMENT_MIME_TYPES, bedrockFilePartProviderOptions, amazonBedrockLanguageModelOptions, MODELS_WITHOUT_STRICT_TOOL_SUPPORT, MODELS_WITHOUT_RELIABLE_NATIVE_STRUCTURED_OUTPUT, BedrockErrorSchema, createBedrockEventStreamResponseHandler, bedrockReasoningMetadataSchema, anthropicProviderOptions, BedrockChatLanguageModel, JsonObjectTextExtractor, BedrockStopReasonSchema, BedrockAdditionalModelResponseFieldsSchema, BedrockToolUseSchema, BedrockReasoningTextSchema, BedrockRedactedReasoningSchema, AmazonBedrockCacheDetailSchema, BedrockResponseSchema, BedrockStreamSchema, amazonBedrockEmbeddingModelOptionsSchema, BedrockEmbeddingModel, BedrockEmbeddingResponseSchema, modelMaxImagesPerCall, BedrockImageModel, bedrockImageResponseSchema, VERSION3, bedrockRerankingResponseSchema, amazonBedrockRerankingModelOptionsSchema, BedrockRerankingModel, bedrock;
28291
+ var init_dist5 = __esm({
25874
28292
  "node_modules/@ai-sdk/amazon-bedrock/dist/index.mjs"() {
25875
28293
  import_internal = require("@ai-sdk/anthropic/internal");
25876
- init_dist2();
25877
- init_dist2();
28294
+ init_dist3();
28295
+ init_dist3();
25878
28296
  import_internal2 = require("@ai-sdk/anthropic/internal");
25879
28297
  init_v4();
25880
28298
  init_v4();
25881
28299
  init_v4();
25882
28300
  init_dist();
25883
- init_dist2();
28301
+ init_dist3();
25884
28302
  import_eventstream_codec = __toESM(require_dist_cjs2(), 1);
25885
28303
  import_util_utf8 = __toESM(require_dist_cjs3(), 1);
25886
28304
  init_dist();
25887
- init_dist2();
28305
+ init_dist3();
25888
28306
  import_internal3 = require("@ai-sdk/anthropic/internal");
25889
28307
  init_dist();
25890
- init_dist2();
28308
+ init_dist3();
25891
28309
  init_v4();
25892
28310
  init_dist();
25893
- init_dist2();
28311
+ init_dist3();
25894
28312
  init_v4();
25895
28313
  init_v4();
25896
- init_dist2();
28314
+ init_dist3();
25897
28315
  init_v4();
25898
- init_dist2();
28316
+ init_dist3();
25899
28317
  init_aws4fetch_esm();
25900
- init_dist2();
25901
- init_dist2();
28318
+ init_dist3();
28319
+ init_dist3();
25902
28320
  init_v4();
25903
- init_dist2();
28321
+ init_dist3();
25904
28322
  init_v4();
25905
28323
  BEDROCK_STOP_REASONS = [
25906
28324
  "stop",
@@ -25944,6 +28362,14 @@ var init_dist3 = __esm({
25944
28362
  }).optional()
25945
28363
  });
25946
28364
  amazonBedrockLanguageModelOptions = external_exports.object({
28365
+ /**
28366
+ * Determines how structured outputs are generated for Anthropic models.
28367
+ *
28368
+ * - `outputFormat`: Use the native `output_config.format` parameter.
28369
+ * - `jsonTool`: Use a special 'json' tool to specify the structured output format.
28370
+ * - `auto`: Use `outputFormat` when supported, otherwise use `jsonTool` (default).
28371
+ */
28372
+ structuredOutputMode: external_exports.enum(["outputFormat", "jsonTool", "auto"]).optional(),
25947
28373
  /**
25948
28374
  * Additional inference parameters that the model supports,
25949
28375
  * beyond the base set of inference parameters that Converse
@@ -25975,13 +28401,18 @@ var init_dist3 = __esm({
25975
28401
  */
25976
28402
  serviceTier: external_exports.enum(["reserved", "priority", "default", "flex"]).optional()
25977
28403
  });
25978
- MODELS_REJECTING_NEWER_SCHEMA_FIELDS = [
28404
+ MODELS_WITHOUT_STRICT_TOOL_SUPPORT = [
25979
28405
  "claude-opus-4-7",
25980
28406
  "claude-opus-4-8",
25981
28407
  "claude-opus-5",
25982
28408
  "claude-fable-5",
25983
28409
  "claude-sonnet-5"
25984
28410
  ];
28411
+ MODELS_WITHOUT_RELIABLE_NATIVE_STRUCTURED_OUTPUT = [
28412
+ ...MODELS_WITHOUT_STRICT_TOOL_SUPPORT,
28413
+ "claude-sonnet-4-6",
28414
+ "claude-haiku-4-5"
28415
+ ];
25985
28416
  BedrockErrorSchema = external_exports.object({
25986
28417
  message: external_exports.string(),
25987
28418
  type: external_exports.string().nullish()
@@ -26032,7 +28463,8 @@ var init_dist3 = __esm({
26032
28463
  redactedContent: external_exports.string().optional()
26033
28464
  });
26034
28465
  anthropicProviderOptions = external_exports.object({
26035
- disableParallelToolUse: external_exports.boolean().optional()
28466
+ disableParallelToolUse: external_exports.boolean().optional(),
28467
+ structuredOutputMode: external_exports.enum(["outputFormat", "jsonTool", "auto"]).optional()
26036
28468
  });
26037
28469
  BedrockChatLanguageModel = class {
26038
28470
  constructor(modelId, config2) {
@@ -26059,7 +28491,7 @@ var init_dist3 = __esm({
26059
28491
  toolChoice,
26060
28492
  providerOptions
26061
28493
  }) {
26062
- var _a17, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
28494
+ var _a17, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
26063
28495
  const bedrockOptions = (_a17 = await parseProviderOptions({
26064
28496
  provider: "bedrock",
26065
28497
  providerOptions,
@@ -26117,15 +28549,33 @@ var init_dist3 = __esm({
26117
28549
  const isOpenAIGptOssModel = (_d = openAIModelId == null ? void 0 : openAIModelId.startsWith("openai.gpt-oss-")) != null ? _d : false;
26118
28550
  const isThinkingEnabled = ((_e = bedrockOptions.reasoningConfig) == null ? void 0 : _e.type) === "enabled" || ((_f = bedrockOptions.reasoningConfig) == null ? void 0 : _f.type) === "adaptive";
26119
28551
  const { supportsStructuredOutput: modelSupportsStructuredOutput } = (0, import_internal2.getModelCapabilities)(this.modelId);
26120
- const useNativeStructuredOutput = isAnthropicModel && supportsNativeStructuredOutput(this.modelId) && (modelSupportsStructuredOutput || isThinkingEnabled) && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null;
26121
- const useJsonInstructionForStructuredOutput = isAnthropicModel && !supportsStrictTools(this.modelId) && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && tools2 != null && tools2.length > 0;
28552
+ const structuredOutputMode = (_h = (_g = bedrockOptions.structuredOutputMode) != null ? _g : anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _h : "auto";
28553
+ if (structuredOutputMode === "jsonTool") {
28554
+ const additionalModelRequestFields = {
28555
+ ...bedrockOptions.additionalModelRequestFields
28556
+ };
28557
+ const outputConfig = additionalModelRequestFields.output_config;
28558
+ if (outputConfig != null && typeof outputConfig === "object" && !Array.isArray(outputConfig)) {
28559
+ const outputConfigWithoutFormat = { ...outputConfig };
28560
+ delete outputConfigWithoutFormat.format;
28561
+ if (Object.keys(outputConfigWithoutFormat).length > 0) {
28562
+ additionalModelRequestFields.output_config = outputConfigWithoutFormat;
28563
+ } else {
28564
+ delete additionalModelRequestFields.output_config;
28565
+ }
28566
+ bedrockOptions.additionalModelRequestFields = additionalModelRequestFields;
28567
+ }
28568
+ }
28569
+ const modelSupportsNativeStructuredOutput = supportsNativeStructuredOutput(this.modelId) && (modelSupportsStructuredOutput || isThinkingEnabled);
28570
+ const useNativeStructuredOutput = isAnthropicModel && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && (structuredOutputMode === "outputFormat" || structuredOutputMode === "auto" && modelSupportsNativeStructuredOutput);
28571
+ const useJsonInstructionForStructuredOutput = !useNativeStructuredOutput && structuredOutputMode !== "jsonTool" && isAnthropicModel && !supportsStrictTools(this.modelId) && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && tools2 != null && tools2.length > 0;
26122
28572
  const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !useNativeStructuredOutput && !useJsonInstructionForStructuredOutput ? {
26123
28573
  type: "function",
26124
28574
  name: "json",
26125
28575
  description: "Respond with a JSON object.",
26126
28576
  inputSchema: responseFormat.schema
26127
28577
  } : void 0;
26128
- const { toolConfig, additionalTools, toolWarnings, betas } = await prepareTools({
28578
+ const { toolConfig, additionalTools, toolWarnings, betas } = await prepareTools2({
26129
28579
  tools: jsonResponseTool ? [...tools2 != null ? tools2 : [], jsonResponseTool] : tools2,
26130
28580
  toolChoice: jsonResponseTool != null ? { type: "required" } : toolChoice,
26131
28581
  modelId: this.modelId,
@@ -26139,16 +28589,16 @@ var init_dist3 = __esm({
26139
28589
  };
26140
28590
  }
26141
28591
  if (betas.size > 0 || bedrockOptions.anthropicBeta) {
26142
- const existingBetas = (_g = bedrockOptions.anthropicBeta) != null ? _g : [];
28592
+ const existingBetas = (_i = bedrockOptions.anthropicBeta) != null ? _i : [];
26143
28593
  const mergedBetas = betas.size > 0 ? [...existingBetas, ...Array.from(betas)] : existingBetas;
26144
28594
  bedrockOptions.additionalModelRequestFields = {
26145
28595
  ...bedrockOptions.additionalModelRequestFields,
26146
28596
  anthropic_beta: mergedBetas
26147
28597
  };
26148
28598
  }
26149
- const thinkingType = (_h = bedrockOptions.reasoningConfig) == null ? void 0 : _h.type;
26150
- const thinkingBudget = thinkingType === "enabled" ? (_i = bedrockOptions.reasoningConfig) == null ? void 0 : _i.budgetTokens : void 0;
26151
- const thinkingDisplay = thinkingType === "adaptive" ? (_j = bedrockOptions.reasoningConfig) == null ? void 0 : _j.display : void 0;
28599
+ const thinkingType = (_j = bedrockOptions.reasoningConfig) == null ? void 0 : _j.type;
28600
+ const thinkingBudget = thinkingType === "enabled" ? (_k = bedrockOptions.reasoningConfig) == null ? void 0 : _k.budgetTokens : void 0;
28601
+ const thinkingDisplay = thinkingType === "adaptive" ? (_l = bedrockOptions.reasoningConfig) == null ? void 0 : _l.display : void 0;
26152
28602
  const isAnthropicThinkingEnabled = isAnthropicModel && isThinkingEnabled;
26153
28603
  const inferenceConfig = {
26154
28604
  ...maxOutputTokens != null && { maxTokens: maxOutputTokens },
@@ -26181,7 +28631,7 @@ var init_dist3 = __esm({
26181
28631
  };
26182
28632
  }
26183
28633
  } else if (!isAnthropicModel) {
26184
- if (((_k = bedrockOptions.reasoningConfig) == null ? void 0 : _k.budgetTokens) != null) {
28634
+ if (((_m = bedrockOptions.reasoningConfig) == null ? void 0 : _m.budgetTokens) != null) {
26185
28635
  warnings.push({
26186
28636
  type: "unsupported",
26187
28637
  feature: "budgetTokens",
@@ -26196,13 +28646,13 @@ var init_dist3 = __esm({
26196
28646
  });
26197
28647
  }
26198
28648
  }
26199
- const maxReasoningEffort = (_l = bedrockOptions.reasoningConfig) == null ? void 0 : _l.maxReasoningEffort;
28649
+ const maxReasoningEffort = (_n = bedrockOptions.reasoningConfig) == null ? void 0 : _n.maxReasoningEffort;
26200
28650
  if (maxReasoningEffort != null) {
26201
28651
  if (isAnthropicModel) {
26202
28652
  bedrockOptions.additionalModelRequestFields = {
26203
28653
  ...bedrockOptions.additionalModelRequestFields,
26204
28654
  output_config: {
26205
- ...(_m = bedrockOptions.additionalModelRequestFields) == null ? void 0 : _m.output_config,
28655
+ ...(_o = bedrockOptions.additionalModelRequestFields) == null ? void 0 : _o.output_config,
26206
28656
  effort: maxReasoningEffort
26207
28657
  }
26208
28658
  };
@@ -26213,7 +28663,7 @@ var init_dist3 = __esm({
26213
28663
  } : {
26214
28664
  ...bedrockOptions.additionalModelRequestFields,
26215
28665
  reasoning: {
26216
- ...(_n = bedrockOptions.additionalModelRequestFields) == null ? void 0 : _n.reasoning,
28666
+ ...(_p = bedrockOptions.additionalModelRequestFields) == null ? void 0 : _p.reasoning,
26217
28667
  effort: maxReasoningEffort
26218
28668
  }
26219
28669
  };
@@ -26232,7 +28682,7 @@ var init_dist3 = __esm({
26232
28682
  bedrockOptions.additionalModelRequestFields = {
26233
28683
  ...bedrockOptions.additionalModelRequestFields,
26234
28684
  output_config: {
26235
- ...(_o = bedrockOptions.additionalModelRequestFields) == null ? void 0 : _o.output_config,
28685
+ ...(_q = bedrockOptions.additionalModelRequestFields) == null ? void 0 : _q.output_config,
26236
28686
  format: {
26237
28687
  type: "json_schema",
26238
28688
  schema: (0, import_internal2.sanitizeJsonSchema)(responseFormat.schema)
@@ -26264,7 +28714,7 @@ var init_dist3 = __esm({
26264
28714
  details: "topK is not supported when thinking is enabled"
26265
28715
  });
26266
28716
  }
26267
- const hasAnyTools = ((_q = (_p = toolConfig.tools) == null ? void 0 : _p.length) != null ? _q : 0) > 0 || additionalTools;
28717
+ const hasAnyTools = ((_s = (_r = toolConfig.tools) == null ? void 0 : _r.length) != null ? _s : 0) > 0 || additionalTools;
26268
28718
  let filteredPrompt = prompt;
26269
28719
  if (!hasAnyTools) {
26270
28720
  const hasToolContent = prompt.some(
@@ -26306,6 +28756,7 @@ var init_dist3 = __esm({
26306
28756
  reasoningConfig: _,
26307
28757
  additionalModelRequestFields: __,
26308
28758
  serviceTier: ___,
28759
+ structuredOutputMode: ____,
26309
28760
  ...filteredBedrockOptions
26310
28761
  } = (providerOptions == null ? void 0 : providerOptions.bedrock) || {};
26311
28762
  const additionalModelResponseFieldPaths = isAnthropicModel ? ["/delta/stop_sequence"] : void 0;
@@ -26412,7 +28863,7 @@ var init_dist3 = __esm({
26412
28863
  }
26413
28864
  }
26414
28865
  if (part.toolUse) {
26415
- const isJsonResponseTool = usesJsonResponseTool && part.toolUse.name === "json";
28866
+ const isJsonResponseTool = usesJsonResponseTool && isJsonResponseToolName(part.toolUse.name);
26416
28867
  if (isJsonResponseTool) {
26417
28868
  isJsonResponseFromTool = true;
26418
28869
  content.push({
@@ -26747,7 +29198,7 @@ var init_dist3 = __esm({
26747
29198
  if (((_q = contentBlockStart == null ? void 0 : contentBlockStart.start) == null ? void 0 : _q.toolUse) != null) {
26748
29199
  const toolUse = contentBlockStart.start.toolUse;
26749
29200
  const blockIndex = contentBlockStart.contentBlockIndex;
26750
- const isJsonResponseTool = usesJsonResponseTool && toolUse.name === "json";
29201
+ const isJsonResponseTool = usesJsonResponseTool && isJsonResponseToolName(toolUse.name);
26751
29202
  const normalizedToolCallId = normalizeToolCallId(
26752
29203
  toolUse.toolUseId,
26753
29204
  isMistral
@@ -27369,7 +29820,7 @@ var init_dist3 = __esm({
27369
29820
  details: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
27370
29821
  preview: external_exports.unknown().optional()
27371
29822
  });
27372
- VERSION2 = true ? "4.0.167" : "0.0.0-test";
29823
+ VERSION3 = true ? "4.0.169" : "0.0.0-test";
27373
29824
  bedrockRerankingResponseSchema = lazySchema(
27374
29825
  () => zodSchema(
27375
29826
  external_exports.object({
@@ -27487,10 +29938,17 @@ function createProviderInstance(config2) {
27487
29938
  ...config2.baseURL && { baseURL: config2.baseURL }
27488
29939
  });
27489
29940
  case "openai": {
29941
+ if (config2.baseURL) {
29942
+ const provider = createOpenAICompatible({
29943
+ name: "openai-compatible",
29944
+ baseURL: config2.baseURL,
29945
+ apiKey: config2.apiKey
29946
+ });
29947
+ return provider;
29948
+ }
27490
29949
  const openai = (0, import_openai.createOpenAI)({
27491
29950
  compatibility: "strict",
27492
- apiKey: config2.apiKey,
27493
- ...config2.baseURL && { baseURL: config2.baseURL }
29951
+ apiKey: config2.apiKey
27494
29952
  });
27495
29953
  const chatProvider = (modelId, settings) => openai.chat(modelId, settings);
27496
29954
  chatProvider.chat = openai.chat.bind(openai);
@@ -27570,8 +30028,9 @@ var init_provider = __esm({
27570
30028
  "use strict";
27571
30029
  import_anthropic = require("@ai-sdk/anthropic");
27572
30030
  import_openai = require("@ai-sdk/openai");
30031
+ init_dist4();
27573
30032
  import_google = require("@ai-sdk/google");
27574
- init_dist3();
30033
+ init_dist5();
27575
30034
  DEFAULT_MODELS = {
27576
30035
  anthropic: "claude-sonnet-4-6",
27577
30036
  openai: "gpt-5.2",
@@ -33672,7 +36131,7 @@ var require_parser = __commonJS({
33672
36131
  /* LispType.None */
33673
36132
  });
33674
36133
  var lispTypes = /* @__PURE__ */ new Map();
33675
- var ParseError = class extends Error {
36134
+ var ParseError2 = class extends Error {
33676
36135
  constructor(message, code) {
33677
36136
  super(message + ": " + code.substring(0, 40));
33678
36137
  this.code = code;
@@ -34607,7 +37066,7 @@ var require_parser = __commonJS({
34607
37066
  lispTypes.get(type)?.(constants, type, part, res, expect, ctx);
34608
37067
  } catch (e) {
34609
37068
  if (topLevel && e instanceof SyntaxError) {
34610
- throw new ParseError(e.message, str);
37069
+ throw new ParseError2(e.message, str);
34611
37070
  }
34612
37071
  throw e;
34613
37072
  }
@@ -34619,7 +37078,7 @@ var require_parser = __commonJS({
34619
37078
  }
34620
37079
  if (!res && part.length) {
34621
37080
  if (topLevel) {
34622
- throw new ParseError(`Unexpected token after ${lastType}: ${part.char(0)}`, str);
37081
+ throw new ParseError2(`Unexpected token after ${lastType}: ${part.char(0)}`, str);
34623
37082
  }
34624
37083
  throw new SyntaxError(`Unexpected token after ${lastType}: ${part.char(0)}`);
34625
37084
  }
@@ -34914,7 +37373,7 @@ var require_parser = __commonJS({
34914
37373
  }
34915
37374
  function parse11(code, eager = false, expression = false) {
34916
37375
  if (typeof code !== "string")
34917
- throw new ParseError(`Cannot parse ${code}`, code);
37376
+ throw new ParseError2(`Cannot parse ${code}`, code);
34918
37377
  let str = " " + code;
34919
37378
  const constants = { strings: [], literals: [], regexes: [], eager };
34920
37379
  str = extractConstants(constants, str).str;
@@ -34924,7 +37383,7 @@ var require_parser = __commonJS({
34924
37383
  }
34925
37384
  return { tree: lispifyFunction(new utils.CodeString(str), constants, expression), constants };
34926
37385
  }
34927
- exports2.ParseError = ParseError;
37386
+ exports2.ParseError = ParseError2;
34928
37387
  exports2.checkRegex = checkRegex;
34929
37388
  exports2.default = parse11;
34930
37389
  exports2.expectTypes = expectTypes;
@@ -55266,12 +57725,12 @@ var init_apply = __esm({
55266
57725
  });
55267
57726
 
55268
57727
  // node_modules/lodash-es/noop.js
55269
- function noop() {
57728
+ function noop2() {
55270
57729
  }
55271
57730
  var noop_default;
55272
57731
  var init_noop = __esm({
55273
57732
  "node_modules/lodash-es/noop.js"() {
55274
- noop_default = noop;
57733
+ noop_default = noop2;
55275
57734
  }
55276
57735
  });
55277
57736
 
@@ -77220,9 +79679,9 @@ var require_arrayIncludesWith = __commonJS({
77220
79679
  // node_modules/lodash/noop.js
77221
79680
  var require_noop = __commonJS({
77222
79681
  "node_modules/lodash/noop.js"(exports2, module2) {
77223
- function noop2() {
79682
+ function noop3() {
77224
79683
  }
77225
- module2.exports = noop2;
79684
+ module2.exports = noop3;
77226
79685
  }
77227
79686
  });
77228
79687
 
@@ -77230,10 +79689,10 @@ var require_noop = __commonJS({
77230
79689
  var require_createSet = __commonJS({
77231
79690
  "node_modules/lodash/_createSet.js"(exports2, module2) {
77232
79691
  var Set3 = require_Set();
77233
- var noop2 = require_noop();
79692
+ var noop3 = require_noop();
77234
79693
  var setToArray2 = require_setToArray();
77235
79694
  var INFINITY5 = 1 / 0;
77236
- var createSet2 = !(Set3 && 1 / setToArray2(new Set3([, -0]))[1] == INFINITY5) ? noop2 : function(values2) {
79695
+ var createSet2 = !(Set3 && 1 / setToArray2(new Set3([, -0]))[1] == INFINITY5) ? noop3 : function(values2) {
77237
79696
  return new Set3(values2);
77238
79697
  };
77239
79698
  module2.exports = createSet2;
@@ -88350,7 +90809,7 @@ var require_utils2 = __commonJS({
88350
90809
  "node_modules/fast-uri/lib/utils.js"(exports2, module2) {
88351
90810
  "use strict";
88352
90811
  var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
88353
- var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
90812
+ var isIPv42 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
88354
90813
  var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
88355
90814
  var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
88356
90815
  var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u);
@@ -88450,7 +90909,7 @@ var require_utils2 = __commonJS({
88450
90909
  const part = parts[i];
88451
90910
  if (part === "") return void 0;
88452
90911
  if (part.indexOf(".") !== -1) {
88453
- if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv4(part)) return void 0;
90912
+ if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv42(part)) return void 0;
88454
90913
  hextetCount += 2;
88455
90914
  continue;
88456
90915
  }
@@ -88801,7 +91260,7 @@ var require_utils2 = __commonJS({
88801
91260
  }
88802
91261
  if (component.host !== void 0) {
88803
91262
  let host = component.host;
88804
- if (!isIPv4(host)) {
91263
+ if (!isIPv42(host)) {
88805
91264
  let ipV6res = normalizeIPv6(host);
88806
91265
  if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
88807
91266
  host = normalizePercentEncoding(host, true);
@@ -88834,7 +91293,7 @@ var require_utils2 = __commonJS({
88834
91293
  encodeFragment,
88835
91294
  escapePreservingEscapes,
88836
91295
  removeDotSegments,
88837
- isIPv4,
91296
+ isIPv4: isIPv42,
88838
91297
  isUUID,
88839
91298
  normalizeIPv6,
88840
91299
  stringArrayToHexStripped
@@ -89057,7 +91516,7 @@ var require_schemes = __commonJS({
89057
91516
  var require_fast_uri = __commonJS({
89058
91517
  "node_modules/fast-uri/index.js"(exports2, module2) {
89059
91518
  "use strict";
89060
- var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils2();
91519
+ var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4: isIPv42, nonSimpleDomain } = require_utils2();
89061
91520
  var { SCHEMES, getSchemeHandler } = require_schemes();
89062
91521
  var VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
89063
91522
  var MALFORMED_SCHEME_ERROR = "URI scheme is malformed.";
@@ -89102,7 +91561,7 @@ var require_fast_uri = __commonJS({
89102
91561
  const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
89103
91562
  const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme);
89104
91563
  const resolvedHost = resolved.host;
89105
- const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
91564
+ const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv42(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
89106
91565
  canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
89107
91566
  const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !/\P{ASCII}/u.test(resolvedHost);
89108
91567
  if (resolved.error && !encodedASCIIHost) {
@@ -89350,7 +91809,7 @@ var require_fast_uri = __commonJS({
89350
91809
  malformedAuthorityOrPort = true;
89351
91810
  }
89352
91811
  if (parsed.host) {
89353
- const ipv4result = isIPv4(parsed.host);
91812
+ const ipv4result = isIPv42(parsed.host);
89354
91813
  if (ipv4result === false) {
89355
91814
  const bracketedIPLiteral = parsed.host[0] === "[" && parsed.host[parsed.host.length - 1] === "]";
89356
91815
  const ipv6result = normalizeIPv6(parsed.host);