@agentdocumentformat/cli 0.7.8 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +1 -1
  2. package/dist/adf.mjs +59 -8
  3. package/dist/chunks/{APEv2Parser-2CNNHMXV.mjs → APEv2Parser-WIXRJLHB.mjs} +2 -2
  4. package/dist/chunks/{AiffParser-7BR4RL6G.mjs → AiffParser-ZC4QFOVJ.mjs} +5 -5
  5. package/dist/chunks/{App-7RIIOHJJ.mjs → App-4AZZJNN2.mjs} +917 -826
  6. package/dist/chunks/{DsdiffParser-CMD4AX7A.mjs → DsdiffParser-UAPAJHFX.mjs} +5 -5
  7. package/dist/chunks/{DsfParser-UOGZDS2M.mjs → DsfParser-NNYZK2QX.mjs} +6 -6
  8. package/dist/chunks/{FlacParser-HB3T3CD4.mjs → FlacParser-MW2W4LO3.mjs} +6 -6
  9. package/dist/chunks/{MP4Parser-66HBRUSX.mjs → MP4Parser-Z57SYOOQ.mjs} +4 -4
  10. package/dist/chunks/{MpegParser-YW6LIUEW.mjs → MpegParser-XIIPAZVM.mjs} +7 -7
  11. package/dist/chunks/{MusepackParser-PAUSXP7D.mjs → MusepackParser-QWNDEYHJ.mjs} +6 -6
  12. package/dist/chunks/{OggParser-NUBV3GWC.mjs → OggParser-WRX53F77.mjs} +9 -9
  13. package/dist/chunks/{WavPackParser-WQAGT7TC.mjs → WavPackParser-MJ7WCSJ5.mjs} +2 -2
  14. package/dist/chunks/{WaveParser-EWLQVDX4.mjs → WaveParser-RAVLHZ5S.mjs} +7 -7
  15. package/dist/chunks/{adf-schema-US4NFHMR.mjs → adf-schema-AIPBQTR2.mjs} +9 -3
  16. package/dist/chunks/auth-manager-AJ32FZWS.mjs +19 -0
  17. package/dist/chunks/auth-manager-C5OBEQK2.mjs +18 -0
  18. package/dist/chunks/auth-manager-TBNKCJ45.mjs +17 -0
  19. package/dist/chunks/{chatgpt-subscription-E4MXTIAT.mjs → chatgpt-subscription-MMGNW5KJ.mjs} +5 -2
  20. package/dist/chunks/chunk-2Z7X3UUR.mjs +678 -0
  21. package/dist/chunks/chunk-3UGZFWIF.mjs +26 -0
  22. package/dist/chunks/{chunk-XNPZBLYL.mjs → chunk-75DC5EWN.mjs} +13 -2
  23. package/dist/chunks/{chunk-5PO5PKRV.mjs → chunk-7JZXMDDF.mjs} +158 -67
  24. package/dist/chunks/chunk-AEAJDCVK.mjs +517 -0
  25. package/dist/chunks/{chunk-6VQEXLE2.mjs → chunk-BHY7QDCM.mjs} +41 -3
  26. package/dist/chunks/{chunk-CD3ATSXE.mjs → chunk-BR3AD5QZ.mjs} +8 -2
  27. package/dist/chunks/chunk-BS3USVEA.mjs +301 -0
  28. package/dist/chunks/chunk-C2S64Y6F.mjs +203 -0
  29. package/dist/chunks/chunk-D7A77SNL.mjs +976 -0
  30. package/dist/chunks/chunk-DDTTSKGG.mjs +2443 -0
  31. package/dist/chunks/{chunk-VAUOM3IN.mjs → chunk-DLWCKKIO.mjs} +1 -1
  32. package/dist/chunks/{chunk-G6PH7RPW.mjs → chunk-E7LC6SHP.mjs} +3 -3
  33. package/dist/chunks/{chunk-ZESQMP66.mjs → chunk-F3WSCAJD.mjs} +3 -3
  34. package/dist/chunks/{chunk-KXEF4F4E.mjs → chunk-GAZO6UMI.mjs} +1 -1
  35. package/dist/chunks/{chunk-XYTWGHFS.mjs → chunk-H3XLRWVE.mjs} +1 -1
  36. package/dist/chunks/{chunk-7T2YMTWL.mjs → chunk-H4C65MTP.mjs} +4 -4
  37. package/dist/chunks/chunk-HBOFZRUS.mjs +738 -0
  38. package/dist/chunks/{chunk-VN7UH7I5.mjs → chunk-IMVMSU3A.mjs} +251 -68
  39. package/dist/chunks/{chunk-XYV3VCIX.mjs → chunk-JZFONJSL.mjs} +79 -20
  40. package/dist/chunks/chunk-KCIRFUZH.mjs +12799 -0
  41. package/dist/chunks/chunk-KDDVQKCG.mjs +65 -0
  42. package/dist/chunks/chunk-KRPKWOMB.mjs +290 -0
  43. package/dist/chunks/chunk-LKFHERRV.mjs +145 -0
  44. package/dist/chunks/chunk-LTX74NU6.mjs +29 -0
  45. package/dist/chunks/{chunk-HSBV6YFU.mjs → chunk-LVF2DRBR.mjs} +634 -99
  46. package/dist/chunks/chunk-M2F7C2UJ.mjs +425 -0
  47. package/dist/chunks/{chunk-62NE4LG4.mjs → chunk-MQAMI5BF.mjs} +5 -5
  48. package/dist/chunks/chunk-MZRXFWPQ.mjs +278 -0
  49. package/dist/chunks/{chunk-PRMGZZM5.mjs → chunk-NZLEPJ5M.mjs} +2 -0
  50. package/dist/chunks/{chunk-I3UYSITV.mjs → chunk-O7XKQ6CH.mjs} +1 -1
  51. package/dist/chunks/chunk-P3RG5LQA.mjs +244 -0
  52. package/dist/chunks/chunk-PAK5JCO2.mjs +48 -0
  53. package/dist/chunks/chunk-PC63YFB7.mjs +34 -0
  54. package/dist/chunks/{daemon-control-HKFVSQTQ.mjs → chunk-RHBGCOS3.mjs} +67 -26
  55. package/dist/chunks/{chunk-J74STFKE.mjs → chunk-RJDOVMM4.mjs} +362 -58
  56. package/dist/chunks/{chunk-QPLEAE6V.mjs → chunk-SOSPQPEN.mjs} +167 -650
  57. package/dist/chunks/{chunk-LFMB4PAA.mjs → chunk-TKXIH27X.mjs} +974 -113
  58. package/dist/chunks/{chunk-5W7KES6P.mjs → chunk-UZPDETEU.mjs} +1 -1
  59. package/dist/chunks/chunk-V3MM6PCH.mjs +366 -0
  60. package/dist/chunks/chunk-VENQBMOA.mjs +62 -0
  61. package/dist/chunks/chunk-WJGPNHGX.mjs +67 -0
  62. package/dist/chunks/{chunk-Y5ZLKFLE.mjs → chunk-XNNJQCZP.mjs} +196 -165
  63. package/dist/chunks/{chunk-HDBPBORT.mjs → chunk-YRBFIDLB.mjs} +46 -10
  64. package/dist/chunks/{chunk-BNXUAOO4.mjs → chunk-ZGXUOAWZ.mjs} +3186 -959
  65. package/dist/chunks/chunk-ZPB3HYM7.mjs +45 -0
  66. package/dist/chunks/claude-subscription-EB4LAAVV.mjs +29 -0
  67. package/dist/chunks/{cli-NMFIAR7Z.mjs → cli-PCVFB6B4.mjs} +797 -56
  68. package/dist/chunks/{commands-KPJWFRUE.mjs → commands-KOMPXJZS.mjs} +4 -3
  69. package/dist/chunks/{daemon-YDIK3AAM.mjs → daemon-BVDB565V.mjs} +83142 -64424
  70. package/dist/chunks/daemon-control-MKN7G5M3.mjs +59 -0
  71. package/dist/chunks/{daemon-token-WRSULP7G.mjs → daemon-token-L5QKTHU5.mjs} +3 -1
  72. package/dist/chunks/{discord-DSP4HUWI.mjs → discord-IR62565M.mjs} +3 -52
  73. package/dist/chunks/{email-BRG7KUO2.mjs → email-KHHTJBDW.mjs} +4 -2
  74. package/dist/chunks/{grok-subscription-4PYX7TBF.mjs → grok-subscription-E74FS5EG.mjs} +5 -2
  75. package/dist/chunks/{layout-EPJQNFAI.mjs → layout-ECWGJF6M.mjs} +2 -2
  76. package/dist/chunks/{lib-N7FCZWKH.mjs → lib-L27L5PXM.mjs} +22 -22
  77. package/dist/chunks/{open-VAU7PXT6.mjs → open-3OR6WT4T.mjs} +6 -6
  78. package/dist/chunks/{parser-JVY2PWSM.mjs → parser-7GARNT5L.mjs} +1 -1
  79. package/dist/chunks/{pipeline-executor-O77NTGLP.mjs → pipeline-executor-DRYEEFDR.mjs} +6 -5
  80. package/dist/chunks/prompt-RRHZX4YT.mjs +13 -0
  81. package/dist/chunks/remote-access-cli-GLEEP7DI.mjs +268 -0
  82. package/dist/chunks/remote-hello-UFWUBDQI.mjs +37 -0
  83. package/dist/chunks/sdk-OJOAF4DP.mjs +30014 -0
  84. package/dist/chunks/{slack-OCNNF4DX.mjs → slack-IYC5RAB5.mjs} +3 -4
  85. package/dist/chunks/{store-HUVDJPYN.mjs → store-55CQSAOX.mjs} +7 -3
  86. package/dist/chunks/tailscale-WLJATFMB.mjs +25 -0
  87. package/dist/chunks/{theme-SFE3JMA2.mjs → theme-HLBDTF6F.mjs} +1 -1
  88. package/dist/chunks/{themes-YLXLOIJF.mjs → themes-BQ72P446.mjs} +2 -2
  89. package/dist/chunks/{token-6G3HCMNX.mjs → token-6D22WECM.mjs} +20 -16
  90. package/dist/chunks/{token-util-UXYSDQIW.mjs → token-util-YF3ZWBZ4.mjs} +1 -2
  91. package/dist/chunks/{tui-UQJLK7XI.mjs → tui-RAUVFOYY.mjs} +21 -18
  92. package/dist/chunks/{welcome-XHXFV7SH.mjs → welcome-J5JZZAM5.mjs} +1 -1
  93. package/dist/chunks/{whatsapp-AJMRQBT7.mjs → whatsapp-YJFFVN4Q.mjs} +9 -9
  94. package/package.json +1 -1
  95. package/dist/chunks/chunk-GKKCMXIZ.mjs +0 -94
  96. package/dist/chunks/chunk-IHDDCZBS.mjs +0 -112
  97. package/dist/chunks/chunk-KWFOS5WC.mjs +0 -41
  98. package/dist/chunks/chunk-UEZR2CNS.mjs +0 -65
  99. package/dist/chunks/chunk-VMHTYDH4.mjs +0 -172
  100. package/dist/chunks/chunk-Y2QA53AN.mjs +0 -259
  101. package/dist/chunks/{chunk-NBTUWMGP.mjs → chunk-2MTE22CR.mjs} +3 -3
  102. package/dist/chunks/{chunk-APRU6PHC.mjs → chunk-JZ7AQNPM.mjs} +3 -3
  103. package/dist/chunks/{telegram-2EFGKIVK.mjs → telegram-JYY2VDTI.mjs} +5 -5
