@mastra/agent-builder 1.1.30-alpha.4 → 1.1.30-alpha.6

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/dist/index.js CHANGED
@@ -4548,12 +4548,12 @@ const shouldAbortWorkflow = (stepResult) => {
4548
4548
  return stepResult?.success === false || stepResult?.error;
4549
4549
  };
4550
4550
  //#endregion
4551
- //#region ../_vendored/ai_v5/dist/dist-t0U7Z3o0.js
4552
- var marker$2 = "vercel.ai.error";
4553
- var symbol$2 = Symbol.for(marker$2);
4554
- var _a$2;
4555
- var _b$2;
4556
- var AISDKError$1 = class _AISDKError extends (_b$2 = Error, _a$2 = symbol$2, _b$2) {
4551
+ //#region ../_vendored/ai_v5/dist/dist-D-EBFNkO.js
4552
+ var marker$1 = "vercel.ai.error";
4553
+ var symbol$1 = Symbol.for(marker$1);
4554
+ var _a$1;
4555
+ var _b$1;
4556
+ var AISDKError = class _AISDKError extends (_b$1 = Error, _a$1 = symbol$1, _b$1) {
4557
4557
  /**
4558
4558
  * Creates an AI SDK Error.
4559
4559
  *
@@ -4564,7 +4564,7 @@ var AISDKError$1 = class _AISDKError extends (_b$2 = Error, _a$2 = symbol$2, _b$
4564
4564
  */
4565
4565
  constructor({ name: name14, message, cause }) {
4566
4566
  super(message);
4567
- this[_a$2] = true;
4567
+ this[_a$1] = true;
4568
4568
  this.name = name14;
4569
4569
  this.cause = cause;
4570
4570
  }
@@ -4574,26 +4574,26 @@ var AISDKError$1 = class _AISDKError extends (_b$2 = Error, _a$2 = symbol$2, _b$
4574
4574
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
4575
4575
  */
4576
4576
  static isInstance(error) {
4577
- return _AISDKError.hasMarker(error, marker$2);
4577
+ return _AISDKError.hasMarker(error, marker$1);
4578
4578
  }
4579
4579
  static hasMarker(error, marker15) {
4580
4580
  const markerSymbol = Symbol.for(marker15);
4581
4581
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
4582
4582
  }
4583
4583
  };
4584
- var name$2 = "AI_APICallError";
4585
- var marker2$1$1 = `vercel.ai.error.${name$2}`;
4586
- var symbol2$1$1 = Symbol.for(marker2$1$1);
4587
- var _a2$1$1;
4588
- var _b2$1;
4589
- var APICallError$1 = class extends (_b2$1 = AISDKError$1, _a2$1$1 = symbol2$1$1, _b2$1) {
4584
+ var name$1 = "AI_APICallError";
4585
+ var marker2$1 = `vercel.ai.error.${name$1}`;
4586
+ var symbol2$1 = Symbol.for(marker2$1);
4587
+ var _a2$1;
4588
+ var _b2;
4589
+ (class extends (_b2 = AISDKError, _a2$1 = symbol2$1, _b2) {
4590
4590
  constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
4591
4591
  super({
4592
- name: name$2,
4592
+ name: name$1,
4593
4593
  message,
4594
4594
  cause
4595
4595
  });
4596
- this[_a2$1$1] = true;
4596
+ this[_a2$1] = true;
4597
4597
  this.url = url;
4598
4598
  this.requestBodyValues = requestBodyValues;
4599
4599
  this.statusCode = statusCode;
@@ -4603,148 +4603,148 @@ var APICallError$1 = class extends (_b2$1 = AISDKError$1, _a2$1$1 = symbol2$1$1,
4603
4603
  this.data = data;
4604
4604
  }
4605
4605
  static isInstance(error) {
4606
- return AISDKError$1.hasMarker(error, marker2$1$1);
4606
+ return AISDKError.hasMarker(error, marker2$1);
4607
4607
  }
4608
- };
4609
- var name2$1$1 = "AI_EmptyResponseBodyError";
4610
- var marker3$1$1 = `vercel.ai.error.${name2$1$1}`;
4611
- var symbol3$1$1 = Symbol.for(marker3$1$1);
4612
- var _a3$1$1;
4613
- var _b3$1;
4614
- var EmptyResponseBodyError$1 = class extends (_b3$1 = AISDKError$1, _a3$1$1 = symbol3$1$1, _b3$1) {
4608
+ });
4609
+ var name2$1 = "AI_EmptyResponseBodyError";
4610
+ var marker3$1 = `vercel.ai.error.${name2$1}`;
4611
+ var symbol3$1 = Symbol.for(marker3$1);
4612
+ var _a3$1;
4613
+ var _b3;
4614
+ (class extends (_b3 = AISDKError, _a3$1 = symbol3$1, _b3) {
4615
4615
  constructor({ message = "Empty response body" } = {}) {
4616
4616
  super({
4617
- name: name2$1$1,
4617
+ name: name2$1,
4618
4618
  message
4619
4619
  });
4620
- this[_a3$1$1] = true;
4620
+ this[_a3$1] = true;
4621
4621
  }
4622
4622
  static isInstance(error) {
4623
- return AISDKError$1.hasMarker(error, marker3$1$1);
4623
+ return AISDKError.hasMarker(error, marker3$1);
4624
4624
  }
4625
- };
4626
- function getErrorMessage$2(error) {
4625
+ });
4626
+ function getErrorMessage$1(error) {
4627
4627
  if (error == null) return "unknown error";
4628
4628
  if (typeof error === "string") return error;
4629
4629
  if (error instanceof Error) return error.message;
4630
4630
  return JSON.stringify(error);
4631
4631
  }
4632
- var name3$1$1 = "AI_InvalidArgumentError";
4633
- var marker4$1$1 = `vercel.ai.error.${name3$1$1}`;
4634
- var symbol4$1$1 = Symbol.for(marker4$1$1);
4635
- var _a4$1$1;
4636
- var _b4$1;
4637
- var InvalidArgumentError$1 = class extends (_b4$1 = AISDKError$1, _a4$1$1 = symbol4$1$1, _b4$1) {
4632
+ var name3$1 = "AI_InvalidArgumentError";
4633
+ var marker4$1 = `vercel.ai.error.${name3$1}`;
4634
+ var symbol4$1 = Symbol.for(marker4$1);
4635
+ var _a4$1;
4636
+ var _b4;
4637
+ var InvalidArgumentError = class extends (_b4 = AISDKError, _a4$1 = symbol4$1, _b4) {
4638
4638
  constructor({ message, cause, argument }) {
4639
4639
  super({
4640
- name: name3$1$1,
4640
+ name: name3$1,
4641
4641
  message,
4642
4642
  cause
4643
4643
  });
4644
- this[_a4$1$1] = true;
4644
+ this[_a4$1] = true;
4645
4645
  this.argument = argument;
4646
4646
  }
4647
4647
  static isInstance(error) {
4648
- return AISDKError$1.hasMarker(error, marker4$1$1);
4648
+ return AISDKError.hasMarker(error, marker4$1);
4649
4649
  }
4650
4650
  };
4651
- var name4$1$1 = "AI_InvalidPromptError";
4652
- var marker5$1$1 = `vercel.ai.error.${name4$1$1}`;
4653
- var symbol5$1$1 = Symbol.for(marker5$1$1);
4654
- var _a5$1$1;
4655
- var _b5$1;
4656
- (class extends (_b5$1 = AISDKError$1, _a5$1$1 = symbol5$1$1, _b5$1) {
4651
+ var name4$1 = "AI_InvalidPromptError";
4652
+ var marker5$1 = `vercel.ai.error.${name4$1}`;
4653
+ var symbol5$1 = Symbol.for(marker5$1);
4654
+ var _a5$1;
4655
+ var _b5;
4656
+ (class extends (_b5 = AISDKError, _a5$1 = symbol5$1, _b5) {
4657
4657
  constructor({ prompt, message, cause }) {
4658
4658
  super({
4659
- name: name4$1$1,
4659
+ name: name4$1,
4660
4660
  message: `Invalid prompt: ${message}`,
4661
4661
  cause
4662
4662
  });
4663
- this[_a5$1$1] = true;
4663
+ this[_a5$1] = true;
4664
4664
  this.prompt = prompt;
4665
4665
  }
4666
4666
  static isInstance(error) {
4667
- return AISDKError$1.hasMarker(error, marker5$1$1);
4667
+ return AISDKError.hasMarker(error, marker5$1);
4668
4668
  }
4669
4669
  });
4670
- var name5$1$1 = "AI_InvalidResponseDataError";
4671
- var marker6$1$1 = `vercel.ai.error.${name5$1$1}`;
4672
- var symbol6$1$1 = Symbol.for(marker6$1$1);
4673
- var _a6$1$1;
4674
- var _b6$1;
4675
- (class extends (_b6$1 = AISDKError$1, _a6$1$1 = symbol6$1$1, _b6$1) {
4670
+ var name5$1 = "AI_InvalidResponseDataError";
4671
+ var marker6$1 = `vercel.ai.error.${name5$1}`;
4672
+ var symbol6$1 = Symbol.for(marker6$1);
4673
+ var _a6$1;
4674
+ var _b6;
4675
+ (class extends (_b6 = AISDKError, _a6$1 = symbol6$1, _b6) {
4676
4676
  constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
4677
4677
  super({
4678
- name: name5$1$1,
4678
+ name: name5$1,
4679
4679
  message
4680
4680
  });
4681
- this[_a6$1$1] = true;
4681
+ this[_a6$1] = true;
4682
4682
  this.data = data;
4683
4683
  }
4684
4684
  static isInstance(error) {
4685
- return AISDKError$1.hasMarker(error, marker6$1$1);
4685
+ return AISDKError.hasMarker(error, marker6$1);
4686
4686
  }
4687
4687
  });
4688
- var name6$1$1 = "AI_JSONParseError";
4689
- var marker7$1$1 = `vercel.ai.error.${name6$1$1}`;
4690
- var symbol7$1$1 = Symbol.for(marker7$1$1);
4691
- var _a7$1$1;
4692
- var _b7$1;
4693
- var JSONParseError$1 = class extends (_b7$1 = AISDKError$1, _a7$1$1 = symbol7$1$1, _b7$1) {
4688
+ var name6$1 = "AI_JSONParseError";
4689
+ var marker7$1 = `vercel.ai.error.${name6$1}`;
4690
+ var symbol7$1 = Symbol.for(marker7$1);
4691
+ var _a7$1;
4692
+ var _b7;
4693
+ var JSONParseError = class extends (_b7 = AISDKError, _a7$1 = symbol7$1, _b7) {
4694
4694
  constructor({ text, cause }) {
4695
4695
  super({
4696
- name: name6$1$1,
4696
+ name: name6$1,
4697
4697
  message: `JSON parsing failed: Text: ${text}.
4698
- Error message: ${getErrorMessage$2(cause)}`,
4698
+ Error message: ${getErrorMessage$1(cause)}`,
4699
4699
  cause
4700
4700
  });
4701
- this[_a7$1$1] = true;
4701
+ this[_a7$1] = true;
4702
4702
  this.text = text;
4703
4703
  }
4704
4704
  static isInstance(error) {
4705
- return AISDKError$1.hasMarker(error, marker7$1$1);
4705
+ return AISDKError.hasMarker(error, marker7$1);
4706
4706
  }
4707
4707
  };
4708
- var name7$1$1 = "AI_LoadAPIKeyError";
4709
- var marker8$1$1 = `vercel.ai.error.${name7$1$1}`;
4710
- var symbol8$1$1 = Symbol.for(marker8$1$1);
4711
- var _a8$1$1;
4712
- var _b8$1;
4713
- (class extends (_b8$1 = AISDKError$1, _a8$1$1 = symbol8$1$1, _b8$1) {
4708
+ var name7$1 = "AI_LoadAPIKeyError";
4709
+ var marker8$1 = `vercel.ai.error.${name7$1}`;
4710
+ var symbol8$1 = Symbol.for(marker8$1);
4711
+ var _a8$1;
4712
+ var _b8;
4713
+ (class extends (_b8 = AISDKError, _a8$1 = symbol8$1, _b8) {
4714
4714
  constructor({ message }) {
4715
4715
  super({
4716
- name: name7$1$1,
4716
+ name: name7$1,
4717
4717
  message
4718
4718
  });
4719
- this[_a8$1$1] = true;
4719
+ this[_a8$1] = true;
4720
4720
  }
4721
4721
  static isInstance(error) {
4722
- return AISDKError$1.hasMarker(error, marker8$1$1);
4722
+ return AISDKError.hasMarker(error, marker8$1);
4723
4723
  }
4724
4724
  });
4725
- var name8$1$1 = "AI_LoadSettingError";
4726
- var marker9$1$1 = `vercel.ai.error.${name8$1$1}`;
4727
- var symbol9$1$1 = Symbol.for(marker9$1$1);
4728
- var _a9$1$1;
4729
- var _b9$1;
4730
- (class extends (_b9$1 = AISDKError$1, _a9$1$1 = symbol9$1$1, _b9$1) {
4725
+ var name8$1 = "AI_LoadSettingError";
4726
+ var marker9$1 = `vercel.ai.error.${name8$1}`;
4727
+ var symbol9$1 = Symbol.for(marker9$1);
4728
+ var _a9$1;
4729
+ var _b9;
4730
+ (class extends (_b9 = AISDKError, _a9$1 = symbol9$1, _b9) {
4731
4731
  constructor({ message }) {
4732
4732
  super({
4733
- name: name8$1$1,
4733
+ name: name8$1,
4734
4734
  message
4735
4735
  });
4736
- this[_a9$1$1] = true;
4736
+ this[_a9$1] = true;
4737
4737
  }
4738
4738
  static isInstance(error) {
4739
- return AISDKError$1.hasMarker(error, marker9$1$1);
4739
+ return AISDKError.hasMarker(error, marker9$1);
4740
4740
  }
4741
4741
  });
4742
4742
  var name9$1 = "AI_NoContentGeneratedError";
4743
4743
  var marker10$1 = `vercel.ai.error.${name9$1}`;
4744
4744
  var symbol10$1 = Symbol.for(marker10$1);
4745
4745
  var _a10$1;
4746
- var _b10$1;
4747
- (class extends (_b10$1 = AISDKError$1, _a10$1 = symbol10$1, _b10$1) {
4746
+ var _b10;
4747
+ (class extends (_b10 = AISDKError, _a10$1 = symbol10$1, _b10) {
4748
4748
  constructor({ message = "No content generated." } = {}) {
4749
4749
  super({
4750
4750
  name: name9$1,
@@ -4753,15 +4753,15 @@ var _b10$1;
4753
4753
  this[_a10$1] = true;
4754
4754
  }
4755
4755
  static isInstance(error) {
4756
- return AISDKError$1.hasMarker(error, marker10$1);
4756
+ return AISDKError.hasMarker(error, marker10$1);
4757
4757
  }
4758
4758
  });
4759
4759
  var name10$1 = "AI_NoSuchModelError";
4760
4760
  var marker11$1 = `vercel.ai.error.${name10$1}`;
4761
4761
  var symbol11$1 = Symbol.for(marker11$1);
4762
4762
  var _a11$1;
4763
- var _b11$1;
4764
- (class extends (_b11$1 = AISDKError$1, _a11$1 = symbol11$1, _b11$1) {
4763
+ var _b11;
4764
+ (class extends (_b11 = AISDKError, _a11$1 = symbol11$1, _b11) {
4765
4765
  constructor({ errorName = name10$1, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {
4766
4766
  super({
4767
4767
  name: errorName,
@@ -4772,15 +4772,15 @@ var _b11$1;
4772
4772
  this.modelType = modelType;
4773
4773
  }
4774
4774
  static isInstance(error) {
4775
- return AISDKError$1.hasMarker(error, marker11$1);
4775
+ return AISDKError.hasMarker(error, marker11$1);
4776
4776
  }
4777
4777
  });
4778
4778
  var name11$1 = "AI_TooManyEmbeddingValuesForCallError";
4779
4779
  var marker12$1 = `vercel.ai.error.${name11$1}`;
4780
4780
  var symbol12$1 = Symbol.for(marker12$1);
4781
4781
  var _a12$1;
4782
- var _b12$1;
4783
- (class extends (_b12$1 = AISDKError$1, _a12$1 = symbol12$1, _b12$1) {
4782
+ var _b12;
4783
+ (class extends (_b12 = AISDKError, _a12$1 = symbol12$1, _b12) {
4784
4784
  constructor(options) {
4785
4785
  super({
4786
4786
  name: name11$1,
@@ -4793,27 +4793,27 @@ var _b12$1;
4793
4793
  this.values = options.values;
4794
4794
  }
4795
4795
  static isInstance(error) {
4796
- return AISDKError$1.hasMarker(error, marker12$1);
4796
+ return AISDKError.hasMarker(error, marker12$1);
4797
4797
  }
4798
4798
  });
4799
4799
  var name12$1 = "AI_TypeValidationError";
4800
4800
  var marker13$1 = `vercel.ai.error.${name12$1}`;
4801
4801
  var symbol13$1 = Symbol.for(marker13$1);
4802
4802
  var _a13$1;
4803
- var _b13$1;
4804
- var TypeValidationError$1 = class _TypeValidationError extends (_b13$1 = AISDKError$1, _a13$1 = symbol13$1, _b13$1) {
4803
+ var _b13;
4804
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13$1 = symbol13$1, _b13) {
4805
4805
  constructor({ value, cause }) {
4806
4806
  super({
4807
4807
  name: name12$1,
4808
4808
  message: `Type validation failed: Value: ${JSON.stringify(value)}.
4809
- Error message: ${getErrorMessage$2(cause)}`,
4809
+ Error message: ${getErrorMessage$1(cause)}`,
4810
4810
  cause
4811
4811
  });
4812
4812
  this[_a13$1] = true;
4813
4813
  this.value = value;
4814
4814
  }
4815
4815
  static isInstance(error) {
4816
- return AISDKError$1.hasMarker(error, marker13$1);
4816
+ return AISDKError.hasMarker(error, marker13$1);
4817
4817
  }
4818
4818
  /**
4819
4819
  * Wraps an error into a TypeValidationError.
@@ -4836,8 +4836,8 @@ var name13$1 = "AI_UnsupportedFunctionalityError";
4836
4836
  var marker14$1 = `vercel.ai.error.${name13$1}`;
4837
4837
  var symbol14$1 = Symbol.for(marker14$1);
4838
4838
  var _a14$1;
4839
- var _b14$1;
4840
- (class extends (_b14$1 = AISDKError$1, _a14$1 = symbol14$1, _b14$1) {
4839
+ var _b14;
4840
+ (class extends (_b14 = AISDKError, _a14$1 = symbol14$1, _b14) {
4841
4841
  constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
4842
4842
  super({
4843
4843
  name: name13$1,
@@ -4847,238 +4847,31 @@ var _b14$1;
4847
4847
  this.functionality = functionality;
4848
4848
  }
4849
4849
  static isInstance(error) {
4850
- return AISDKError$1.hasMarker(error, marker14$1);
4850
+ return AISDKError.hasMarker(error, marker14$1);
4851
4851
  }
4852
4852
  });
4853
- var ParseError = class extends Error {
4854
- constructor(message, options) {
4855
- super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
4856
- }
4857
- };
4858
- const LF = 10;
4859
- const CR = 13;
4860
- const SPACE = 32;
4861
- function noop(_arg) {}
4862
- function createParser(callbacks) {
4863
- if (typeof callbacks == "function") throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
4864
- const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];
4865
- let isFirstChunk = !0, id, data = "", dataLines = 0, eventType;
4866
- function feed(chunk) {
4867
- if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
4868
- const trailing2 = processLines(chunk);
4869
- trailing2 !== "" && pendingFragments.push(trailing2);
4870
- return;
4871
- }
4872
- if (chunk.indexOf(`
4873
- `) === -1 && chunk.indexOf("\r") === -1) {
4874
- pendingFragments.push(chunk);
4875
- return;
4876
- }
4877
- pendingFragments.push(chunk);
4878
- const input = pendingFragments.join("");
4879
- pendingFragments.length = 0;
4880
- const trailing = processLines(input);
4881
- trailing !== "" && pendingFragments.push(trailing);
4882
- }
4883
- function processLines(chunk) {
4884
- let searchIndex = 0;
4885
- if (chunk.indexOf("\r") === -1) {
4886
- let lfIndex = chunk.indexOf(`
4887
- `, searchIndex);
4888
- for (; lfIndex !== -1;) {
4889
- if (searchIndex === lfIndex) {
4890
- dataLines > 0 && onEvent({
4891
- id,
4892
- event: eventType,
4893
- data
4894
- }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
4895
- `, searchIndex);
4896
- continue;
4897
- }
4898
- const firstCharCode = chunk.charCodeAt(searchIndex);
4899
- if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
4900
- const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
4901
- if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
4902
- onEvent({
4903
- id,
4904
- event: eventType,
4905
- data: value
4906
- }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
4907
- `, searchIndex);
4908
- continue;
4909
- }
4910
- data = dataLines === 0 ? value : `${data}
4911
- ${value}`, dataLines++;
4912
- } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0 : parseLine(chunk, searchIndex, lfIndex);
4913
- searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
4914
- `, searchIndex);
4915
- }
4916
- return chunk.slice(searchIndex);
4917
- }
4918
- for (; searchIndex < chunk.length;) {
4919
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
4920
- `, searchIndex);
4921
- let lineEnd = -1;
4922
- 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) break;
4923
- parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
4924
- }
4925
- return chunk.slice(searchIndex);
4926
- }
4927
- function parseLine(chunk, start, end) {
4928
- if (start === end) {
4929
- dispatchEvent();
4930
- return;
4931
- }
4932
- const firstCharCode = chunk.charCodeAt(start);
4933
- if (isDataPrefix(chunk, start, firstCharCode)) {
4934
- const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
4935
- data = dataLines === 0 ? value2 : `${data}
4936
- ${value2}`, dataLines++;
4937
- return;
4938
- }
4939
- if (isEventPrefix(chunk, start, firstCharCode)) {
4940
- eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
4941
- return;
4942
- }
4943
- if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
4944
- const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
4945
- id = value2.includes("\0") ? void 0 : value2;
4946
- return;
4947
- }
4948
- if (firstCharCode === 58) {
4949
- if (onComment) {
4950
- const line2 = chunk.slice(start, end);
4951
- onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
4952
- }
4953
- return;
4954
- }
4955
- const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
4956
- if (fieldSeparatorIndex === -1) {
4957
- processField(line, "", line);
4958
- return;
4959
- }
4960
- const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;
4961
- processField(field, line.slice(fieldSeparatorIndex + offset), line);
4962
- }
4963
- function processField(field, value, line) {
4964
- switch (field) {
4965
- case "event":
4966
- eventType = value || void 0;
4967
- break;
4968
- case "data":
4969
- data = dataLines === 0 ? value : `${data}
4970
- ${value}`, dataLines++;
4971
- break;
4972
- case "id":
4973
- id = value.includes("\0") ? void 0 : value;
4974
- break;
4975
- case "retry":
4976
- /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
4977
- type: "invalid-retry",
4978
- value,
4979
- line
4980
- }));
4981
- break;
4982
- default:
4983
- onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
4984
- type: "unknown-field",
4985
- field,
4986
- value,
4987
- line
4988
- }));
4989
- break;
4990
- }
4991
- }
4992
- function dispatchEvent() {
4993
- dataLines > 0 && onEvent({
4994
- id,
4995
- event: eventType,
4996
- data
4997
- }), id = void 0, data = "", dataLines = 0, eventType = void 0;
4998
- }
4999
- function reset(options = {}) {
5000
- if (options.consume && pendingFragments.length > 0) {
5001
- const incompleteLine = pendingFragments.join("");
5002
- parseLine(incompleteLine, 0, incompleteLine.length);
5003
- }
5004
- isFirstChunk = !0, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0;
5005
- }
5006
- return {
5007
- feed,
5008
- reset
5009
- };
5010
- }
5011
- function isDataPrefix(chunk, i, firstCharCode) {
5012
- return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
5013
- }
5014
- function isEventPrefix(chunk, i, firstCharCode) {
5015
- 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;
5016
- }
5017
- var EventSourceParserStream = class extends TransformStream {
5018
- constructor({ onError, onRetry, onComment } = {}) {
5019
- let parser;
5020
- super({
5021
- start(controller) {
5022
- parser = createParser({
5023
- onEvent: (event) => {
5024
- controller.enqueue(event);
5025
- },
5026
- onError(error) {
5027
- onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
5028
- },
5029
- onRetry,
5030
- onComment
5031
- });
5032
- },
5033
- transform(chunk) {
5034
- parser.feed(chunk);
5035
- }
5036
- });
5037
- }
5038
- };
5039
- function combineHeaders(...headers) {
5040
- return headers.reduce((combinedHeaders, currentHeaders) => ({
5041
- ...combinedHeaders,
5042
- ...currentHeaders
5043
- }), {});
5044
- }
5045
- function extractResponseHeaders(response) {
5046
- return Object.fromEntries([...response.headers]);
5047
- }
5048
- var name$1$1 = "AI_DownloadError";
5049
- var marker$1 = `vercel.ai.error.${name$1$1}`;
5050
- var symbol$1$1 = Symbol.for(marker$1);
5051
- var _a$1$1;
5052
- var _b$1;
5053
- var DownloadError = class extends (_b$1 = AISDKError$1, _a$1$1 = symbol$1$1, _b$1) {
4853
+ TransformStream;
4854
+ var name$2 = "AI_DownloadError";
4855
+ var marker$2 = `vercel.ai.error.${name$2}`;
4856
+ var symbol$2 = Symbol.for(marker$2);
4857
+ var _a$2;
4858
+ var _b;
4859
+ (class extends (_b = AISDKError, _a$2 = symbol$2, _b) {
5054
4860
  constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {
5055
4861
  super({
5056
- name: name$1$1,
4862
+ name: name$2,
5057
4863
  message,
5058
4864
  cause
5059
4865
  });
5060
- this[_a$1$1] = true;
4866
+ this[_a$2] = true;
5061
4867
  this.url = url;
5062
4868
  this.statusCode = statusCode;
5063
4869
  this.statusText = statusText;
5064
4870
  }
5065
4871
  static isInstance(error) {
5066
- return AISDKError$1.hasMarker(error, marker$1);
4872
+ return AISDKError.hasMarker(error, marker$2);
5067
4873
  }
5068
- };
5069
- async function cancelResponseBody(response) {
5070
- var _a2;
5071
- try {
5072
- await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
5073
- } catch (e) {}
5074
- }
5075
- var initialGlobalFetch = globalThis.fetch;
5076
- isNodeDefaultFetch(initialGlobalFetch);
5077
- function isNodeDefaultFetch(fetch) {
5078
- if (typeof fetch !== "function") return false;
5079
- const source = Function.prototype.toString.call(fetch);
5080
- return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
5081
- }
4874
+ });
5082
4875
  function getCurrentModulePath() {
5083
4876
  const originalPrepareStackTrace = Error.prepareStackTrace;
5084
4877
  try {
@@ -5093,50 +4886,6 @@ function getCurrentModulePath() {
5093
4886
  Error.prepareStackTrace = originalPrepareStackTrace;
5094
4887
  }
5095
4888
  }
5096
- var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
5097
- async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) {
5098
- const contentLength = response.headers.get("content-length");
5099
- if (contentLength != null) {
5100
- const length = parseInt(contentLength, 10);
5101
- if (!isNaN(length) && length > maxBytes) {
5102
- await cancelResponseBody(response);
5103
- throw new DownloadError({
5104
- url,
5105
- message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`
5106
- });
5107
- }
5108
- }
5109
- const body = response.body;
5110
- if (body == null) return /* @__PURE__ */ new Uint8Array(0);
5111
- const reader = body.getReader();
5112
- const chunks = [];
5113
- let totalBytes = 0;
5114
- try {
5115
- while (true) {
5116
- const { done, value } = await reader.read();
5117
- if (done) break;
5118
- totalBytes += value.length;
5119
- if (totalBytes > maxBytes) throw new DownloadError({
5120
- url,
5121
- message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
5122
- });
5123
- chunks.push(value);
5124
- }
5125
- } finally {
5126
- try {
5127
- await reader.cancel();
5128
- } catch (e) {} finally {
5129
- reader.releaseLock();
5130
- }
5131
- }
5132
- const result = new Uint8Array(totalBytes);
5133
- let offset = 0;
5134
- for (const chunk of chunks) {
5135
- result.set(chunk, offset);
5136
- offset += chunk.length;
5137
- }
5138
- return result;
5139
- }
5140
4889
  var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
5141
4890
  const generator = () => {
5142
4891
  const alphabetLength = alphabet.length;
@@ -5145,166 +4894,13 @@ var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKL
5145
4894
  return chars.join("");
5146
4895
  };
5147
4896
  if (prefix == null) return generator;
5148
- if (alphabet.includes(separator)) throw new InvalidArgumentError$1({
4897
+ if (alphabet.includes(separator)) throw new InvalidArgumentError({
5149
4898
  argument: "separator",
5150
4899
  message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
5151
4900
  });
5152
4901
  return () => `${prefix}${separator}${generator()}`;
5153
4902
  };
5154
4903
  createIdGenerator();
5155
- function isAbortError(error) {
5156
- return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
5157
- }
5158
- var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
5159
- var RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
5160
- "ConnectionRefused",
5161
- "ConnectionClosed",
5162
- "FailedToOpenSocket",
5163
- "ECONNRESET",
5164
- "ECONNREFUSED",
5165
- "ETIMEDOUT",
5166
- "EPIPE",
5167
- "UND_ERR_SOCKET",
5168
- "UND_ERR_HEADERS_TIMEOUT",
5169
- "UND_ERR_BODY_TIMEOUT",
5170
- "UND_ERR_CONNECT_TIMEOUT"
5171
- ]);
5172
- function findNetworkError(error) {
5173
- const visited = /* @__PURE__ */ new Set();
5174
- let current = error;
5175
- while (current instanceof Error && !visited.has(current)) {
5176
- visited.add(current);
5177
- const errorWithCode = current;
5178
- if (typeof errorWithCode.code === "string" && RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code)) return errorWithCode;
5179
- current = current.cause;
5180
- }
5181
- }
5182
- function handleFetchError({ error, url, requestBodyValues }) {
5183
- if (isAbortError(error)) return error;
5184
- if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
5185
- const cause = error.cause;
5186
- if (cause != null) return new APICallError$1({
5187
- message: `Cannot connect to API: ${cause.message}`,
5188
- cause,
5189
- url,
5190
- requestBodyValues,
5191
- isRetryable: true
5192
- });
5193
- }
5194
- const networkError = findNetworkError(error);
5195
- if (networkError != null) {
5196
- if (APICallError$1.isInstance(error)) return new APICallError$1({
5197
- message: error.message,
5198
- cause: error.cause,
5199
- url: error.url,
5200
- requestBodyValues: error.requestBodyValues,
5201
- statusCode: error.statusCode,
5202
- responseHeaders: error.responseHeaders,
5203
- responseBody: error.responseBody,
5204
- data: error.data,
5205
- isRetryable: true
5206
- });
5207
- return new APICallError$1({
5208
- message: `Cannot connect to API: ${error instanceof Error ? error.message : networkError.message}`,
5209
- cause: error,
5210
- url,
5211
- requestBodyValues,
5212
- isRetryable: true
5213
- });
5214
- }
5215
- return error;
5216
- }
5217
- function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
5218
- var _a2, _b2, _c;
5219
- if (globalThisAny.window) return `runtime/browser`;
5220
- if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
5221
- if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
5222
- if (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`;
5223
- return "runtime/unknown";
5224
- }
5225
- function normalizeHeaders(headers) {
5226
- if (headers == null) return {};
5227
- const normalized = {};
5228
- if (headers instanceof Headers) headers.forEach((value, key) => {
5229
- normalized[key.toLowerCase()] = value;
5230
- });
5231
- else {
5232
- if (!Array.isArray(headers)) headers = Object.entries(headers);
5233
- for (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;
5234
- }
5235
- return normalized;
5236
- }
5237
- function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
5238
- const normalizedHeaders = new Headers(normalizeHeaders(headers));
5239
- const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
5240
- normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
5241
- return Object.fromEntries(normalizedHeaders.entries());
5242
- }
5243
- var VERSION$3 = "3.0.40";
5244
- var getOriginalFetch = () => globalThis.fetch;
5245
- var getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch() }) => {
5246
- try {
5247
- const response = await fetch(url, {
5248
- method: "GET",
5249
- headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION$3}`, getRuntimeEnvironmentUserAgent()),
5250
- signal: abortSignal
5251
- });
5252
- const responseHeaders = extractResponseHeaders(response);
5253
- if (!response.ok) {
5254
- let errorInformation;
5255
- try {
5256
- errorInformation = await failedResponseHandler({
5257
- response,
5258
- url,
5259
- requestBodyValues: {}
5260
- });
5261
- } catch (error) {
5262
- if (isAbortError(error) || APICallError$1.isInstance(error)) throw error;
5263
- throw new APICallError$1({
5264
- message: "Failed to process error response",
5265
- cause: error,
5266
- statusCode: response.status,
5267
- url,
5268
- responseHeaders,
5269
- requestBodyValues: {}
5270
- });
5271
- }
5272
- throw errorInformation.value;
5273
- }
5274
- try {
5275
- return await successfulResponseHandler({
5276
- response,
5277
- url,
5278
- requestBodyValues: {}
5279
- });
5280
- } catch (error) {
5281
- if (error instanceof Error) {
5282
- if (isAbortError(error) || APICallError$1.isInstance(error)) throw error;
5283
- }
5284
- throw new APICallError$1({
5285
- message: "Failed to process successful response",
5286
- cause: error,
5287
- statusCode: response.status,
5288
- url,
5289
- responseHeaders,
5290
- requestBodyValues: {}
5291
- });
5292
- }
5293
- } catch (error) {
5294
- throw handleFetchError({
5295
- error,
5296
- url,
5297
- requestBodyValues: {}
5298
- });
5299
- }
5300
- };
5301
- function loadOptionalSetting({ settingValue, environmentVariableName }) {
5302
- if (typeof settingValue === "string") return settingValue;
5303
- if (settingValue != null || typeof process === "undefined") return;
5304
- settingValue = process.env[environmentVariableName];
5305
- if (settingValue == null || typeof settingValue !== "string") return;
5306
- return settingValue;
5307
- }
5308
4904
  var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
5309
4905
  var 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*:/;
5310
4906
  function _parse(text) {
@@ -5352,13 +4948,6 @@ function validator(validate) {
5352
4948
  function isValidator(value) {
5353
4949
  return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
5354
4950
  }
5355
- function lazyValidator(createValidator) {
5356
- let validator2;
5357
- return () => {
5358
- if (validator2 == null) validator2 = createValidator();
5359
- return validator2;
5360
- };
5361
- }
5362
4951
  function asValidator(value) {
5363
4952
  return isValidator(value) ? value : "~standard" in value ? standardSchemaValidator(value) : value();
5364
4953
  }
@@ -5370,24 +4959,13 @@ function standardSchemaValidator(standardSchema) {
5370
4959
  value: result.value
5371
4960
  } : {
5372
4961
  success: false,
5373
- error: new TypeValidationError$1({
4962
+ error: new TypeValidationError({
5374
4963
  value,
5375
4964
  cause: result.issues
5376
4965
  })
5377
4966
  };
5378
4967
  });
5379
4968
  }
5380
- async function validateTypes({ value, schema }) {
5381
- const result = await safeValidateTypes({
5382
- value,
5383
- schema
5384
- });
5385
- if (!result.success) throw TypeValidationError$1.wrap({
5386
- value,
5387
- cause: result.error
5388
- });
5389
- return result.value;
5390
- }
5391
4969
  async function safeValidateTypes({ value, schema }) {
5392
4970
  const validator2 = asValidator(schema);
5393
4971
  try {
@@ -5404,7 +4982,7 @@ async function safeValidateTypes({ value, schema }) {
5404
4982
  };
5405
4983
  return {
5406
4984
  success: false,
5407
- error: TypeValidationError$1.wrap({
4985
+ error: TypeValidationError.wrap({
5408
4986
  value,
5409
4987
  cause: result.error
5410
4988
  }),
@@ -5413,7 +4991,7 @@ async function safeValidateTypes({ value, schema }) {
5413
4991
  } catch (error) {
5414
4992
  return {
5415
4993
  success: false,
5416
- error: TypeValidationError$1.wrap({
4994
+ error: TypeValidationError.wrap({
5417
4995
  value,
5418
4996
  cause: error
5419
4997
  }),
@@ -5421,22 +4999,6 @@ async function safeValidateTypes({ value, schema }) {
5421
4999
  };
5422
5000
  }
5423
5001
  }
5424
- async function parseJSON({ text, schema }) {
5425
- try {
5426
- const value = secureJsonParse(text);
5427
- if (schema == null) return value;
5428
- return validateTypes({
5429
- value,
5430
- schema
5431
- });
5432
- } catch (error) {
5433
- if (JSONParseError$1.isInstance(error) || TypeValidationError$1.isInstance(error)) throw error;
5434
- throw new JSONParseError$1({
5435
- text,
5436
- cause: error
5437
- });
5438
- }
5439
- }
5440
5002
  async function safeParseJSON({ text, schema }) {
5441
5003
  try {
5442
5004
  const value = secureJsonParse(text);
@@ -5452,7 +5014,7 @@ async function safeParseJSON({ text, schema }) {
5452
5014
  } catch (error) {
5453
5015
  return {
5454
5016
  success: false,
5455
- error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({
5017
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({
5456
5018
  text,
5457
5019
  cause: error
5458
5020
  }),
@@ -5460,264 +5022,8 @@ async function safeParseJSON({ text, schema }) {
5460
5022
  };
5461
5023
  }
5462
5024
  }
5463
- function parseJsonEventStream({ stream, schema }) {
5464
- return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new TransformStream({ async transform({ data }, controller) {
5465
- if (data === "[DONE]") return;
5466
- controller.enqueue(await safeParseJSON({
5467
- text: data,
5468
- schema
5469
- }));
5470
- } }));
5471
- }
5472
- var getOriginalFetch2 = () => globalThis.fetch;
5473
- var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi({
5474
- url,
5475
- headers: {
5476
- "Content-Type": "application/json",
5477
- ...headers
5478
- },
5479
- body: {
5480
- content: JSON.stringify(body),
5481
- values: body
5482
- },
5483
- failedResponseHandler,
5484
- successfulResponseHandler,
5485
- abortSignal,
5486
- fetch
5487
- });
5488
- var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2() }) => {
5489
- try {
5490
- const response = await fetch(url, {
5491
- method: "POST",
5492
- headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION$3}`, getRuntimeEnvironmentUserAgent()),
5493
- body: body.content,
5494
- signal: abortSignal
5495
- });
5496
- const responseHeaders = extractResponseHeaders(response);
5497
- if (!response.ok) {
5498
- let errorInformation;
5499
- try {
5500
- errorInformation = await failedResponseHandler({
5501
- response,
5502
- url,
5503
- requestBodyValues: body.values
5504
- });
5505
- } catch (error) {
5506
- if (isAbortError(error) || APICallError$1.isInstance(error)) throw error;
5507
- throw new APICallError$1({
5508
- message: "Failed to process error response",
5509
- cause: error,
5510
- statusCode: response.status,
5511
- url,
5512
- responseHeaders,
5513
- requestBodyValues: body.values
5514
- });
5515
- }
5516
- throw errorInformation.value;
5517
- }
5518
- try {
5519
- return await successfulResponseHandler({
5520
- response,
5521
- url,
5522
- requestBodyValues: body.values
5523
- });
5524
- } catch (error) {
5525
- if (error instanceof Error) {
5526
- if (isAbortError(error) || APICallError$1.isInstance(error)) throw error;
5527
- }
5528
- throw new APICallError$1({
5529
- message: "Failed to process successful response",
5530
- cause: error,
5531
- statusCode: response.status,
5532
- url,
5533
- responseHeaders,
5534
- requestBodyValues: body.values
5535
- });
5536
- }
5537
- } catch (error) {
5538
- throw handleFetchError({
5539
- error,
5540
- url,
5541
- requestBodyValues: body.values
5542
- });
5543
- }
5544
- };
5545
- function tool(tool2) {
5546
- return tool2;
5547
- }
5548
- function createProviderDefinedToolFactoryWithOutputSchema({ id, name: name2, inputSchema, outputSchema }) {
5549
- return ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({
5550
- type: "provider-defined",
5551
- id,
5552
- name: name2,
5553
- args,
5554
- inputSchema,
5555
- outputSchema,
5556
- execute,
5557
- toModelOutput,
5558
- onInputStart,
5559
- onInputDelta,
5560
- onInputAvailable
5561
- });
5562
- }
5563
- async function resolve$1(value) {
5564
- if (typeof value === "function") value = value();
5565
- return Promise.resolve(value);
5566
- }
5567
- var textDecoder = new TextDecoder();
5568
- function wrapResponseBodyStream({ stream, url, requestBodyValues, statusCode, responseHeaders }) {
5569
- const reader = stream.getReader();
5570
- let readerReleased = false;
5571
- const releaseReader = () => {
5572
- if (!readerReleased) {
5573
- reader.releaseLock();
5574
- readerReleased = true;
5575
- }
5576
- };
5577
- return new ReadableStream({
5578
- async pull(controller) {
5579
- try {
5580
- const { done, value } = await reader.read();
5581
- if (done) {
5582
- releaseReader();
5583
- controller.close();
5584
- } else controller.enqueue(value);
5585
- } catch (error) {
5586
- releaseReader();
5587
- if (isAbortError(error)) {
5588
- controller.error(error);
5589
- return;
5590
- }
5591
- controller.error(handleFetchError({
5592
- error: new APICallError$1({
5593
- message: "Failed to process successful response",
5594
- cause: error,
5595
- statusCode,
5596
- url,
5597
- responseHeaders,
5598
- requestBodyValues
5599
- }),
5600
- url,
5601
- requestBodyValues
5602
- }));
5603
- }
5604
- },
5605
- async cancel(reason) {
5606
- try {
5607
- await reader.cancel(reason);
5608
- } finally {
5609
- releaseReader();
5610
- }
5611
- }
5612
- });
5613
- }
5614
- async function readResponseBodyAsText({ response, url }) {
5615
- return textDecoder.decode(await readResponseWithSizeLimit({
5616
- response,
5617
- url
5618
- }));
5619
- }
5620
- var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {
5621
- const responseBody = await readResponseBodyAsText({
5622
- response,
5623
- url
5624
- });
5625
- const responseHeaders = extractResponseHeaders(response);
5626
- if (responseBody.trim() === "") return {
5627
- responseHeaders,
5628
- value: new APICallError$1({
5629
- message: response.statusText,
5630
- url,
5631
- requestBodyValues,
5632
- statusCode: response.status,
5633
- responseHeaders,
5634
- responseBody,
5635
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5636
- })
5637
- };
5638
- try {
5639
- const parsedError = await parseJSON({
5640
- text: responseBody,
5641
- schema: errorSchema
5642
- });
5643
- return {
5644
- responseHeaders,
5645
- value: new APICallError$1({
5646
- message: errorToMessage(parsedError),
5647
- url,
5648
- requestBodyValues,
5649
- statusCode: response.status,
5650
- responseHeaders,
5651
- responseBody,
5652
- data: parsedError,
5653
- isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
5654
- })
5655
- };
5656
- } catch (parseError) {
5657
- return {
5658
- responseHeaders,
5659
- value: new APICallError$1({
5660
- message: response.statusText,
5661
- url,
5662
- requestBodyValues,
5663
- statusCode: response.status,
5664
- responseHeaders,
5665
- responseBody,
5666
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5667
- })
5668
- };
5669
- }
5670
- };
5671
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response, url, requestBodyValues }) => {
5672
- const responseHeaders = extractResponseHeaders(response);
5673
- if (response.body == null) throw new EmptyResponseBodyError$1({});
5674
- return {
5675
- responseHeaders,
5676
- value: parseJsonEventStream({
5677
- stream: wrapResponseBodyStream({
5678
- stream: response.body,
5679
- url,
5680
- requestBodyValues,
5681
- statusCode: response.status,
5682
- responseHeaders
5683
- }),
5684
- schema: chunkSchema
5685
- })
5686
- };
5687
- };
5688
- var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
5689
- const responseBody = await readResponseBodyAsText({
5690
- response,
5691
- url
5692
- });
5693
- const parsedResult = await safeParseJSON({
5694
- text: responseBody,
5695
- schema: responseSchema
5696
- });
5697
- const responseHeaders = extractResponseHeaders(response);
5698
- if (!parsedResult.success) throw new APICallError$1({
5699
- message: "Invalid JSON response",
5700
- cause: parsedResult.error,
5701
- statusCode: response.status,
5702
- responseHeaders,
5703
- responseBody,
5704
- url,
5705
- requestBodyValues
5706
- });
5707
- return {
5708
- responseHeaders,
5709
- value: parsedResult.value,
5710
- rawValue: parsedResult.rawValue
5711
- };
5712
- };
5025
+ new TextDecoder();
5713
5026
  var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
5714
- function lazySchema(createSchema) {
5715
- let schema;
5716
- return () => {
5717
- if (schema == null) schema = createSchema();
5718
- return schema;
5719
- };
5720
- }
5721
5027
  function jsonSchema(jsonSchema2, { validate } = {}) {
5722
5028
  return {
5723
5029
  [schemaSymbol]: true,
@@ -6675,1388 +5981,9 @@ function asSchema(schema) {
6675
5981
  additionalProperties: false
6676
5982
  }) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
6677
5983
  }
6678
- var { btoa, atob } = globalThis;
6679
- function withoutTrailingSlash(url) {
6680
- return url == null ? void 0 : url.replace(/\/$/, "");
6681
- }
6682
- var marker$3 = "vercel.ai.error";
6683
- var symbol$3 = Symbol.for(marker$3);
6684
- var _a$3;
6685
- var _b$3;
6686
- var AISDKError = class _AISDKError extends (_b$3 = Error, _a$3 = symbol$3, _b$3) {
6687
- /**
6688
- * Creates an AI SDK Error.
6689
- *
6690
- * @param {Object} params - The parameters for creating the error.
6691
- * @param {string} params.name - The name of the error.
6692
- * @param {string} params.message - The error message.
6693
- * @param {unknown} [params.cause] - The underlying cause of the error.
6694
- */
6695
- constructor({ name: name14, message, cause }) {
6696
- super(message);
6697
- this[_a$3] = true;
6698
- this.name = name14;
6699
- this.cause = cause;
6700
- }
6701
- /**
6702
- * Checks if the given error is an AI SDK Error.
6703
- * @param {unknown} error - The error to check.
6704
- * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
6705
- */
6706
- static isInstance(error) {
6707
- return _AISDKError.hasMarker(error, marker$3);
6708
- }
6709
- static hasMarker(error, marker15) {
6710
- const markerSymbol = Symbol.for(marker15);
6711
- return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
6712
- }
6713
- };
6714
- var name$3 = "AI_APICallError";
6715
- var marker2$2 = `vercel.ai.error.${name$3}`;
6716
- var symbol2$2 = Symbol.for(marker2$2);
6717
- var _a2$2;
6718
- var _b2$2;
6719
- var APICallError = class extends (_b2$2 = AISDKError, _a2$2 = symbol2$2, _b2$2) {
6720
- constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
6721
- super({
6722
- name: name$3,
6723
- message,
6724
- cause
6725
- });
6726
- this[_a2$2] = true;
6727
- this.url = url;
6728
- this.requestBodyValues = requestBodyValues;
6729
- this.statusCode = statusCode;
6730
- this.responseHeaders = responseHeaders;
6731
- this.responseBody = responseBody;
6732
- this.isRetryable = isRetryable;
6733
- this.data = data;
6734
- }
6735
- static isInstance(error) {
6736
- return AISDKError.hasMarker(error, marker2$2);
6737
- }
6738
- };
6739
- var name2$2 = "AI_EmptyResponseBodyError";
6740
- var marker3$2 = `vercel.ai.error.${name2$2}`;
6741
- var symbol3$2 = Symbol.for(marker3$2);
6742
- var _a3$2;
6743
- var _b3$2;
6744
- (class extends (_b3$2 = AISDKError, _a3$2 = symbol3$2, _b3$2) {
6745
- constructor({ message = "Empty response body" } = {}) {
6746
- super({
6747
- name: name2$2,
6748
- message
6749
- });
6750
- this[_a3$2] = true;
6751
- }
6752
- static isInstance(error) {
6753
- return AISDKError.hasMarker(error, marker3$2);
6754
- }
6755
- });
6756
- function getErrorMessage(error) {
6757
- if (error == null) return "unknown error";
6758
- if (typeof error === "string") return error;
6759
- if (error instanceof Error) return error.message;
6760
- return JSON.stringify(error);
6761
- }
6762
- var name3$2 = "AI_InvalidArgumentError";
6763
- var marker4$2 = `vercel.ai.error.${name3$2}`;
6764
- var symbol4$2 = Symbol.for(marker4$2);
6765
- var _a4$2;
6766
- var _b4$2;
6767
- (class extends (_b4$2 = AISDKError, _a4$2 = symbol4$2, _b4$2) {
6768
- constructor({ message, cause, argument }) {
6769
- super({
6770
- name: name3$2,
6771
- message,
6772
- cause
6773
- });
6774
- this[_a4$2] = true;
6775
- this.argument = argument;
6776
- }
6777
- static isInstance(error) {
6778
- return AISDKError.hasMarker(error, marker4$2);
6779
- }
6780
- });
6781
- var name4$2 = "AI_InvalidPromptError";
6782
- var marker5$2 = `vercel.ai.error.${name4$2}`;
6783
- var symbol5$2 = Symbol.for(marker5$2);
6784
- var _a5$2;
6785
- var _b5$2;
6786
- (class extends (_b5$2 = AISDKError, _a5$2 = symbol5$2, _b5$2) {
6787
- constructor({ prompt, message, cause }) {
6788
- super({
6789
- name: name4$2,
6790
- message: `Invalid prompt: ${message}`,
6791
- cause
6792
- });
6793
- this[_a5$2] = true;
6794
- this.prompt = prompt;
6795
- }
6796
- static isInstance(error) {
6797
- return AISDKError.hasMarker(error, marker5$2);
6798
- }
6799
- });
6800
- var name5$2 = "AI_InvalidResponseDataError";
6801
- var marker6$2 = `vercel.ai.error.${name5$2}`;
6802
- var symbol6$2 = Symbol.for(marker6$2);
6803
- var _a6$2;
6804
- var _b6$2;
6805
- (class extends (_b6$2 = AISDKError, _a6$2 = symbol6$2, _b6$2) {
6806
- constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
6807
- super({
6808
- name: name5$2,
6809
- message
6810
- });
6811
- this[_a6$2] = true;
6812
- this.data = data;
6813
- }
6814
- static isInstance(error) {
6815
- return AISDKError.hasMarker(error, marker6$2);
6816
- }
6817
- });
6818
- var name6$2 = "AI_JSONParseError";
6819
- var marker7$2 = `vercel.ai.error.${name6$2}`;
6820
- var symbol7$2 = Symbol.for(marker7$2);
6821
- var _a7$2;
6822
- var _b7$2;
6823
- (class extends (_b7$2 = AISDKError, _a7$2 = symbol7$2, _b7$2) {
6824
- constructor({ text, cause }) {
6825
- super({
6826
- name: name6$2,
6827
- message: `JSON parsing failed: Text: ${text}.
6828
- Error message: ${getErrorMessage(cause)}`,
6829
- cause
6830
- });
6831
- this[_a7$2] = true;
6832
- this.text = text;
6833
- }
6834
- static isInstance(error) {
6835
- return AISDKError.hasMarker(error, marker7$2);
6836
- }
6837
- });
6838
- var name7$2 = "AI_LoadAPIKeyError";
6839
- var marker8$2 = `vercel.ai.error.${name7$2}`;
6840
- var symbol8$2 = Symbol.for(marker8$2);
6841
- var _a8$2;
6842
- var _b8$2;
6843
- (class extends (_b8$2 = AISDKError, _a8$2 = symbol8$2, _b8$2) {
6844
- constructor({ message }) {
6845
- super({
6846
- name: name7$2,
6847
- message
6848
- });
6849
- this[_a8$2] = true;
6850
- }
6851
- static isInstance(error) {
6852
- return AISDKError.hasMarker(error, marker8$2);
6853
- }
6854
- });
6855
- var name8$2 = "AI_LoadSettingError";
6856
- var marker9$2 = `vercel.ai.error.${name8$2}`;
6857
- var symbol9$2 = Symbol.for(marker9$2);
6858
- var _a9$2;
6859
- var _b9$2;
6860
- (class extends (_b9$2 = AISDKError, _a9$2 = symbol9$2, _b9$2) {
6861
- constructor({ message }) {
6862
- super({
6863
- name: name8$2,
6864
- message
6865
- });
6866
- this[_a9$2] = true;
6867
- }
6868
- static isInstance(error) {
6869
- return AISDKError.hasMarker(error, marker9$2);
6870
- }
6871
- });
6872
- var name9$2 = "AI_NoContentGeneratedError";
6873
- var marker10$2 = `vercel.ai.error.${name9$2}`;
6874
- var symbol10$2 = Symbol.for(marker10$2);
6875
- var _a10$2;
6876
- var _b10;
6877
- (class extends (_b10 = AISDKError, _a10$2 = symbol10$2, _b10) {
6878
- constructor({ message = "No content generated." } = {}) {
6879
- super({
6880
- name: name9$2,
6881
- message
6882
- });
6883
- this[_a10$2] = true;
6884
- }
6885
- static isInstance(error) {
6886
- return AISDKError.hasMarker(error, marker10$2);
6887
- }
6888
- });
6889
- var name10$2 = "AI_NoSuchModelError";
6890
- var marker11$2 = `vercel.ai.error.${name10$2}`;
6891
- var symbol11$2 = Symbol.for(marker11$2);
6892
- var _a11$2;
6893
- var _b11;
6894
- (class extends (_b11 = AISDKError, _a11$2 = symbol11$2, _b11) {
6895
- constructor({ errorName = name10$2, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {
6896
- super({
6897
- name: errorName,
6898
- message
6899
- });
6900
- this[_a11$2] = true;
6901
- this.modelId = modelId;
6902
- this.modelType = modelType;
6903
- }
6904
- static isInstance(error) {
6905
- return AISDKError.hasMarker(error, marker11$2);
6906
- }
6907
- });
6908
- var name11$2 = "AI_TooManyEmbeddingValuesForCallError";
6909
- var marker12$2 = `vercel.ai.error.${name11$2}`;
6910
- var symbol12$2 = Symbol.for(marker12$2);
6911
- var _a12$2;
6912
- var _b12;
6913
- (class extends (_b12 = AISDKError, _a12$2 = symbol12$2, _b12) {
6914
- constructor(options) {
6915
- super({
6916
- name: name11$2,
6917
- message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
6918
- });
6919
- this[_a12$2] = true;
6920
- this.provider = options.provider;
6921
- this.modelId = options.modelId;
6922
- this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
6923
- this.values = options.values;
6924
- }
6925
- static isInstance(error) {
6926
- return AISDKError.hasMarker(error, marker12$2);
6927
- }
6928
- });
6929
- var name12$2 = "AI_TypeValidationError";
6930
- var marker13$2 = `vercel.ai.error.${name12$2}`;
6931
- var symbol13$2 = Symbol.for(marker13$2);
6932
- var _a13$2;
6933
- var _b13;
6934
- (class _TypeValidationError extends (_b13 = AISDKError, _a13$2 = symbol13$2, _b13) {
6935
- constructor({ value, cause }) {
6936
- super({
6937
- name: name12$2,
6938
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
6939
- Error message: ${getErrorMessage(cause)}`,
6940
- cause
6941
- });
6942
- this[_a13$2] = true;
6943
- this.value = value;
6944
- }
6945
- static isInstance(error) {
6946
- return AISDKError.hasMarker(error, marker13$2);
6947
- }
6948
- /**
6949
- * Wraps an error into a TypeValidationError.
6950
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
6951
- * Otherwise, it creates a new TypeValidationError.
6952
- *
6953
- * @param {Object} params - The parameters for wrapping the error.
6954
- * @param {unknown} params.value - The value that failed validation.
6955
- * @param {unknown} params.cause - The original error or cause of the validation failure.
6956
- * @returns {TypeValidationError} A TypeValidationError instance.
6957
- */
6958
- static wrap({ value, cause }) {
6959
- return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({
6960
- value,
6961
- cause
6962
- });
6963
- }
6964
- });
6965
- var name13$2 = "AI_UnsupportedFunctionalityError";
6966
- var marker14$2 = `vercel.ai.error.${name13$2}`;
6967
- var symbol14$2 = Symbol.for(marker14$2);
6968
- var _a14$2;
6969
- var _b14;
6970
- (class extends (_b14 = AISDKError, _a14$2 = symbol14$2, _b14) {
6971
- constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
6972
- super({
6973
- name: name13$2,
6974
- message
6975
- });
6976
- this[_a14$2] = true;
6977
- this.functionality = functionality;
6978
- }
6979
- static isInstance(error) {
6980
- return AISDKError.hasMarker(error, marker14$2);
6981
- }
6982
- });
5984
+ var { btoa, atob: atob$1 } = globalThis;
6983
5985
  //#endregion
6984
5986
  //#region ../_vendored/ai_v5/dist/index.js
6985
- function getContext() {
6986
- return { headers: {} };
6987
- }
6988
- async function getVercelOidcToken() {
6989
- if (process.env.VERCEL_OIDC_TOKEN) return process.env.VERCEL_OIDC_TOKEN ?? "";
6990
- throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
6991
- }
6992
- var symbol$1 = Symbol.for("vercel.ai.gateway.error");
6993
- var _a$1;
6994
- var _b;
6995
- var GatewayError = class _GatewayError extends (_b = Error, _a$1 = symbol$1, _b) {
6996
- constructor({ message, statusCode = 500, cause }) {
6997
- super(message);
6998
- this[_a$1] = true;
6999
- this.statusCode = statusCode;
7000
- this.cause = cause;
7001
- }
7002
- /**
7003
- * Checks if the given error is a Gateway Error.
7004
- * @param {unknown} error - The error to check.
7005
- * @returns {boolean} True if the error is a Gateway Error, false otherwise.
7006
- */
7007
- static isInstance(error) {
7008
- return _GatewayError.hasMarker(error);
7009
- }
7010
- static hasMarker(error) {
7011
- return typeof error === "object" && error !== null && symbol$1 in error && error[symbol$1] === true;
7012
- }
7013
- };
7014
- var name$1 = "GatewayAuthenticationError";
7015
- var marker2$1 = `vercel.ai.gateway.error.${name$1}`;
7016
- var symbol2$1 = Symbol.for(marker2$1);
7017
- var _a2$1;
7018
- var _b2;
7019
- var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2$1 = symbol2$1, _b2) {
7020
- constructor({ message = "Authentication failed", statusCode = 401, cause } = {}) {
7021
- super({
7022
- message,
7023
- statusCode,
7024
- cause
7025
- });
7026
- this[_a2$1] = true;
7027
- this.name = name$1;
7028
- this.type = "authentication_error";
7029
- }
7030
- static isInstance(error) {
7031
- return GatewayError.hasMarker(error) && symbol2$1 in error;
7032
- }
7033
- /**
7034
- * Creates a contextual error message when authentication fails
7035
- */
7036
- static createContextualError({ apiKeyProvided, oidcTokenProvided, message = "Authentication failed", statusCode = 401, cause }) {
7037
- let contextualMessage;
7038
- if (apiKeyProvided) contextualMessage = `AI Gateway authentication failed: Invalid API key.
7039
-
7040
- Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
7041
-
7042
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
7043
- else if (oidcTokenProvided) contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.
7044
-
7045
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
7046
-
7047
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;
7048
- else contextualMessage = `AI Gateway authentication failed: No authentication provided.
7049
-
7050
- Option 1 - API key:
7051
- Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
7052
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
7053
-
7054
- Option 2 - OIDC token:
7055
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;
7056
- return new _GatewayAuthenticationError({
7057
- message: contextualMessage,
7058
- statusCode,
7059
- cause
7060
- });
7061
- }
7062
- };
7063
- var name2$1 = "GatewayForbiddenError";
7064
- var marker3$1 = `vercel.ai.gateway.error.${name2$1}`;
7065
- var symbol3$1 = Symbol.for(marker3$1);
7066
- var forbiddenParamSchema = lazyValidator(() => zodSchema(z$1.object({ ruleId: z$1.string() })));
7067
- var _a3$1;
7068
- var _b3;
7069
- var GatewayForbiddenError = class extends (_b3 = GatewayError, _a3$1 = symbol3$1, _b3) {
7070
- constructor({ message = "Forbidden", statusCode = 403, cause, ruleId } = {}) {
7071
- super({
7072
- message,
7073
- statusCode,
7074
- cause
7075
- });
7076
- this[_a3$1] = true;
7077
- this.name = name2$1;
7078
- this.type = "forbidden";
7079
- this.ruleId = ruleId;
7080
- }
7081
- static isInstance(error) {
7082
- return GatewayError.hasMarker(error) && symbol3$1 in error;
7083
- }
7084
- };
7085
- var name3$1 = "GatewayInvalidRequestError";
7086
- var marker4$1 = `vercel.ai.gateway.error.${name3$1}`;
7087
- var symbol4$1 = Symbol.for(marker4$1);
7088
- var _a4$1;
7089
- var _b4;
7090
- var GatewayInvalidRequestError = class extends (_b4 = GatewayError, _a4$1 = symbol4$1, _b4) {
7091
- constructor({ message = "Invalid request", statusCode = 400, cause } = {}) {
7092
- super({
7093
- message,
7094
- statusCode,
7095
- cause
7096
- });
7097
- this[_a4$1] = true;
7098
- this.name = name3$1;
7099
- this.type = "invalid_request_error";
7100
- }
7101
- static isInstance(error) {
7102
- return GatewayError.hasMarker(error) && symbol4$1 in error;
7103
- }
7104
- };
7105
- var name4$1 = "GatewayRateLimitError";
7106
- var marker5$1 = `vercel.ai.gateway.error.${name4$1}`;
7107
- var symbol5$1 = Symbol.for(marker5$1);
7108
- var _a5$1;
7109
- var _b5;
7110
- var GatewayRateLimitError = class extends (_b5 = GatewayError, _a5$1 = symbol5$1, _b5) {
7111
- constructor({ message = "Rate limit exceeded", statusCode = 429, cause } = {}) {
7112
- super({
7113
- message,
7114
- statusCode,
7115
- cause
7116
- });
7117
- this[_a5$1] = true;
7118
- this.name = name4$1;
7119
- this.type = "rate_limit_exceeded";
7120
- }
7121
- static isInstance(error) {
7122
- return GatewayError.hasMarker(error) && symbol5$1 in error;
7123
- }
7124
- };
7125
- var name5$1 = "GatewayModelNotFoundError";
7126
- var marker6$1 = `vercel.ai.gateway.error.${name5$1}`;
7127
- var symbol6$1 = Symbol.for(marker6$1);
7128
- var modelNotFoundParamSchema = lazyValidator(() => zodSchema(z$1.object({ modelId: z$1.string() })));
7129
- var _a6$1;
7130
- var _b6;
7131
- var GatewayModelNotFoundError = class extends (_b6 = GatewayError, _a6$1 = symbol6$1, _b6) {
7132
- constructor({ message = "Model not found", statusCode = 404, modelId, cause } = {}) {
7133
- super({
7134
- message,
7135
- statusCode,
7136
- cause
7137
- });
7138
- this[_a6$1] = true;
7139
- this.name = name5$1;
7140
- this.type = "model_not_found";
7141
- this.modelId = modelId;
7142
- }
7143
- static isInstance(error) {
7144
- return GatewayError.hasMarker(error) && symbol6$1 in error;
7145
- }
7146
- };
7147
- var name6$1 = "GatewayInternalServerError";
7148
- var marker7$1 = `vercel.ai.gateway.error.${name6$1}`;
7149
- var symbol7$1 = Symbol.for(marker7$1);
7150
- var _a7$1;
7151
- var _b7;
7152
- var GatewayInternalServerError = class extends (_b7 = GatewayError, _a7$1 = symbol7$1, _b7) {
7153
- constructor({ message = "Internal server error", statusCode = 500, cause } = {}) {
7154
- super({
7155
- message,
7156
- statusCode,
7157
- cause
7158
- });
7159
- this[_a7$1] = true;
7160
- this.name = name6$1;
7161
- this.type = "internal_server_error";
7162
- }
7163
- static isInstance(error) {
7164
- return GatewayError.hasMarker(error) && symbol7$1 in error;
7165
- }
7166
- };
7167
- var name7$1 = "GatewayResponseError";
7168
- var marker8$1 = `vercel.ai.gateway.error.${name7$1}`;
7169
- var symbol8$1 = Symbol.for(marker8$1);
7170
- var _a8$1;
7171
- var _b8;
7172
- var GatewayResponseError = class extends (_b8 = GatewayError, _a8$1 = symbol8$1, _b8) {
7173
- constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause } = {}) {
7174
- super({
7175
- message,
7176
- statusCode,
7177
- cause
7178
- });
7179
- this[_a8$1] = true;
7180
- this.name = name7$1;
7181
- this.type = "response_error";
7182
- this.response = response;
7183
- this.validationError = validationError;
7184
- }
7185
- static isInstance(error) {
7186
- return GatewayError.hasMarker(error) && symbol8$1 in error;
7187
- }
7188
- };
7189
- async function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod }) {
7190
- const parseResult = await safeValidateTypes({
7191
- value: response,
7192
- schema: gatewayErrorResponseSchema
7193
- });
7194
- if (!parseResult.success) return new GatewayResponseError({
7195
- message: `Invalid error response format: ${defaultMessage}`,
7196
- statusCode,
7197
- response,
7198
- validationError: parseResult.error,
7199
- cause
7200
- });
7201
- const validatedResponse = parseResult.value;
7202
- const errorType = validatedResponse.error.type;
7203
- const message = validatedResponse.error.message;
7204
- switch (errorType) {
7205
- case "authentication_error": return GatewayAuthenticationError.createContextualError({
7206
- apiKeyProvided: authMethod === "api-key",
7207
- oidcTokenProvided: authMethod === "oidc",
7208
- statusCode,
7209
- cause
7210
- });
7211
- case "invalid_request_error": return new GatewayInvalidRequestError({
7212
- message,
7213
- statusCode,
7214
- cause
7215
- });
7216
- case "rate_limit_exceeded": return new GatewayRateLimitError({
7217
- message,
7218
- statusCode,
7219
- cause
7220
- });
7221
- case "model_not_found": {
7222
- const modelResult = await safeValidateTypes({
7223
- value: validatedResponse.error.param,
7224
- schema: modelNotFoundParamSchema
7225
- });
7226
- return new GatewayModelNotFoundError({
7227
- message,
7228
- statusCode,
7229
- modelId: modelResult.success ? modelResult.value.modelId : void 0,
7230
- cause
7231
- });
7232
- }
7233
- case "internal_server_error": return new GatewayInternalServerError({
7234
- message,
7235
- statusCode,
7236
- cause
7237
- });
7238
- case "forbidden": {
7239
- const ruleResult = await safeValidateTypes({
7240
- value: validatedResponse.error.param,
7241
- schema: forbiddenParamSchema
7242
- });
7243
- return new GatewayForbiddenError({
7244
- message,
7245
- statusCode,
7246
- cause,
7247
- ruleId: ruleResult.success ? ruleResult.value.ruleId : void 0
7248
- });
7249
- }
7250
- default: return new GatewayInternalServerError({
7251
- message,
7252
- statusCode,
7253
- cause
7254
- });
7255
- }
7256
- }
7257
- var gatewayErrorResponseSchema = lazyValidator(() => zodSchema(z$1.object({ error: z$1.object({
7258
- message: z$1.string(),
7259
- type: z$1.string().nullish(),
7260
- param: z$1.unknown().nullish(),
7261
- code: z$1.union([z$1.string(), z$1.number()]).nullish()
7262
- }) })));
7263
- function extractApiCallResponse(error) {
7264
- if (error.data !== void 0) return error.data;
7265
- if (error.responseBody != null) try {
7266
- return JSON.parse(error.responseBody);
7267
- } catch (e) {
7268
- return error.responseBody;
7269
- }
7270
- return {};
7271
- }
7272
- var name8$1 = "GatewayTimeoutError";
7273
- var marker9$1 = `vercel.ai.gateway.error.${name8$1}`;
7274
- var symbol9$1 = Symbol.for(marker9$1);
7275
- var _a9$1;
7276
- var _b9;
7277
- var GatewayTimeoutError = class _GatewayTimeoutError extends (_b9 = GatewayError, _a9$1 = symbol9$1, _b9) {
7278
- constructor({ message = "Request timed out", statusCode = 408, cause } = {}) {
7279
- super({
7280
- message,
7281
- statusCode,
7282
- cause
7283
- });
7284
- this[_a9$1] = true;
7285
- this.name = name8$1;
7286
- this.type = "timeout_error";
7287
- }
7288
- static isInstance(error) {
7289
- return GatewayError.hasMarker(error) && symbol9$1 in error;
7290
- }
7291
- /**
7292
- * Creates a helpful timeout error message with troubleshooting guidance
7293
- */
7294
- static createTimeoutError({ originalMessage, statusCode = 408, cause }) {
7295
- const message = `Gateway request timed out: ${originalMessage}
7296
-
7297
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;
7298
- return new _GatewayTimeoutError({
7299
- message,
7300
- statusCode,
7301
- cause
7302
- });
7303
- }
7304
- };
7305
- function isTimeoutError(error) {
7306
- if (!(error instanceof Error)) return false;
7307
- const errorCode = error.code;
7308
- if (typeof errorCode === "string") return [
7309
- "UND_ERR_HEADERS_TIMEOUT",
7310
- "UND_ERR_BODY_TIMEOUT",
7311
- "UND_ERR_CONNECT_TIMEOUT"
7312
- ].includes(errorCode);
7313
- return false;
7314
- }
7315
- async function asGatewayError(error, authMethod) {
7316
- var _a10;
7317
- if (GatewayError.isInstance(error)) return error;
7318
- if (isTimeoutError(error)) return GatewayTimeoutError.createTimeoutError({
7319
- originalMessage: error instanceof Error ? error.message : "Unknown error",
7320
- cause: error
7321
- });
7322
- if (APICallError.isInstance(error)) {
7323
- if (error.cause && isTimeoutError(error.cause)) return GatewayTimeoutError.createTimeoutError({
7324
- originalMessage: error.message,
7325
- cause: error
7326
- });
7327
- return await createGatewayErrorFromResponse({
7328
- response: extractApiCallResponse(error),
7329
- statusCode: (_a10 = error.statusCode) != null ? _a10 : 500,
7330
- defaultMessage: "Gateway request failed",
7331
- cause: error,
7332
- authMethod
7333
- });
7334
- }
7335
- return await createGatewayErrorFromResponse({
7336
- response: {},
7337
- statusCode: 500,
7338
- defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
7339
- cause: error,
7340
- authMethod
7341
- });
7342
- }
7343
- var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
7344
- async function parseAuthMethod(headers) {
7345
- const result = await safeValidateTypes({
7346
- value: headers[GATEWAY_AUTH_METHOD_HEADER],
7347
- schema: gatewayAuthMethodSchema
7348
- });
7349
- return result.success ? result.value : void 0;
7350
- }
7351
- var gatewayAuthMethodSchema = lazyValidator(() => zodSchema(z$1.union([z$1.literal("api-key"), z$1.literal("oidc")])));
7352
- var KNOWN_MODEL_TYPES = [
7353
- "embedding",
7354
- "image",
7355
- "language"
7356
- ];
7357
- var GatewayFetchMetadata = class {
7358
- constructor(config) {
7359
- this.config = config;
7360
- }
7361
- async getAvailableModels() {
7362
- try {
7363
- const { value } = await getFromApi({
7364
- url: `${this.config.baseURL}/config`,
7365
- headers: await resolve$1(this.config.headers()),
7366
- successfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),
7367
- failedResponseHandler: createJsonErrorResponseHandler({
7368
- errorSchema: z$1.any(),
7369
- errorToMessage: (data) => data
7370
- }),
7371
- fetch: this.config.fetch
7372
- });
7373
- return value;
7374
- } catch (error) {
7375
- throw await asGatewayError(error);
7376
- }
7377
- }
7378
- async getCredits() {
7379
- try {
7380
- const { value } = await getFromApi({
7381
- url: `${new URL(this.config.baseURL).origin}/v1/credits`,
7382
- headers: await resolve$1(this.config.headers()),
7383
- successfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),
7384
- failedResponseHandler: createJsonErrorResponseHandler({
7385
- errorSchema: z$1.any(),
7386
- errorToMessage: (data) => data
7387
- }),
7388
- fetch: this.config.fetch
7389
- });
7390
- return value;
7391
- } catch (error) {
7392
- throw await asGatewayError(error);
7393
- }
7394
- }
7395
- };
7396
- var gatewayAvailableModelsResponseSchema = lazyValidator(() => zodSchema(z$1.object({ models: z$1.array(z$1.object({
7397
- id: z$1.string(),
7398
- name: z$1.string(),
7399
- description: z$1.string().nullish(),
7400
- pricing: z$1.object({
7401
- input: z$1.string(),
7402
- output: z$1.string(),
7403
- input_cache_read: z$1.string().nullish(),
7404
- input_cache_write: z$1.string().nullish()
7405
- }).transform(({ input, output, input_cache_read, input_cache_write }) => ({
7406
- input,
7407
- output,
7408
- ...input_cache_read ? { cachedInputTokens: input_cache_read } : {},
7409
- ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
7410
- })).nullish(),
7411
- specification: z$1.object({
7412
- specificationVersion: z$1.literal("v2"),
7413
- provider: z$1.string(),
7414
- modelId: z$1.string()
7415
- }),
7416
- modelType: z$1.string().nullish()
7417
- })).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType))) })));
7418
- var gatewayCreditsResponseSchema = lazyValidator(() => zodSchema(z$1.object({
7419
- balance: z$1.string(),
7420
- total_used: z$1.string()
7421
- }).transform(({ balance, total_used }) => ({
7422
- balance,
7423
- totalUsed: total_used
7424
- }))));
7425
- var GatewaySpendReport = class {
7426
- constructor(config) {
7427
- this.config = config;
7428
- }
7429
- async getSpendReport(params) {
7430
- try {
7431
- const baseUrl = new URL(this.config.baseURL);
7432
- const searchParams = new URLSearchParams();
7433
- searchParams.set("start_date", params.startDate);
7434
- searchParams.set("end_date", params.endDate);
7435
- if (params.groupBy) searchParams.set("group_by", params.groupBy);
7436
- if (params.datePart) searchParams.set("date_part", params.datePart);
7437
- if (params.userId) searchParams.set("user_id", params.userId);
7438
- if (params.model) searchParams.set("model", params.model);
7439
- if (params.provider) searchParams.set("provider", params.provider);
7440
- if (params.credentialType) searchParams.set("credential_type", params.credentialType);
7441
- if (params.tags && params.tags.length > 0) searchParams.set("tags", params.tags.join(","));
7442
- const { value } = await getFromApi({
7443
- url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
7444
- headers: await resolve$1(this.config.headers()),
7445
- successfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),
7446
- failedResponseHandler: createJsonErrorResponseHandler({
7447
- errorSchema: z$1.any(),
7448
- errorToMessage: (data) => data
7449
- }),
7450
- fetch: this.config.fetch
7451
- });
7452
- return value;
7453
- } catch (error) {
7454
- throw await asGatewayError(error);
7455
- }
7456
- }
7457
- };
7458
- var gatewaySpendReportResponseSchema = lazySchema(() => zodSchema(z$1.object({ results: z$1.array(z$1.object({
7459
- day: z$1.string().optional(),
7460
- hour: z$1.string().optional(),
7461
- user: z$1.string().optional(),
7462
- model: z$1.string().optional(),
7463
- tag: z$1.string().optional(),
7464
- provider: z$1.string().optional(),
7465
- credential_type: z$1.enum(["byok", "system"]).optional(),
7466
- total_cost: z$1.number(),
7467
- market_cost: z$1.number().optional(),
7468
- input_tokens: z$1.number().optional(),
7469
- output_tokens: z$1.number().optional(),
7470
- cached_input_tokens: z$1.number().optional(),
7471
- cache_creation_input_tokens: z$1.number().optional(),
7472
- reasoning_tokens: z$1.number().optional(),
7473
- request_count: z$1.number().optional()
7474
- }).transform(({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({
7475
- ...rest,
7476
- ...credential_type !== void 0 ? { credentialType: credential_type } : {},
7477
- totalCost: total_cost,
7478
- ...market_cost !== void 0 ? { marketCost: market_cost } : {},
7479
- ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
7480
- ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
7481
- ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
7482
- ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
7483
- ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
7484
- ...request_count !== void 0 ? { requestCount: request_count } : {}
7485
- }))) })));
7486
- var GatewayGenerationInfoFetcher = class {
7487
- constructor(config) {
7488
- this.config = config;
7489
- }
7490
- async getGenerationInfo(params) {
7491
- try {
7492
- const { value } = await getFromApi({
7493
- url: `${new URL(this.config.baseURL).origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
7494
- headers: await resolve$1(this.config.headers()),
7495
- successfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),
7496
- failedResponseHandler: createJsonErrorResponseHandler({
7497
- errorSchema: z$1.any(),
7498
- errorToMessage: (data) => data
7499
- }),
7500
- fetch: this.config.fetch
7501
- });
7502
- return value;
7503
- } catch (error) {
7504
- throw await asGatewayError(error);
7505
- }
7506
- }
7507
- };
7508
- var gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(z$1.object({ data: z$1.object({
7509
- id: z$1.string(),
7510
- total_cost: z$1.number(),
7511
- upstream_inference_cost: z$1.number(),
7512
- usage: z$1.number(),
7513
- created_at: z$1.string(),
7514
- model: z$1.string(),
7515
- is_byok: z$1.boolean(),
7516
- provider_name: z$1.string(),
7517
- streamed: z$1.boolean(),
7518
- finish_reason: z$1.string(),
7519
- latency: z$1.number(),
7520
- generation_time: z$1.number(),
7521
- native_tokens_prompt: z$1.number(),
7522
- native_tokens_completion: z$1.number(),
7523
- native_tokens_reasoning: z$1.number(),
7524
- native_tokens_cached: z$1.number(),
7525
- native_tokens_cache_creation: z$1.number(),
7526
- billable_web_search_calls: z$1.number()
7527
- }).transform(({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({
7528
- ...rest,
7529
- totalCost: total_cost,
7530
- upstreamInferenceCost: upstream_inference_cost,
7531
- createdAt: created_at,
7532
- isByok: is_byok,
7533
- providerName: provider_name,
7534
- finishReason: finish_reason,
7535
- generationTime: generation_time,
7536
- promptTokens: native_tokens_prompt,
7537
- completionTokens: native_tokens_completion,
7538
- reasoningTokens: native_tokens_reasoning,
7539
- cachedTokens: native_tokens_cached,
7540
- cacheCreationTokens: native_tokens_cache_creation,
7541
- billableWebSearchCalls: billable_web_search_calls
7542
- })) }).transform(({ data }) => data)));
7543
- var GatewayLanguageModel = class {
7544
- constructor(modelId, config) {
7545
- this.modelId = modelId;
7546
- this.config = config;
7547
- this.specificationVersion = "v2";
7548
- this.supportedUrls = { "*/*": [/.*/] };
7549
- }
7550
- get provider() {
7551
- return this.config.provider;
7552
- }
7553
- async getArgs(options) {
7554
- const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
7555
- return {
7556
- args: this.maybeEncodeFileParts(optionsWithoutSignal),
7557
- warnings: []
7558
- };
7559
- }
7560
- async doGenerate(options) {
7561
- const { args, warnings } = await this.getArgs(options);
7562
- const { abortSignal } = options;
7563
- const resolvedHeaders = await resolve$1(this.config.headers());
7564
- try {
7565
- const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({
7566
- url: this.getUrl(),
7567
- headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve$1(this.config.o11yHeaders)),
7568
- body: args,
7569
- successfulResponseHandler: createJsonResponseHandler(z$1.any()),
7570
- failedResponseHandler: createJsonErrorResponseHandler({
7571
- errorSchema: z$1.any(),
7572
- errorToMessage: (data) => data
7573
- }),
7574
- ...abortSignal && { abortSignal },
7575
- fetch: this.config.fetch
7576
- });
7577
- return {
7578
- ...responseBody,
7579
- request: { body: args },
7580
- response: {
7581
- headers: responseHeaders,
7582
- body: rawResponse
7583
- },
7584
- warnings
7585
- };
7586
- } catch (error) {
7587
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7588
- }
7589
- }
7590
- async doStream(options) {
7591
- const { args, warnings } = await this.getArgs(options);
7592
- const { abortSignal } = options;
7593
- const resolvedHeaders = await resolve$1(this.config.headers());
7594
- try {
7595
- const { value: response, responseHeaders } = await postJsonToApi({
7596
- url: this.getUrl(),
7597
- headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve$1(this.config.o11yHeaders)),
7598
- body: args,
7599
- successfulResponseHandler: createEventSourceResponseHandler(z$1.any()),
7600
- failedResponseHandler: createJsonErrorResponseHandler({
7601
- errorSchema: z$1.any(),
7602
- errorToMessage: (data) => data
7603
- }),
7604
- ...abortSignal && { abortSignal },
7605
- fetch: this.config.fetch
7606
- });
7607
- return {
7608
- stream: response.pipeThrough(new TransformStream({
7609
- start(controller) {
7610
- if (warnings.length > 0) controller.enqueue({
7611
- type: "stream-start",
7612
- warnings
7613
- });
7614
- },
7615
- transform(chunk, controller) {
7616
- if (chunk.success) {
7617
- const streamPart = chunk.value;
7618
- if (streamPart.type === "raw" && !options.includeRawChunks) return;
7619
- if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") streamPart.timestamp = new Date(streamPart.timestamp);
7620
- controller.enqueue(streamPart);
7621
- } else controller.error(chunk.error);
7622
- }
7623
- })),
7624
- request: { body: args },
7625
- response: { headers: responseHeaders }
7626
- };
7627
- } catch (error) {
7628
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7629
- }
7630
- }
7631
- isFilePart(part) {
7632
- return part && typeof part === "object" && "type" in part && part.type === "file";
7633
- }
7634
- /**
7635
- * Encodes file parts in the prompt to base64. Mutates the passed options
7636
- * instance directly to avoid copying the file data.
7637
- * @param options - The options to encode.
7638
- * @returns The options with the file parts encoded.
7639
- */
7640
- maybeEncodeFileParts(options) {
7641
- for (const message of options.prompt) for (const part of message.content) if (this.isFilePart(part)) {
7642
- const filePart = part;
7643
- if (filePart.data instanceof Uint8Array) {
7644
- const buffer = Uint8Array.from(filePart.data);
7645
- const base64Data = Buffer.from(buffer).toString("base64");
7646
- filePart.data = new URL(`data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}`);
7647
- }
7648
- }
7649
- return options;
7650
- }
7651
- getUrl() {
7652
- return `${this.config.baseURL}/language-model`;
7653
- }
7654
- getModelConfigHeaders(modelId, streaming) {
7655
- return {
7656
- "ai-language-model-specification-version": "2",
7657
- "ai-language-model-id": modelId,
7658
- "ai-language-model-streaming": String(streaming)
7659
- };
7660
- }
7661
- };
7662
- var GatewayEmbeddingModel = class {
7663
- constructor(modelId, config) {
7664
- this.modelId = modelId;
7665
- this.config = config;
7666
- this.specificationVersion = "v2";
7667
- this.maxEmbeddingsPerCall = 2048;
7668
- this.supportsParallelCalls = true;
7669
- }
7670
- get provider() {
7671
- return this.config.provider;
7672
- }
7673
- async doEmbed({ values, headers, abortSignal, providerOptions }) {
7674
- var _a10;
7675
- const resolvedHeaders = await resolve$1(this.config.headers());
7676
- try {
7677
- const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
7678
- url: this.getUrl(),
7679
- headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve$1(this.config.o11yHeaders)),
7680
- body: {
7681
- input: values.length === 1 ? values[0] : values,
7682
- ...providerOptions ? { providerOptions } : {}
7683
- },
7684
- successfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),
7685
- failedResponseHandler: createJsonErrorResponseHandler({
7686
- errorSchema: z$1.any(),
7687
- errorToMessage: (data) => data
7688
- }),
7689
- ...abortSignal && { abortSignal },
7690
- fetch: this.config.fetch
7691
- });
7692
- return {
7693
- embeddings: responseBody.embeddings,
7694
- usage: (_a10 = responseBody.usage) != null ? _a10 : void 0,
7695
- providerMetadata: responseBody.providerMetadata,
7696
- response: {
7697
- headers: responseHeaders,
7698
- body: rawValue
7699
- }
7700
- };
7701
- } catch (error) {
7702
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7703
- }
7704
- }
7705
- getUrl() {
7706
- return `${this.config.baseURL}/embedding-model`;
7707
- }
7708
- getModelConfigHeaders() {
7709
- return {
7710
- "ai-embedding-model-specification-version": "2",
7711
- "ai-model-id": this.modelId
7712
- };
7713
- }
7714
- };
7715
- var gatewayEmbeddingResponseSchema = lazyValidator(() => zodSchema(z$1.object({
7716
- embeddings: z$1.array(z$1.array(z$1.number())),
7717
- usage: z$1.object({ tokens: z$1.number() }).nullish(),
7718
- providerMetadata: z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.unknown())).optional()
7719
- })));
7720
- var GatewayImageModel = class {
7721
- constructor(modelId, config) {
7722
- this.modelId = modelId;
7723
- this.config = config;
7724
- this.specificationVersion = "v2";
7725
- this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
7726
- }
7727
- get provider() {
7728
- return this.config.provider;
7729
- }
7730
- async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) {
7731
- var _a10, _b10, _c, _d;
7732
- const resolvedHeaders = await resolve$1(this.config.headers());
7733
- try {
7734
- const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
7735
- url: this.getUrl(),
7736
- headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve$1(this.config.o11yHeaders)),
7737
- body: {
7738
- prompt,
7739
- n,
7740
- ...size && { size },
7741
- ...aspectRatio && { aspectRatio },
7742
- ...seed && { seed },
7743
- ...providerOptions && { providerOptions }
7744
- },
7745
- successfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema),
7746
- failedResponseHandler: createJsonErrorResponseHandler({
7747
- errorSchema: z$1.any(),
7748
- errorToMessage: (data) => data
7749
- }),
7750
- ...abortSignal && { abortSignal },
7751
- fetch: this.config.fetch
7752
- });
7753
- return {
7754
- images: responseBody.images,
7755
- warnings: (_a10 = responseBody.warnings) != null ? _a10 : [],
7756
- providerMetadata: responseBody.providerMetadata,
7757
- response: {
7758
- timestamp: /* @__PURE__ */ new Date(),
7759
- modelId: this.modelId,
7760
- headers: responseHeaders
7761
- },
7762
- ...responseBody.usage != null && { usage: {
7763
- inputTokens: (_b10 = responseBody.usage.inputTokens) != null ? _b10 : void 0,
7764
- outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
7765
- totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
7766
- } }
7767
- };
7768
- } catch (error) {
7769
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7770
- }
7771
- }
7772
- getUrl() {
7773
- return `${this.config.baseURL}/image-model`;
7774
- }
7775
- getModelConfigHeaders() {
7776
- return {
7777
- "ai-image-model-specification-version": "2",
7778
- "ai-model-id": this.modelId
7779
- };
7780
- }
7781
- };
7782
- var providerMetadataEntrySchema = z$1.object({ images: z$1.array(z$1.unknown()).optional() }).catchall(z$1.unknown());
7783
- var gatewayImageUsageSchema = z$1.object({
7784
- inputTokens: z$1.number().nullish(),
7785
- outputTokens: z$1.number().nullish(),
7786
- totalTokens: z$1.number().nullish()
7787
- });
7788
- var gatewayImageResponseSchema = z$1.object({
7789
- images: z$1.array(z$1.string()),
7790
- warnings: z$1.array(z$1.object({
7791
- type: z$1.literal("other"),
7792
- message: z$1.string()
7793
- })).optional(),
7794
- providerMetadata: z$1.record(z$1.string(), providerMetadataEntrySchema).optional(),
7795
- usage: gatewayImageUsageSchema.optional()
7796
- });
7797
- var parallelSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
7798
- id: "gateway.parallel_search",
7799
- name: "parallel_search",
7800
- inputSchema: lazySchema(() => zodSchema(z.object({
7801
- objective: z.string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),
7802
- search_queries: z.array(z.string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),
7803
- mode: z.enum(["one-shot", "agentic"]).optional().describe("Mode preset: \"one-shot\" for comprehensive results with longer excerpts (default), \"agentic\" for concise, token-efficient results for multi-step workflows."),
7804
- max_results: z.number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),
7805
- source_policy: z.object({
7806
- include_domains: z.array(z.string()).optional().describe("List of domains to include in search results."),
7807
- exclude_domains: z.array(z.string()).optional().describe("List of domains to exclude from search results."),
7808
- after_date: z.string().optional().describe("Only include results published after this date (ISO 8601 format).")
7809
- }).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),
7810
- excerpts: z.object({
7811
- max_chars_per_result: z.number().optional().describe("Maximum characters per result."),
7812
- max_chars_total: z.number().optional().describe("Maximum total characters across all results.")
7813
- }).optional().describe("Excerpt configuration for controlling result length."),
7814
- fetch_policy: z.object({ max_age_seconds: z.number().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.") }).optional().describe("Fetch policy for controlling content freshness.")
7815
- }))),
7816
- outputSchema: lazySchema(() => zodSchema(z.union([z.object({
7817
- searchId: z.string(),
7818
- results: z.array(z.object({
7819
- url: z.string(),
7820
- title: z.string(),
7821
- excerpt: z.string(),
7822
- publishDate: z.string().nullable().optional(),
7823
- relevanceScore: z.number().optional()
7824
- }))
7825
- }), z.object({
7826
- error: z.enum([
7827
- "api_error",
7828
- "rate_limit",
7829
- "timeout",
7830
- "invalid_input",
7831
- "configuration_error",
7832
- "unknown"
7833
- ]),
7834
- statusCode: z.number().optional(),
7835
- message: z.string()
7836
- })])))
7837
- });
7838
- var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
7839
- var perplexitySearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
7840
- id: "gateway.perplexity_search",
7841
- name: "perplexity_search",
7842
- inputSchema: lazySchema(() => zodSchema(z.object({
7843
- query: z.union([z.string(), z.array(z.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),
7844
- max_results: z.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),
7845
- max_tokens_per_page: z.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),
7846
- max_tokens: z.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),
7847
- country: z.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),
7848
- search_domain_filter: z.array(z.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),
7849
- search_language_filter: z.array(z.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),
7850
- search_after_date: z.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),
7851
- search_before_date: z.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),
7852
- last_updated_after_filter: z.string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),
7853
- last_updated_before_filter: z.string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),
7854
- search_recency_filter: z.enum([
7855
- "day",
7856
- "week",
7857
- "month",
7858
- "year"
7859
- ]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")
7860
- }))),
7861
- outputSchema: lazySchema(() => zodSchema(z.union([z.object({
7862
- results: z.array(z.object({
7863
- title: z.string(),
7864
- url: z.string(),
7865
- snippet: z.string(),
7866
- date: z.string().optional(),
7867
- lastUpdated: z.string().optional()
7868
- })),
7869
- id: z.string()
7870
- }), z.object({
7871
- error: z.enum([
7872
- "api_error",
7873
- "rate_limit",
7874
- "timeout",
7875
- "invalid_input",
7876
- "unknown"
7877
- ]),
7878
- statusCode: z.number().optional(),
7879
- message: z.string()
7880
- })])))
7881
- });
7882
- var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
7883
- var gatewayTools = {
7884
- /**
7885
- * Search the web using Parallel AI's Search API for LLM-optimized excerpts.
7886
- *
7887
- * Takes a natural language objective and returns relevant excerpts,
7888
- * replacing multiple keyword searches with a single call for broad
7889
- * or complex queries. Supports different search types for depth vs
7890
- * breadth tradeoffs.
7891
- */
7892
- parallelSearch,
7893
- /**
7894
- * Search the web using Perplexity's Search API for real-time information,
7895
- * news, research papers, and articles.
7896
- *
7897
- * Provides ranked search results with advanced filtering options including
7898
- * domain, language, date range, and recency filters.
7899
- */
7900
- perplexitySearch
7901
- };
7902
- async function getVercelRequestId() {
7903
- var _a10;
7904
- return (_a10 = getContext().headers) == null ? void 0 : _a10["x-vercel-id"];
7905
- }
7906
- var VERSION$2 = "2.0.125";
7907
- var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
7908
- function createGatewayProvider(options = {}) {
7909
- var _a10, _b10;
7910
- let pendingMetadata = null;
7911
- let metadataCache = null;
7912
- const cacheRefreshMillis = (_a10 = options.metadataCacheRefreshMillis) != null ? _a10 : 1e3 * 60 * 5;
7913
- let lastFetchTime = 0;
7914
- const baseURL = (_b10 = withoutTrailingSlash(options.baseURL)) != null ? _b10 : "https://ai-gateway.vercel.sh/v1/ai";
7915
- const getHeaders = async () => {
7916
- const auth = await getGatewayAuthToken(options);
7917
- if (auth) return withUserAgentSuffix({
7918
- Authorization: `Bearer ${auth.token}`,
7919
- "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
7920
- [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
7921
- ...options.headers
7922
- }, `ai-sdk/gateway/${VERSION$2}`);
7923
- throw GatewayAuthenticationError.createContextualError({
7924
- apiKeyProvided: false,
7925
- oidcTokenProvided: false,
7926
- statusCode: 401
7927
- });
7928
- };
7929
- const createO11yHeaders = () => {
7930
- const deploymentId = loadOptionalSetting({
7931
- settingValue: void 0,
7932
- environmentVariableName: "VERCEL_DEPLOYMENT_ID"
7933
- });
7934
- const environment = loadOptionalSetting({
7935
- settingValue: void 0,
7936
- environmentVariableName: "VERCEL_ENV"
7937
- });
7938
- const region = loadOptionalSetting({
7939
- settingValue: void 0,
7940
- environmentVariableName: "VERCEL_REGION"
7941
- });
7942
- const projectId = loadOptionalSetting({
7943
- settingValue: void 0,
7944
- environmentVariableName: "VERCEL_PROJECT_ID"
7945
- });
7946
- return async () => {
7947
- const requestId = await getVercelRequestId();
7948
- return {
7949
- ...deploymentId && { "ai-o11y-deployment-id": deploymentId },
7950
- ...environment && { "ai-o11y-environment": environment },
7951
- ...region && { "ai-o11y-region": region },
7952
- ...requestId && { "ai-o11y-request-id": requestId },
7953
- ...projectId && { "ai-o11y-project-id": projectId }
7954
- };
7955
- };
7956
- };
7957
- const createLanguageModel = (modelId) => {
7958
- return new GatewayLanguageModel(modelId, {
7959
- provider: "gateway",
7960
- baseURL,
7961
- headers: getHeaders,
7962
- fetch: options.fetch,
7963
- o11yHeaders: createO11yHeaders()
7964
- });
7965
- };
7966
- const getAvailableModels = async () => {
7967
- var _a11, _b11, _c;
7968
- const now = (_c = (_b11 = (_a11 = options._internal) == null ? void 0 : _a11.currentDate) == null ? void 0 : _b11.call(_a11).getTime()) != null ? _c : Date.now();
7969
- if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {
7970
- lastFetchTime = now;
7971
- pendingMetadata = new GatewayFetchMetadata({
7972
- baseURL,
7973
- headers: getHeaders,
7974
- fetch: options.fetch
7975
- }).getAvailableModels().then((metadata) => {
7976
- metadataCache = metadata;
7977
- return metadata;
7978
- }).catch(async (error) => {
7979
- throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
7980
- });
7981
- }
7982
- return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;
7983
- };
7984
- const getCredits = async () => {
7985
- return new GatewayFetchMetadata({
7986
- baseURL,
7987
- headers: getHeaders,
7988
- fetch: options.fetch
7989
- }).getCredits().catch(async (error) => {
7990
- throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
7991
- });
7992
- };
7993
- const getSpendReport = async (params) => {
7994
- return new GatewaySpendReport({
7995
- baseURL,
7996
- headers: getHeaders,
7997
- fetch: options.fetch
7998
- }).getSpendReport(params).catch(async (error) => {
7999
- throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
8000
- });
8001
- };
8002
- const getGenerationInfo = async (params) => {
8003
- return new GatewayGenerationInfoFetcher({
8004
- baseURL,
8005
- headers: getHeaders,
8006
- fetch: options.fetch
8007
- }).getGenerationInfo(params).catch(async (error) => {
8008
- throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
8009
- });
8010
- };
8011
- const provider = function(modelId) {
8012
- if (new.target) throw new Error("The Gateway Provider model function cannot be called with the new keyword.");
8013
- return createLanguageModel(modelId);
8014
- };
8015
- provider.getAvailableModels = getAvailableModels;
8016
- provider.getCredits = getCredits;
8017
- provider.getSpendReport = getSpendReport;
8018
- provider.getGenerationInfo = getGenerationInfo;
8019
- provider.imageModel = (modelId) => {
8020
- return new GatewayImageModel(modelId, {
8021
- provider: "gateway",
8022
- baseURL,
8023
- headers: getHeaders,
8024
- fetch: options.fetch,
8025
- o11yHeaders: createO11yHeaders()
8026
- });
8027
- };
8028
- provider.languageModel = createLanguageModel;
8029
- provider.textEmbeddingModel = (modelId) => {
8030
- return new GatewayEmbeddingModel(modelId, {
8031
- provider: "gateway",
8032
- baseURL,
8033
- headers: getHeaders,
8034
- fetch: options.fetch,
8035
- o11yHeaders: createO11yHeaders()
8036
- });
8037
- };
8038
- provider.tools = gatewayTools;
8039
- return provider;
8040
- }
8041
- createGatewayProvider();
8042
- async function getGatewayAuthToken(options) {
8043
- const apiKey = loadOptionalSetting({
8044
- settingValue: options.apiKey,
8045
- environmentVariableName: "AI_GATEWAY_API_KEY"
8046
- });
8047
- if (apiKey) return {
8048
- token: apiKey,
8049
- authMethod: "api-key"
8050
- };
8051
- try {
8052
- return {
8053
- token: await getVercelOidcToken(),
8054
- authMethod: "oidc"
8055
- };
8056
- } catch (e) {
8057
- return null;
8058
- }
8059
- }
8060
5987
  /** only globals that common to node and browsers are allowed */
8061
5988
  var _globalThis = typeof globalThis === "object" ? globalThis : global;
8062
5989
  var VERSION$1 = "1.9.0";
@@ -8885,7 +6812,7 @@ var jsonValueSchema = z$1.lazy(() => z$1.union([
8885
6812
  z$1.string(),
8886
6813
  z$1.number(),
8887
6814
  z$1.boolean(),
8888
- z$1.record(z$1.string(), jsonValueSchema),
6815
+ z$1.record(z$1.string(), jsonValueSchema.optional()),
8889
6816
  z$1.array(jsonValueSchema)
8890
6817
  ]));
8891
6818
  var providerMetadataSchema = z$1.record(z$1.string(), z$1.record(z$1.string(), jsonValueSchema));
@@ -9271,10 +7198,12 @@ createIdGenerator({
9271
7198
  prefix: "aitxt",
9272
7199
  size: 24
9273
7200
  });
7201
+ new TextEncoder();
9274
7202
  createIdGenerator({
9275
7203
  prefix: "aiobj",
9276
7204
  size: 24
9277
7205
  });
7206
+ var { atob } = globalThis;
9278
7207
  createIdGenerator({
9279
7208
  prefix: "aiobj",
9280
7209
  size: 24