@@ -4,6 +4,10 @@ import { dirname as __adfDirname } from 'node:path';
4
4
  const require = __adfCreateRequire(import.meta.url);
5
5
  const __filename = __adfFileURLToPath(import.meta.url);
6
6
  const __dirname = __adfDirname(__filename);
7
+ import {
8
+ fileRefKind,
9
+ isFileRefBlock
10
+ } from "./chunk-LKFHERRV.mjs";
7
11
  import {
8
12
  ZodFirstPartyTypeKind
9
13
  } from "./chunk-RIX34QHC.mjs";
@@ -11,6 +15,48 @@ import {
11
15
  __export
12
16
  } from "./chunk-M2RX3S2T.mjs";
13
17
 
18
+ // src/main/providers/media-capabilities.ts
19
+ var MEDIA_KINDS = ["image", "audio", "video"], ALL_MEDIA = Object.freeze({ image: !0, audio: !0, video: !0 }), IMAGE_ONLY_MEDIA = Object.freeze({ image: !0, audio: !1, video: !1 });
20
+ function connectorMedia(provider) {
21
+ return provider?.media ?? ALL_MEDIA;
22
+ }
23
+ function mediaToggle(model, kind) {
24
+ return kind === "image" ? model?.multimodal?.image ?? model?.vision ?? !1 : model?.multimodal?.[kind] ?? !1;
25
+ }
26
+ function effectiveMediaSupport(model, provider) {
27
+ let carried = connectorMedia(provider);
28
+ return {
29
+ image: carried.image && mediaToggle(model, "image"),
30
+ audio: carried.audio && mediaToggle(model, "audio"),
31
+ video: carried.video && mediaToggle(model, "video")
32
+ };
33
+ }
34
+ function mediaKindOf(block) {
35
+ if (block.type === "image_url") return "image";
36
+ if (block.type === "input_audio") return "audio";
37
+ if (block.type === "video_url") return "video";
38
+ if (isFileRefBlock(block) && !block.file_ref.deleted) return fileRefKind(block.file_ref);
39
+ }
40
+ function mediaOmissionReason(kind, model, provider) {
41
+ return connectorMedia(provider)[kind] ? `${kind} input is off in this agent's model settings` : `${provider?.name || "This provider"} does not accept ${kind} input`;
42
+ }
43
+ function mediaRefusals(model, provider) {
44
+ let support = effectiveMediaSupport(model, provider), refusals = {};
45
+ for (let kind of MEDIA_KINDS) support[kind] || (refusals[kind] = mediaOmissionReason(kind, model, provider));
46
+ return refusals;
47
+ }
48
+ function unsupportedMediaInput(content, model, provider) {
49
+ if (!content?.length) return null;
50
+ let refusals = mediaRefusals(model, provider), refused = /* @__PURE__ */ new Set();
51
+ for (let block of content) {
52
+ let kind = mediaKindOf(block);
53
+ kind && refusals[kind] && refused.add(kind);
54
+ }
55
+ if (refused.size === 0) return null;
56
+ let reasons = MEDIA_KINDS.filter((kind) => refused.has(kind)).map((kind) => refusals[kind]), first = reasons[0];
57
+ return `${[first[0].toUpperCase() + first.slice(1), ...reasons.slice(1)].join("; ")}. Remove the attachment, or change the model settings.`;
58
+ }
59
+
14
60
  // node_modules/@ai-sdk/provider/dist/index.mjs
15
61
  var marker = "vercel.ai.error", symbol = Symbol.for(marker), _a, _b, AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
16
62
  /**
@@ -217,6 +263,16 @@ Error message: ${getErrorMessage(cause)}`,
217
263
  return AISDKError.hasMarker(error40, marker14);
218
264
  }
219
265
  };
266
+ function isJSONValue(value) {
267
+ return value === null || typeof value == "string" || typeof value == "number" || typeof value == "boolean" ? !0 : Array.isArray(value) ? value.every(isJSONValue) : typeof value == "object" ? Object.entries(value).every(
268
+ ([key, val]) => typeof key == "string" && (val === void 0 || isJSONValue(val))
269
+ ) : !1;
270
+ }
271
+ function isJSONObject(value) {
272
+ return value != null && typeof value == "object" && Object.entries(value).every(
273
+ ([key, val]) => typeof key == "string" && (val === void 0 || isJSONValue(val))
274
+ );
275
+ }
220
276
 
221
277
  // node_modules/zod/v4/classic/external.js
222
278
  var external_exports = {};
@@ -8845,49 +8901,129 @@ var ParseError = class extends Error {
8845
8901
  constructor(message, options) {
8846
8902
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
8847
8903
  }
8848
- };
8904
+ }, LF = 10, CR = 13, SPACE = 32;
8849
8905
  function noop(_arg) {
8850
8906
  }
8851
- function createParser(callbacks) {
8852
- if (typeof callbacks == "function")
8907
+ function createParser(config2) {
8908
+ if (typeof config2 == "function")
8853
8909
  throw new TypeError(
8854
- "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
8910
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
8855
8911
  );
8856
- let { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, incompleteLine = "", isFirstChunk = !0, id, data = "", eventType = "";
8857
- function feed(newChunk) {
8858
- let chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
8859
- for (let line of complete)
8860
- parseLine(line);
8861
- incompleteLine = incomplete, isFirstChunk = !1;
8862
- }
8863
- function parseLine(line) {
8864
- if (line === "") {
8912
+ let { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config2, pendingFragments = [], pendingFragmentsLength = 0, isFirstChunk = !0, id, data = "", dataLines = 0, eventType, terminated = !1;
8913
+ function feed(chunk) {
8914
+ if (terminated)
8915
+ throw new Error(
8916
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
8917
+ );
8918
+ if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
8919
+ let trailing2 = processLines(chunk);
8920
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
8921
+ return;
8922
+ }
8923
+ if (chunk.indexOf(`
8924
+ `) === -1 && chunk.indexOf("\r") === -1) {
8925
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
8926
+ return;
8927
+ }
8928
+ pendingFragments.push(chunk);
8929
+ let input = pendingFragments.join("");
8930
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
8931
+ let trailing = processLines(input);
8932
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
8933
+ }
8934
+ function checkBufferSize() {
8935
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
8936
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
8937
+ type: "max-buffer-size-exceeded"
8938
+ })
8939
+ )));
8940
+ }
8941
+ function processLines(chunk) {
8942
+ let searchIndex = 0;
8943
+ if (chunk.indexOf("\r") === -1) {
8944
+ let lfIndex = chunk.indexOf(`
8945
+ `, searchIndex);
8946
+ for (; lfIndex !== -1; ) {
8947
+ if (searchIndex === lfIndex) {
8948
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
8949
+ `, searchIndex);
8950
+ continue;
8951
+ }
8952
+ let firstCharCode = chunk.charCodeAt(searchIndex);
8953
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
8954
+ let valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
8955
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
8956
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
8957
+ `, searchIndex);
8958
+ continue;
8959
+ }
8960
+ data = dataLines === 0 ? value : `${data}
8961
+ ${value}`, dataLines++;
8962
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
8963
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
8964
+ lfIndex
8965
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
8966
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
8967
+ `, searchIndex);
8968
+ }
8969
+ return chunk.slice(searchIndex);
8970
+ }
8971
+ for (; searchIndex < chunk.length; ) {
8972
+ let crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
8973
+ `, searchIndex), lineEnd = -1;
8974
+ 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)
8975
+ break;
8976
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
8977
+ }
8978
+ return chunk.slice(searchIndex);
8979
+ }
8980
+ function parseLine(chunk, start, end) {
8981
+ if (start === end) {
8865
8982
  dispatchEvent();
8866
8983
  return;
8867
8984
  }
8868
- if (line.startsWith(":")) {
8869
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
8985
+ let firstCharCode = chunk.charCodeAt(start);
8986
+ if (isDataPrefix(chunk, start, firstCharCode)) {
8987
+ let valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
8988
+ data = dataLines === 0 ? value2 : `${data}
8989
+ ${value2}`, dataLines++;
8990
+ return;
8991
+ }
8992
+ if (isEventPrefix(chunk, start, firstCharCode)) {
8993
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
8870
8994
  return;
8871
8995
  }
8872
- let fieldSeparatorIndex = line.indexOf(":");
8873
- if (fieldSeparatorIndex !== -1) {
8874
- let field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
8875
- processField(field, value, line);
8996
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
8997
+ let value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
8998
+ value2.includes("\0") || (id = value2);
8876
8999
  return;
8877
9000
  }
8878
- processField(line, "", line);
9001
+ if (firstCharCode === 58) {
9002
+ if (onComment) {
9003
+ let line2 = chunk.slice(start, end);
9004
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
9005
+ }
9006
+ return;
9007
+ }
9008
+ let line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
9009
+ if (fieldSeparatorIndex === -1) {
9010
+ processField(line, "", line);
9011
+ return;
9012
+ }
9013
+ let field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
9014
+ processField(field, value, line);
8879
9015
  }
8880
9016
  function processField(field, value, line) {
8881
9017
  switch (field) {
8882
9018
  case "event":
8883
- eventType = value;
9019
+ eventType = value || void 0;
8884
9020
  break;
8885
9021
  case "data":
8886
- data = `${data}${value}
8887
- `;
9022
+ data = dataLines === 0 ? value : `${data}
9023
+ ${value}`, dataLines++;
8888
9024
  break;
8889
9025
  case "id":
8890
- id = value.includes("\0") ? void 0 : value;
9026
+ value.includes("\0") || (id = value);
8891
9027
  break;
8892
9028
  case "retry":
8893
9029
  /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
@@ -8909,40 +9045,31 @@ function createParser(callbacks) {
8909
9045
  }
8910
9046
  }
8911
9047
  function dispatchEvent() {
8912
- data.length > 0 && onEvent({
9048
+ dataLines > 0 && onEvent({
8913
9049
  id,
8914
- event: eventType || void 0,
8915
- // If the data buffer's last character is a U+000A LINE FEED (LF) character,
8916
- // then remove the last character from the data buffer.
8917
- data: data.endsWith(`
8918
- `) ? data.slice(0, -1) : data
8919
- }), id = void 0, data = "", eventType = "";
9050
+ event: eventType,
9051
+ data
9052
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
8920
9053
  }
8921
9054
  function reset(options = {}) {
8922
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = "", eventType = "", incompleteLine = "";
9055
+ if (options.consume && pendingFragments.length > 0) {
9056
+ let incompleteLine = pendingFragments.join("");
9057
+ parseLine(incompleteLine, 0, incompleteLine.length);
9058
+ }
9059
+ isFirstChunk = !0, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;
8923
9060
  }
8924
9061
  return { feed, reset };
8925
9062
  }
8926
- function splitLines(chunk) {
8927
- let lines = [], incompleteLine = "", searchIndex = 0;
8928
- for (; searchIndex < chunk.length; ) {
8929
- let crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
8930
- `, searchIndex), lineEnd = -1;
8931
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
8932
- incompleteLine = chunk.slice(searchIndex);
8933
- break;
8934
- } else {
8935
- let line = chunk.slice(searchIndex, lineEnd);
8936
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
8937
- ` && searchIndex++;
8938
- }
8939
- }
8940
- return [lines, incompleteLine];
9063
+ function isDataPrefix(chunk, i, firstCharCode) {
9064
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
9065
+ }
9066
+ function isEventPrefix(chunk, i, firstCharCode) {
9067
+ 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;
8941
9068
  }
8942
9069
 
8943
9070
  // node_modules/eventsource-parser/dist/stream.js
8944
9071
  var EventSourceParserStream = class extends TransformStream {
8945
- constructor({ onError, onRetry, onComment } = {}) {
9072
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
8946
9073
  let parser;
8947
9074
  super({
8948
9075
  start(controller) {
@@ -8951,10 +9078,11 @@ var EventSourceParserStream = class extends TransformStream {
8951
9078
  controller.enqueue(event);
8952
9079
  },
8953
9080
  onError(error40) {
8954
- onError === "terminate" ? controller.error(error40) : typeof onError == "function" && onError(error40);
9081
+ typeof onError == "function" && onError(error40), (onError === "terminate" || error40.type === "max-buffer-size-exceeded") && controller.error(error40);
8955
9082
  },
8956
9083
  onRetry,
8957
- onComment
9084
+ onComment,
9085
+ maxBufferSize
8958
9086
  });
8959
9087
  },
8960
9088
  transform(chunk) {
@@ -8969,35 +9097,39 @@ function combineHeaders(...headers) {
8969
9097
  return headers.reduce(
8970
9098
  (combinedHeaders, currentHeaders) => ({
8971
9099
  ...combinedHeaders,
8972
- ...currentHeaders ?? {}
9100
+ ...currentHeaders
8973
9101
  }),
8974
9102
  {}
8975
9103
  );
8976
9104
  }
8977
9105
  function createToolNameMapping({
8978
9106
  tools = [],
8979
- providerToolNames
9107
+ providerToolNames,
9108
+ resolveProviderToolName
8980
9109
  }) {
9110
+ var _a22;
8981
9111
  let customToolNameToProviderToolName = {}, providerToolNameToCustomToolName = {};
8982
9112
  for (let tool2 of tools)
8983
- if (tool2.type === "provider" && tool2.id in providerToolNames) {
8984
- let providerToolName = providerToolNames[tool2.id];
9113
+ if (tool2.type === "provider") {
9114
+ let providerToolName = (_a22 = resolveProviderToolName?.(tool2)) != null ? _a22 : tool2.id in providerToolNames ? providerToolNames[tool2.id] : void 0;
9115
+ if (providerToolName == null)
9116
+ continue;
8985
9117
  customToolNameToProviderToolName[tool2.name] = providerToolName, providerToolNameToCustomToolName[providerToolName] = tool2.name;
8986
9118
  }
8987
9119
  return {
8988
9120
  toProviderToolName: (customToolName) => {
8989
- var _a22;
8990
- return (_a22 = customToolNameToProviderToolName[customToolName]) != null ? _a22 : customToolName;
9121
+ var _a32;
9122
+ return (_a32 = customToolNameToProviderToolName[customToolName]) != null ? _a32 : customToolName;
8991
9123
  },
8992
9124
  toCustomToolName: (providerToolName) => {
8993
- var _a22;
8994
- return (_a22 = providerToolNameToCustomToolName[providerToolName]) != null ? _a22 : providerToolName;
9125
+ var _a32;
9126
+ return (_a32 = providerToolNameToCustomToolName[providerToolName]) != null ? _a32 : providerToolName;
8995
9127
  }
8996
9128
  };
8997
9129
  }
8998
9130
  async function delay(delayInMs, options) {
8999
9131
  if (delayInMs == null)
9000
- return Promise.resolve();
9132
+ return;
9001
9133
  let signal = options?.abortSignal;
9002
9134
  return new Promise((resolve2, reject) => {
9003
9135
  if (signal?.aborted) {
@@ -9053,10 +9185,10 @@ function convertBase64ToUint8Array(base64String) {
9053
9185
  return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
9054
9186
  }
9055
9187
  function convertUint8ArrayToBase64(array2) {
9056
- let latin1string = "";
9057
- for (let i = 0; i < array2.length; i++)
9058
- latin1string += String.fromCodePoint(array2[i]);
9059
- return btoa(latin1string);
9188
+ let chunks = [];
9189
+ for (let i = 0; i < array2.length; i += 4096)
9190
+ chunks.push(String.fromCodePoint(...array2.subarray(i, i + 4096)));
9191
+ return btoa(chunks.join(""));
9060
9192
  }
9061
9193
  function convertToBase64(value) {
9062
9194
  return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
@@ -9079,6 +9211,13 @@ function convertToFormData(input, options = {}) {
9079
9211
  }
9080
9212
  return formData;
9081
9213
  }
9214
+ async function cancelResponseBody(response) {
9215
+ var _a22;
9216
+ try {
9217
+ await ((_a22 = response.body) == null ? void 0 : _a22.cancel());
9218
+ } catch {
9219
+ }
9220
+ }
9082
9221
  var name14 = "AI_DownloadError", marker15 = `vercel.ai.error.${name14}`, symbol16 = Symbol.for(marker15), _a15, _b15, DownloadError = class extends (_b15 = AISDKError, _a15 = symbol16, _b15) {
9083
9222
  constructor({
9084
9223
  url: url2,
@@ -9093,20 +9232,315 @@ var name14 = "AI_DownloadError", marker15 = `vercel.ai.error.${name14}`, symbol1
9093
9232
  return AISDKError.hasMarker(error40, marker15);
9094
9233
  }
9095
9234
  };
9096
- async function downloadBlob(url2) {
9235
+ function isBrowserRuntime(globalThisAny = globalThis) {
9236
+ return globalThisAny.window != null;
9237
+ }
9238
+ function isSameOrigin(url2, baseUrl) {
9097
9239
  try {
9098
- let response = await fetch(url2);
9099
- if (!response.ok)
9240
+ return new URL(url2).origin === new URL(baseUrl).origin;
9241
+ } catch {
9242
+ return !1;
9243
+ }
9244
+ }
9245
+ function validateDownloadUrl(url2) {
9246
+ let parsed;
9247
+ try {
9248
+ parsed = new URL(url2);
9249
+ } catch {
9250
+ throw new DownloadError({
9251
+ url: url2,
9252
+ message: `Invalid URL: ${url2}`
9253
+ });
9254
+ }
9255
+ if (parsed.protocol === "data:")
9256
+ return;
9257
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
9258
+ throw new DownloadError({
9259
+ url: url2,
9260
+ message: `URL scheme must be http, https, or data, got ${parsed.protocol}`
9261
+ });
9262
+ let hostname2 = parsed.hostname.toLowerCase().replace(/\.+$/, "");
9263
+ if (!hostname2)
9264
+ throw new DownloadError({
9265
+ url: url2,
9266
+ message: "URL must have a hostname"
9267
+ });
9268
+ if (hostname2 === "localhost" || hostname2.endsWith(".local") || hostname2.endsWith(".localhost"))
9269
+ throw new DownloadError({
9270
+ url: url2,
9271
+ message: `URL with hostname ${hostname2} is not allowed`
9272
+ });
9273
+ if (hostname2.startsWith("[") && hostname2.endsWith("]")) {
9274
+ let ipv63 = hostname2.slice(1, -1);
9275
+ if (isPrivateIPv6(ipv63))
9100
9276
  throw new DownloadError({
9277
+ url: url2,
9278
+ message: `URL with IPv6 address ${hostname2} is not allowed`
9279
+ });
9280
+ return;
9281
+ }
9282
+ if (isIPv4(hostname2) && isPrivateIPv4(hostname2))
9283
+ throw new DownloadError({
9284
+ url: url2,
9285
+ message: `URL with IP address ${hostname2} is not allowed`
9286
+ });
9287
+ }
9288
+ function validateDownloadAddress({
9289
+ address,
9290
+ family,
9291
+ hostname: hostname2
9292
+ }) {
9293
+ if (family === 4 ? !isIPv4(address) || isPrivateIPv4(address) : family === 6 ? isPrivateIPv6(address) : !0)
9294
+ throw new DownloadError({
9295
+ url: hostname2,
9296
+ message: `Hostname ${hostname2} resolved to disallowed IP address ${address}`
9297
+ });
9298
+ }
9299
+ function isIPv4(hostname2) {
9300
+ let parts = hostname2.split(".");
9301
+ return parts.length !== 4 ? !1 : parts.every((part) => {
9302
+ let num = Number(part);
9303
+ return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
9304
+ });
9305
+ }
9306
+ function isPrivateIPv4(ip) {
9307
+ let parts = ip.split(".").map(Number), [a, b, c] = parts;
9308
+ return a === 0 || a === 10 || a === 100 && b >= 64 && b <= 127 || a === 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 0 && c === 0 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 240;
9309
+ }
9310
+ function parseIPv6(ip) {
9311
+ let address = ip.toLowerCase(), zoneIndex = address.indexOf("%");
9312
+ zoneIndex !== -1 && (address = address.slice(0, zoneIndex));
9313
+ let halves = address.split("::");
9314
+ if (halves.length > 2) return null;
9315
+ let toGroups = (segment) => {
9316
+ if (segment === "") return [];
9317
+ let groups = [], parts = segment.split(":");
9318
+ for (let i = 0; i < parts.length; i++) {
9319
+ let part = parts[i];
9320
+ if (part.includes(".")) {
9321
+ if (i !== parts.length - 1 || !isIPv4(part)) return null;
9322
+ let [a, b, c, d] = part.split(".").map(Number);
9323
+ groups.push(a << 8 | b, c << 8 | d);
9324
+ continue;
9325
+ }
9326
+ if (!/^[0-9a-f]{1,4}$/.test(part)) return null;
9327
+ groups.push(parseInt(part, 16));
9328
+ }
9329
+ return groups;
9330
+ }, head = toGroups(halves[0]);
9331
+ if (head === null) return null;
9332
+ if (halves.length === 2) {
9333
+ let tail = toGroups(halves[1]);
9334
+ if (tail === null) return null;
9335
+ let fill = 8 - head.length - tail.length;
9336
+ return fill < 0 ? null : [...head, ...new Array(fill).fill(0), ...tail];
9337
+ }
9338
+ return head.length === 8 ? head : null;
9339
+ }
9340
+ function isPrivateIPv6(ip) {
9341
+ let groups = parseIPv6(ip);
9342
+ if (groups === null) return !0;
9343
+ let topZero = (count) => groups.slice(0, count).every((group) => group === 0);
9344
+ if (topZero(7) && (groups[7] === 0 || groups[7] === 1) || (groups[0] & 65024) === 64512 || (groups[0] & 65472) === 65152 || (groups[0] & 65472) === 65216 || (groups[0] & 65280) === 65280) return !0;
9345
+ if (
9346
+ // ::/96 — IPv4-compatible (deprecated)
9347
+ topZero(6) || // ::ffff:0:0/96 — IPv4-mapped (ffff in group 5)
9348
+ topZero(5) && groups[5] === 65535 || // ::ffff:0:0/96 — IPv4-translated form (ffff in group 4, group 5 zero)
9349
+ topZero(4) && groups[4] === 65535 && groups[5] === 0 || // 64:ff9b::/96 — NAT64 well-known prefix
9350
+ 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
9351
+ groups[0] === 100 && groups[1] === 65435 && groups[2] === 1
9352
+ ) {
9353
+ let a = groups[6] >> 8 & 255, b = groups[6] & 255, c = groups[7] >> 8 & 255, d = groups[7] & 255;
9354
+ return isPrivateIPv4(`${a}.${b}.${c}.${d}`);
9355
+ }
9356
+ return !1;
9357
+ }
9358
+ function createSafeLookup(lookup) {
9359
+ return ((hostname2, options, callback) => {
9360
+ lookup(hostname2, { ...options, all: !0 }, (error40, addresses) => {
9361
+ if (error40) {
9362
+ callback(error40);
9363
+ return;
9364
+ }
9365
+ try {
9366
+ let [firstAddress] = addresses;
9367
+ if (firstAddress == null)
9368
+ throw new Error(`Hostname ${hostname2} did not resolve to an address`);
9369
+ for (let { address, family } of addresses)
9370
+ validateDownloadAddress({ address, family, hostname: hostname2 });
9371
+ options.all === !0 ? callback(null, addresses) : callback(
9372
+ null,
9373
+ firstAddress.address,
9374
+ firstAddress.family
9375
+ );
9376
+ } catch (error210) {
9377
+ callback(
9378
+ error210 instanceof Error ? error210 : new Error(String(error210))
9379
+ );
9380
+ }
9381
+ });
9382
+ });
9383
+ }
9384
+ var safeNodeFetchPromise;
9385
+ function isNodeRuntime() {
9386
+ var _a22, _b22, _c;
9387
+ let runtimeProcess = globalThis.process;
9388
+ return ((_a22 = runtimeProcess?.release) == null ? void 0 : _a22.name) === "node" && ((_b22 = runtimeProcess.versions) == null ? void 0 : _b22.bun) == null && ((_c = runtimeProcess.versions) == null ? void 0 : _c.deno) == null && runtimeProcess.title !== "workerd" && globalThis.EdgeRuntime == null;
9389
+ }
9390
+ async function getDefaultDownloadFetch() {
9391
+ return isNodeRuntime() ? safeNodeFetchPromise ?? (safeNodeFetchPromise = createSafeNodeFetch()) : globalThis.fetch;
9392
+ }
9393
+ async function createSafeNodeFetch() {
9394
+ let [module, { lookup }] = await Promise.all([
9395
+ loadNodeModule("node:module"),
9396
+ loadNodeModule("node:dns")
9397
+ ]), nodeRequire = module.createRequire(getCurrentModulePath()), { Agent, fetch } = nodeRequire("undici"), dispatcher = new Agent({
9398
+ connect: {
9399
+ lookup: createSafeLookup(lookup)
9400
+ }
9401
+ });
9402
+ return ((input, init) => fetch(
9403
+ input,
9404
+ {
9405
+ ...init,
9406
+ dispatcher
9407
+ }
9408
+ ));
9409
+ }
9410
+ async function loadNodeModule(id) {
9411
+ var _a22;
9412
+ let processWithBuiltins = globalThis.process, builtinModule = (_a22 = processWithBuiltins?.getBuiltinModule) == null ? void 0 : _a22.call(processWithBuiltins, id);
9413
+ if (builtinModule == null)
9414
+ throw new Error(`Node.js built-in module ${id} is unavailable`);
9415
+ return builtinModule;
9416
+ }
9417
+ function getCurrentModulePath() {
9418
+ let originalPrepareStackTrace = Error.prepareStackTrace;
9419
+ try {
9420
+ Error.prepareStackTrace = (_error, callSites) => callSites;
9421
+ let error40 = new Error("Capture current module path");
9422
+ Error.captureStackTrace(error40, getCurrentModulePath);
9423
+ let [caller] = error40.stack, fileName = caller?.getFileName();
9424
+ if (fileName == null)
9425
+ throw new Error("Unable to determine the current module path");
9426
+ return fileName;
9427
+ } finally {
9428
+ Error.prepareStackTrace = originalPrepareStackTrace;
9429
+ }
9430
+ }
9431
+ var MAX_DOWNLOAD_REDIRECTS = 10;
9432
+ async function getValidatedFetch(customFetch) {
9433
+ return customFetch == null || customFetch === globalThis.fetch ? await getDefaultDownloadFetch() : customFetch;
9434
+ }
9435
+ async function fetchWithValidatedRedirects({
9436
+ url: url2,
9437
+ headers,
9438
+ abortSignal,
9439
+ maxRedirects = MAX_DOWNLOAD_REDIRECTS,
9440
+ fetch: customFetch,
9441
+ trustedOrigin
9442
+ }) {
9443
+ var _a22;
9444
+ let baseInit = { signal: abortSignal };
9445
+ headers !== void 0 && (baseInit.headers = headers);
9446
+ let currentUrl = url2;
9447
+ for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
9448
+ let isTrustedHop = trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin);
9449
+ isTrustedHop || validateDownloadUrl(currentUrl);
9450
+ let fetch = isTrustedHop && customFetch != null ? customFetch : isTrustedHop ? globalThis.fetch : await getValidatedFetch(customFetch), response = await fetch(currentUrl, {
9451
+ ...baseInit,
9452
+ redirect: "manual"
9453
+ });
9454
+ if (response.type === "opaqueredirect") {
9455
+ if (!isBrowserRuntime())
9456
+ throw new DownloadError({
9457
+ url: url2,
9458
+ message: `Redirect from ${currentUrl} could not be validated and was blocked`
9459
+ });
9460
+ return await fetch(currentUrl, { ...baseInit, redirect: "follow" });
9461
+ }
9462
+ let location = (_a22 = response.headers) == null ? void 0 : _a22.get("location");
9463
+ if (response.status >= 300 && response.status < 400 && location) {
9464
+ await cancelResponseBody(response), currentUrl = new URL(location, currentUrl).toString();
9465
+ continue;
9466
+ }
9467
+ return response;
9468
+ }
9469
+ throw new DownloadError({
9470
+ url: url2,
9471
+ message: `Too many redirects (max ${maxRedirects})`
9472
+ });
9473
+ }
9474
+ var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
9475
+ async function readResponseWithSizeLimit({
9476
+ response,
9477
+ url: url2,
9478
+ maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE
9479
+ }) {
9480
+ let contentLength = response.headers.get("content-length");
9481
+ if (contentLength != null) {
9482
+ let length = parseInt(contentLength, 10);
9483
+ if (!isNaN(length) && length > maxBytes)
9484
+ throw await cancelResponseBody(response), new DownloadError({
9485
+ url: url2,
9486
+ message: `Download of ${url2} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`
9487
+ });
9488
+ }
9489
+ let body = response.body;
9490
+ if (body == null)
9491
+ return new Uint8Array(0);
9492
+ let reader = body.getReader(), chunks = [], totalBytes = 0;
9493
+ try {
9494
+ for (; ; ) {
9495
+ let { done, value } = await reader.read();
9496
+ if (done)
9497
+ break;
9498
+ if (totalBytes += value.length, totalBytes > maxBytes)
9499
+ throw new DownloadError({
9500
+ url: url2,
9501
+ message: `Download of ${url2} exceeded maximum size of ${maxBytes} bytes.`
9502
+ });
9503
+ chunks.push(value);
9504
+ }
9505
+ } finally {
9506
+ try {
9507
+ await reader.cancel();
9508
+ } catch {
9509
+ } finally {
9510
+ reader.releaseLock();
9511
+ }
9512
+ }
9513
+ let result = new Uint8Array(totalBytes), offset = 0;
9514
+ for (let chunk of chunks)
9515
+ result.set(chunk, offset), offset += chunk.length;
9516
+ return result;
9517
+ }
9518
+ async function downloadBlob(url2, options) {
9519
+ var _a22, _b22;
9520
+ try {
9521
+ let response = await fetchWithValidatedRedirects({
9522
+ url: url2,
9523
+ abortSignal: options?.abortSignal
9524
+ });
9525
+ if (!response.ok)
9526
+ throw await cancelResponseBody(response), new DownloadError({
9101
9527
  url: url2,
9102
9528
  statusCode: response.status,
9103
9529
  statusText: response.statusText
9104
9530
  });
9105
- return await response.blob();
9531
+ let data = await readResponseWithSizeLimit({
9532
+ response,
9533
+ url: url2,
9534
+ maxBytes: (_a22 = options?.maxBytes) != null ? _a22 : DEFAULT_MAX_DOWNLOAD_SIZE
9535
+ }), contentType = (_b22 = response.headers.get("content-type")) != null ? _b22 : void 0;
9536
+ return new Blob([data], contentType ? { type: contentType } : void 0);
9106
9537
  } catch (error40) {
9107
9538
  throw DownloadError.isInstance(error40) ? error40 : new DownloadError({ url: url2, cause: error40 });
9108
9539
  }
9109
9540
  }
9541
+ var EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL = /* @__PURE__ */ Symbol.for(
9542
+ "vercel.ai.embeddingModel.maxInputBytesPerCall"
9543
+ );
9110
9544
  var createIdGenerator = ({
9111
9545
  prefix,
9112
9546
  size = 16,
@@ -9135,20 +9569,28 @@ function isAbortError(error40) {
9135
9569
  return (error40 instanceof Error || error40 instanceof DOMException) && (error40.name === "AbortError" || error40.name === "ResponseAborted" || // Next.js
9136
9570
  error40.name === "TimeoutError");
9137
9571
  }
9138
- var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"], BUN_ERROR_CODES = [
9572
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"], RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
9139
9573
  "ConnectionRefused",
9140
9574
  "ConnectionClosed",
9141
9575
  "FailedToOpenSocket",
9142
9576
  "ECONNRESET",
9143
9577
  "ECONNREFUSED",
9144
9578
  "ETIMEDOUT",
9145
- "EPIPE"
9146
- ];
9147
- function isBunNetworkError(error40) {
9148
- if (!(error40 instanceof Error))
9149
- return !1;
9150
- let code = error40.code;
9151
- return !!(typeof code == "string" && BUN_ERROR_CODES.includes(code));
9579
+ "EPIPE",
9580
+ "UND_ERR_SOCKET",
9581
+ "UND_ERR_HEADERS_TIMEOUT",
9582
+ "UND_ERR_BODY_TIMEOUT",
9583
+ "UND_ERR_CONNECT_TIMEOUT"
9584
+ ]);
9585
+ function findNetworkError(error40) {
9586
+ let visited = /* @__PURE__ */ new Set(), current = error40;
9587
+ for (; current instanceof Error && !visited.has(current); ) {
9588
+ visited.add(current);
9589
+ let errorWithCode = current;
9590
+ if (typeof errorWithCode.code == "string" && RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code))
9591
+ return errorWithCode;
9592
+ current = current.cause;
9593
+ }
9152
9594
  }
9153
9595
  function handleFetchError({
9154
9596
  error: error40,
@@ -9169,8 +9611,19 @@ function handleFetchError({
9169
9611
  // retry when network error
9170
9612
  });
9171
9613
  }
9172
- return isBunNetworkError(error40) ? new APICallError({
9173
- message: `Cannot connect to API: ${error40.message}`,
9614
+ let networkError = findNetworkError(error40);
9615
+ return networkError != null ? APICallError.isInstance(error40) ? new APICallError({
9616
+ message: error40.message,
9617
+ cause: error40.cause,
9618
+ url: error40.url,
9619
+ requestBodyValues: error40.requestBodyValues,
9620
+ statusCode: error40.statusCode,
9621
+ responseHeaders: error40.responseHeaders,
9622
+ responseBody: error40.responseBody,
9623
+ data: error40.data,
9624
+ isRetryable: !0
9625
+ }) : new APICallError({
9626
+ message: `Cannot connect to API: ${error40 instanceof Error ? error40.message : networkError.message}`,
9174
9627
  cause: error40,
9175
9628
  url: url2,
9176
9629
  requestBodyValues,
@@ -9203,16 +9656,16 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
9203
9656
  [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
9204
9657
  ), Object.fromEntries(normalizedHeaders.entries());
9205
9658
  }
9206
- var VERSION = "4.0.13", getOriginalFetch = () => globalThis.fetch, getFromApi = async ({
9659
+ var VERSION = "4.0.58", getOriginalFetch = () => globalThis.fetch, getFromApi = async ({
9207
9660
  url: url2,
9208
9661
  headers = {},
9209
9662
  successfulResponseHandler,
9210
9663
  failedResponseHandler,
9211
9664
  abortSignal,
9212
- fetch: fetch2 = getOriginalFetch()
9665
+ fetch = getOriginalFetch()
9213
9666
  }) => {
9214
9667
  try {
9215
- let response = await fetch2(url2, {
9668
+ let response = await fetch(url2, {
9216
9669
  method: "GET",
9217
9670
  headers: withUserAgentSuffix(
9218
9671
  headers,
@@ -9272,7 +9725,9 @@ function isUrlSupported({
9272
9725
  return url2 = url2.toLowerCase(), mediaType = mediaType.toLowerCase(), Object.entries(supportedUrls).map(([key, value]) => {
9273
9726
  let mediaType2 = key.toLowerCase();
9274
9727
  return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value };
9275
- }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url2));
9728
+ }).filter(
9729
+ ({ mediaTypePrefix }) => mediaTypePrefix === "" || mediaTypePrefix.endsWith("/") ? mediaType.startsWith(mediaTypePrefix) : mediaType === mediaTypePrefix
9730
+ ).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url2));
9276
9731
  }
9277
9732
  function loadApiKey({
9278
9733
  apiKey,
@@ -9288,7 +9743,7 @@ function loadApiKey({
9288
9743
  });
9289
9744
  if (typeof process > "u")
9290
9745
  throw new LoadAPIKeyError({
9291
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
9746
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.`
9292
9747
  });
9293
9748
  if (apiKey = process.env[environmentVariableName], apiKey == null)
9294
9749
  throw new LoadAPIKeyError({
@@ -9320,7 +9775,7 @@ function mediaTypeToExtension(mediaType) {
9320
9775
  "x-m4a": "m4a"
9321
9776
  }[subtype]) != null ? _a22 : subtype;
9322
9777
  }
9323
- var suspectProtoRx = /"__proto__"\s*:/, suspectConstructorRx = /"constructor"\s*:/;
9778
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/, suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
9324
9779
  function _parse2(text) {
9325
9780
  let obj = JSON.parse(text);
9326
9781
  return obj === null || typeof obj != "object" || suspectProtoRx.test(text) === !1 && suspectConstructorRx.test(text) === !1 ? obj : filter(obj);
@@ -9333,7 +9788,7 @@ function filter(obj) {
9333
9788
  for (let node of nodes) {
9334
9789
  if (Object.prototype.hasOwnProperty.call(node, "__proto__"))
9335
9790
  throw new SyntaxError("Object contains forbidden prototype property");
9336
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype"))
9791
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor == "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype"))
9337
9792
  throw new SyntaxError("Object contains forbidden prototype property");
9338
9793
  for (let key in node) {
9339
9794
  let value = node[key];
@@ -9358,7 +9813,8 @@ function secureJsonParse(text) {
9358
9813
  }
9359
9814
  function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
9360
9815
  if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
9361
- jsonSchema2.additionalProperties = !1;
9816
+ let { additionalProperties } = jsonSchema2;
9817
+ jsonSchema2.additionalProperties = additionalProperties != null && typeof additionalProperties != "boolean" ? visit(additionalProperties) : !1;
9362
9818
  let { properties } = jsonSchema2;
9363
9819
  if (properties != null)
9364
9820
  for (let key of Object.keys(properties))
@@ -9540,7 +9996,7 @@ var emojiRegex = void 0, zodPatterns = {
9540
9996
  /**
9541
9997
  * `a-z` was added to replicate /i flag
9542
9998
  */
9543
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
9999
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,
9544
10000
  /**
9545
10001
  * Constructed a valid Unicode RegExp
9546
10002
  *
@@ -10301,15 +10757,25 @@ function isSchema(value) {
10301
10757
  return typeof value == "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === !0 && "jsonSchema" in value && "validate" in value;
10302
10758
  }
10303
10759
  function asSchema(schema) {
10304
- return schema == null ? jsonSchema({ properties: {}, additionalProperties: !1 }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
10760
+ return schema == null ? jsonSchema({
10761
+ type: "object",
10762
+ properties: {},
10763
+ additionalProperties: !1
10764
+ }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
10305
10765
  }
10306
10766
  function standardSchema(standardSchema2) {
10307
10767
  return jsonSchema(
10308
- () => addAdditionalPropertiesToJsonSchema(
10309
- standardSchema2["~standard"].jsonSchema.input({
10310
- target: "draft-07"
10311
- })
10312
- ),
10768
+ () => {
10769
+ if (!hasStandardJsonSchema(standardSchema2))
10770
+ throw new Error(
10771
+ `Standard schema vendor '${standardSchema2["~standard"].vendor}' does not support JSON Schema conversion.`
10772
+ );
10773
+ return addAdditionalPropertiesToJsonSchema(
10774
+ standardSchema2["~standard"].jsonSchema.input({
10775
+ target: "draft-07"
10776
+ })
10777
+ );
10778
+ },
10313
10779
  {
10314
10780
  validate: async (value) => {
10315
10781
  let result = await standardSchema2["~standard"].validate(value);
@@ -10324,6 +10790,9 @@ function standardSchema(standardSchema2) {
10324
10790
  }
10325
10791
  );
10326
10792
  }
10793
+ function hasStandardJsonSchema(schema) {
10794
+ return schema["~standard"].jsonSchema != null;
10795
+ }
10327
10796
  function zod3Schema(zodSchema2, options) {
10328
10797
  var _a22;
10329
10798
  let useReferences = (_a22 = options?.useReferences) != null ? _a22 : !1;
@@ -10425,13 +10894,6 @@ async function safeParseJSON({
10425
10894
  };
10426
10895
  }
10427
10896
  }
10428
- function isParsableJson(input) {
10429
- try {
10430
- return secureJsonParse(input), !0;
10431
- } catch {
10432
- return !1;
10433
- }
10434
- }
10435
10897
  function parseJsonEventStream({
10436
10898
  stream,
10437
10899
  schema
@@ -10470,7 +10932,7 @@ var getOriginalFetch2 = () => globalThis.fetch, postJsonToApi = async ({
10470
10932
  failedResponseHandler,
10471
10933
  successfulResponseHandler,
10472
10934
  abortSignal,
10473
- fetch: fetch2
10935
+ fetch
10474
10936
  }) => postToApi({
10475
10937
  url: url2,
10476
10938
  headers: {
@@ -10484,7 +10946,7 @@ var getOriginalFetch2 = () => globalThis.fetch, postJsonToApi = async ({
10484
10946
  failedResponseHandler,
10485
10947
  successfulResponseHandler,
10486
10948
  abortSignal,
10487
- fetch: fetch2
10949
+ fetch
10488
10950
  }), postFormDataToApi = async ({
10489
10951
  url: url2,
10490
10952
  headers,
@@ -10492,7 +10954,7 @@ var getOriginalFetch2 = () => globalThis.fetch, postJsonToApi = async ({
10492
10954
  failedResponseHandler,
10493
10955
  successfulResponseHandler,
10494
10956
  abortSignal,
10495
- fetch: fetch2
10957
+ fetch
10496
10958
  }) => postToApi({
10497
10959
  url: url2,
10498
10960
  headers,
@@ -10503,7 +10965,7 @@ var getOriginalFetch2 = () => globalThis.fetch, postJsonToApi = async ({
10503
10965
  failedResponseHandler,
10504
10966
  successfulResponseHandler,
10505
10967
  abortSignal,
10506
- fetch: fetch2
10968
+ fetch
10507
10969
  }), postToApi = async ({
10508
10970
  url: url2,
10509
10971
  headers = {},
@@ -10511,10 +10973,10 @@ var getOriginalFetch2 = () => globalThis.fetch, postJsonToApi = async ({
10511
10973
  successfulResponseHandler,
10512
10974
  failedResponseHandler,
10513
10975
  abortSignal,
10514
- fetch: fetch2 = getOriginalFetch2()
10976
+ fetch = getOriginalFetch2()
10515
10977
  }) => {
10516
10978
  try {
10517
- let response = await fetch2(url2, {
10979
+ let response = await fetch(url2, {
10518
10980
  method: "POST",
10519
10981
  headers: withUserAgentSuffix(
10520
10982
  headers,
@@ -10621,14 +11083,136 @@ function createProviderToolFactoryWithOutputSchema({
10621
11083
  });
10622
11084
  }
10623
11085
  async function resolve(value) {
10624
- return typeof value == "function" && (value = value()), Promise.resolve(value);
11086
+ return typeof value == "function" && (value = value()), value;
11087
+ }
11088
+ var retryWithExponentialBackoff = ({
11089
+ maxRetries = 2,
11090
+ initialDelayInMs = 2e3,
11091
+ backoffFactor = 2,
11092
+ abortSignal,
11093
+ shouldRetry,
11094
+ getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay,
11095
+ createRetryError = ({ message }) => new Error(message)
11096
+ }) => async (f) => retryWithExponentialBackoffInternal(f, {
11097
+ maxRetries,
11098
+ delayInMs: initialDelayInMs,
11099
+ backoffFactor,
11100
+ abortSignal,
11101
+ shouldRetry,
11102
+ getDelayInMs,
11103
+ createRetryError
11104
+ });
11105
+ async function retryWithExponentialBackoffInternal(f, {
11106
+ maxRetries,
11107
+ delayInMs,
11108
+ backoffFactor,
11109
+ abortSignal,
11110
+ shouldRetry,
11111
+ getDelayInMs,
11112
+ createRetryError
11113
+ }, errors = []) {
11114
+ try {
11115
+ return await f();
11116
+ } catch (error40) {
11117
+ if (isAbortError(error40) || maxRetries === 0)
11118
+ throw error40;
11119
+ let errorMessage = getErrorMessage2(error40), newErrors = [...errors, error40], tryNumber = newErrors.length;
11120
+ if (tryNumber > maxRetries)
11121
+ throw createRetryError({
11122
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
11123
+ reason: "maxRetriesExceeded",
11124
+ errors: newErrors
11125
+ });
11126
+ if (await shouldRetry(error40) && tryNumber <= maxRetries)
11127
+ return await delay(
11128
+ getDelayInMs({
11129
+ error: error40,
11130
+ exponentialBackoffDelay: delayInMs
11131
+ }),
11132
+ { abortSignal }
11133
+ ), retryWithExponentialBackoffInternal(
11134
+ f,
11135
+ {
11136
+ maxRetries,
11137
+ delayInMs: backoffFactor * delayInMs,
11138
+ backoffFactor,
11139
+ abortSignal,
11140
+ shouldRetry,
11141
+ getDelayInMs,
11142
+ createRetryError
11143
+ },
11144
+ newErrors
11145
+ );
11146
+ throw tryNumber === 1 ? error40 : createRetryError({
11147
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
11148
+ reason: "errorNotRetryable",
11149
+ errors: newErrors
11150
+ });
11151
+ }
11152
+ }
11153
+ var textDecoder = new TextDecoder();
11154
+ function wrapResponseBodyStream({
11155
+ stream,
11156
+ url: url2,
11157
+ requestBodyValues,
11158
+ statusCode,
11159
+ responseHeaders
11160
+ }) {
11161
+ let reader = stream.getReader(), readerReleased = !1, releaseReader = () => {
11162
+ readerReleased || (reader.releaseLock(), readerReleased = !0);
11163
+ };
11164
+ return new ReadableStream({
11165
+ async pull(controller) {
11166
+ try {
11167
+ let { done, value } = await reader.read();
11168
+ done ? (releaseReader(), controller.close()) : controller.enqueue(value);
11169
+ } catch (error40) {
11170
+ if (releaseReader(), isAbortError(error40)) {
11171
+ controller.error(error40);
11172
+ return;
11173
+ }
11174
+ controller.error(
11175
+ handleFetchError({
11176
+ error: new APICallError({
11177
+ message: "Failed to process successful response",
11178
+ cause: error40,
11179
+ statusCode,
11180
+ url: url2,
11181
+ responseHeaders,
11182
+ requestBodyValues
11183
+ }),
11184
+ url: url2,
11185
+ requestBodyValues
11186
+ })
11187
+ );
11188
+ }
11189
+ },
11190
+ async cancel(reason) {
11191
+ try {
11192
+ await reader.cancel(reason);
11193
+ } finally {
11194
+ releaseReader();
11195
+ }
11196
+ }
11197
+ });
11198
+ }
11199
+ async function readResponseBodyAsText({
11200
+ response,
11201
+ url: url2
11202
+ }) {
11203
+ return textDecoder.decode(
11204
+ await readResponseWithSizeLimit({
11205
+ response,
11206
+ url: url2
11207
+ })
11208
+ );
10625
11209
  }
10626
11210
  var createJsonErrorResponseHandler = ({
10627
11211
  errorSchema,
10628
11212
  errorToMessage,
10629
11213
  isRetryable
10630
11214
  }) => async ({ response, url: url2, requestBodyValues }) => {
10631
- let responseBody = await response.text(), responseHeaders = extractResponseHeaders(response);
11215
+ let responseBody = await readResponseBodyAsText({ response, url: url2 }), responseHeaders = extractResponseHeaders(response);
10632
11216
  if (responseBody.trim() === "")
10633
11217
  return {
10634
11218
  responseHeaders,
@@ -10674,19 +11258,25 @@ var createJsonErrorResponseHandler = ({
10674
11258
  })
10675
11259
  };
10676
11260
  }
10677
- }, createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
11261
+ }, createEventSourceResponseHandler = (chunkSchema) => async ({ response, url: url2, requestBodyValues }) => {
10678
11262
  let responseHeaders = extractResponseHeaders(response);
10679
11263
  if (response.body == null)
10680
11264
  throw new EmptyResponseBodyError({});
10681
11265
  return {
10682
11266
  responseHeaders,
10683
11267
  value: parseJsonEventStream({
10684
- stream: response.body,
11268
+ stream: wrapResponseBodyStream({
11269
+ stream: response.body,
11270
+ url: url2,
11271
+ requestBodyValues,
11272
+ statusCode: response.status,
11273
+ responseHeaders
11274
+ }),
10685
11275
  schema: chunkSchema
10686
11276
  })
10687
11277
  };
10688
11278
  }, createJsonResponseHandler = (responseSchema) => async ({ response, url: url2, requestBodyValues }) => {
10689
- let responseBody = await response.text(), parsedResult = await safeParseJSON({
11279
+ let responseBody = await readResponseBodyAsText({ response, url: url2 }), parsedResult = await safeParseJSON({
10690
11280
  text: responseBody,
10691
11281
  schema: responseSchema
10692
11282
  }), responseHeaders = extractResponseHeaders(response);
@@ -10734,6 +11324,259 @@ var createJsonErrorResponseHandler = ({
10734
11324
  });
10735
11325
  }
10736
11326
  };
11327
+ function startsWithStructuredValue(value) {
11328
+ if (typeof value != "string")
11329
+ return !1;
11330
+ let firstCharacter = value.trimStart()[0];
11331
+ return firstCharacter === "{" || firstCharacter === "[";
11332
+ }
11333
+ var StreamingToolCallArgumentState = class {
11334
+ constructor(initialValue = "") {
11335
+ this.structure = { kind: "undetermined" }, this.append(initialValue);
11336
+ }
11337
+ get hasCompleteStructuredValue() {
11338
+ return this.structure.kind === "structured" && this.structure.complete === !0;
11339
+ }
11340
+ append(delta) {
11341
+ let nextStructure = this.structure;
11342
+ for (let character of delta) {
11343
+ if (nextStructure.kind === "undetermined") {
11344
+ if (/\s/.test(character))
11345
+ continue;
11346
+ if (character !== "{" && character !== "[") {
11347
+ nextStructure = { kind: "other" };
11348
+ continue;
11349
+ }
11350
+ nextStructure = {
11351
+ kind: "structured",
11352
+ stack: [character],
11353
+ inString: !1,
11354
+ escaped: !1,
11355
+ complete: !1
11356
+ };
11357
+ continue;
11358
+ }
11359
+ if (!(nextStructure.kind !== "structured" || nextStructure.complete)) {
11360
+ if (nextStructure.inString) {
11361
+ nextStructure.escaped ? nextStructure.escaped = !1 : character === "\\" ? nextStructure.escaped = !0 : character === '"' && (nextStructure.inString = !1);
11362
+ continue;
11363
+ }
11364
+ if (character === '"')
11365
+ nextStructure.inString = !0;
11366
+ else if (character === "{" || character === "[")
11367
+ nextStructure.stack.push(character);
11368
+ else if (character === "}" || character === "]") {
11369
+ let expectedOpening = character === "}" ? "{" : "[";
11370
+ if (nextStructure.stack[nextStructure.stack.length - 1] !== expectedOpening) {
11371
+ nextStructure = { kind: "other" };
11372
+ continue;
11373
+ }
11374
+ nextStructure.stack.pop(), nextStructure.stack.length === 0 && (nextStructure.complete = !0);
11375
+ }
11376
+ }
11377
+ }
11378
+ this.structure = nextStructure;
11379
+ }
11380
+ }, StreamingToolCallTracker = class {
11381
+ constructor(controller, options = {}) {
11382
+ this.toolCalls = [], this.toolCallsById = /* @__PURE__ */ new Map(), this.toolCallsByIndex = /* @__PURE__ */ new Map(), this.usedToolCallIds = /* @__PURE__ */ new Set(), this.nextGeneratedIdSuffixes = /* @__PURE__ */ new Map();
11383
+ var _a22, _b22;
11384
+ this.controller = controller, this._generateId = (_a22 = options.generateId) != null ? _a22 : generateId, this.typeValidation = (_b22 = options.typeValidation) != null ? _b22 : "none", this.extractMetadata = options.extractMetadata, this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;
11385
+ }
11386
+ processDelta(toolCallDelta) {
11387
+ var _a22, _b22;
11388
+ let wireName = (_a22 = toolCallDelta.function) == null ? void 0 : _a22.name, hasBlankName = typeof wireName == "string" && wireName.trim().length === 0, wireId = this.getNonBlankString(toolCallDelta.id), name22 = this.getNonBlankString(wireName), { index } = toolCallDelta, resolution = this.resolveToolCall({
11389
+ wireId,
11390
+ index,
11391
+ name: name22,
11392
+ hasExplicitCallStart: name22 != null && startsWithStructuredValue((_b22 = toolCallDelta.function) == null ? void 0 : _b22.arguments)
11393
+ });
11394
+ if (resolution.kind === "ambiguous")
11395
+ return;
11396
+ let toolCall;
11397
+ if (resolution.kind === "new") {
11398
+ if (hasBlankName)
11399
+ return;
11400
+ toolCall = this.processNewToolCall(toolCallDelta, {
11401
+ wireId,
11402
+ index,
11403
+ name: name22
11404
+ });
11405
+ } else
11406
+ toolCall = resolution.toolCall, wireId != null && this.associateWireId(toolCall, wireId), this.processExistingToolCall(toolCall, toolCallDelta);
11407
+ index != null && this.associateIndex(toolCall, index);
11408
+ }
11409
+ flush() {
11410
+ let toolCalls = this.toolCalls.every((toolCall) => toolCall.index != null) ? [...this.toolCalls].sort(
11411
+ (a, b) => a.index - b.index || a.sequence - b.sequence
11412
+ ) : this.toolCalls;
11413
+ for (let toolCall of toolCalls)
11414
+ toolCall.hasFinished || this.finishToolCall(toolCall);
11415
+ }
11416
+ resolveToolCall({
11417
+ wireId,
11418
+ index,
11419
+ name: name22,
11420
+ hasExplicitCallStart
11421
+ }) {
11422
+ let indexedToolCalls = index != null ? this.toolCallsByIndex.get(index) : void 0, matchingIndexedToolCalls = this.filterToolCallsByName(
11423
+ indexedToolCalls,
11424
+ name22
11425
+ );
11426
+ if (wireId != null) {
11427
+ let toolCallsWithId = this.toolCallsById.get(wireId);
11428
+ if (toolCallsWithId != null) {
11429
+ if (index != null) {
11430
+ let matchingToolCalls = matchingIndexedToolCalls.filter(
11431
+ (toolCall) => toolCallsWithId.has(toolCall)
11432
+ ), matchingToolCall = this.resolveMatchingToolCall(
11433
+ matchingToolCalls,
11434
+ hasExplicitCallStart
11435
+ );
11436
+ return matchingToolCall.kind !== "new" ? matchingToolCall : name22 != null ? { kind: "new" } : indexedToolCalls != null ? { kind: "ambiguous" } : this.resolveMatchingToolCall([...toolCallsWithId], !1);
11437
+ }
11438
+ if (name22 != null) {
11439
+ let matchingToolCalls = [...toolCallsWithId].filter(
11440
+ (toolCall) => toolCall.function.name === name22
11441
+ );
11442
+ return this.resolveMatchingToolCall(
11443
+ matchingToolCalls,
11444
+ hasExplicitCallStart
11445
+ );
11446
+ }
11447
+ return this.resolveMatchingToolCall([...toolCallsWithId], !1);
11448
+ }
11449
+ return matchingIndexedToolCalls.length > 0 ? hasExplicitCallStart ? { kind: "new" } : this.resolveMatchingToolCall(matchingIndexedToolCalls, !1) : { kind: "new" };
11450
+ }
11451
+ if (indexedToolCalls != null)
11452
+ return this.resolveMatchingToolCall(
11453
+ matchingIndexedToolCalls,
11454
+ hasExplicitCallStart
11455
+ );
11456
+ if (name22 != null)
11457
+ return { kind: "new" };
11458
+ let unfinishedToolCalls = this.toolCalls.filter(
11459
+ (toolCall) => !toolCall.hasFinished
11460
+ );
11461
+ return unfinishedToolCalls.length === 1 ? { kind: "existing", toolCall: unfinishedToolCalls[0] } : unfinishedToolCalls.length > 1 ? { kind: "ambiguous" } : { kind: "new" };
11462
+ }
11463
+ filterToolCallsByName(toolCalls, name22) {
11464
+ return toolCalls == null ? [] : [...toolCalls].filter(
11465
+ (toolCall) => name22 == null || toolCall.function.name === name22
11466
+ );
11467
+ }
11468
+ resolveMatchingToolCall(toolCalls, hasExplicitCallStart) {
11469
+ if (toolCalls.length === 0)
11470
+ return { kind: "new" };
11471
+ if (!hasExplicitCallStart)
11472
+ return toolCalls.length === 1 ? { kind: "existing", toolCall: toolCalls[0] } : { kind: "ambiguous" };
11473
+ let continuableToolCalls = toolCalls.filter(
11474
+ (toolCall) => !toolCall.argumentState.hasCompleteStructuredValue
11475
+ );
11476
+ return continuableToolCalls.length === 1 ? { kind: "existing", toolCall: continuableToolCalls[0] } : continuableToolCalls.length > 1 ? { kind: "ambiguous" } : { kind: "new" };
11477
+ }
11478
+ processNewToolCall(toolCallDelta, {
11479
+ wireId,
11480
+ index,
11481
+ name: name22
11482
+ }) {
11483
+ var _a22, _b22, _c, _d, _e;
11484
+ if (this.typeValidation === "required") {
11485
+ if (toolCallDelta.type !== "function")
11486
+ throw new InvalidResponseDataError({
11487
+ data: toolCallDelta,
11488
+ message: "Expected 'function' type."
11489
+ });
11490
+ } else if (this.typeValidation === "if-present" && toolCallDelta.type != null && toolCallDelta.type !== "function")
11491
+ throw new InvalidResponseDataError({
11492
+ data: toolCallDelta,
11493
+ message: "Expected 'function' type."
11494
+ });
11495
+ if (name22 == null)
11496
+ throw new InvalidResponseDataError({
11497
+ data: toolCallDelta,
11498
+ message: "Expected 'function.name' to be a string."
11499
+ });
11500
+ let id = this.createToolCallId(wireId);
11501
+ this.controller.enqueue({
11502
+ type: "tool-input-start",
11503
+ id,
11504
+ toolName: name22
11505
+ });
11506
+ let toolCall = {
11507
+ id,
11508
+ index: index ?? void 0,
11509
+ sequence: this.toolCalls.length,
11510
+ type: "function",
11511
+ function: {
11512
+ name: name22,
11513
+ arguments: (_b22 = (_a22 = toolCallDelta.function) == null ? void 0 : _a22.arguments) != null ? _b22 : ""
11514
+ },
11515
+ argumentState: new StreamingToolCallArgumentState(
11516
+ (_d = (_c = toolCallDelta.function) == null ? void 0 : _c.arguments) != null ? _d : ""
11517
+ ),
11518
+ hasFinished: !1,
11519
+ metadata: (_e = this.extractMetadata) == null ? void 0 : _e.call(this, toolCallDelta)
11520
+ };
11521
+ return this.toolCalls.push(toolCall), wireId != null && this.associateWireId(toolCall, wireId), toolCall.function.arguments.length > 0 && this.controller.enqueue({
11522
+ type: "tool-input-delta",
11523
+ id: toolCall.id,
11524
+ delta: toolCall.function.arguments
11525
+ }), toolCall;
11526
+ }
11527
+ associateWireId(toolCall, wireId) {
11528
+ let toolCallsWithId = this.toolCallsById.get(wireId);
11529
+ toolCallsWithId == null && (toolCallsWithId = /* @__PURE__ */ new Set(), this.toolCallsById.set(wireId, toolCallsWithId)), toolCallsWithId.add(toolCall);
11530
+ }
11531
+ associateIndex(toolCall, index) {
11532
+ let toolCallsWithIndex = this.toolCallsByIndex.get(index);
11533
+ toolCallsWithIndex == null && (toolCallsWithIndex = /* @__PURE__ */ new Set(), this.toolCallsByIndex.set(index, toolCallsWithIndex)), toolCallsWithIndex.add(toolCall);
11534
+ }
11535
+ createToolCallId(wireId) {
11536
+ var _a22, _b22;
11537
+ if (wireId != null && !this.usedToolCallIds.has(wireId))
11538
+ return this.usedToolCallIds.add(wireId), wireId;
11539
+ let generatedId = (_a22 = this.getNonBlankString(this._generateId())) != null ? _a22 : "tool-call";
11540
+ if (!this.usedToolCallIds.has(generatedId))
11541
+ return this.usedToolCallIds.add(generatedId), generatedId;
11542
+ let initialSuffix = (_b22 = this.nextGeneratedIdSuffixes.get(generatedId)) != null ? _b22 : 1, maximumSuffix = initialSuffix + this.usedToolCallIds.size;
11543
+ for (let suffix = initialSuffix; suffix <= maximumSuffix; suffix++) {
11544
+ let suffixedId = `${generatedId}-${suffix}`;
11545
+ if (!this.usedToolCallIds.has(suffixedId))
11546
+ return this.usedToolCallIds.add(suffixedId), this.nextGeneratedIdSuffixes.set(generatedId, suffix + 1), suffixedId;
11547
+ }
11548
+ throw new Error("Failed to create a unique tool call ID.");
11549
+ }
11550
+ getNonBlankString(value) {
11551
+ return value != null && value.trim().length > 0 ? value : void 0;
11552
+ }
11553
+ processExistingToolCall(toolCall, toolCallDelta) {
11554
+ var _a22;
11555
+ !toolCall.hasFinished && ((_a22 = toolCallDelta.function) == null ? void 0 : _a22.arguments) != null && (toolCall.argumentState.append(toolCallDelta.function.arguments), toolCall.function.arguments += toolCallDelta.function.arguments, this.controller.enqueue({
11556
+ type: "tool-input-delta",
11557
+ id: toolCall.id,
11558
+ delta: toolCallDelta.function.arguments
11559
+ }));
11560
+ }
11561
+ finishToolCall(toolCall) {
11562
+ var _a22;
11563
+ this.controller.enqueue({
11564
+ type: "tool-input-end",
11565
+ id: toolCall.id
11566
+ });
11567
+ let providerMetadata = (_a22 = this.buildToolCallProviderMetadata) == null ? void 0 : _a22.call(
11568
+ this,
11569
+ toolCall.metadata
11570
+ );
11571
+ this.controller.enqueue({
11572
+ type: "tool-call",
11573
+ toolCallId: toolCall.id,
11574
+ toolName: toolCall.function.name,
11575
+ input: toolCall.function.arguments,
11576
+ ...providerMetadata ? { providerMetadata } : {}
11577
+ }), toolCall.hasFinished = !0;
11578
+ }
11579
+ };
10737
11580
  function withoutTrailingSlash(url2) {
10738
11581
  return url2?.replace(/\/$/, "");
10739
11582
  }
@@ -10766,19 +11609,24 @@ export {
10766
11609
  TooManyEmbeddingValuesForCallError,
10767
11610
  TypeValidationError,
10768
11611
  UnsupportedFunctionalityError,
11612
+ isJSONObject,
10769
11613
  toJSONSchema,
10770
11614
  safeParseAsync2 as safeParseAsync,
10771
11615
  external_exports,
10772
11616
  combineHeaders,
10773
11617
  createToolNameMapping,
10774
- delay,
10775
11618
  DelayedPromise,
10776
11619
  convertBase64ToUint8Array,
10777
11620
  convertUint8ArrayToBase64,
10778
11621
  convertToBase64,
10779
11622
  convertToFormData,
11623
+ cancelResponseBody,
10780
11624
  DownloadError,
11625
+ fetchWithValidatedRedirects,
11626
+ DEFAULT_MAX_DOWNLOAD_SIZE,
11627
+ readResponseWithSizeLimit,
10781
11628
  downloadBlob,
11629
+ EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL,
10782
11630
  createIdGenerator,
10783
11631
  generateId,
10784
11632
  getErrorMessage2,
@@ -10791,24 +11639,37 @@ export {
10791
11639
  loadApiKey,
10792
11640
  loadOptionalSetting,
10793
11641
  mediaTypeToExtension,
11642
+ secureJsonParse,
10794
11643
  lazySchema,
10795
11644
  jsonSchema,
10796
11645
  asSchema,
10797
11646
  zodSchema,
10798
11647
  validateTypes,
10799
11648
  safeValidateTypes,
11649
+ parseJSON,
10800
11650
  safeParseJSON,
10801
- isParsableJson,
11651
+ parseJsonEventStream,
10802
11652
  parseProviderOptions,
10803
11653
  postJsonToApi,
10804
11654
  postFormDataToApi,
10805
11655
  createProviderToolFactory,
10806
11656
  createProviderToolFactoryWithOutputSchema,
10807
11657
  resolve,
11658
+ retryWithExponentialBackoff,
10808
11659
  createJsonErrorResponseHandler,
10809
11660
  createEventSourceResponseHandler,
10810
11661
  createJsonResponseHandler,
10811
11662
  createBinaryResponseHandler,
11663
+ StreamingToolCallTracker,
10812
11664
  withoutTrailingSlash,
10813
- executeTool
11665
+ executeTool,
11666
+ MEDIA_KINDS,
11667
+ ALL_MEDIA,
11668
+ IMAGE_ONLY_MEDIA,
11669
+ connectorMedia,
11670
+ effectiveMediaSupport,
11671
+ mediaKindOf,
11672
+ mediaOmissionReason,
11673
+ mediaRefusals,
11674
+ unsupportedMediaInput
10814
11675
  };