@eko-ai/eko 2.1.6 → 2.1.7-alpha.2

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.esm.js CHANGED
@@ -395,6 +395,18 @@ class Context {
395
395
  }
396
396
  }
397
397
  }
398
+ currentAgent() {
399
+ const agentNode = this.chain.agents[this.chain.agents.length - 1];
400
+ if (!agentNode) {
401
+ return null;
402
+ }
403
+ const agent = this.agents.filter((agent) => agent.Name == agentNode.agent.name)[0];
404
+ if (!agent) {
405
+ return null;
406
+ }
407
+ const agentContext = agent["agentContext"];
408
+ return [agent, agentNode.agent, agentContext];
409
+ }
398
410
  }
399
411
  class AgentContext {
400
412
  constructor(context, agent, agentChain) {
@@ -407,10 +419,10 @@ class AgentContext {
407
419
  }
408
420
 
409
421
  // src/errors/ai-sdk-error.ts
410
- var marker$1 = "vercel.ai.error";
411
- var symbol$1 = Symbol.for(marker$1);
412
- var _a$1;
413
- var _AISDKError$1 = class _AISDKError extends Error {
422
+ var marker = "vercel.ai.error";
423
+ var symbol = Symbol.for(marker);
424
+ var _a;
425
+ var _AISDKError = class _AISDKError extends Error {
414
426
  /**
415
427
  * Creates an AI SDK Error.
416
428
  *
@@ -425,7 +437,7 @@ var _AISDKError$1 = class _AISDKError extends Error {
425
437
  cause
426
438
  }) {
427
439
  super(message);
428
- this[_a$1] = true;
440
+ this[_a] = true;
429
441
  this.name = name14;
430
442
  this.cause = cause;
431
443
  }
@@ -435,22 +447,22 @@ var _AISDKError$1 = class _AISDKError extends Error {
435
447
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
436
448
  */
437
449
  static isInstance(error) {
438
- return _AISDKError.hasMarker(error, marker$1);
450
+ return _AISDKError.hasMarker(error, marker);
439
451
  }
440
452
  static hasMarker(error, marker15) {
441
453
  const markerSymbol = Symbol.for(marker15);
442
454
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
443
455
  }
444
456
  };
445
- _a$1 = symbol$1;
446
- var AISDKError$1 = _AISDKError$1;
457
+ _a = symbol;
458
+ var AISDKError = _AISDKError;
447
459
 
448
460
  // src/errors/api-call-error.ts
449
- var name$1 = "AI_APICallError";
450
- var marker2$1 = `vercel.ai.error.${name$1}`;
451
- var symbol2$1 = Symbol.for(marker2$1);
452
- var _a2$1;
453
- var APICallError$1 = class APICallError extends AISDKError$1 {
461
+ var name = "AI_APICallError";
462
+ var marker2 = `vercel.ai.error.${name}`;
463
+ var symbol2 = Symbol.for(marker2);
464
+ var _a2;
465
+ var APICallError = class extends AISDKError {
454
466
  constructor({
455
467
  message,
456
468
  url,
@@ -466,8 +478,8 @@ var APICallError$1 = class APICallError extends AISDKError$1 {
466
478
  // server error
467
479
  data
468
480
  }) {
469
- super({ name: name$1, message, cause });
470
- this[_a2$1] = true;
481
+ super({ name, message, cause });
482
+ this[_a2] = true;
471
483
  this.url = url;
472
484
  this.requestBodyValues = requestBodyValues;
473
485
  this.statusCode = statusCode;
@@ -477,30 +489,30 @@ var APICallError$1 = class APICallError extends AISDKError$1 {
477
489
  this.data = data;
478
490
  }
479
491
  static isInstance(error) {
480
- return AISDKError$1.hasMarker(error, marker2$1);
492
+ return AISDKError.hasMarker(error, marker2);
481
493
  }
482
494
  };
483
- _a2$1 = symbol2$1;
495
+ _a2 = symbol2;
484
496
 
485
497
  // src/errors/empty-response-body-error.ts
486
- var name2$1 = "AI_EmptyResponseBodyError";
487
- var marker3$1 = `vercel.ai.error.${name2$1}`;
488
- var symbol3$1 = Symbol.for(marker3$1);
489
- var _a3$1;
490
- var EmptyResponseBodyError$1 = class EmptyResponseBodyError extends AISDKError$1 {
498
+ var name2 = "AI_EmptyResponseBodyError";
499
+ var marker3 = `vercel.ai.error.${name2}`;
500
+ var symbol3 = Symbol.for(marker3);
501
+ var _a3;
502
+ var EmptyResponseBodyError = class extends AISDKError {
491
503
  // used in isInstance
492
504
  constructor({ message = "Empty response body" } = {}) {
493
- super({ name: name2$1, message });
494
- this[_a3$1] = true;
505
+ super({ name: name2, message });
506
+ this[_a3] = true;
495
507
  }
496
508
  static isInstance(error) {
497
- return AISDKError$1.hasMarker(error, marker3$1);
509
+ return AISDKError.hasMarker(error, marker3);
498
510
  }
499
511
  };
500
- _a3$1 = symbol3$1;
512
+ _a3 = symbol3;
501
513
 
502
514
  // src/errors/get-error-message.ts
503
- function getErrorMessage$1(error) {
515
+ function getErrorMessage(error) {
504
516
  if (error == null) {
505
517
  return "unknown error";
506
518
  }
@@ -514,119 +526,119 @@ function getErrorMessage$1(error) {
514
526
  }
515
527
 
516
528
  // src/errors/invalid-argument-error.ts
517
- var name3$1 = "AI_InvalidArgumentError";
518
- var marker4$1 = `vercel.ai.error.${name3$1}`;
519
- var symbol4$1 = Symbol.for(marker4$1);
520
- var _a4$1;
521
- var InvalidArgumentError$1 = class InvalidArgumentError extends AISDKError$1 {
529
+ var name3 = "AI_InvalidArgumentError";
530
+ var marker4 = `vercel.ai.error.${name3}`;
531
+ var symbol4 = Symbol.for(marker4);
532
+ var _a4;
533
+ var InvalidArgumentError = class extends AISDKError {
522
534
  constructor({
523
535
  message,
524
536
  cause,
525
537
  argument
526
538
  }) {
527
- super({ name: name3$1, message, cause });
528
- this[_a4$1] = true;
539
+ super({ name: name3, message, cause });
540
+ this[_a4] = true;
529
541
  this.argument = argument;
530
542
  }
531
543
  static isInstance(error) {
532
- return AISDKError$1.hasMarker(error, marker4$1);
544
+ return AISDKError.hasMarker(error, marker4);
533
545
  }
534
546
  };
535
- _a4$1 = symbol4$1;
547
+ _a4 = symbol4;
536
548
 
537
549
  // src/errors/invalid-prompt-error.ts
538
- var name4$1 = "AI_InvalidPromptError";
539
- var marker5$1 = `vercel.ai.error.${name4$1}`;
540
- var symbol5$1 = Symbol.for(marker5$1);
541
- var _a5$1;
542
- var InvalidPromptError$1 = class InvalidPromptError extends AISDKError$1 {
550
+ var name4 = "AI_InvalidPromptError";
551
+ var marker5 = `vercel.ai.error.${name4}`;
552
+ var symbol5 = Symbol.for(marker5);
553
+ var _a5;
554
+ var InvalidPromptError = class extends AISDKError {
543
555
  constructor({
544
556
  prompt,
545
557
  message,
546
558
  cause
547
559
  }) {
548
- super({ name: name4$1, message: `Invalid prompt: ${message}`, cause });
549
- this[_a5$1] = true;
560
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
561
+ this[_a5] = true;
550
562
  this.prompt = prompt;
551
563
  }
552
564
  static isInstance(error) {
553
- return AISDKError$1.hasMarker(error, marker5$1);
565
+ return AISDKError.hasMarker(error, marker5);
554
566
  }
555
567
  };
556
- _a5$1 = symbol5$1;
568
+ _a5 = symbol5;
557
569
 
558
570
  // src/errors/invalid-response-data-error.ts
559
- var name5$1 = "AI_InvalidResponseDataError";
560
- var marker6$1 = `vercel.ai.error.${name5$1}`;
561
- var symbol6$1 = Symbol.for(marker6$1);
562
- var _a6$1;
563
- var InvalidResponseDataError$1 = class InvalidResponseDataError extends AISDKError$1 {
571
+ var name5 = "AI_InvalidResponseDataError";
572
+ var marker6 = `vercel.ai.error.${name5}`;
573
+ var symbol6 = Symbol.for(marker6);
574
+ var _a6;
575
+ var InvalidResponseDataError = class extends AISDKError {
564
576
  constructor({
565
577
  data,
566
578
  message = `Invalid response data: ${JSON.stringify(data)}.`
567
579
  }) {
568
- super({ name: name5$1, message });
569
- this[_a6$1] = true;
580
+ super({ name: name5, message });
581
+ this[_a6] = true;
570
582
  this.data = data;
571
583
  }
572
584
  static isInstance(error) {
573
- return AISDKError$1.hasMarker(error, marker6$1);
585
+ return AISDKError.hasMarker(error, marker6);
574
586
  }
575
587
  };
576
- _a6$1 = symbol6$1;
588
+ _a6 = symbol6;
577
589
 
578
590
  // src/errors/json-parse-error.ts
579
- var name6$1 = "AI_JSONParseError";
580
- var marker7$1 = `vercel.ai.error.${name6$1}`;
581
- var symbol7$1 = Symbol.for(marker7$1);
582
- var _a7$1;
583
- var JSONParseError$1 = class JSONParseError extends AISDKError$1 {
591
+ var name6 = "AI_JSONParseError";
592
+ var marker7 = `vercel.ai.error.${name6}`;
593
+ var symbol7 = Symbol.for(marker7);
594
+ var _a7;
595
+ var JSONParseError = class extends AISDKError {
584
596
  constructor({ text, cause }) {
585
597
  super({
586
- name: name6$1,
598
+ name: name6,
587
599
  message: `JSON parsing failed: Text: ${text}.
588
- Error message: ${getErrorMessage$1(cause)}`,
600
+ Error message: ${getErrorMessage(cause)}`,
589
601
  cause
590
602
  });
591
- this[_a7$1] = true;
603
+ this[_a7] = true;
592
604
  this.text = text;
593
605
  }
594
606
  static isInstance(error) {
595
- return AISDKError$1.hasMarker(error, marker7$1);
607
+ return AISDKError.hasMarker(error, marker7);
596
608
  }
597
609
  };
598
- _a7$1 = symbol7$1;
610
+ _a7 = symbol7;
599
611
 
600
612
  // src/errors/load-api-key-error.ts
601
- var name7$1 = "AI_LoadAPIKeyError";
602
- var marker8$1 = `vercel.ai.error.${name7$1}`;
603
- var symbol8$1 = Symbol.for(marker8$1);
604
- var _a8$1;
605
- var LoadAPIKeyError$1 = class LoadAPIKeyError extends AISDKError$1 {
613
+ var name7 = "AI_LoadAPIKeyError";
614
+ var marker8 = `vercel.ai.error.${name7}`;
615
+ var symbol8 = Symbol.for(marker8);
616
+ var _a8;
617
+ var LoadAPIKeyError = class extends AISDKError {
606
618
  // used in isInstance
607
619
  constructor({ message }) {
608
- super({ name: name7$1, message });
609
- this[_a8$1] = true;
620
+ super({ name: name7, message });
621
+ this[_a8] = true;
610
622
  }
611
623
  static isInstance(error) {
612
- return AISDKError$1.hasMarker(error, marker8$1);
624
+ return AISDKError.hasMarker(error, marker8);
613
625
  }
614
626
  };
615
- _a8$1 = symbol8$1;
627
+ _a8 = symbol8;
616
628
 
617
629
  // src/errors/load-setting-error.ts
618
630
  var name8 = "AI_LoadSettingError";
619
631
  var marker9 = `vercel.ai.error.${name8}`;
620
632
  var symbol9 = Symbol.for(marker9);
621
633
  var _a9;
622
- var LoadSettingError = class extends AISDKError$1 {
634
+ var LoadSettingError = class extends AISDKError {
623
635
  // used in isInstance
624
636
  constructor({ message }) {
625
637
  super({ name: name8, message });
626
638
  this[_a9] = true;
627
639
  }
628
640
  static isInstance(error) {
629
- return AISDKError$1.hasMarker(error, marker9);
641
+ return AISDKError.hasMarker(error, marker9);
630
642
  }
631
643
  };
632
644
  _a9 = symbol9;
@@ -636,7 +648,7 @@ var name10 = "AI_NoSuchModelError";
636
648
  var marker11 = `vercel.ai.error.${name10}`;
637
649
  var symbol11 = Symbol.for(marker11);
638
650
  var _a11;
639
- var NoSuchModelError = class extends AISDKError$1 {
651
+ var NoSuchModelError = class extends AISDKError {
640
652
  constructor({
641
653
  errorName = name10,
642
654
  modelId,
@@ -649,7 +661,7 @@ var NoSuchModelError = class extends AISDKError$1 {
649
661
  this.modelType = modelType;
650
662
  }
651
663
  static isInstance(error) {
652
- return AISDKError$1.hasMarker(error, marker11);
664
+ return AISDKError.hasMarker(error, marker11);
653
665
  }
654
666
  };
655
667
  _a11 = symbol11;
@@ -659,7 +671,7 @@ var name11 = "AI_TooManyEmbeddingValuesForCallError";
659
671
  var marker12 = `vercel.ai.error.${name11}`;
660
672
  var symbol12 = Symbol.for(marker12);
661
673
  var _a12;
662
- var TooManyEmbeddingValuesForCallError = class extends AISDKError$1 {
674
+ var TooManyEmbeddingValuesForCallError = class extends AISDKError {
663
675
  constructor(options) {
664
676
  super({
665
677
  name: name11,
@@ -672,29 +684,29 @@ var TooManyEmbeddingValuesForCallError = class extends AISDKError$1 {
672
684
  this.values = options.values;
673
685
  }
674
686
  static isInstance(error) {
675
- return AISDKError$1.hasMarker(error, marker12);
687
+ return AISDKError.hasMarker(error, marker12);
676
688
  }
677
689
  };
678
690
  _a12 = symbol12;
679
691
 
680
692
  // src/errors/type-validation-error.ts
681
- var name12$1 = "AI_TypeValidationError";
682
- var marker13$1 = `vercel.ai.error.${name12$1}`;
683
- var symbol13$1 = Symbol.for(marker13$1);
684
- var _a13$1;
685
- var _TypeValidationError$1 = class _TypeValidationError extends AISDKError$1 {
693
+ var name12 = "AI_TypeValidationError";
694
+ var marker13 = `vercel.ai.error.${name12}`;
695
+ var symbol13 = Symbol.for(marker13);
696
+ var _a13;
697
+ var _TypeValidationError = class _TypeValidationError extends AISDKError {
686
698
  constructor({ value, cause }) {
687
699
  super({
688
- name: name12$1,
700
+ name: name12,
689
701
  message: `Type validation failed: Value: ${JSON.stringify(value)}.
690
- Error message: ${getErrorMessage$1(cause)}`,
702
+ Error message: ${getErrorMessage(cause)}`,
691
703
  cause
692
704
  });
693
- this[_a13$1] = true;
705
+ this[_a13] = true;
694
706
  this.value = value;
695
707
  }
696
708
  static isInstance(error) {
697
- return AISDKError$1.hasMarker(error, marker13$1);
709
+ return AISDKError.hasMarker(error, marker13);
698
710
  }
699
711
  /**
700
712
  * Wraps an error into a TypeValidationError.
@@ -713,28 +725,28 @@ Error message: ${getErrorMessage$1(cause)}`,
713
725
  return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
714
726
  }
715
727
  };
716
- _a13$1 = symbol13$1;
717
- var TypeValidationError$1 = _TypeValidationError$1;
728
+ _a13 = symbol13;
729
+ var TypeValidationError = _TypeValidationError;
718
730
 
719
731
  // src/errors/unsupported-functionality-error.ts
720
- var name13$1 = "AI_UnsupportedFunctionalityError";
721
- var marker14$1 = `vercel.ai.error.${name13$1}`;
722
- var symbol14$1 = Symbol.for(marker14$1);
723
- var _a14$1;
724
- var UnsupportedFunctionalityError$1 = class UnsupportedFunctionalityError extends AISDKError$1 {
732
+ var name13 = "AI_UnsupportedFunctionalityError";
733
+ var marker14 = `vercel.ai.error.${name13}`;
734
+ var symbol14 = Symbol.for(marker14);
735
+ var _a14;
736
+ var UnsupportedFunctionalityError = class extends AISDKError {
725
737
  constructor({
726
738
  functionality,
727
739
  message = `'${functionality}' functionality not supported.`
728
740
  }) {
729
- super({ name: name13$1, message });
730
- this[_a14$1] = true;
741
+ super({ name: name13, message });
742
+ this[_a14] = true;
731
743
  this.functionality = functionality;
732
744
  }
733
745
  static isInstance(error) {
734
- return AISDKError$1.hasMarker(error, marker14$1);
746
+ return AISDKError.hasMarker(error, marker14);
735
747
  }
736
748
  };
737
- _a14$1 = symbol14$1;
749
+ _a14 = symbol14;
738
750
 
739
751
  let customAlphabet = (alphabet, defaultSize = 21) => {
740
752
  return (size = defaultSize) => {
@@ -890,7 +902,7 @@ var secureJsonParseExports = requireSecureJsonParse();
890
902
  var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
891
903
 
892
904
  // src/combine-headers.ts
893
- function combineHeaders$1(...headers) {
905
+ function combineHeaders(...headers) {
894
906
  return headers.reduce(
895
907
  (combinedHeaders, currentHeaders) => ({
896
908
  ...combinedHeaders,
@@ -959,7 +971,7 @@ function createEventSourceParserStream() {
959
971
  }
960
972
  return new TransformStream({
961
973
  transform(chunk, controller) {
962
- const { lines, incompleteLine } = splitLines$1(buffer, chunk);
974
+ const { lines, incompleteLine } = splitLines(buffer, chunk);
963
975
  buffer = incompleteLine;
964
976
  for (let i = 0; i < lines.length; i++) {
965
977
  parseLine(lines[i], controller);
@@ -971,7 +983,7 @@ function createEventSourceParserStream() {
971
983
  }
972
984
  });
973
985
  }
974
- function splitLines$1(buffer, chunk) {
986
+ function splitLines(buffer, chunk) {
975
987
  const lines = [];
976
988
  let currentLine = buffer;
977
989
  for (let i = 0; i < chunk.length; ) {
@@ -993,14 +1005,14 @@ function splitLines$1(buffer, chunk) {
993
1005
  }
994
1006
 
995
1007
  // src/extract-response-headers.ts
996
- function extractResponseHeaders$1(response) {
1008
+ function extractResponseHeaders(response) {
997
1009
  const headers = {};
998
1010
  response.headers.forEach((value, key) => {
999
1011
  headers[key] = value;
1000
1012
  });
1001
1013
  return headers;
1002
1014
  }
1003
- var createIdGenerator$1 = ({
1015
+ var createIdGenerator = ({
1004
1016
  prefix,
1005
1017
  size: defaultSize = 16,
1006
1018
  alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
@@ -1011,27 +1023,27 @@ var createIdGenerator$1 = ({
1011
1023
  return generator;
1012
1024
  }
1013
1025
  if (alphabet.includes(separator)) {
1014
- throw new InvalidArgumentError$1({
1026
+ throw new InvalidArgumentError({
1015
1027
  argument: "separator",
1016
1028
  message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
1017
1029
  });
1018
1030
  }
1019
1031
  return (size) => `${prefix}${separator}${generator(size)}`;
1020
1032
  };
1021
- var generateId$1 = createIdGenerator$1();
1033
+ var generateId = createIdGenerator();
1022
1034
 
1023
1035
  // src/remove-undefined-entries.ts
1024
- function removeUndefinedEntries$1(record) {
1036
+ function removeUndefinedEntries(record) {
1025
1037
  return Object.fromEntries(
1026
1038
  Object.entries(record).filter(([_key, value]) => value != null)
1027
1039
  );
1028
1040
  }
1029
1041
 
1030
1042
  // src/is-abort-error.ts
1031
- function isAbortError$1(error) {
1043
+ function isAbortError(error) {
1032
1044
  return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
1033
1045
  }
1034
- function loadApiKey$1({
1046
+ function loadApiKey({
1035
1047
  apiKey,
1036
1048
  environmentVariableName,
1037
1049
  apiKeyParameterName = "apiKey",
@@ -1041,23 +1053,23 @@ function loadApiKey$1({
1041
1053
  return apiKey;
1042
1054
  }
1043
1055
  if (apiKey != null) {
1044
- throw new LoadAPIKeyError$1({
1056
+ throw new LoadAPIKeyError({
1045
1057
  message: `${description} API key must be a string.`
1046
1058
  });
1047
1059
  }
1048
1060
  if (typeof process === "undefined") {
1049
- throw new LoadAPIKeyError$1({
1061
+ throw new LoadAPIKeyError({
1050
1062
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
1051
1063
  });
1052
1064
  }
1053
1065
  apiKey = process.env[environmentVariableName];
1054
1066
  if (apiKey == null) {
1055
- throw new LoadAPIKeyError$1({
1067
+ throw new LoadAPIKeyError({
1056
1068
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
1057
1069
  });
1058
1070
  }
1059
1071
  if (typeof apiKey !== "string") {
1060
- throw new LoadAPIKeyError$1({
1072
+ throw new LoadAPIKeyError({
1061
1073
  message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
1062
1074
  });
1063
1075
  }
@@ -1115,39 +1127,39 @@ function loadSetting({
1115
1127
  }
1116
1128
 
1117
1129
  // src/validator.ts
1118
- var validatorSymbol$1 = Symbol.for("vercel.ai.validator");
1119
- function validator$1(validate) {
1120
- return { [validatorSymbol$1]: true, validate };
1130
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
1131
+ function validator(validate) {
1132
+ return { [validatorSymbol]: true, validate };
1121
1133
  }
1122
- function isValidator$1(value) {
1123
- return typeof value === "object" && value !== null && validatorSymbol$1 in value && value[validatorSymbol$1] === true && "validate" in value;
1134
+ function isValidator(value) {
1135
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
1124
1136
  }
1125
- function asValidator$1(value) {
1126
- return isValidator$1(value) ? value : zodValidator$1(value);
1137
+ function asValidator(value) {
1138
+ return isValidator(value) ? value : zodValidator(value);
1127
1139
  }
1128
- function zodValidator$1(zodSchema) {
1129
- return validator$1((value) => {
1140
+ function zodValidator(zodSchema) {
1141
+ return validator((value) => {
1130
1142
  const result = zodSchema.safeParse(value);
1131
1143
  return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1132
1144
  });
1133
1145
  }
1134
1146
 
1135
1147
  // src/validate-types.ts
1136
- function validateTypes$1({
1148
+ function validateTypes({
1137
1149
  value,
1138
1150
  schema: inputSchema
1139
1151
  }) {
1140
- const result = safeValidateTypes$1({ value, schema: inputSchema });
1152
+ const result = safeValidateTypes({ value, schema: inputSchema });
1141
1153
  if (!result.success) {
1142
- throw TypeValidationError$1.wrap({ value, cause: result.error });
1154
+ throw TypeValidationError.wrap({ value, cause: result.error });
1143
1155
  }
1144
1156
  return result.value;
1145
1157
  }
1146
- function safeValidateTypes$1({
1158
+ function safeValidateTypes({
1147
1159
  value,
1148
1160
  schema
1149
1161
  }) {
1150
- const validator2 = asValidator$1(schema);
1162
+ const validator2 = asValidator(schema);
1151
1163
  try {
1152
1164
  if (validator2.validate == null) {
1153
1165
  return { success: true, value };
@@ -1158,18 +1170,18 @@ function safeValidateTypes$1({
1158
1170
  }
1159
1171
  return {
1160
1172
  success: false,
1161
- error: TypeValidationError$1.wrap({ value, cause: result.error })
1173
+ error: TypeValidationError.wrap({ value, cause: result.error })
1162
1174
  };
1163
1175
  } catch (error) {
1164
1176
  return {
1165
1177
  success: false,
1166
- error: TypeValidationError$1.wrap({ value, cause: error })
1178
+ error: TypeValidationError.wrap({ value, cause: error })
1167
1179
  };
1168
1180
  }
1169
1181
  }
1170
1182
 
1171
1183
  // src/parse-json.ts
1172
- function parseJSON$1({
1184
+ function parseJSON({
1173
1185
  text,
1174
1186
  schema
1175
1187
  }) {
@@ -1178,15 +1190,15 @@ function parseJSON$1({
1178
1190
  if (schema == null) {
1179
1191
  return value;
1180
1192
  }
1181
- return validateTypes$1({ value, schema });
1193
+ return validateTypes({ value, schema });
1182
1194
  } catch (error) {
1183
- if (JSONParseError$1.isInstance(error) || TypeValidationError$1.isInstance(error)) {
1195
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
1184
1196
  throw error;
1185
1197
  }
1186
- throw new JSONParseError$1({ text, cause: error });
1198
+ throw new JSONParseError({ text, cause: error });
1187
1199
  }
1188
1200
  }
1189
- function safeParseJSON$1({
1201
+ function safeParseJSON({
1190
1202
  text,
1191
1203
  schema
1192
1204
  }) {
@@ -1195,16 +1207,16 @@ function safeParseJSON$1({
1195
1207
  if (schema == null) {
1196
1208
  return { success: true, value, rawValue: value };
1197
1209
  }
1198
- const validationResult = safeValidateTypes$1({ value, schema });
1210
+ const validationResult = safeValidateTypes({ value, schema });
1199
1211
  return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
1200
1212
  } catch (error) {
1201
1213
  return {
1202
1214
  success: false,
1203
- error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({ text, cause: error })
1215
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
1204
1216
  };
1205
1217
  }
1206
1218
  }
1207
- function isParsableJson$1(input) {
1219
+ function isParsableJson(input) {
1208
1220
  try {
1209
1221
  SecureJSON.parse(input);
1210
1222
  return true;
@@ -1220,12 +1232,12 @@ function parseProviderOptions({
1220
1232
  if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
1221
1233
  return void 0;
1222
1234
  }
1223
- const parsedProviderOptions = safeValidateTypes$1({
1235
+ const parsedProviderOptions = safeValidateTypes({
1224
1236
  value: providerOptions[provider],
1225
1237
  schema
1226
1238
  });
1227
1239
  if (!parsedProviderOptions.success) {
1228
- throw new InvalidArgumentError$1({
1240
+ throw new InvalidArgumentError({
1229
1241
  argument: "providerOptions",
1230
1242
  message: `invalid ${provider} provider options`,
1231
1243
  cause: parsedProviderOptions.error
@@ -1233,8 +1245,8 @@ function parseProviderOptions({
1233
1245
  }
1234
1246
  return parsedProviderOptions.value;
1235
1247
  }
1236
- var getOriginalFetch2$1 = () => globalThis.fetch;
1237
- var postJsonToApi$1 = async ({
1248
+ var getOriginalFetch2 = () => globalThis.fetch;
1249
+ var postJsonToApi = async ({
1238
1250
  url,
1239
1251
  headers,
1240
1252
  body,
@@ -1242,7 +1254,7 @@ var postJsonToApi$1 = async ({
1242
1254
  successfulResponseHandler,
1243
1255
  abortSignal,
1244
1256
  fetch
1245
- }) => postToApi$1({
1257
+ }) => postToApi({
1246
1258
  url,
1247
1259
  headers: {
1248
1260
  "Content-Type": "application/json",
@@ -1265,7 +1277,7 @@ var postFormDataToApi = async ({
1265
1277
  successfulResponseHandler,
1266
1278
  abortSignal,
1267
1279
  fetch
1268
- }) => postToApi$1({
1280
+ }) => postToApi({
1269
1281
  url,
1270
1282
  headers,
1271
1283
  body: {
@@ -1277,23 +1289,23 @@ var postFormDataToApi = async ({
1277
1289
  abortSignal,
1278
1290
  fetch
1279
1291
  });
1280
- var postToApi$1 = async ({
1292
+ var postToApi = async ({
1281
1293
  url,
1282
1294
  headers = {},
1283
1295
  body,
1284
1296
  successfulResponseHandler,
1285
1297
  failedResponseHandler,
1286
1298
  abortSignal,
1287
- fetch = getOriginalFetch2$1()
1299
+ fetch = getOriginalFetch2()
1288
1300
  }) => {
1289
1301
  try {
1290
1302
  const response = await fetch(url, {
1291
1303
  method: "POST",
1292
- headers: removeUndefinedEntries$1(headers),
1304
+ headers: removeUndefinedEntries(headers),
1293
1305
  body: body.content,
1294
1306
  signal: abortSignal
1295
1307
  });
1296
- const responseHeaders = extractResponseHeaders$1(response);
1308
+ const responseHeaders = extractResponseHeaders(response);
1297
1309
  if (!response.ok) {
1298
1310
  let errorInformation;
1299
1311
  try {
@@ -1303,10 +1315,10 @@ var postToApi$1 = async ({
1303
1315
  requestBodyValues: body.values
1304
1316
  });
1305
1317
  } catch (error) {
1306
- if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
1318
+ if (isAbortError(error) || APICallError.isInstance(error)) {
1307
1319
  throw error;
1308
1320
  }
1309
- throw new APICallError$1({
1321
+ throw new APICallError({
1310
1322
  message: "Failed to process error response",
1311
1323
  cause: error,
1312
1324
  statusCode: response.status,
@@ -1325,11 +1337,11 @@ var postToApi$1 = async ({
1325
1337
  });
1326
1338
  } catch (error) {
1327
1339
  if (error instanceof Error) {
1328
- if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
1340
+ if (isAbortError(error) || APICallError.isInstance(error)) {
1329
1341
  throw error;
1330
1342
  }
1331
1343
  }
1332
- throw new APICallError$1({
1344
+ throw new APICallError({
1333
1345
  message: "Failed to process successful response",
1334
1346
  cause: error,
1335
1347
  statusCode: response.status,
@@ -1339,13 +1351,13 @@ var postToApi$1 = async ({
1339
1351
  });
1340
1352
  }
1341
1353
  } catch (error) {
1342
- if (isAbortError$1(error)) {
1354
+ if (isAbortError(error)) {
1343
1355
  throw error;
1344
1356
  }
1345
1357
  if (error instanceof TypeError && error.message === "fetch failed") {
1346
1358
  const cause = error.cause;
1347
1359
  if (cause != null) {
1348
- throw new APICallError$1({
1360
+ throw new APICallError({
1349
1361
  message: `Cannot connect to API: ${cause.message}`,
1350
1362
  cause,
1351
1363
  url,
@@ -1366,17 +1378,17 @@ async function resolve(value) {
1366
1378
  }
1367
1379
  return Promise.resolve(value);
1368
1380
  }
1369
- var createJsonErrorResponseHandler$1 = ({
1381
+ var createJsonErrorResponseHandler = ({
1370
1382
  errorSchema,
1371
1383
  errorToMessage,
1372
1384
  isRetryable
1373
1385
  }) => async ({ response, url, requestBodyValues }) => {
1374
1386
  const responseBody = await response.text();
1375
- const responseHeaders = extractResponseHeaders$1(response);
1387
+ const responseHeaders = extractResponseHeaders(response);
1376
1388
  if (responseBody.trim() === "") {
1377
1389
  return {
1378
1390
  responseHeaders,
1379
- value: new APICallError$1({
1391
+ value: new APICallError({
1380
1392
  message: response.statusText,
1381
1393
  url,
1382
1394
  requestBodyValues,
@@ -1388,13 +1400,13 @@ var createJsonErrorResponseHandler$1 = ({
1388
1400
  };
1389
1401
  }
1390
1402
  try {
1391
- const parsedError = parseJSON$1({
1403
+ const parsedError = parseJSON({
1392
1404
  text: responseBody,
1393
1405
  schema: errorSchema
1394
1406
  });
1395
1407
  return {
1396
1408
  responseHeaders,
1397
- value: new APICallError$1({
1409
+ value: new APICallError({
1398
1410
  message: errorToMessage(parsedError),
1399
1411
  url,
1400
1412
  requestBodyValues,
@@ -1408,7 +1420,7 @@ var createJsonErrorResponseHandler$1 = ({
1408
1420
  } catch (parseError) {
1409
1421
  return {
1410
1422
  responseHeaders,
1411
- value: new APICallError$1({
1423
+ value: new APICallError({
1412
1424
  message: response.statusText,
1413
1425
  url,
1414
1426
  requestBodyValues,
@@ -1420,10 +1432,10 @@ var createJsonErrorResponseHandler$1 = ({
1420
1432
  };
1421
1433
  }
1422
1434
  };
1423
- var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) => {
1424
- const responseHeaders = extractResponseHeaders$1(response);
1435
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
1436
+ const responseHeaders = extractResponseHeaders(response);
1425
1437
  if (response.body == null) {
1426
- throw new EmptyResponseBodyError$1({});
1438
+ throw new EmptyResponseBodyError({});
1427
1439
  }
1428
1440
  return {
1429
1441
  responseHeaders,
@@ -1434,7 +1446,7 @@ var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) =
1434
1446
  return;
1435
1447
  }
1436
1448
  controller.enqueue(
1437
- safeParseJSON$1({
1449
+ safeParseJSON({
1438
1450
  text: data,
1439
1451
  schema: chunkSchema
1440
1452
  })
@@ -1444,15 +1456,15 @@ var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) =
1444
1456
  )
1445
1457
  };
1446
1458
  };
1447
- var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
1459
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
1448
1460
  const responseBody = await response.text();
1449
- const parsedResult = safeParseJSON$1({
1461
+ const parsedResult = safeParseJSON({
1450
1462
  text: responseBody,
1451
1463
  schema: responseSchema
1452
1464
  });
1453
- const responseHeaders = extractResponseHeaders$1(response);
1465
+ const responseHeaders = extractResponseHeaders(response);
1454
1466
  if (!parsedResult.success) {
1455
- throw new APICallError$1({
1467
+ throw new APICallError({
1456
1468
  message: "Invalid JSON response",
1457
1469
  cause: parsedResult.error,
1458
1470
  statusCode: response.status,
@@ -1469,9 +1481,9 @@ var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, re
1469
1481
  };
1470
1482
  };
1471
1483
  var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
1472
- const responseHeaders = extractResponseHeaders$1(response);
1484
+ const responseHeaders = extractResponseHeaders(response);
1473
1485
  if (!response.body) {
1474
- throw new APICallError$1({
1486
+ throw new APICallError({
1475
1487
  message: "Response body is empty",
1476
1488
  url,
1477
1489
  requestBodyValues,
@@ -1487,7 +1499,7 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
1487
1499
  value: new Uint8Array(buffer)
1488
1500
  };
1489
1501
  } catch (error) {
1490
- throw new APICallError$1({
1502
+ throw new APICallError({
1491
1503
  message: "Failed to read response as array buffer",
1492
1504
  url,
1493
1505
  requestBodyValues,
@@ -1500,22 +1512,22 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
1500
1512
  };
1501
1513
 
1502
1514
  // src/uint8-utils.ts
1503
- var { btoa: btoa$1, atob: atob$1 } = globalThis;
1515
+ var { btoa, atob: atob$1 } = globalThis;
1504
1516
  function convertBase64ToUint8Array(base64String) {
1505
1517
  const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
1506
1518
  const latin1string = atob$1(base64Url);
1507
1519
  return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
1508
1520
  }
1509
- function convertUint8ArrayToBase64$1(array) {
1521
+ function convertUint8ArrayToBase64(array) {
1510
1522
  let latin1string = "";
1511
1523
  for (let i = 0; i < array.length; i++) {
1512
1524
  latin1string += String.fromCodePoint(array[i]);
1513
1525
  }
1514
- return btoa$1(latin1string);
1526
+ return btoa(latin1string);
1515
1527
  }
1516
1528
 
1517
1529
  // src/without-trailing-slash.ts
1518
- function withoutTrailingSlash$1(url) {
1530
+ function withoutTrailingSlash(url) {
1519
1531
  return url == null ? void 0 : url.replace(/\/$/, "");
1520
1532
  }
1521
1533
 
@@ -5973,7 +5985,7 @@ function convertToOpenAIChatMessages({
5973
5985
  return {
5974
5986
  type: "image_url",
5975
5987
  image_url: {
5976
- url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
5988
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
5977
5989
  // OpenAI specific extension: image detail
5978
5990
  detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
5979
5991
  }
@@ -5981,7 +5993,7 @@ function convertToOpenAIChatMessages({
5981
5993
  }
5982
5994
  case "file": {
5983
5995
  if (part.data instanceof URL) {
5984
- throw new UnsupportedFunctionalityError$1({
5996
+ throw new UnsupportedFunctionalityError({
5985
5997
  functionality: "'File content parts with URL data' functionality not supported."
5986
5998
  });
5987
5999
  }
@@ -6009,7 +6021,7 @@ function convertToOpenAIChatMessages({
6009
6021
  };
6010
6022
  }
6011
6023
  default: {
6012
- throw new UnsupportedFunctionalityError$1({
6024
+ throw new UnsupportedFunctionalityError({
6013
6025
  functionality: `File content part type ${part.mimeType} in user messages`
6014
6026
  });
6015
6027
  }
@@ -6044,7 +6056,7 @@ function convertToOpenAIChatMessages({
6044
6056
  }
6045
6057
  if (useLegacyFunctionCalling) {
6046
6058
  if (toolCalls.length > 1) {
6047
- throw new UnsupportedFunctionalityError$1({
6059
+ throw new UnsupportedFunctionalityError({
6048
6060
  functionality: "useLegacyFunctionCalling with multiple tool calls in one message"
6049
6061
  });
6050
6062
  }
@@ -6129,7 +6141,7 @@ var openaiErrorDataSchema = z.object({
6129
6141
  code: z.union([z.string(), z.number()]).nullish()
6130
6142
  })
6131
6143
  });
6132
- var openaiFailedResponseHandler = createJsonErrorResponseHandler$1({
6144
+ var openaiFailedResponseHandler = createJsonErrorResponseHandler({
6133
6145
  errorSchema: openaiErrorDataSchema,
6134
6146
  errorToMessage: (data) => data.error.message
6135
6147
  });
@@ -6189,7 +6201,7 @@ function prepareTools$3({
6189
6201
  toolWarnings
6190
6202
  };
6191
6203
  case "required":
6192
- throw new UnsupportedFunctionalityError$1({
6204
+ throw new UnsupportedFunctionalityError({
6193
6205
  functionality: "useLegacyFunctionCalling and toolChoice: required"
6194
6206
  });
6195
6207
  default:
@@ -6238,7 +6250,7 @@ function prepareTools$3({
6238
6250
  };
6239
6251
  default: {
6240
6252
  const _exhaustiveCheck = type;
6241
- throw new UnsupportedFunctionalityError$1({
6253
+ throw new UnsupportedFunctionalityError({
6242
6254
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
6243
6255
  });
6244
6256
  }
@@ -6301,12 +6313,12 @@ var OpenAIChatLanguageModel = class {
6301
6313
  }
6302
6314
  const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling;
6303
6315
  if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) {
6304
- throw new UnsupportedFunctionalityError$1({
6316
+ throw new UnsupportedFunctionalityError({
6305
6317
  functionality: "useLegacyFunctionCalling with parallelToolCalls"
6306
6318
  });
6307
6319
  }
6308
6320
  if (useLegacyFunctionCalling && this.supportsStructuredOutputs) {
6309
- throw new UnsupportedFunctionalityError$1({
6321
+ throw new UnsupportedFunctionalityError({
6310
6322
  functionality: "structuredOutputs with useLegacyFunctionCalling"
6311
6323
  });
6312
6324
  }
@@ -6507,15 +6519,15 @@ var OpenAIChatLanguageModel = class {
6507
6519
  responseHeaders,
6508
6520
  value: response,
6509
6521
  rawValue: rawResponse
6510
- } = await postJsonToApi$1({
6522
+ } = await postJsonToApi({
6511
6523
  url: this.config.url({
6512
6524
  path: "/chat/completions",
6513
6525
  modelId: this.modelId
6514
6526
  }),
6515
- headers: combineHeaders$1(this.config.headers(), options.headers),
6527
+ headers: combineHeaders(this.config.headers(), options.headers),
6516
6528
  body,
6517
6529
  failedResponseHandler: openaiFailedResponseHandler,
6518
- successfulResponseHandler: createJsonResponseHandler$1(
6530
+ successfulResponseHandler: createJsonResponseHandler(
6519
6531
  openaiChatResponseSchema
6520
6532
  ),
6521
6533
  abortSignal: options.abortSignal,
@@ -6543,7 +6555,7 @@ var OpenAIChatLanguageModel = class {
6543
6555
  toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [
6544
6556
  {
6545
6557
  toolCallType: "function",
6546
- toolCallId: generateId$1(),
6558
+ toolCallId: generateId(),
6547
6559
  toolName: choice.message.function_call.name,
6548
6560
  args: choice.message.function_call.arguments
6549
6561
  }
@@ -6551,7 +6563,7 @@ var OpenAIChatLanguageModel = class {
6551
6563
  var _a2;
6552
6564
  return {
6553
6565
  toolCallType: "function",
6554
- toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId$1(),
6566
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
6555
6567
  toolName: toolCall.function.name,
6556
6568
  args: toolCall.function.arguments
6557
6569
  };
@@ -6621,15 +6633,15 @@ var OpenAIChatLanguageModel = class {
6621
6633
  // only include stream_options when in strict compatibility mode:
6622
6634
  stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
6623
6635
  };
6624
- const { responseHeaders, value: response } = await postJsonToApi$1({
6636
+ const { responseHeaders, value: response } = await postJsonToApi({
6625
6637
  url: this.config.url({
6626
6638
  path: "/chat/completions",
6627
6639
  modelId: this.modelId
6628
6640
  }),
6629
- headers: combineHeaders$1(this.config.headers(), options.headers),
6641
+ headers: combineHeaders(this.config.headers(), options.headers),
6630
6642
  body,
6631
6643
  failedResponseHandler: openaiFailedResponseHandler,
6632
- successfulResponseHandler: createEventSourceResponseHandler$1(
6644
+ successfulResponseHandler: createEventSourceResponseHandler(
6633
6645
  openaiChatChunkSchema
6634
6646
  ),
6635
6647
  abortSignal: options.abortSignal,
@@ -6717,7 +6729,7 @@ var OpenAIChatLanguageModel = class {
6717
6729
  const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [
6718
6730
  {
6719
6731
  type: "function",
6720
- id: generateId$1(),
6732
+ id: generateId(),
6721
6733
  function: delta.function_call,
6722
6734
  index: 0
6723
6735
  }
@@ -6727,19 +6739,19 @@ var OpenAIChatLanguageModel = class {
6727
6739
  const index = toolCallDelta.index;
6728
6740
  if (toolCalls[index] == null) {
6729
6741
  if (toolCallDelta.type !== "function") {
6730
- throw new InvalidResponseDataError$1({
6742
+ throw new InvalidResponseDataError({
6731
6743
  data: toolCallDelta,
6732
6744
  message: `Expected 'function' type.`
6733
6745
  });
6734
6746
  }
6735
6747
  if (toolCallDelta.id == null) {
6736
- throw new InvalidResponseDataError$1({
6748
+ throw new InvalidResponseDataError({
6737
6749
  data: toolCallDelta,
6738
6750
  message: `Expected 'id' to be a string.`
6739
6751
  });
6740
6752
  }
6741
6753
  if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
6742
- throw new InvalidResponseDataError$1({
6754
+ throw new InvalidResponseDataError({
6743
6755
  data: toolCallDelta,
6744
6756
  message: `Expected 'function.name' to be a string.`
6745
6757
  });
@@ -6764,11 +6776,11 @@ var OpenAIChatLanguageModel = class {
6764
6776
  argsTextDelta: toolCall2.function.arguments
6765
6777
  });
6766
6778
  }
6767
- if (isParsableJson$1(toolCall2.function.arguments)) {
6779
+ if (isParsableJson(toolCall2.function.arguments)) {
6768
6780
  controller.enqueue({
6769
6781
  type: "tool-call",
6770
6782
  toolCallType: "function",
6771
- toolCallId: (_e = toolCall2.id) != null ? _e : generateId$1(),
6783
+ toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
6772
6784
  toolName: toolCall2.function.name,
6773
6785
  args: toolCall2.function.arguments
6774
6786
  });
@@ -6791,11 +6803,11 @@ var OpenAIChatLanguageModel = class {
6791
6803
  toolName: toolCall.function.name,
6792
6804
  argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
6793
6805
  });
6794
- if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson$1(toolCall.function.arguments)) {
6806
+ if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
6795
6807
  controller.enqueue({
6796
6808
  type: "tool-call",
6797
6809
  toolCallType: "function",
6798
- toolCallId: (_l = toolCall.id) != null ? _l : generateId$1(),
6810
+ toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
6799
6811
  toolName: toolCall.function.name,
6800
6812
  args: toolCall.function.arguments
6801
6813
  });
@@ -6994,7 +7006,7 @@ function convertToOpenAICompletionPrompt({
6994
7006
  for (const { role, content } of prompt) {
6995
7007
  switch (role) {
6996
7008
  case "system": {
6997
- throw new InvalidPromptError$1({
7009
+ throw new InvalidPromptError({
6998
7010
  message: "Unexpected system message in prompt: ${content}",
6999
7011
  prompt
7000
7012
  });
@@ -7006,7 +7018,7 @@ function convertToOpenAICompletionPrompt({
7006
7018
  return part.text;
7007
7019
  }
7008
7020
  case "image": {
7009
- throw new UnsupportedFunctionalityError$1({
7021
+ throw new UnsupportedFunctionalityError({
7010
7022
  functionality: "images"
7011
7023
  });
7012
7024
  }
@@ -7025,7 +7037,7 @@ ${userMessage}
7025
7037
  return part.text;
7026
7038
  }
7027
7039
  case "tool-call": {
7028
- throw new UnsupportedFunctionalityError$1({
7040
+ throw new UnsupportedFunctionalityError({
7029
7041
  functionality: "tool-call messages"
7030
7042
  });
7031
7043
  }
@@ -7038,7 +7050,7 @@ ${assistantMessage}
7038
7050
  break;
7039
7051
  }
7040
7052
  case "tool": {
7041
- throw new UnsupportedFunctionalityError$1({
7053
+ throw new UnsupportedFunctionalityError({
7042
7054
  functionality: "tool messages"
7043
7055
  });
7044
7056
  }
@@ -7139,24 +7151,24 @@ var OpenAICompletionLanguageModel = class {
7139
7151
  switch (type) {
7140
7152
  case "regular": {
7141
7153
  if ((_a = mode.tools) == null ? void 0 : _a.length) {
7142
- throw new UnsupportedFunctionalityError$1({
7154
+ throw new UnsupportedFunctionalityError({
7143
7155
  functionality: "tools"
7144
7156
  });
7145
7157
  }
7146
7158
  if (mode.toolChoice) {
7147
- throw new UnsupportedFunctionalityError$1({
7159
+ throw new UnsupportedFunctionalityError({
7148
7160
  functionality: "toolChoice"
7149
7161
  });
7150
7162
  }
7151
7163
  return { args: baseArgs, warnings };
7152
7164
  }
7153
7165
  case "object-json": {
7154
- throw new UnsupportedFunctionalityError$1({
7166
+ throw new UnsupportedFunctionalityError({
7155
7167
  functionality: "object-json mode"
7156
7168
  });
7157
7169
  }
7158
7170
  case "object-tool": {
7159
- throw new UnsupportedFunctionalityError$1({
7171
+ throw new UnsupportedFunctionalityError({
7160
7172
  functionality: "object-tool mode"
7161
7173
  });
7162
7174
  }
@@ -7172,15 +7184,15 @@ var OpenAICompletionLanguageModel = class {
7172
7184
  responseHeaders,
7173
7185
  value: response,
7174
7186
  rawValue: rawResponse
7175
- } = await postJsonToApi$1({
7187
+ } = await postJsonToApi({
7176
7188
  url: this.config.url({
7177
7189
  path: "/completions",
7178
7190
  modelId: this.modelId
7179
7191
  }),
7180
- headers: combineHeaders$1(this.config.headers(), options.headers),
7192
+ headers: combineHeaders(this.config.headers(), options.headers),
7181
7193
  body: args,
7182
7194
  failedResponseHandler: openaiFailedResponseHandler,
7183
- successfulResponseHandler: createJsonResponseHandler$1(
7195
+ successfulResponseHandler: createJsonResponseHandler(
7184
7196
  openaiCompletionResponseSchema
7185
7197
  ),
7186
7198
  abortSignal: options.abortSignal,
@@ -7211,15 +7223,15 @@ var OpenAICompletionLanguageModel = class {
7211
7223
  // only include stream_options when in strict compatibility mode:
7212
7224
  stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
7213
7225
  };
7214
- const { responseHeaders, value: response } = await postJsonToApi$1({
7226
+ const { responseHeaders, value: response } = await postJsonToApi({
7215
7227
  url: this.config.url({
7216
7228
  path: "/completions",
7217
7229
  modelId: this.modelId
7218
7230
  }),
7219
- headers: combineHeaders$1(this.config.headers(), options.headers),
7231
+ headers: combineHeaders(this.config.headers(), options.headers),
7220
7232
  body,
7221
7233
  failedResponseHandler: openaiFailedResponseHandler,
7222
- successfulResponseHandler: createEventSourceResponseHandler$1(
7234
+ successfulResponseHandler: createEventSourceResponseHandler(
7223
7235
  openaiCompletionChunkSchema
7224
7236
  ),
7225
7237
  abortSignal: options.abortSignal,
@@ -7371,12 +7383,12 @@ var OpenAIEmbeddingModel = class {
7371
7383
  values
7372
7384
  });
7373
7385
  }
7374
- const { responseHeaders, value: response } = await postJsonToApi$1({
7386
+ const { responseHeaders, value: response } = await postJsonToApi({
7375
7387
  url: this.config.url({
7376
7388
  path: "/embeddings",
7377
7389
  modelId: this.modelId
7378
7390
  }),
7379
- headers: combineHeaders$1(this.config.headers(), headers),
7391
+ headers: combineHeaders(this.config.headers(), headers),
7380
7392
  body: {
7381
7393
  model: this.modelId,
7382
7394
  input: values,
@@ -7385,7 +7397,7 @@ var OpenAIEmbeddingModel = class {
7385
7397
  user: this.settings.user
7386
7398
  },
7387
7399
  failedResponseHandler: openaiFailedResponseHandler,
7388
- successfulResponseHandler: createJsonResponseHandler$1(
7400
+ successfulResponseHandler: createJsonResponseHandler(
7389
7401
  openaiTextEmbeddingResponseSchema
7390
7402
  ),
7391
7403
  abortSignal,
@@ -7449,12 +7461,12 @@ var OpenAIImageModel = class {
7449
7461
  warnings.push({ type: "unsupported-setting", setting: "seed" });
7450
7462
  }
7451
7463
  const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
7452
- const { value: response, responseHeaders } = await postJsonToApi$1({
7464
+ const { value: response, responseHeaders } = await postJsonToApi({
7453
7465
  url: this.config.url({
7454
7466
  path: "/images/generations",
7455
7467
  modelId: this.modelId
7456
7468
  }),
7457
- headers: combineHeaders$1(this.config.headers(), headers),
7469
+ headers: combineHeaders(this.config.headers(), headers),
7458
7470
  body: {
7459
7471
  model: this.modelId,
7460
7472
  prompt,
@@ -7464,7 +7476,7 @@ var OpenAIImageModel = class {
7464
7476
  ...!hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {}
7465
7477
  },
7466
7478
  failedResponseHandler: openaiFailedResponseHandler,
7467
- successfulResponseHandler: createJsonResponseHandler$1(
7479
+ successfulResponseHandler: createJsonResponseHandler(
7468
7480
  openaiImageResponseSchema
7469
7481
  ),
7470
7482
  abortSignal,
@@ -7608,10 +7620,10 @@ var OpenAITranscriptionModel = class {
7608
7620
  path: "/audio/transcriptions",
7609
7621
  modelId: this.modelId
7610
7622
  }),
7611
- headers: combineHeaders$1(this.config.headers(), options.headers),
7623
+ headers: combineHeaders(this.config.headers(), options.headers),
7612
7624
  formData,
7613
7625
  failedResponseHandler: openaiFailedResponseHandler,
7614
- successfulResponseHandler: createJsonResponseHandler$1(
7626
+ successfulResponseHandler: createJsonResponseHandler(
7615
7627
  openaiTranscriptionResponseSchema
7616
7628
  ),
7617
7629
  abortSignal: options.abortSignal,
@@ -7695,14 +7707,14 @@ function convertToOpenAIResponsesMessages({
7695
7707
  case "image": {
7696
7708
  return {
7697
7709
  type: "input_image",
7698
- image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
7710
+ image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
7699
7711
  // OpenAI specific extension: image detail
7700
7712
  detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
7701
7713
  };
7702
7714
  }
7703
7715
  case "file": {
7704
7716
  if (part.data instanceof URL) {
7705
- throw new UnsupportedFunctionalityError$1({
7717
+ throw new UnsupportedFunctionalityError({
7706
7718
  functionality: "File URLs in user messages"
7707
7719
  });
7708
7720
  }
@@ -7715,7 +7727,7 @@ function convertToOpenAIResponsesMessages({
7715
7727
  };
7716
7728
  }
7717
7729
  default: {
7718
- throw new UnsupportedFunctionalityError$1({
7730
+ throw new UnsupportedFunctionalityError({
7719
7731
  functionality: "Only PDF files are supported in user messages"
7720
7732
  });
7721
7733
  }
@@ -7857,7 +7869,7 @@ function prepareResponsesTools({
7857
7869
  }
7858
7870
  default: {
7859
7871
  const _exhaustiveCheck = type;
7860
- throw new UnsupportedFunctionalityError$1({
7872
+ throw new UnsupportedFunctionalityError({
7861
7873
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
7862
7874
  });
7863
7875
  }
@@ -8056,15 +8068,15 @@ var OpenAIResponsesLanguageModel = class {
8056
8068
  responseHeaders,
8057
8069
  value: response,
8058
8070
  rawValue: rawResponse
8059
- } = await postJsonToApi$1({
8071
+ } = await postJsonToApi({
8060
8072
  url: this.config.url({
8061
8073
  path: "/responses",
8062
8074
  modelId: this.modelId
8063
8075
  }),
8064
- headers: combineHeaders$1(this.config.headers(), options.headers),
8076
+ headers: combineHeaders(this.config.headers(), options.headers),
8065
8077
  body,
8066
8078
  failedResponseHandler: openaiFailedResponseHandler,
8067
- successfulResponseHandler: createJsonResponseHandler$1(
8079
+ successfulResponseHandler: createJsonResponseHandler(
8068
8080
  z.object({
8069
8081
  id: z.string(),
8070
8082
  created_at: z.number(),
@@ -8135,7 +8147,7 @@ var OpenAIResponsesLanguageModel = class {
8135
8147
  var _a2, _b2, _c2;
8136
8148
  return {
8137
8149
  sourceType: "url",
8138
- id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId$1(),
8150
+ id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId(),
8139
8151
  url: annotation.url,
8140
8152
  title: annotation.title
8141
8153
  };
@@ -8182,18 +8194,18 @@ var OpenAIResponsesLanguageModel = class {
8182
8194
  }
8183
8195
  async doStream(options) {
8184
8196
  const { args: body, warnings } = this.getArgs(options);
8185
- const { responseHeaders, value: response } = await postJsonToApi$1({
8197
+ const { responseHeaders, value: response } = await postJsonToApi({
8186
8198
  url: this.config.url({
8187
8199
  path: "/responses",
8188
8200
  modelId: this.modelId
8189
8201
  }),
8190
- headers: combineHeaders$1(this.config.headers(), options.headers),
8202
+ headers: combineHeaders(this.config.headers(), options.headers),
8191
8203
  body: {
8192
8204
  ...body,
8193
8205
  stream: true
8194
8206
  },
8195
8207
  failedResponseHandler: openaiFailedResponseHandler,
8196
- successfulResponseHandler: createEventSourceResponseHandler$1(
8208
+ successfulResponseHandler: createEventSourceResponseHandler(
8197
8209
  openaiResponsesChunkSchema
8198
8210
  ),
8199
8211
  abortSignal: options.abortSignal,
@@ -8286,7 +8298,7 @@ var OpenAIResponsesLanguageModel = class {
8286
8298
  type: "source",
8287
8299
  source: {
8288
8300
  sourceType: "url",
8289
- id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId$1(),
8301
+ id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId(),
8290
8302
  url: value.annotation.url,
8291
8303
  title: value.annotation.title
8292
8304
  }
@@ -8554,12 +8566,12 @@ var OpenAISpeechModel = class {
8554
8566
  value: audio,
8555
8567
  responseHeaders,
8556
8568
  rawValue: rawResponse
8557
- } = await postJsonToApi$1({
8569
+ } = await postJsonToApi({
8558
8570
  url: this.config.url({
8559
8571
  path: "/audio/speech",
8560
8572
  modelId: this.modelId
8561
8573
  }),
8562
- headers: combineHeaders$1(this.config.headers(), options.headers),
8574
+ headers: combineHeaders(this.config.headers(), options.headers),
8563
8575
  body: requestBody,
8564
8576
  failedResponseHandler: openaiFailedResponseHandler,
8565
8577
  successfulResponseHandler: createBinaryResponseHandler(),
@@ -8585,11 +8597,11 @@ var OpenAISpeechModel = class {
8585
8597
  // src/openai-provider.ts
8586
8598
  function createOpenAI(options = {}) {
8587
8599
  var _a, _b, _c;
8588
- const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
8600
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
8589
8601
  const compatibility = (_b = options.compatibility) != null ? _b : "compatible";
8590
8602
  const providerName = (_c = options.name) != null ? _c : "openai";
8591
8603
  const getHeaders = () => ({
8592
- Authorization: `Bearer ${loadApiKey$1({
8604
+ Authorization: `Bearer ${loadApiKey({
8593
8605
  apiKey: options.apiKey,
8594
8606
  environmentVariableName: "OPENAI_API_KEY",
8595
8607
  description: "OpenAI"
@@ -8690,7 +8702,7 @@ var anthropicErrorDataSchema = z.object({
8690
8702
  message: z.string()
8691
8703
  })
8692
8704
  });
8693
- var anthropicFailedResponseHandler = createJsonErrorResponseHandler$1({
8705
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
8694
8706
  errorSchema: anthropicErrorDataSchema,
8695
8707
  errorToMessage: (data) => data.error.message
8696
8708
  });
@@ -8808,7 +8820,7 @@ function prepareTools$2(mode) {
8808
8820
  };
8809
8821
  default: {
8810
8822
  const _exhaustiveCheck = type;
8811
- throw new UnsupportedFunctionalityError$1({
8823
+ throw new UnsupportedFunctionalityError({
8812
8824
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
8813
8825
  });
8814
8826
  }
@@ -8837,7 +8849,7 @@ function convertToAnthropicMessagesPrompt({
8837
8849
  switch (type) {
8838
8850
  case "system": {
8839
8851
  if (system != null) {
8840
- throw new UnsupportedFunctionalityError$1({
8852
+ throw new UnsupportedFunctionalityError({
8841
8853
  functionality: "Multiple system messages that are separated by user/assistant messages"
8842
8854
  });
8843
8855
  }
@@ -8876,7 +8888,7 @@ function convertToAnthropicMessagesPrompt({
8876
8888
  } : {
8877
8889
  type: "base64",
8878
8890
  media_type: (_b = part.mimeType) != null ? _b : "image/jpeg",
8879
- data: convertUint8ArrayToBase64$1(part.image)
8891
+ data: convertUint8ArrayToBase64(part.image)
8880
8892
  },
8881
8893
  cache_control: cacheControl
8882
8894
  });
@@ -8884,7 +8896,7 @@ function convertToAnthropicMessagesPrompt({
8884
8896
  }
8885
8897
  case "file": {
8886
8898
  if (part.mimeType !== "application/pdf") {
8887
- throw new UnsupportedFunctionalityError$1({
8899
+ throw new UnsupportedFunctionalityError({
8888
8900
  functionality: "Non-PDF files in user messages"
8889
8901
  });
8890
8902
  }
@@ -9181,7 +9193,7 @@ var AnthropicMessagesLanguageModel = class {
9181
9193
  };
9182
9194
  if (isThinking) {
9183
9195
  if (thinkingBudget == null) {
9184
- throw new UnsupportedFunctionalityError$1({
9196
+ throw new UnsupportedFunctionalityError({
9185
9197
  functionality: "thinking requires a budget"
9186
9198
  });
9187
9199
  }
@@ -9226,7 +9238,7 @@ var AnthropicMessagesLanguageModel = class {
9226
9238
  };
9227
9239
  }
9228
9240
  case "object-json": {
9229
- throw new UnsupportedFunctionalityError$1({
9241
+ throw new UnsupportedFunctionalityError({
9230
9242
  functionality: "json-mode object generation"
9231
9243
  });
9232
9244
  }
@@ -9252,7 +9264,7 @@ var AnthropicMessagesLanguageModel = class {
9252
9264
  betas,
9253
9265
  headers
9254
9266
  }) {
9255
- return combineHeaders$1(
9267
+ return combineHeaders(
9256
9268
  await resolve(this.config.headers),
9257
9269
  betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
9258
9270
  headers
@@ -9273,12 +9285,12 @@ var AnthropicMessagesLanguageModel = class {
9273
9285
  responseHeaders,
9274
9286
  value: response,
9275
9287
  rawValue: rawResponse
9276
- } = await postJsonToApi$1({
9288
+ } = await postJsonToApi({
9277
9289
  url: this.buildRequestUrl(false),
9278
9290
  headers: await this.getHeaders({ betas, headers: options.headers }),
9279
9291
  body: this.transformRequestBody(args),
9280
9292
  failedResponseHandler: anthropicFailedResponseHandler,
9281
- successfulResponseHandler: createJsonResponseHandler$1(
9293
+ successfulResponseHandler: createJsonResponseHandler(
9282
9294
  anthropicMessagesResponseSchema
9283
9295
  ),
9284
9296
  abortSignal: options.abortSignal,
@@ -9348,12 +9360,12 @@ var AnthropicMessagesLanguageModel = class {
9348
9360
  async doStream(options) {
9349
9361
  const { args, warnings, betas } = await this.getArgs(options);
9350
9362
  const body = { ...args, stream: true };
9351
- const { responseHeaders, value: response } = await postJsonToApi$1({
9363
+ const { responseHeaders, value: response } = await postJsonToApi({
9352
9364
  url: this.buildRequestUrl(true),
9353
9365
  headers: await this.getHeaders({ betas, headers: options.headers }),
9354
9366
  body: this.transformRequestBody(body),
9355
9367
  failedResponseHandler: anthropicFailedResponseHandler,
9356
- successfulResponseHandler: createEventSourceResponseHandler$1(
9368
+ successfulResponseHandler: createEventSourceResponseHandler(
9357
9369
  anthropicMessagesChunkSchema
9358
9370
  ),
9359
9371
  abortSignal: options.abortSignal,
@@ -9794,10 +9806,10 @@ var anthropicTools = {
9794
9806
  // src/anthropic-provider.ts
9795
9807
  function createAnthropic(options = {}) {
9796
9808
  var _a;
9797
- const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
9809
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
9798
9810
  const getHeaders = () => ({
9799
9811
  "anthropic-version": "2023-06-01",
9800
- "x-api-key": loadApiKey$1({
9812
+ "x-api-key": loadApiKey({
9801
9813
  apiKey: options.apiKey,
9802
9814
  environmentVariableName: "ANTHROPIC_API_KEY",
9803
9815
  description: "Anthropic"
@@ -9937,7 +9949,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
9937
9949
  switch (role) {
9938
9950
  case "system": {
9939
9951
  if (!systemMessagesAllowed) {
9940
- throw new UnsupportedFunctionalityError$1({
9952
+ throw new UnsupportedFunctionalityError({
9941
9953
  functionality: "system messages are only supported at the beginning of the conversation"
9942
9954
  });
9943
9955
  }
@@ -9963,7 +9975,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
9963
9975
  } : {
9964
9976
  inlineData: {
9965
9977
  mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg",
9966
- data: convertUint8ArrayToBase64$1(part.image)
9978
+ data: convertUint8ArrayToBase64(part.image)
9967
9979
  }
9968
9980
  }
9969
9981
  );
@@ -10001,12 +10013,12 @@ function convertToGoogleGenerativeAIMessages(prompt) {
10001
10013
  }
10002
10014
  case "file": {
10003
10015
  if (part.mimeType !== "image/png") {
10004
- throw new UnsupportedFunctionalityError$1({
10016
+ throw new UnsupportedFunctionalityError({
10005
10017
  functionality: "Only PNG images are supported in assistant messages"
10006
10018
  });
10007
10019
  }
10008
10020
  if (part.data instanceof URL) {
10009
- throw new UnsupportedFunctionalityError$1({
10021
+ throw new UnsupportedFunctionalityError({
10010
10022
  functionality: "File data URLs in assistant messages are not supported"
10011
10023
  });
10012
10024
  }
@@ -10065,7 +10077,7 @@ var googleErrorDataSchema = z.object({
10065
10077
  status: z.string()
10066
10078
  })
10067
10079
  });
10068
- var googleFailedResponseHandler = createJsonErrorResponseHandler$1({
10080
+ var googleFailedResponseHandler = createJsonErrorResponseHandler({
10069
10081
  errorSchema: googleErrorDataSchema,
10070
10082
  errorToMessage: (data) => data.error.message
10071
10083
  });
@@ -10140,7 +10152,7 @@ function prepareTools$1(mode, useSearchGrounding, dynamicRetrievalConfig, modelI
10140
10152
  };
10141
10153
  default: {
10142
10154
  const _exhaustiveCheck = type;
10143
- throw new UnsupportedFunctionalityError$1({
10155
+ throw new UnsupportedFunctionalityError({
10144
10156
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
10145
10157
  });
10146
10158
  }
@@ -10317,7 +10329,7 @@ var GoogleGenerativeAILanguageModel = class {
10317
10329
  var _a, _b, _c, _d, _e;
10318
10330
  const { args, warnings } = await this.getArgs(options);
10319
10331
  const body = JSON.stringify(args);
10320
- const mergedHeaders = combineHeaders$1(
10332
+ const mergedHeaders = combineHeaders(
10321
10333
  await resolve(this.config.headers),
10322
10334
  options.headers
10323
10335
  );
@@ -10325,14 +10337,14 @@ var GoogleGenerativeAILanguageModel = class {
10325
10337
  responseHeaders,
10326
10338
  value: response,
10327
10339
  rawValue: rawResponse
10328
- } = await postJsonToApi$1({
10340
+ } = await postJsonToApi({
10329
10341
  url: `${this.config.baseURL}/${getModelPath(
10330
10342
  this.modelId
10331
10343
  )}:generateContent`,
10332
10344
  headers: mergedHeaders,
10333
10345
  body: args,
10334
10346
  failedResponseHandler: googleFailedResponseHandler,
10335
- successfulResponseHandler: createJsonResponseHandler$1(responseSchema),
10347
+ successfulResponseHandler: createJsonResponseHandler(responseSchema),
10336
10348
  abortSignal: options.abortSignal,
10337
10349
  fetch: this.config.fetch
10338
10350
  });
@@ -10380,18 +10392,18 @@ var GoogleGenerativeAILanguageModel = class {
10380
10392
  async doStream(options) {
10381
10393
  const { args, warnings } = await this.getArgs(options);
10382
10394
  const body = JSON.stringify(args);
10383
- const headers = combineHeaders$1(
10395
+ const headers = combineHeaders(
10384
10396
  await resolve(this.config.headers),
10385
10397
  options.headers
10386
10398
  );
10387
- const { responseHeaders, value: response } = await postJsonToApi$1({
10399
+ const { responseHeaders, value: response } = await postJsonToApi({
10388
10400
  url: `${this.config.baseURL}/${getModelPath(
10389
10401
  this.modelId
10390
10402
  )}:streamGenerateContent?alt=sse`,
10391
10403
  headers,
10392
10404
  body: args,
10393
10405
  failedResponseHandler: googleFailedResponseHandler,
10394
- successfulResponseHandler: createEventSourceResponseHandler$1(chunkSchema),
10406
+ successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
10395
10407
  abortSignal: options.abortSignal,
10396
10408
  fetch: this.config.fetch
10397
10409
  });
@@ -10538,7 +10550,7 @@ function getTextFromParts(parts) {
10538
10550
  }
10539
10551
  function getReasoningDetailsFromParts(parts) {
10540
10552
  const reasoningParts = parts == null ? void 0 : parts.filter(
10541
- (part) => "text" in part && part.thought === true
10553
+ (part) => "text" in part && part.thought === true && part.text != null
10542
10554
  );
10543
10555
  return reasoningParts == null || reasoningParts.length === 0 ? void 0 : reasoningParts.map((part) => ({ type: "text", text: part.text }));
10544
10556
  }
@@ -10562,13 +10574,9 @@ function extractSources({
10562
10574
  }));
10563
10575
  }
10564
10576
  var contentSchema = z.object({
10565
- role: z.string(),
10566
10577
  parts: z.array(
10567
10578
  z.union([
10568
- z.object({
10569
- text: z.string(),
10570
- thought: z.boolean().nullish()
10571
- }),
10579
+ // note: order matters since text can be fully empty
10572
10580
  z.object({
10573
10581
  functionCall: z.object({
10574
10582
  name: z.string(),
@@ -10580,6 +10588,10 @@ var contentSchema = z.object({
10580
10588
  mimeType: z.string(),
10581
10589
  data: z.string()
10582
10590
  })
10591
+ }),
10592
+ z.object({
10593
+ text: z.string().nullish(),
10594
+ thought: z.boolean().nullish()
10583
10595
  })
10584
10596
  ])
10585
10597
  ).nullish()
@@ -10688,11 +10700,11 @@ var GoogleGenerativeAIEmbeddingModel = class {
10688
10700
  values
10689
10701
  });
10690
10702
  }
10691
- const mergedHeaders = combineHeaders$1(
10703
+ const mergedHeaders = combineHeaders(
10692
10704
  await resolve(this.config.headers),
10693
10705
  headers
10694
10706
  );
10695
- const { responseHeaders, value: response } = await postJsonToApi$1({
10707
+ const { responseHeaders, value: response } = await postJsonToApi({
10696
10708
  url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
10697
10709
  headers: mergedHeaders,
10698
10710
  body: {
@@ -10704,7 +10716,7 @@ var GoogleGenerativeAIEmbeddingModel = class {
10704
10716
  }))
10705
10717
  },
10706
10718
  failedResponseHandler: googleFailedResponseHandler,
10707
- successfulResponseHandler: createJsonResponseHandler$1(
10719
+ successfulResponseHandler: createJsonResponseHandler(
10708
10720
  googleGenerativeAITextEmbeddingResponseSchema
10709
10721
  ),
10710
10722
  abortSignal,
@@ -10729,9 +10741,9 @@ function isSupportedFileUrl(url) {
10729
10741
  // src/google-provider.ts
10730
10742
  function createGoogleGenerativeAI(options = {}) {
10731
10743
  var _a;
10732
- const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
10744
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
10733
10745
  const getHeaders = () => ({
10734
- "x-goog-api-key": loadApiKey$1({
10746
+ "x-goog-api-key": loadApiKey({
10735
10747
  apiKey: options.apiKey,
10736
10748
  environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
10737
10749
  description: "Google Generative AI"
@@ -10744,7 +10756,7 @@ function createGoogleGenerativeAI(options = {}) {
10744
10756
  provider: "google.generative-ai",
10745
10757
  baseURL,
10746
10758
  headers: getHeaders,
10747
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId$1,
10759
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
10748
10760
  isSupportedUrl: isSupportedFileUrl,
10749
10761
  fetch: options.fetch
10750
10762
  });
@@ -11553,9 +11565,9 @@ var BedrockErrorSchema = z.object({
11553
11565
  type: z.string().nullish()
11554
11566
  });
11555
11567
  var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response }) => {
11556
- const responseHeaders = extractResponseHeaders$1(response);
11568
+ const responseHeaders = extractResponseHeaders(response);
11557
11569
  if (response.body == null) {
11558
- throw new EmptyResponseBodyError$1({});
11570
+ throw new EmptyResponseBodyError({});
11559
11571
  }
11560
11572
  const codec = new EventStreamCodec(toUtf8, fromUtf8);
11561
11573
  let buffer = new Uint8Array(0);
@@ -11585,7 +11597,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
11585
11597
  buffer = buffer.slice(totalLength);
11586
11598
  if (((_a = decoded.headers[":message-type"]) == null ? void 0 : _a.value) === "event") {
11587
11599
  const data = textDecoder.decode(decoded.body);
11588
- const parsedDataResult = safeParseJSON$1({ text: data });
11600
+ const parsedDataResult = safeParseJSON({ text: data });
11589
11601
  if (!parsedDataResult.success) {
11590
11602
  controller.enqueue(parsedDataResult);
11591
11603
  break;
@@ -11594,7 +11606,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
11594
11606
  let wrappedData = {
11595
11607
  [(_b = decoded.headers[":event-type"]) == null ? void 0 : _b.value]: parsedDataResult.value
11596
11608
  };
11597
- const validatedWrappedData = safeValidateTypes$1({
11609
+ const validatedWrappedData = safeValidateTypes({
11598
11610
  value: wrappedData,
11599
11611
  schema: chunkSchema
11600
11612
  });
@@ -11677,13 +11689,13 @@ function prepareTools(mode) {
11677
11689
  };
11678
11690
  default: {
11679
11691
  const _exhaustiveCheck = type;
11680
- throw new UnsupportedFunctionalityError$1({
11692
+ throw new UnsupportedFunctionalityError({
11681
11693
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
11682
11694
  });
11683
11695
  }
11684
11696
  }
11685
11697
  }
11686
- var generateFileId = createIdGenerator$1({ prefix: "file", size: 16 });
11698
+ var generateFileId = createIdGenerator({ prefix: "file", size: 16 });
11687
11699
  function getCachePoint(providerMetadata) {
11688
11700
  var _a;
11689
11701
  return (_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.cachePoint;
@@ -11700,7 +11712,7 @@ function convertToBedrockChatMessages(prompt) {
11700
11712
  switch (type) {
11701
11713
  case "system": {
11702
11714
  if (messages.length > 0) {
11703
- throw new UnsupportedFunctionalityError$1({
11715
+ throw new UnsupportedFunctionalityError({
11704
11716
  functionality: "Multiple system messages that are separated by user/assistant messages"
11705
11717
  });
11706
11718
  }
@@ -11729,7 +11741,7 @@ function convertToBedrockChatMessages(prompt) {
11729
11741
  }
11730
11742
  case "image": {
11731
11743
  if (part.image instanceof URL) {
11732
- throw new UnsupportedFunctionalityError$1({
11744
+ throw new UnsupportedFunctionalityError({
11733
11745
  functionality: "Image URLs in user messages"
11734
11746
  });
11735
11747
  }
@@ -11739,7 +11751,7 @@ function convertToBedrockChatMessages(prompt) {
11739
11751
  "/"
11740
11752
  )) == null ? void 0 : _b[1],
11741
11753
  source: {
11742
- bytes: convertUint8ArrayToBase64$1(
11754
+ bytes: convertUint8ArrayToBase64(
11743
11755
  (_c = part.image) != null ? _c : part.image
11744
11756
  )
11745
11757
  }
@@ -11749,7 +11761,7 @@ function convertToBedrockChatMessages(prompt) {
11749
11761
  }
11750
11762
  case "file": {
11751
11763
  if (part.data instanceof URL) {
11752
- throw new UnsupportedFunctionalityError$1({
11764
+ throw new UnsupportedFunctionalityError({
11753
11765
  functionality: "File URLs in user messages"
11754
11766
  });
11755
11767
  }
@@ -12039,7 +12051,7 @@ var BedrockChatLanguageModel = class {
12039
12051
  (_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.reasoning_config
12040
12052
  );
12041
12053
  if (!reasoningConfigOptions.success) {
12042
- throw new InvalidArgumentError$1({
12054
+ throw new InvalidArgumentError({
12043
12055
  argument: "providerOptions.bedrock.reasoning_config",
12044
12056
  message: "invalid reasoning configuration options",
12045
12057
  cause: reasoningConfigOptions.error
@@ -12104,7 +12116,7 @@ var BedrockChatLanguageModel = class {
12104
12116
  };
12105
12117
  }
12106
12118
  case "object-json": {
12107
- throw new UnsupportedFunctionalityError$1({
12119
+ throw new UnsupportedFunctionalityError({
12108
12120
  functionality: "json-mode object generation"
12109
12121
  });
12110
12122
  }
@@ -12140,21 +12152,21 @@ var BedrockChatLanguageModel = class {
12140
12152
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
12141
12153
  const { command: args, warnings } = this.getArgs(options);
12142
12154
  const url = `${this.getUrl(this.modelId)}/converse`;
12143
- const { value: response, responseHeaders } = await postJsonToApi$1({
12155
+ const { value: response, responseHeaders } = await postJsonToApi({
12144
12156
  url,
12145
- headers: combineHeaders$1(
12157
+ headers: combineHeaders(
12146
12158
  await resolve(this.config.headers),
12147
12159
  options.headers
12148
12160
  ),
12149
12161
  body: args,
12150
- failedResponseHandler: createJsonErrorResponseHandler$1({
12162
+ failedResponseHandler: createJsonErrorResponseHandler({
12151
12163
  errorSchema: BedrockErrorSchema,
12152
12164
  errorToMessage: (error) => {
12153
12165
  var _a2;
12154
12166
  return `${(_a2 = error.message) != null ? _a2 : "Unknown error"}`;
12155
12167
  }
12156
12168
  }),
12157
- successfulResponseHandler: createJsonResponseHandler$1(
12169
+ successfulResponseHandler: createJsonResponseHandler(
12158
12170
  BedrockResponseSchema
12159
12171
  ),
12160
12172
  abortSignal: options.abortSignal,
@@ -12222,14 +12234,14 @@ var BedrockChatLanguageModel = class {
12222
12234
  async doStream(options) {
12223
12235
  const { command: args, warnings } = this.getArgs(options);
12224
12236
  const url = `${this.getUrl(this.modelId)}/converse-stream`;
12225
- const { value: response, responseHeaders } = await postJsonToApi$1({
12237
+ const { value: response, responseHeaders } = await postJsonToApi({
12226
12238
  url,
12227
- headers: combineHeaders$1(
12239
+ headers: combineHeaders(
12228
12240
  await resolve(this.config.headers),
12229
12241
  options.headers
12230
12242
  ),
12231
12243
  body: args,
12232
- failedResponseHandler: createJsonErrorResponseHandler$1({
12244
+ failedResponseHandler: createJsonErrorResponseHandler({
12233
12245
  errorSchema: BedrockErrorSchema,
12234
12246
  errorToMessage: (error) => `${error.type}: ${error.message}`
12235
12247
  }),
@@ -12512,17 +12524,17 @@ var BedrockEmbeddingModel = class {
12512
12524
  normalize: this.settings.normalize
12513
12525
  };
12514
12526
  const url = this.getUrl(this.modelId);
12515
- const { value: response } = await postJsonToApi$1({
12527
+ const { value: response } = await postJsonToApi({
12516
12528
  url,
12517
12529
  headers: await resolve(
12518
- combineHeaders$1(await resolve(this.config.headers), headers)
12530
+ combineHeaders(await resolve(this.config.headers), headers)
12519
12531
  ),
12520
12532
  body: args,
12521
- failedResponseHandler: createJsonErrorResponseHandler$1({
12533
+ failedResponseHandler: createJsonErrorResponseHandler({
12522
12534
  errorSchema: BedrockErrorSchema,
12523
12535
  errorToMessage: (error) => `${error.type}: ${error.message}`
12524
12536
  }),
12525
- successfulResponseHandler: createJsonResponseHandler$1(
12537
+ successfulResponseHandler: createJsonResponseHandler(
12526
12538
  BedrockEmbeddingResponseSchema
12527
12539
  ),
12528
12540
  fetch: this.config.fetch,
@@ -12607,17 +12619,17 @@ var BedrockImageModel = class {
12607
12619
  });
12608
12620
  }
12609
12621
  const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
12610
- const { value: response, responseHeaders } = await postJsonToApi$1({
12622
+ const { value: response, responseHeaders } = await postJsonToApi({
12611
12623
  url: this.getUrl(this.modelId),
12612
12624
  headers: await resolve(
12613
- combineHeaders$1(await resolve(this.config.headers), headers)
12625
+ combineHeaders(await resolve(this.config.headers), headers)
12614
12626
  ),
12615
12627
  body: args,
12616
- failedResponseHandler: createJsonErrorResponseHandler$1({
12628
+ failedResponseHandler: createJsonErrorResponseHandler({
12617
12629
  errorSchema: BedrockErrorSchema,
12618
12630
  errorToMessage: (error) => `${error.type}: ${error.message}`
12619
12631
  }),
12620
- successfulResponseHandler: createJsonResponseHandler$1(
12632
+ successfulResponseHandler: createJsonResponseHandler(
12621
12633
  bedrockImageResponseSchema
12622
12634
  ),
12623
12635
  abortSignal,
@@ -12676,7 +12688,7 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
12676
12688
  const signer = new AwsV4Signer({
12677
12689
  url,
12678
12690
  method: "POST",
12679
- headers: Object.entries(removeUndefinedEntries$1(originalHeaders)),
12691
+ headers: Object.entries(removeUndefinedEntries(originalHeaders)),
12680
12692
  body,
12681
12693
  region: credentials.region,
12682
12694
  accessKeyId: credentials.accessKeyId,
@@ -12689,8 +12701,8 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
12689
12701
  return fetch(input, {
12690
12702
  ...init,
12691
12703
  body,
12692
- headers: removeUndefinedEntries$1(
12693
- combineHeaders$1(originalHeaders, signedHeaders)
12704
+ headers: removeUndefinedEntries(
12705
+ combineHeaders(originalHeaders, signedHeaders)
12694
12706
  )
12695
12707
  });
12696
12708
  };
@@ -12744,7 +12756,7 @@ function createAmazonBedrock(options = {}) {
12744
12756
  }, options.fetch);
12745
12757
  const getBaseUrl = () => {
12746
12758
  var _a, _b;
12747
- return (_b = withoutTrailingSlash$1(
12759
+ return (_b = withoutTrailingSlash(
12748
12760
  (_a = options.baseURL) != null ? _a : `https://bedrock-runtime.${loadSetting({
12749
12761
  settingValue: options.region,
12750
12762
  settingName: "region",
@@ -12759,7 +12771,7 @@ function createAmazonBedrock(options = {}) {
12759
12771
  baseUrl: getBaseUrl,
12760
12772
  headers: (_a = options.headers) != null ? _a : {},
12761
12773
  fetch: sigv4Fetch,
12762
- generateId: generateId$1
12774
+ generateId
12763
12775
  });
12764
12776
  };
12765
12777
  const provider = function(modelId, settings) {
@@ -12796,802 +12808,6 @@ function createAmazonBedrock(options = {}) {
12796
12808
  }
12797
12809
  createAmazonBedrock();
12798
12810
 
12799
- // src/errors/ai-sdk-error.ts
12800
- var marker = "vercel.ai.error";
12801
- var symbol = Symbol.for(marker);
12802
- var _a;
12803
- var _AISDKError = class _AISDKError extends Error {
12804
- /**
12805
- * Creates an AI SDK Error.
12806
- *
12807
- * @param {Object} params - The parameters for creating the error.
12808
- * @param {string} params.name - The name of the error.
12809
- * @param {string} params.message - The error message.
12810
- * @param {unknown} [params.cause] - The underlying cause of the error.
12811
- */
12812
- constructor({
12813
- name: name14,
12814
- message,
12815
- cause
12816
- }) {
12817
- super(message);
12818
- this[_a] = true;
12819
- this.name = name14;
12820
- this.cause = cause;
12821
- }
12822
- /**
12823
- * Checks if the given error is an AI SDK Error.
12824
- * @param {unknown} error - The error to check.
12825
- * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
12826
- */
12827
- static isInstance(error) {
12828
- return _AISDKError.hasMarker(error, marker);
12829
- }
12830
- static hasMarker(error, marker15) {
12831
- const markerSymbol = Symbol.for(marker15);
12832
- return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
12833
- }
12834
- };
12835
- _a = symbol;
12836
- var AISDKError = _AISDKError;
12837
-
12838
- // src/errors/api-call-error.ts
12839
- var name = "AI_APICallError";
12840
- var marker2 = `vercel.ai.error.${name}`;
12841
- var symbol2 = Symbol.for(marker2);
12842
- var _a2;
12843
- var APICallError = class extends AISDKError {
12844
- constructor({
12845
- message,
12846
- url,
12847
- requestBodyValues,
12848
- statusCode,
12849
- responseHeaders,
12850
- responseBody,
12851
- cause,
12852
- isRetryable = statusCode != null && (statusCode === 408 || // request timeout
12853
- statusCode === 409 || // conflict
12854
- statusCode === 429 || // too many requests
12855
- statusCode >= 500),
12856
- // server error
12857
- data
12858
- }) {
12859
- super({ name, message, cause });
12860
- this[_a2] = true;
12861
- this.url = url;
12862
- this.requestBodyValues = requestBodyValues;
12863
- this.statusCode = statusCode;
12864
- this.responseHeaders = responseHeaders;
12865
- this.responseBody = responseBody;
12866
- this.isRetryable = isRetryable;
12867
- this.data = data;
12868
- }
12869
- static isInstance(error) {
12870
- return AISDKError.hasMarker(error, marker2);
12871
- }
12872
- };
12873
- _a2 = symbol2;
12874
-
12875
- // src/errors/empty-response-body-error.ts
12876
- var name2 = "AI_EmptyResponseBodyError";
12877
- var marker3 = `vercel.ai.error.${name2}`;
12878
- var symbol3 = Symbol.for(marker3);
12879
- var _a3;
12880
- var EmptyResponseBodyError = class extends AISDKError {
12881
- // used in isInstance
12882
- constructor({ message = "Empty response body" } = {}) {
12883
- super({ name: name2, message });
12884
- this[_a3] = true;
12885
- }
12886
- static isInstance(error) {
12887
- return AISDKError.hasMarker(error, marker3);
12888
- }
12889
- };
12890
- _a3 = symbol3;
12891
-
12892
- // src/errors/get-error-message.ts
12893
- function getErrorMessage(error) {
12894
- if (error == null) {
12895
- return "unknown error";
12896
- }
12897
- if (typeof error === "string") {
12898
- return error;
12899
- }
12900
- if (error instanceof Error) {
12901
- return error.message;
12902
- }
12903
- return JSON.stringify(error);
12904
- }
12905
-
12906
- // src/errors/invalid-argument-error.ts
12907
- var name3 = "AI_InvalidArgumentError";
12908
- var marker4 = `vercel.ai.error.${name3}`;
12909
- var symbol4 = Symbol.for(marker4);
12910
- var _a4;
12911
- var InvalidArgumentError = class extends AISDKError {
12912
- constructor({
12913
- message,
12914
- cause,
12915
- argument
12916
- }) {
12917
- super({ name: name3, message, cause });
12918
- this[_a4] = true;
12919
- this.argument = argument;
12920
- }
12921
- static isInstance(error) {
12922
- return AISDKError.hasMarker(error, marker4);
12923
- }
12924
- };
12925
- _a4 = symbol4;
12926
-
12927
- // src/errors/invalid-prompt-error.ts
12928
- var name4 = "AI_InvalidPromptError";
12929
- var marker5 = `vercel.ai.error.${name4}`;
12930
- var symbol5 = Symbol.for(marker5);
12931
- var _a5;
12932
- var InvalidPromptError = class extends AISDKError {
12933
- constructor({
12934
- prompt,
12935
- message,
12936
- cause
12937
- }) {
12938
- super({ name: name4, message: `Invalid prompt: ${message}`, cause });
12939
- this[_a5] = true;
12940
- this.prompt = prompt;
12941
- }
12942
- static isInstance(error) {
12943
- return AISDKError.hasMarker(error, marker5);
12944
- }
12945
- };
12946
- _a5 = symbol5;
12947
-
12948
- // src/errors/invalid-response-data-error.ts
12949
- var name5 = "AI_InvalidResponseDataError";
12950
- var marker6 = `vercel.ai.error.${name5}`;
12951
- var symbol6 = Symbol.for(marker6);
12952
- var _a6;
12953
- var InvalidResponseDataError = class extends AISDKError {
12954
- constructor({
12955
- data,
12956
- message = `Invalid response data: ${JSON.stringify(data)}.`
12957
- }) {
12958
- super({ name: name5, message });
12959
- this[_a6] = true;
12960
- this.data = data;
12961
- }
12962
- static isInstance(error) {
12963
- return AISDKError.hasMarker(error, marker6);
12964
- }
12965
- };
12966
- _a6 = symbol6;
12967
-
12968
- // src/errors/json-parse-error.ts
12969
- var name6 = "AI_JSONParseError";
12970
- var marker7 = `vercel.ai.error.${name6}`;
12971
- var symbol7 = Symbol.for(marker7);
12972
- var _a7;
12973
- var JSONParseError = class extends AISDKError {
12974
- constructor({ text, cause }) {
12975
- super({
12976
- name: name6,
12977
- message: `JSON parsing failed: Text: ${text}.
12978
- Error message: ${getErrorMessage(cause)}`,
12979
- cause
12980
- });
12981
- this[_a7] = true;
12982
- this.text = text;
12983
- }
12984
- static isInstance(error) {
12985
- return AISDKError.hasMarker(error, marker7);
12986
- }
12987
- };
12988
- _a7 = symbol7;
12989
-
12990
- // src/errors/load-api-key-error.ts
12991
- var name7 = "AI_LoadAPIKeyError";
12992
- var marker8 = `vercel.ai.error.${name7}`;
12993
- var symbol8 = Symbol.for(marker8);
12994
- var _a8;
12995
- var LoadAPIKeyError = class extends AISDKError {
12996
- // used in isInstance
12997
- constructor({ message }) {
12998
- super({ name: name7, message });
12999
- this[_a8] = true;
13000
- }
13001
- static isInstance(error) {
13002
- return AISDKError.hasMarker(error, marker8);
13003
- }
13004
- };
13005
- _a8 = symbol8;
13006
-
13007
- // src/errors/type-validation-error.ts
13008
- var name12 = "AI_TypeValidationError";
13009
- var marker13 = `vercel.ai.error.${name12}`;
13010
- var symbol13 = Symbol.for(marker13);
13011
- var _a13;
13012
- var _TypeValidationError = class _TypeValidationError extends AISDKError {
13013
- constructor({ value, cause }) {
13014
- super({
13015
- name: name12,
13016
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
13017
- Error message: ${getErrorMessage(cause)}`,
13018
- cause
13019
- });
13020
- this[_a13] = true;
13021
- this.value = value;
13022
- }
13023
- static isInstance(error) {
13024
- return AISDKError.hasMarker(error, marker13);
13025
- }
13026
- /**
13027
- * Wraps an error into a TypeValidationError.
13028
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
13029
- * Otherwise, it creates a new TypeValidationError.
13030
- *
13031
- * @param {Object} params - The parameters for wrapping the error.
13032
- * @param {unknown} params.value - The value that failed validation.
13033
- * @param {unknown} params.cause - The original error or cause of the validation failure.
13034
- * @returns {TypeValidationError} A TypeValidationError instance.
13035
- */
13036
- static wrap({
13037
- value,
13038
- cause
13039
- }) {
13040
- return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
13041
- }
13042
- };
13043
- _a13 = symbol13;
13044
- var TypeValidationError = _TypeValidationError;
13045
-
13046
- // src/errors/unsupported-functionality-error.ts
13047
- var name13 = "AI_UnsupportedFunctionalityError";
13048
- var marker14 = `vercel.ai.error.${name13}`;
13049
- var symbol14 = Symbol.for(marker14);
13050
- var _a14;
13051
- var UnsupportedFunctionalityError = class extends AISDKError {
13052
- constructor({
13053
- functionality,
13054
- message = `'${functionality}' functionality not supported.`
13055
- }) {
13056
- super({ name: name13, message });
13057
- this[_a14] = true;
13058
- this.functionality = functionality;
13059
- }
13060
- static isInstance(error) {
13061
- return AISDKError.hasMarker(error, marker14);
13062
- }
13063
- };
13064
- _a14 = symbol14;
13065
-
13066
- class ParseError extends Error {
13067
- constructor(message, options) {
13068
- super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
13069
- }
13070
- }
13071
- function noop(_arg) {
13072
- }
13073
- function createParser(callbacks) {
13074
- if (typeof callbacks == "function")
13075
- throw new TypeError(
13076
- "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
13077
- );
13078
- const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
13079
- let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
13080
- function feed(newChunk) {
13081
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
13082
- for (const line of complete)
13083
- parseLine(line);
13084
- incompleteLine = incomplete, isFirstChunk = false;
13085
- }
13086
- function parseLine(line) {
13087
- if (line === "") {
13088
- dispatchEvent();
13089
- return;
13090
- }
13091
- if (line.startsWith(":")) {
13092
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
13093
- return;
13094
- }
13095
- const fieldSeparatorIndex = line.indexOf(":");
13096
- if (fieldSeparatorIndex !== -1) {
13097
- const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
13098
- processField(field, value, line);
13099
- return;
13100
- }
13101
- processField(line, "", line);
13102
- }
13103
- function processField(field, value, line) {
13104
- switch (field) {
13105
- case "event":
13106
- eventType = value;
13107
- break;
13108
- case "data":
13109
- data = `${data}${value}
13110
- `;
13111
- break;
13112
- case "id":
13113
- id = value.includes("\0") ? void 0 : value;
13114
- break;
13115
- case "retry":
13116
- /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
13117
- new ParseError(`Invalid \`retry\` value: "${value}"`, {
13118
- type: "invalid-retry",
13119
- value,
13120
- line
13121
- })
13122
- );
13123
- break;
13124
- default:
13125
- onError(
13126
- new ParseError(
13127
- `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
13128
- { type: "unknown-field", field, value, line }
13129
- )
13130
- );
13131
- break;
13132
- }
13133
- }
13134
- function dispatchEvent() {
13135
- data.length > 0 && onEvent({
13136
- id,
13137
- event: eventType || void 0,
13138
- // If the data buffer's last character is a U+000A LINE FEED (LF) character,
13139
- // then remove the last character from the data buffer.
13140
- data: data.endsWith(`
13141
- `) ? data.slice(0, -1) : data
13142
- }), id = void 0, data = "", eventType = "";
13143
- }
13144
- function reset(options = {}) {
13145
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
13146
- }
13147
- return { feed, reset };
13148
- }
13149
- function splitLines(chunk) {
13150
- const lines = [];
13151
- let incompleteLine = "", searchIndex = 0;
13152
- for (; searchIndex < chunk.length; ) {
13153
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
13154
- `, searchIndex);
13155
- let lineEnd = -1;
13156
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
13157
- incompleteLine = chunk.slice(searchIndex);
13158
- break;
13159
- } else {
13160
- const line = chunk.slice(searchIndex, lineEnd);
13161
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
13162
- ` && searchIndex++;
13163
- }
13164
- }
13165
- return [lines, incompleteLine];
13166
- }
13167
-
13168
- class EventSourceParserStream extends TransformStream {
13169
- constructor({ onError, onRetry, onComment } = {}) {
13170
- let parser;
13171
- super({
13172
- start(controller) {
13173
- parser = createParser({
13174
- onEvent: (event) => {
13175
- controller.enqueue(event);
13176
- },
13177
- onError(error) {
13178
- onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
13179
- },
13180
- onRetry,
13181
- onComment
13182
- });
13183
- },
13184
- transform(chunk) {
13185
- parser.feed(chunk);
13186
- }
13187
- });
13188
- }
13189
- }
13190
-
13191
- // src/combine-headers.ts
13192
- function combineHeaders(...headers) {
13193
- return headers.reduce(
13194
- (combinedHeaders, currentHeaders) => ({
13195
- ...combinedHeaders,
13196
- ...currentHeaders != null ? currentHeaders : {}
13197
- }),
13198
- {}
13199
- );
13200
- }
13201
-
13202
- // src/extract-response-headers.ts
13203
- function extractResponseHeaders(response) {
13204
- const headers = {};
13205
- response.headers.forEach((value, key) => {
13206
- headers[key] = value;
13207
- });
13208
- return headers;
13209
- }
13210
- var createIdGenerator = ({
13211
- prefix,
13212
- size: defaultSize = 16,
13213
- alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
13214
- separator = "-"
13215
- } = {}) => {
13216
- const generator = customAlphabet(alphabet, defaultSize);
13217
- if (prefix == null) {
13218
- return generator;
13219
- }
13220
- if (alphabet.includes(separator)) {
13221
- throw new InvalidArgumentError({
13222
- argument: "separator",
13223
- message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
13224
- });
13225
- }
13226
- return (size) => `${prefix}${separator}${generator(size)}`;
13227
- };
13228
- var generateId = createIdGenerator();
13229
-
13230
- // src/remove-undefined-entries.ts
13231
- function removeUndefinedEntries(record) {
13232
- return Object.fromEntries(
13233
- Object.entries(record).filter(([_key, value]) => value != null)
13234
- );
13235
- }
13236
-
13237
- // src/is-abort-error.ts
13238
- function isAbortError(error) {
13239
- return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
13240
- }
13241
- function loadApiKey({
13242
- apiKey,
13243
- environmentVariableName,
13244
- apiKeyParameterName = "apiKey",
13245
- description
13246
- }) {
13247
- if (typeof apiKey === "string") {
13248
- return apiKey;
13249
- }
13250
- if (apiKey != null) {
13251
- throw new LoadAPIKeyError({
13252
- message: `${description} API key must be a string.`
13253
- });
13254
- }
13255
- if (typeof process === "undefined") {
13256
- throw new LoadAPIKeyError({
13257
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
13258
- });
13259
- }
13260
- apiKey = process.env[environmentVariableName];
13261
- if (apiKey == null) {
13262
- throw new LoadAPIKeyError({
13263
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
13264
- });
13265
- }
13266
- if (typeof apiKey !== "string") {
13267
- throw new LoadAPIKeyError({
13268
- message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
13269
- });
13270
- }
13271
- return apiKey;
13272
- }
13273
-
13274
- // src/validator.ts
13275
- var validatorSymbol = Symbol.for("vercel.ai.validator");
13276
- function validator(validate) {
13277
- return { [validatorSymbol]: true, validate };
13278
- }
13279
- function isValidator(value) {
13280
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
13281
- }
13282
- function asValidator(value) {
13283
- return isValidator(value) ? value : zodValidator(value);
13284
- }
13285
- function zodValidator(zodSchema) {
13286
- return validator((value) => {
13287
- const result = zodSchema.safeParse(value);
13288
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
13289
- });
13290
- }
13291
-
13292
- // src/validate-types.ts
13293
- function validateTypes({
13294
- value,
13295
- schema: inputSchema
13296
- }) {
13297
- const result = safeValidateTypes({ value, schema: inputSchema });
13298
- if (!result.success) {
13299
- throw TypeValidationError.wrap({ value, cause: result.error });
13300
- }
13301
- return result.value;
13302
- }
13303
- function safeValidateTypes({
13304
- value,
13305
- schema
13306
- }) {
13307
- const validator2 = asValidator(schema);
13308
- try {
13309
- if (validator2.validate == null) {
13310
- return { success: true, value };
13311
- }
13312
- const result = validator2.validate(value);
13313
- if (result.success) {
13314
- return result;
13315
- }
13316
- return {
13317
- success: false,
13318
- error: TypeValidationError.wrap({ value, cause: result.error })
13319
- };
13320
- } catch (error) {
13321
- return {
13322
- success: false,
13323
- error: TypeValidationError.wrap({ value, cause: error })
13324
- };
13325
- }
13326
- }
13327
-
13328
- // src/parse-json.ts
13329
- function parseJSON({
13330
- text,
13331
- schema
13332
- }) {
13333
- try {
13334
- const value = SecureJSON.parse(text);
13335
- if (schema == null) {
13336
- return value;
13337
- }
13338
- return validateTypes({ value, schema });
13339
- } catch (error) {
13340
- if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
13341
- throw error;
13342
- }
13343
- throw new JSONParseError({ text, cause: error });
13344
- }
13345
- }
13346
- function safeParseJSON({
13347
- text,
13348
- schema
13349
- }) {
13350
- try {
13351
- const value = SecureJSON.parse(text);
13352
- if (schema == null) {
13353
- return { success: true, value, rawValue: value };
13354
- }
13355
- const validationResult = safeValidateTypes({ value, schema });
13356
- return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
13357
- } catch (error) {
13358
- return {
13359
- success: false,
13360
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
13361
- };
13362
- }
13363
- }
13364
- function isParsableJson(input) {
13365
- try {
13366
- SecureJSON.parse(input);
13367
- return true;
13368
- } catch (e) {
13369
- return false;
13370
- }
13371
- }
13372
- var getOriginalFetch2 = () => globalThis.fetch;
13373
- var postJsonToApi = async ({
13374
- url,
13375
- headers,
13376
- body,
13377
- failedResponseHandler,
13378
- successfulResponseHandler,
13379
- abortSignal,
13380
- fetch
13381
- }) => postToApi({
13382
- url,
13383
- headers: {
13384
- "Content-Type": "application/json",
13385
- ...headers
13386
- },
13387
- body: {
13388
- content: JSON.stringify(body),
13389
- values: body
13390
- },
13391
- failedResponseHandler,
13392
- successfulResponseHandler,
13393
- abortSignal,
13394
- fetch
13395
- });
13396
- var postToApi = async ({
13397
- url,
13398
- headers = {},
13399
- body,
13400
- successfulResponseHandler,
13401
- failedResponseHandler,
13402
- abortSignal,
13403
- fetch = getOriginalFetch2()
13404
- }) => {
13405
- try {
13406
- const response = await fetch(url, {
13407
- method: "POST",
13408
- headers: removeUndefinedEntries(headers),
13409
- body: body.content,
13410
- signal: abortSignal
13411
- });
13412
- const responseHeaders = extractResponseHeaders(response);
13413
- if (!response.ok) {
13414
- let errorInformation;
13415
- try {
13416
- errorInformation = await failedResponseHandler({
13417
- response,
13418
- url,
13419
- requestBodyValues: body.values
13420
- });
13421
- } catch (error) {
13422
- if (isAbortError(error) || APICallError.isInstance(error)) {
13423
- throw error;
13424
- }
13425
- throw new APICallError({
13426
- message: "Failed to process error response",
13427
- cause: error,
13428
- statusCode: response.status,
13429
- url,
13430
- responseHeaders,
13431
- requestBodyValues: body.values
13432
- });
13433
- }
13434
- throw errorInformation.value;
13435
- }
13436
- try {
13437
- return await successfulResponseHandler({
13438
- response,
13439
- url,
13440
- requestBodyValues: body.values
13441
- });
13442
- } catch (error) {
13443
- if (error instanceof Error) {
13444
- if (isAbortError(error) || APICallError.isInstance(error)) {
13445
- throw error;
13446
- }
13447
- }
13448
- throw new APICallError({
13449
- message: "Failed to process successful response",
13450
- cause: error,
13451
- statusCode: response.status,
13452
- url,
13453
- responseHeaders,
13454
- requestBodyValues: body.values
13455
- });
13456
- }
13457
- } catch (error) {
13458
- if (isAbortError(error)) {
13459
- throw error;
13460
- }
13461
- if (error instanceof TypeError && error.message === "fetch failed") {
13462
- const cause = error.cause;
13463
- if (cause != null) {
13464
- throw new APICallError({
13465
- message: `Cannot connect to API: ${cause.message}`,
13466
- cause,
13467
- url,
13468
- requestBodyValues: body.values,
13469
- isRetryable: true
13470
- // retry when network error
13471
- });
13472
- }
13473
- }
13474
- throw error;
13475
- }
13476
- };
13477
- var createJsonErrorResponseHandler = ({
13478
- errorSchema,
13479
- errorToMessage,
13480
- isRetryable
13481
- }) => async ({ response, url, requestBodyValues }) => {
13482
- const responseBody = await response.text();
13483
- const responseHeaders = extractResponseHeaders(response);
13484
- if (responseBody.trim() === "") {
13485
- return {
13486
- responseHeaders,
13487
- value: new APICallError({
13488
- message: response.statusText,
13489
- url,
13490
- requestBodyValues,
13491
- statusCode: response.status,
13492
- responseHeaders,
13493
- responseBody,
13494
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
13495
- })
13496
- };
13497
- }
13498
- try {
13499
- const parsedError = parseJSON({
13500
- text: responseBody,
13501
- schema: errorSchema
13502
- });
13503
- return {
13504
- responseHeaders,
13505
- value: new APICallError({
13506
- message: errorToMessage(parsedError),
13507
- url,
13508
- requestBodyValues,
13509
- statusCode: response.status,
13510
- responseHeaders,
13511
- responseBody,
13512
- data: parsedError,
13513
- isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
13514
- })
13515
- };
13516
- } catch (parseError) {
13517
- return {
13518
- responseHeaders,
13519
- value: new APICallError({
13520
- message: response.statusText,
13521
- url,
13522
- requestBodyValues,
13523
- statusCode: response.status,
13524
- responseHeaders,
13525
- responseBody,
13526
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
13527
- })
13528
- };
13529
- }
13530
- };
13531
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
13532
- const responseHeaders = extractResponseHeaders(response);
13533
- if (response.body == null) {
13534
- throw new EmptyResponseBodyError({});
13535
- }
13536
- return {
13537
- responseHeaders,
13538
- value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
13539
- new TransformStream({
13540
- transform({ data }, controller) {
13541
- if (data === "[DONE]") {
13542
- return;
13543
- }
13544
- controller.enqueue(
13545
- safeParseJSON({
13546
- text: data,
13547
- schema: chunkSchema
13548
- })
13549
- );
13550
- }
13551
- })
13552
- )
13553
- };
13554
- };
13555
- var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
13556
- const responseBody = await response.text();
13557
- const parsedResult = safeParseJSON({
13558
- text: responseBody,
13559
- schema: responseSchema
13560
- });
13561
- const responseHeaders = extractResponseHeaders(response);
13562
- if (!parsedResult.success) {
13563
- throw new APICallError({
13564
- message: "Invalid JSON response",
13565
- cause: parsedResult.error,
13566
- statusCode: response.status,
13567
- responseHeaders,
13568
- responseBody,
13569
- url,
13570
- requestBodyValues
13571
- });
13572
- }
13573
- return {
13574
- responseHeaders,
13575
- value: parsedResult.value,
13576
- rawValue: parsedResult.rawValue
13577
- };
13578
- };
13579
-
13580
- // src/uint8-utils.ts
13581
- var { btoa} = globalThis;
13582
- function convertUint8ArrayToBase64(array) {
13583
- let latin1string = "";
13584
- for (let i = 0; i < array.length; i++) {
13585
- latin1string += String.fromCodePoint(array[i]);
13586
- }
13587
- return btoa(latin1string);
13588
- }
13589
-
13590
- // src/without-trailing-slash.ts
13591
- function withoutTrailingSlash(url) {
13592
- return url == null ? void 0 : url.replace(/\/$/, "");
13593
- }
13594
-
13595
12811
  var __defProp = Object.defineProperty;
13596
12812
  var __defProps = Object.defineProperties;
13597
12813
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
@@ -13623,6 +12839,29 @@ var __objRest = (source, exclude) => {
13623
12839
  }
13624
12840
  return target;
13625
12841
  };
12842
+ var ReasoningDetailSummarySchema = z.object({
12843
+ type: z.literal("reasoning.summary" /* Summary */),
12844
+ summary: z.string()
12845
+ });
12846
+ var ReasoningDetailEncryptedSchema = z.object({
12847
+ type: z.literal("reasoning.encrypted" /* Encrypted */),
12848
+ data: z.string()
12849
+ });
12850
+ var ReasoningDetailTextSchema = z.object({
12851
+ type: z.literal("reasoning.text" /* Text */),
12852
+ text: z.string().nullish(),
12853
+ signature: z.string().nullish()
12854
+ });
12855
+ var ReasoningDetailUnionSchema = z.union([
12856
+ ReasoningDetailSummarySchema,
12857
+ ReasoningDetailEncryptedSchema,
12858
+ ReasoningDetailTextSchema
12859
+ ]);
12860
+ var ReasoningDetailsWithUnknownSchema = z.union([
12861
+ ReasoningDetailUnionSchema,
12862
+ z.unknown().transform(() => null)
12863
+ ]);
12864
+ var ReasoningDetailArraySchema = z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
13626
12865
  function getCacheControl(providerMetadata) {
13627
12866
  var _a, _b, _c;
13628
12867
  const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
@@ -13654,14 +12893,15 @@ function convertToOpenRouterChatMessages(prompt) {
13654
12893
  const messageCacheControl = getCacheControl(providerMetadata);
13655
12894
  const contentParts = content.map(
13656
12895
  (part) => {
13657
- var _a2, _b2, _c2, _d, _e, _f;
12896
+ var _a2, _b2, _c2, _d;
12897
+ const cacheControl = (_a2 = getCacheControl(part.providerMetadata)) != null ? _a2 : messageCacheControl;
13658
12898
  switch (part.type) {
13659
12899
  case "text":
13660
12900
  return {
13661
12901
  type: "text",
13662
12902
  text: part.text,
13663
12903
  // For text parts, only use part-specific cache control
13664
- cache_control: (_a2 = getCacheControl(part.providerMetadata)) != null ? _a2 : messageCacheControl
12904
+ cache_control: cacheControl
13665
12905
  };
13666
12906
  case "image":
13667
12907
  return {
@@ -13672,18 +12912,18 @@ function convertToOpenRouterChatMessages(prompt) {
13672
12912
  )}`
13673
12913
  },
13674
12914
  // For image parts, use part-specific or message-level cache control
13675
- cache_control: (_c2 = getCacheControl(part.providerMetadata)) != null ? _c2 : messageCacheControl
12915
+ cache_control: cacheControl
13676
12916
  };
13677
12917
  case "file":
13678
12918
  return {
13679
12919
  type: "file",
13680
12920
  file: {
13681
12921
  filename: String(
13682
- (_e = (_d = part.providerMetadata) == null ? void 0 : _d.openrouter) == null ? void 0 : _e.filename
12922
+ (_d = (_c2 = part.providerMetadata) == null ? void 0 : _c2.openrouter) == null ? void 0 : _d.filename
13683
12923
  ),
13684
12924
  file_data: part.data instanceof Uint8Array ? `data:${part.mimeType};base64,${convertUint8ArrayToBase64(part.data)}` : `data:${part.mimeType};base64,${part.data}`
13685
12925
  },
13686
- cache_control: (_f = getCacheControl(part.providerMetadata)) != null ? _f : messageCacheControl
12926
+ cache_control: cacheControl
13687
12927
  };
13688
12928
  default: {
13689
12929
  const _exhaustiveCheck = part;
@@ -13702,6 +12942,8 @@ function convertToOpenRouterChatMessages(prompt) {
13702
12942
  }
13703
12943
  case "assistant": {
13704
12944
  let text = "";
12945
+ let reasoning = "";
12946
+ const reasoningDetails = [];
13705
12947
  const toolCalls = [];
13706
12948
  for (const part of content) {
13707
12949
  switch (part.type) {
@@ -13720,9 +12962,23 @@ function convertToOpenRouterChatMessages(prompt) {
13720
12962
  });
13721
12963
  break;
13722
12964
  }
13723
- // TODO: Handle reasoning and redacted-reasoning
13724
- case "reasoning":
13725
- case "redacted-reasoning":
12965
+ case "reasoning": {
12966
+ reasoning += part.text;
12967
+ reasoningDetails.push({
12968
+ type: "reasoning.text" /* Text */,
12969
+ text: part.text,
12970
+ signature: part.signature
12971
+ });
12972
+ break;
12973
+ }
12974
+ case "redacted-reasoning": {
12975
+ reasoningDetails.push({
12976
+ type: "reasoning.encrypted" /* Encrypted */,
12977
+ data: part.data
12978
+ });
12979
+ break;
12980
+ }
12981
+ case "file":
13726
12982
  break;
13727
12983
  default: {
13728
12984
  const _exhaustiveCheck = part;
@@ -13734,6 +12990,8 @@ function convertToOpenRouterChatMessages(prompt) {
13734
12990
  role: "assistant",
13735
12991
  content: text,
13736
12992
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
12993
+ reasoning: reasoning || void 0,
12994
+ reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
13737
12995
  cache_control: getCacheControl(providerMetadata)
13738
12996
  });
13739
12997
  break;
@@ -13789,10 +13047,10 @@ function mapOpenRouterFinishReason(finishReason) {
13789
13047
  }
13790
13048
  var OpenRouterErrorResponseSchema = z.object({
13791
13049
  error: z.object({
13050
+ code: z.union([z.string(), z.number()]).nullable(),
13792
13051
  message: z.string(),
13793
- type: z.string(),
13794
- param: z.any().nullable(),
13795
- code: z.string().nullable()
13052
+ type: z.string().nullable(),
13053
+ param: z.any().nullable()
13796
13054
  })
13797
13055
  });
13798
13056
  var openrouterFailedResponseHandler = createJsonErrorResponseHandler({
@@ -13831,7 +13089,7 @@ var OpenRouterChatLanguageModel = class {
13831
13089
  }) {
13832
13090
  var _a;
13833
13091
  const type = mode.type;
13834
- const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
13092
+ const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata.openrouter) != null ? _a : {};
13835
13093
  const baseArgs = __spreadValues(__spreadValues(__spreadValues({
13836
13094
  // model id:
13837
13095
  model: this.modelId,
@@ -13856,7 +13114,8 @@ var OpenRouterChatLanguageModel = class {
13856
13114
  messages: convertToOpenRouterChatMessages(prompt),
13857
13115
  // OpenRouter specific settings:
13858
13116
  include_reasoning: this.settings.includeReasoning,
13859
- reasoning: this.settings.reasoning
13117
+ reasoning: this.settings.reasoning,
13118
+ usage: this.settings.usage
13860
13119
  }, this.config.extraBody), this.settings.extraBody), extraCallingBody);
13861
13120
  switch (type) {
13862
13121
  case "regular": {
@@ -13892,7 +13151,7 @@ var OpenRouterChatLanguageModel = class {
13892
13151
  }
13893
13152
  }
13894
13153
  async doGenerate(options) {
13895
- var _b, _c, _d, _e, _f, _g, _h;
13154
+ var _b, _c, _d, _e, _f, _g, _h, _i, _j;
13896
13155
  const args = this.getArgs(options);
13897
13156
  const { responseHeaders, value: response } = await postJsonToApi({
13898
13157
  url: this.config.url({
@@ -13913,14 +13172,79 @@ var OpenRouterChatLanguageModel = class {
13913
13172
  if (!choice) {
13914
13173
  throw new Error("No choice in response");
13915
13174
  }
13916
- return {
13175
+ const usageInfo = response.usage ? {
13176
+ promptTokens: (_b = response.usage.prompt_tokens) != null ? _b : 0,
13177
+ completionTokens: (_c = response.usage.completion_tokens) != null ? _c : 0
13178
+ } : {
13179
+ promptTokens: 0,
13180
+ completionTokens: 0
13181
+ };
13182
+ const providerMetadata = {};
13183
+ if (response.usage && ((_d = this.settings.usage) == null ? void 0 : _d.include)) {
13184
+ providerMetadata.openrouter = {
13185
+ usage: {
13186
+ promptTokens: response.usage.prompt_tokens,
13187
+ promptTokensDetails: response.usage.prompt_tokens_details ? {
13188
+ cachedTokens: (_e = response.usage.prompt_tokens_details.cached_tokens) != null ? _e : 0
13189
+ } : void 0,
13190
+ completionTokens: response.usage.completion_tokens,
13191
+ completionTokensDetails: response.usage.completion_tokens_details ? {
13192
+ reasoningTokens: (_f = response.usage.completion_tokens_details.reasoning_tokens) != null ? _f : 0
13193
+ } : void 0,
13194
+ cost: response.usage.cost,
13195
+ totalTokens: (_g = response.usage.total_tokens) != null ? _g : 0
13196
+ }
13197
+ };
13198
+ }
13199
+ const hasProviderMetadata = Object.keys(providerMetadata).length > 0;
13200
+ const reasoningDetails = (_h = choice.message.reasoning_details) != null ? _h : [];
13201
+ const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
13202
+ var _a2;
13203
+ switch (detail.type) {
13204
+ case "reasoning.text" /* Text */: {
13205
+ if (detail.text) {
13206
+ return {
13207
+ type: "text",
13208
+ text: detail.text,
13209
+ signature: (_a2 = detail.signature) != null ? _a2 : void 0
13210
+ };
13211
+ }
13212
+ break;
13213
+ }
13214
+ case "reasoning.summary" /* Summary */: {
13215
+ if (detail.summary) {
13216
+ return {
13217
+ type: "text",
13218
+ text: detail.summary
13219
+ };
13220
+ }
13221
+ break;
13222
+ }
13223
+ case "reasoning.encrypted" /* Encrypted */: {
13224
+ if (detail.data) {
13225
+ return {
13226
+ type: "redacted",
13227
+ data: detail.data
13228
+ };
13229
+ }
13230
+ break;
13231
+ }
13232
+ }
13233
+ return null;
13234
+ }).filter((p) => p !== null) : choice.message.reasoning ? [
13235
+ {
13236
+ type: "text",
13237
+ text: choice.message.reasoning
13238
+ }
13239
+ ] : [];
13240
+ return __spreadValues({
13917
13241
  response: {
13918
13242
  id: response.id,
13919
13243
  modelId: response.model
13920
13244
  },
13921
- text: (_b = choice.message.content) != null ? _b : void 0,
13922
- reasoning: (_c = choice.message.reasoning) != null ? _c : void 0,
13923
- toolCalls: (_d = choice.message.tool_calls) == null ? void 0 : _d.map((toolCall) => {
13245
+ text: (_i = choice.message.content) != null ? _i : void 0,
13246
+ reasoning,
13247
+ toolCalls: (_j = choice.message.tool_calls) == null ? void 0 : _j.map((toolCall) => {
13924
13248
  var _a2;
13925
13249
  return {
13926
13250
  toolCallType: "function",
@@ -13930,17 +13254,15 @@ var OpenRouterChatLanguageModel = class {
13930
13254
  };
13931
13255
  }),
13932
13256
  finishReason: mapOpenRouterFinishReason(choice.finish_reason),
13933
- usage: {
13934
- promptTokens: (_f = (_e = response.usage) == null ? void 0 : _e.prompt_tokens) != null ? _f : 0,
13935
- completionTokens: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : 0
13936
- },
13257
+ usage: usageInfo,
13937
13258
  rawCall: { rawPrompt, rawSettings },
13938
13259
  rawResponse: { headers: responseHeaders },
13939
13260
  warnings: [],
13940
13261
  logprobs: mapOpenRouterChatLogProbsOutput(choice.logprobs)
13941
- };
13262
+ }, hasProviderMetadata ? { providerMetadata } : {});
13942
13263
  }
13943
13264
  async doStream(options) {
13265
+ var _a, _c;
13944
13266
  const args = this.getArgs(options);
13945
13267
  const { responseHeaders, value: response } = await postJsonToApi({
13946
13268
  url: this.config.url({
@@ -13951,7 +13273,9 @@ var OpenRouterChatLanguageModel = class {
13951
13273
  body: __spreadProps(__spreadValues({}, args), {
13952
13274
  stream: true,
13953
13275
  // only include stream_options when in strict compatibility mode:
13954
- stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
13276
+ stream_options: this.config.compatibility === "strict" ? __spreadValues({
13277
+ include_usage: true
13278
+ }, ((_a = this.settings.usage) == null ? void 0 : _a.include) ? { include_usage: true } : {}) : void 0
13955
13279
  }),
13956
13280
  failedResponseHandler: openrouterFailedResponseHandler,
13957
13281
  successfulResponseHandler: createEventSourceResponseHandler(
@@ -13960,7 +13284,7 @@ var OpenRouterChatLanguageModel = class {
13960
13284
  abortSignal: options.abortSignal,
13961
13285
  fetch: this.config.fetch
13962
13286
  });
13963
- const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
13287
+ const _b = args, { messages: rawPrompt } = _b, rawSettings = __objRest(_b, ["messages"]);
13964
13288
  const toolCalls = [];
13965
13289
  let finishReason = "other";
13966
13290
  let usage = {
@@ -13968,11 +13292,13 @@ var OpenRouterChatLanguageModel = class {
13968
13292
  completionTokens: Number.NaN
13969
13293
  };
13970
13294
  let logprobs;
13295
+ const openrouterUsage = {};
13296
+ const shouldIncludeUsageAccounting = !!((_c = this.settings.usage) == null ? void 0 : _c.include);
13971
13297
  return {
13972
13298
  stream: response.pipeThrough(
13973
13299
  new TransformStream({
13974
13300
  transform(chunk, controller) {
13975
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
13301
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
13976
13302
  if (!chunk.success) {
13977
13303
  finishReason = "error";
13978
13304
  controller.enqueue({ type: "error", error: chunk.error });
@@ -14001,6 +13327,20 @@ var OpenRouterChatLanguageModel = class {
14001
13327
  promptTokens: value.usage.prompt_tokens,
14002
13328
  completionTokens: value.usage.completion_tokens
14003
13329
  };
13330
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
13331
+ if (value.usage.prompt_tokens_details) {
13332
+ openrouterUsage.promptTokensDetails = {
13333
+ cachedTokens: (_a2 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a2 : 0
13334
+ };
13335
+ }
13336
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
13337
+ if (value.usage.completion_tokens_details) {
13338
+ openrouterUsage.completionTokensDetails = {
13339
+ reasoningTokens: (_b2 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b2 : 0
13340
+ };
13341
+ }
13342
+ openrouterUsage.cost = value.usage.cost;
13343
+ openrouterUsage.totalTokens = value.usage.total_tokens;
14004
13344
  }
14005
13345
  const choice = value.choices[0];
14006
13346
  if ((choice == null ? void 0 : choice.finish_reason) != null) {
@@ -14022,11 +13362,52 @@ var OpenRouterChatLanguageModel = class {
14022
13362
  textDelta: delta.reasoning
14023
13363
  });
14024
13364
  }
13365
+ if (delta.reasoning_details && delta.reasoning_details.length > 0) {
13366
+ for (const detail of delta.reasoning_details) {
13367
+ switch (detail.type) {
13368
+ case "reasoning.text" /* Text */: {
13369
+ if (detail.text) {
13370
+ controller.enqueue({
13371
+ type: "reasoning",
13372
+ textDelta: detail.text
13373
+ });
13374
+ }
13375
+ if (detail.signature) {
13376
+ controller.enqueue({
13377
+ type: "reasoning-signature",
13378
+ signature: detail.signature
13379
+ });
13380
+ }
13381
+ break;
13382
+ }
13383
+ case "reasoning.encrypted" /* Encrypted */: {
13384
+ if (detail.data) {
13385
+ controller.enqueue({
13386
+ type: "redacted-reasoning",
13387
+ data: detail.data
13388
+ });
13389
+ }
13390
+ break;
13391
+ }
13392
+ case "reasoning.summary" /* Summary */: {
13393
+ if (detail.summary) {
13394
+ controller.enqueue({
13395
+ type: "reasoning",
13396
+ textDelta: detail.summary
13397
+ });
13398
+ }
13399
+ break;
13400
+ }
13401
+ }
13402
+ }
13403
+ }
14025
13404
  const mappedLogprobs = mapOpenRouterChatLogProbsOutput(
14026
13405
  choice == null ? void 0 : choice.logprobs
14027
13406
  );
14028
13407
  if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
14029
- if (logprobs === void 0) logprobs = [];
13408
+ if (logprobs === void 0) {
13409
+ logprobs = [];
13410
+ }
14030
13411
  logprobs.push(...mappedLogprobs);
14031
13412
  }
14032
13413
  if (delta.tool_calls != null) {
@@ -14045,7 +13426,7 @@ var OpenRouterChatLanguageModel = class {
14045
13426
  message: `Expected 'id' to be a string.`
14046
13427
  });
14047
13428
  }
14048
- if (((_a2 = toolCallDelta.function) == null ? void 0 : _a2.name) == null) {
13429
+ if (((_c2 = toolCallDelta.function) == null ? void 0 : _c2.name) == null) {
14049
13430
  throw new InvalidResponseDataError({
14050
13431
  data: toolCallDelta,
14051
13432
  message: `Expected 'function.name' to be a string.`
@@ -14056,7 +13437,7 @@ var OpenRouterChatLanguageModel = class {
14056
13437
  type: "function",
14057
13438
  function: {
14058
13439
  name: toolCallDelta.function.name,
14059
- arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
13440
+ arguments: (_d = toolCallDelta.function.arguments) != null ? _d : ""
14060
13441
  },
14061
13442
  sent: false
14062
13443
  };
@@ -14064,7 +13445,7 @@ var OpenRouterChatLanguageModel = class {
14064
13445
  if (toolCall2 == null) {
14065
13446
  throw new Error("Tool call is missing");
14066
13447
  }
14067
- if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
13448
+ if (((_e = toolCall2.function) == null ? void 0 : _e.name) != null && ((_f = toolCall2.function) == null ? void 0 : _f.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
14068
13449
  controller.enqueue({
14069
13450
  type: "tool-call-delta",
14070
13451
  toolCallType: "function",
@@ -14075,7 +13456,7 @@ var OpenRouterChatLanguageModel = class {
14075
13456
  controller.enqueue({
14076
13457
  type: "tool-call",
14077
13458
  toolCallType: "function",
14078
- toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
13459
+ toolCallId: (_g = toolCall2.id) != null ? _g : generateId(),
14079
13460
  toolName: toolCall2.function.name,
14080
13461
  args: toolCall2.function.arguments
14081
13462
  });
@@ -14087,21 +13468,21 @@ var OpenRouterChatLanguageModel = class {
14087
13468
  if (toolCall == null) {
14088
13469
  throw new Error("Tool call is missing");
14089
13470
  }
14090
- if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
14091
- toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
13471
+ if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
13472
+ toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
14092
13473
  }
14093
13474
  controller.enqueue({
14094
13475
  type: "tool-call-delta",
14095
13476
  toolCallType: "function",
14096
13477
  toolCallId: toolCall.id,
14097
13478
  toolName: toolCall.function.name,
14098
- argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
13479
+ argsTextDelta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
14099
13480
  });
14100
- if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
13481
+ if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && isParsableJson(toolCall.function.arguments)) {
14101
13482
  controller.enqueue({
14102
13483
  type: "tool-call",
14103
13484
  toolCallType: "function",
14104
- toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
13485
+ toolCallId: (_n = toolCall.id) != null ? _n : generateId(),
14105
13486
  toolName: toolCall.function.name,
14106
13487
  args: toolCall.function.arguments
14107
13488
  });
@@ -14127,12 +13508,19 @@ var OpenRouterChatLanguageModel = class {
14127
13508
  }
14128
13509
  }
14129
13510
  }
14130
- controller.enqueue({
13511
+ const providerMetadata = {};
13512
+ if (shouldIncludeUsageAccounting && (openrouterUsage.totalTokens !== void 0 || openrouterUsage.cost !== void 0 || openrouterUsage.promptTokensDetails !== void 0 || openrouterUsage.completionTokensDetails !== void 0)) {
13513
+ providerMetadata.openrouter = {
13514
+ usage: openrouterUsage
13515
+ };
13516
+ }
13517
+ const hasProviderMetadata = Object.keys(providerMetadata).length > 0 && shouldIncludeUsageAccounting;
13518
+ controller.enqueue(__spreadValues({
14131
13519
  type: "finish",
14132
13520
  finishReason,
14133
13521
  logprobs,
14134
13522
  usage
14135
- });
13523
+ }, hasProviderMetadata ? { providerMetadata } : {}));
14136
13524
  }
14137
13525
  })
14138
13526
  ),
@@ -14147,8 +13535,15 @@ var OpenRouterChatCompletionBaseResponseSchema = z.object({
14147
13535
  model: z.string().optional(),
14148
13536
  usage: z.object({
14149
13537
  prompt_tokens: z.number(),
13538
+ prompt_tokens_details: z.object({
13539
+ cached_tokens: z.number()
13540
+ }).nullish(),
14150
13541
  completion_tokens: z.number(),
14151
- total_tokens: z.number()
13542
+ completion_tokens_details: z.object({
13543
+ reasoning_tokens: z.number()
13544
+ }).nullish(),
13545
+ total_tokens: z.number(),
13546
+ cost: z.number().optional()
14152
13547
  }).nullish()
14153
13548
  });
14154
13549
  var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBaseResponseSchema.extend({
@@ -14158,6 +13553,7 @@ var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBa
14158
13553
  role: z.literal("assistant"),
14159
13554
  content: z.string().nullable().optional(),
14160
13555
  reasoning: z.string().nullable().optional(),
13556
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
14161
13557
  tool_calls: z.array(
14162
13558
  z.object({
14163
13559
  id: z.string().optional().nullable(),
@@ -14196,6 +13592,7 @@ var OpenRouterStreamChatCompletionChunkSchema = z.union([
14196
13592
  role: z.enum(["assistant"]).optional(),
14197
13593
  content: z.string().nullish(),
14198
13594
  reasoning: z.string().nullish().optional(),
13595
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
14199
13596
  tool_calls: z.array(
14200
13597
  z.object({
14201
13598
  index: z.number(),
@@ -14245,14 +13642,13 @@ function prepareToolsAndToolChoice(mode) {
14245
13642
  parameters: tool.parameters
14246
13643
  }
14247
13644
  };
14248
- } else {
14249
- return {
14250
- type: "function",
14251
- function: {
14252
- name: tool.name
14253
- }
14254
- };
14255
13645
  }
13646
+ return {
13647
+ type: "function",
13648
+ function: {
13649
+ name: tool.name
13650
+ }
13651
+ };
14256
13652
  });
14257
13653
  const toolChoice = mode.toolChoice;
14258
13654
  if (toolChoice == null) {
@@ -14355,6 +13751,11 @@ ${userMessage}
14355
13751
  functionality: "redacted reasoning messages"
14356
13752
  });
14357
13753
  }
13754
+ case "file": {
13755
+ throw new UnsupportedFunctionalityError({
13756
+ functionality: "file attachments"
13757
+ });
13758
+ }
14358
13759
  default: {
14359
13760
  const _exhaustiveCheck = part;
14360
13761
  throw new Error(
@@ -14433,7 +13834,7 @@ var OpenRouterCompletionLanguageModel = class {
14433
13834
  }) {
14434
13835
  var _a, _b;
14435
13836
  const type = mode.type;
14436
- const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
13837
+ const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata.openrouter) != null ? _a : {};
14437
13838
  const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
14438
13839
  prompt,
14439
13840
  inputFormat
@@ -14601,7 +14002,9 @@ var OpenRouterCompletionLanguageModel = class {
14601
14002
  choice == null ? void 0 : choice.logprobs
14602
14003
  );
14603
14004
  if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
14604
- if (logprobs === void 0) logprobs = [];
14005
+ if (logprobs === void 0) {
14006
+ logprobs = [];
14007
+ }
14605
14008
  logprobs.push(...mappedLogprobs);
14606
14009
  }
14607
14010
  },
@@ -14629,6 +14032,7 @@ var OpenRouterCompletionChunkSchema = z.union([
14629
14032
  z.object({
14630
14033
  text: z.string(),
14631
14034
  reasoning: z.string().nullish().optional(),
14035
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
14632
14036
  finish_reason: z.string().nullish(),
14633
14037
  index: z.number(),
14634
14038
  logprobs: z.object({
@@ -14686,9 +14090,7 @@ function createOpenRouter(options = {}) {
14686
14090
  }
14687
14091
  return createChatModel(modelId, settings);
14688
14092
  };
14689
- const provider = function(modelId, settings) {
14690
- return createLanguageModel(modelId, settings);
14691
- };
14093
+ const provider = (modelId, settings) => createLanguageModel(modelId, settings);
14692
14094
  provider.languageModel = createLanguageModel;
14693
14095
  provider.chat = createChatModel;
14694
14096
  provider.completion = createCompletionModel;
@@ -14721,12 +14123,12 @@ class RetryLanguageModel {
14721
14123
  temperature: request.temperature,
14722
14124
  topP: request.topP,
14723
14125
  topK: request.topK,
14724
- providerMetadata: {},
14725
14126
  abortSignal: request.abortSignal,
14726
14127
  });
14727
14128
  }
14728
14129
  async doGenerate(options) {
14729
14130
  const maxTokens = options.maxTokens;
14131
+ const providerMetadata = options.providerMetadata;
14730
14132
  const names = [...this.names, ...this.names];
14731
14133
  for (let i = 0; i < names.length; i++) {
14732
14134
  const name = names[i];
@@ -14738,11 +14140,17 @@ class RetryLanguageModel {
14738
14140
  options.maxTokens =
14739
14141
  this.llms[name].config?.maxTokens || config.maxTokens;
14740
14142
  }
14143
+ if (!providerMetadata) {
14144
+ options.providerMetadata = {};
14145
+ options.providerMetadata[llm.provider] = this.llms[name].options || {};
14146
+ }
14741
14147
  try {
14742
- let result = await llm.doGenerate(options);
14148
+ let result = (await llm.doGenerate(options));
14743
14149
  if (Log.isEnableDebug()) {
14744
14150
  Log.debug(`LLM nonstream body, name: ${name} => `, result.request?.body);
14745
14151
  }
14152
+ result.llm = name;
14153
+ result.llmConfig = this.llms[name];
14746
14154
  return result;
14747
14155
  }
14748
14156
  catch (e) {
@@ -14773,12 +14181,12 @@ class RetryLanguageModel {
14773
14181
  temperature: request.temperature,
14774
14182
  topP: request.topP,
14775
14183
  topK: request.topK,
14776
- providerMetadata: {},
14777
14184
  abortSignal: request.abortSignal,
14778
14185
  });
14779
14186
  }
14780
14187
  async doStream(options) {
14781
14188
  const maxTokens = options.maxTokens;
14189
+ const providerMetadata = options.providerMetadata;
14782
14190
  const names = [...this.names, ...this.names];
14783
14191
  for (let i = 0; i < names.length; i++) {
14784
14192
  const name = names[i];
@@ -14790,14 +14198,18 @@ class RetryLanguageModel {
14790
14198
  options.maxTokens =
14791
14199
  this.llms[name].config?.maxTokens || config.maxTokens;
14792
14200
  }
14201
+ if (!providerMetadata) {
14202
+ options.providerMetadata = {};
14203
+ options.providerMetadata[llm.provider] = this.llms[name].options || {};
14204
+ }
14793
14205
  try {
14794
14206
  const controller = new AbortController();
14795
14207
  const signal = options.abortSignal
14796
14208
  ? AbortSignal.any([options.abortSignal, controller.signal])
14797
14209
  : controller.signal;
14798
- const result = await call_timeout(async () => await llm.doStream({ ...options, abortSignal: signal }), this.stream_first_timeout, (e) => {
14210
+ const result = (await call_timeout(async () => await llm.doStream({ ...options, abortSignal: signal }), this.stream_first_timeout, (e) => {
14799
14211
  controller.abort();
14800
- });
14212
+ }));
14801
14213
  const stream = result.stream;
14802
14214
  const reader = stream.getReader();
14803
14215
  const { done, value } = await call_timeout(async () => await reader.read(), this.stream_first_timeout, (e) => {
@@ -14819,6 +14231,8 @@ class RetryLanguageModel {
14819
14231
  reader.releaseLock();
14820
14232
  continue;
14821
14233
  }
14234
+ result.llm = name;
14235
+ result.llmConfig = this.llms[name];
14822
14236
  result.stream = this.streamWrapper([chunk], reader);
14823
14237
  return result;
14824
14238
  }
@@ -14862,18 +14276,27 @@ class RetryLanguageModel {
14862
14276
  return createOpenAI({
14863
14277
  apiKey: apiKey,
14864
14278
  baseURL: baseURL,
14279
+ fetch: llm.fetch,
14280
+ organization: llm.config?.organization,
14281
+ project: llm.config?.project,
14282
+ headers: llm.config?.headers,
14283
+ compatibility: llm.config?.compatibility,
14865
14284
  }).languageModel(llm.model);
14866
14285
  }
14867
14286
  else if (llm.provider == "anthropic") {
14868
14287
  return createAnthropic({
14869
14288
  apiKey: apiKey,
14870
14289
  baseURL: baseURL,
14290
+ fetch: llm.fetch,
14291
+ headers: llm.config?.headers,
14871
14292
  }).languageModel(llm.model);
14872
14293
  }
14873
14294
  else if (llm.provider == "google") {
14874
14295
  return createGoogleGenerativeAI({
14875
14296
  apiKey: apiKey,
14876
14297
  baseURL: baseURL,
14298
+ fetch: llm.fetch,
14299
+ headers: llm.config?.headers,
14877
14300
  }).languageModel(llm.model);
14878
14301
  }
14879
14302
  else if (llm.provider == "aws") {
@@ -14883,12 +14306,18 @@ class RetryLanguageModel {
14883
14306
  secretAccessKey: keys[1],
14884
14307
  baseURL: baseURL,
14885
14308
  region: llm.config?.region || "us-west-1",
14309
+ fetch: llm.fetch,
14310
+ headers: llm.config?.headers,
14311
+ sessionToken: llm.config?.sessionToken,
14886
14312
  }).languageModel(llm.model);
14887
14313
  }
14888
14314
  else if (llm.provider == "openrouter") {
14889
14315
  return createOpenRouter({
14890
14316
  apiKey: apiKey,
14891
14317
  baseURL: baseURL,
14318
+ fetch: llm.fetch,
14319
+ headers: llm.config?.headers,
14320
+ compatibility: llm.config?.compatibility,
14892
14321
  }).languageModel(llm.model);
14893
14322
  }
14894
14323
  else {
@@ -14918,6 +14347,12 @@ class RetryLanguageModel {
14918
14347
  },
14919
14348
  });
14920
14349
  }
14350
+ get Llms() {
14351
+ return this.llms;
14352
+ }
14353
+ get Names() {
14354
+ return this.names;
14355
+ }
14921
14356
  }
14922
14357
 
14923
14358
  var domParser = {};
@@ -17365,11 +16800,21 @@ function requireDomParser () {
17365
16800
 
17366
16801
  var domParserExports = requireDomParser();
17367
16802
 
17368
- function parseWorkflow(taskId, xml, done) {
16803
+ function parseWorkflow(taskId, xml, done, thinking) {
16804
+ let _workflow = null;
17369
16805
  try {
16806
+ if (thinking) {
16807
+ _workflow = {
16808
+ taskId: taskId,
16809
+ name: "",
16810
+ thought: thinking,
16811
+ agents: [],
16812
+ xml: xml,
16813
+ };
16814
+ }
17370
16815
  let sIdx = xml.indexOf("<root>");
17371
16816
  if (sIdx == -1) {
17372
- return null;
16817
+ return _workflow;
17373
16818
  }
17374
16819
  xml = xml.substring(sIdx);
17375
16820
  let eIdx = xml.indexOf("</root>");
@@ -17383,13 +16828,14 @@ function parseWorkflow(taskId, xml, done) {
17383
16828
  const doc = parser.parseFromString(xml, "text/xml");
17384
16829
  let root = doc.documentElement;
17385
16830
  if (root.tagName !== "root") {
17386
- return null;
16831
+ return _workflow;
17387
16832
  }
17388
- let agents = [];
16833
+ const agents = [];
16834
+ const thought = root.getElementsByTagName("thought")[0]?.textContent || "";
17389
16835
  const workflow = {
17390
16836
  taskId: taskId,
17391
16837
  name: root.getElementsByTagName("name")[0]?.textContent || "",
17392
- thought: root.getElementsByTagName("thought")[0]?.textContent || "",
16838
+ thought: thinking ? thinking + "\n" + thought : thought,
17393
16839
  agents: agents,
17394
16840
  xml: xml,
17395
16841
  };
@@ -17422,7 +16868,7 @@ function parseWorkflow(taskId, xml, done) {
17422
16868
  throw e;
17423
16869
  }
17424
16870
  else {
17425
- return null;
16871
+ return _workflow;
17426
16872
  }
17427
16873
  }
17428
16874
  }
@@ -17499,7 +16945,8 @@ function buildAgentRootXml(agentXml, mainTaskPrompt, nodeCallback) {
17499
16945
  agentInnerHTML = agentInnerHTML
17500
16946
  .replace("<task>", "<currentTask>")
17501
16947
  .replace("</task>", "</currentTask>");
17502
- return `<root>${prefix}<mainTask>${mainTaskPrompt}</mainTask>${agentInnerHTML}</root>`;
16948
+ const xmlPrompt = `<root>${prefix}<mainTask>${mainTaskPrompt}</mainTask>${agentInnerHTML}</root>`;
16949
+ return xmlPrompt.replace(/ /g, " ").replace(" </root>", "</root>");
17503
16950
  }
17504
16951
  function extractAgentXmlNode(agentXml, nodeId) {
17505
16952
  const parser = new domParserExports.DOMParser();
@@ -18398,9 +17845,8 @@ class McpTool {
18398
17845
 
18399
17846
  const AGENT_SYSTEM_TEMPLATE = `
18400
17847
  You are {name}, an autonomous AI agent for {agent} agent.
18401
- Current datetime: {datetime}
18402
17848
 
18403
- # Task Description
17849
+ # Agent Description
18404
17850
  {description}
18405
17851
  {prompt}
18406
17852
 
@@ -18484,25 +17930,23 @@ function getAgentSystemPrompt(agent, agentNode, context, tools, extSysPrompt) {
18484
17930
  if (extSysPrompt && extSysPrompt.trim()) {
18485
17931
  prompt += "\n" + extSysPrompt.trim() + "\n";
18486
17932
  }
17933
+ prompt += "\nCurrent datetime: {datetime}";
18487
17934
  if (context.chain.agents.length > 1) {
18488
17935
  prompt += "\n Main task: " + context.chain.taskPrompt;
18489
17936
  prompt += "\n\n# Pre-task execution results";
18490
17937
  for (let i = 0; i < context.chain.agents.length; i++) {
18491
17938
  let agentChain = context.chain.agents[i];
18492
17939
  if (agentChain.agentResult) {
18493
- prompt += `\n## ${agentChain.agent.task || agentChain.agent.name}\n${sub(agentChain.agentResult, 500)}`;
17940
+ prompt += `\n## ${agentChain.agent.task || agentChain.agent.name}\n${sub(agentChain.agentResult, 500, true)}`;
18494
17941
  }
18495
17942
  }
18496
17943
  }
18497
- if (prompt) {
18498
- prompt = "\n" + prompt.trim();
18499
- }
18500
17944
  return AGENT_SYSTEM_TEMPLATE.replace("{name}", config.name)
18501
17945
  .replace("{agent}", agent.Name)
18502
17946
  .replace("{description}", agent.Description)
18503
- .replace("{datetime}", new Date().toLocaleString())
18504
- .replace("{prompt}", prompt)
17947
+ .replace("{prompt}", "\n" + prompt.trim())
18505
17948
  .replace("{nodePrompt}", nodePrompt)
17949
+ .replace("{datetime}", new Date().toLocaleString())
18506
17950
  .trim();
18507
17951
  }
18508
17952
  function getAgentUserPrompt(agent, agentNode, context, tools) {
@@ -18529,6 +17973,7 @@ class Agent {
18529
17973
  let mcpClient = this.mcpClient || context.config.defaultMcpClient;
18530
17974
  let agentContext = new AgentContext(context, this, agentChain);
18531
17975
  try {
17976
+ this.agentContext = agentContext;
18532
17977
  mcpClient && !mcpClient.isConnected() && (await mcpClient.connect());
18533
17978
  return this.runWithContext(agentContext, mcpClient, config.maxReactNum);
18534
17979
  }
@@ -18858,6 +18303,11 @@ class Agent {
18858
18303
  addTool(tool) {
18859
18304
  this.tools.push(tool);
18860
18305
  }
18306
+ async onTaskStatus(status, reason) {
18307
+ if (status == "abort" && this.agentContext) {
18308
+ this.agentContext?.variables.clear();
18309
+ }
18310
+ }
18861
18311
  get Llms() {
18862
18312
  return this.llms;
18863
18313
  }
@@ -18904,6 +18354,7 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18904
18354
  let toolParts = [];
18905
18355
  const reader = result.stream.getReader();
18906
18356
  try {
18357
+ let toolPart = null;
18907
18358
  while (true) {
18908
18359
  await context.checkAborted();
18909
18360
  const { done, value } = await reader.read();
@@ -18913,6 +18364,9 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18913
18364
  let chunk = value;
18914
18365
  switch (chunk.type) {
18915
18366
  case "text-delta": {
18367
+ if (toolPart && !chunk.textDelta) {
18368
+ continue;
18369
+ }
18916
18370
  streamText += chunk.textDelta || "";
18917
18371
  await streamCallback.onMessage({
18918
18372
  taskId: context.taskId,
@@ -18923,6 +18377,18 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18923
18377
  streamDone: false,
18924
18378
  text: streamText,
18925
18379
  }, agentContext);
18380
+ if (toolPart) {
18381
+ await streamCallback.onMessage({
18382
+ taskId: context.taskId,
18383
+ agentName: agentNode.name,
18384
+ nodeId: agentNode.id,
18385
+ type: "tool_use",
18386
+ toolId: toolPart.toolCallId,
18387
+ toolName: toolPart.toolName,
18388
+ params: toolPart.args || {},
18389
+ }, agentContext);
18390
+ toolPart = null;
18391
+ }
18926
18392
  break;
18927
18393
  }
18928
18394
  case "reasoning": {
@@ -18961,6 +18427,15 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18961
18427
  toolName: chunk.toolName,
18962
18428
  paramsText: toolArgsText,
18963
18429
  }, agentContext);
18430
+ if (toolPart == null) {
18431
+ toolPart = {
18432
+ type: "tool-call",
18433
+ toolCallId: chunk.toolCallId,
18434
+ toolName: chunk.toolName,
18435
+ args: {},
18436
+ };
18437
+ toolParts.push(toolPart);
18438
+ }
18964
18439
  break;
18965
18440
  }
18966
18441
  case "tool-call": {
@@ -18976,12 +18451,18 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18976
18451
  params: args,
18977
18452
  };
18978
18453
  await streamCallback.onMessage(message, agentContext);
18979
- toolParts.push({
18980
- type: "tool-call",
18981
- toolCallId: chunk.toolCallId,
18982
- toolName: chunk.toolName,
18983
- args: message.params || args,
18984
- });
18454
+ if (toolPart == null) {
18455
+ toolParts.push({
18456
+ type: "tool-call",
18457
+ toolCallId: chunk.toolCallId,
18458
+ toolName: chunk.toolName,
18459
+ args: message.params || args,
18460
+ });
18461
+ }
18462
+ else {
18463
+ toolPart.args = message.params || args;
18464
+ toolPart = null;
18465
+ }
18985
18466
  break;
18986
18467
  }
18987
18468
  case "file": {
@@ -19004,7 +18485,7 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
19004
18485
  type: "error",
19005
18486
  error: chunk.error,
19006
18487
  }, agentContext);
19007
- throw new Error("Plan Error");
18488
+ throw new Error("LLM Error: " + chunk.error);
19008
18489
  }
19009
18490
  case "finish": {
19010
18491
  if (!textStreamDone) {
@@ -19019,6 +18500,18 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
19019
18500
  text: streamText,
19020
18501
  }, agentContext);
19021
18502
  }
18503
+ if (toolPart) {
18504
+ await streamCallback.onMessage({
18505
+ taskId: context.taskId,
18506
+ agentName: agentNode.name,
18507
+ nodeId: agentNode.id,
18508
+ type: "tool_use",
18509
+ toolId: toolPart.toolCallId,
18510
+ toolName: toolPart.toolName,
18511
+ params: toolPart.args || {},
18512
+ }, agentContext);
18513
+ toolPart = null;
18514
+ }
19022
18515
  await streamCallback.onMessage({
19023
18516
  taskId: context.taskId,
19024
18517
  agentName: agentNode.name,
@@ -19067,7 +18560,6 @@ class BaseChatAgent extends Agent {
19067
18560
 
19068
18561
  const PLAN_SYSTEM_TEMPLATE = `
19069
18562
  You are {name}, an autonomous AI Agent Planner.
19070
- Current datetime: {datetime}
19071
18563
 
19072
18564
  ## Task Description
19073
18565
  Your task is to understand the user's requirements, dynamically plan the user's tasks based on the Agent list, and please follow the steps below:
@@ -19084,7 +18576,9 @@ Your task is to understand the user's requirements, dynamically plan the user's
19084
18576
 
19085
18577
  ## Output Rules and Format
19086
18578
  <root>
18579
+ <!-- Task Name (Short) -->
19087
18580
  <name>Task Name</name>
18581
+ <!-- Need to break down the task into multi-agent collaboration. Please think step by step and output a detailed thought process. -->
19088
18582
  <thought>Your thought process on user demand planning</thought>
19089
18583
  <!-- Multiple Agents work together to complete the task -->
19090
18584
  <agents>
@@ -19147,15 +18641,12 @@ Output result:
19147
18641
  </agent>
19148
18642
  </agents>
19149
18643
  </root>`,
19150
- `User: Every morning, help me collect the latest AI news, summarize it, and send it to the "AI Daily Morning Report" group chat on WeChat.
18644
+ `User: Help me collect the latest AI news, summarize it, and send it to the "AI news information" group chat on WeChat.
19151
18645
  Output result:
19152
18646
  <root>
19153
- <name>AI Daily Morning Report</name>
19154
- <thought>OK, the user needs to collect the latest AI news every morning, summarize it, and send it to a WeChat group named "AI Daily Morning Report" This requires automation, including the steps of data collection, processing, and distribution.</thought>
18647
+ <name>Latest AI News</name>
18648
+ <thought>OK, users need to collect the latest AI news, summarize it, and send it to a WeChat group named "AI news information" This requires automation, including the steps of data collection, processing, and distribution.</thought>
19155
18649
  <agents>
19156
- <agent name="Timer">
19157
- <task>Timing: every morning</task>
19158
- </agent>
19159
18650
  <agent name="Browser">
19160
18651
  <task>Search for the latest updates on AI</task>
19161
18652
  <nodes>
@@ -19168,10 +18659,10 @@ Output result:
19168
18659
  </nodes>
19169
18660
  </agent>
19170
18661
  <agent name="Computer">
19171
- <task>Send a message to the WeChat group chat "AI Daily Morning Report"</task>
18662
+ <task>Send a message to the WeChat group chat "AI news information"</task>
19172
18663
  <nodes>
19173
18664
  <node>Open WeChat</node>
19174
- <node>Search for the "AI Daily Morning Report" chat group</node>
18665
+ <node>Search for the "AI news information" chat group</node>
19175
18666
  <node input="summaryInfo">Send summary message</node>
19176
18667
  </nodes>
19177
18668
  </agent>
@@ -19224,11 +18715,13 @@ Output result:
19224
18715
  ];
19225
18716
  const PLAN_USER_TEMPLATE = `
19226
18717
  User Platform: {platform}
18718
+ Current datetime: {datetime}
19227
18719
  Task Description: {task_prompt}
19228
18720
  `;
19229
18721
  const PLAN_USER_TASK_WEBSITE_TEMPLATE = `
19230
18722
  User Platform: {platform}
19231
18723
  Task Website: {task_website}
18724
+ Current datetime: {datetime}
19232
18725
  Task Description: {task_prompt}
19233
18726
  `;
19234
18727
  async function getPlanSystemPrompt(context) {
@@ -19247,32 +18740,33 @@ async function getPlanSystemPrompt(context) {
19247
18740
  .join("\n") +
19248
18741
  "\n</agent>\n\n";
19249
18742
  }
19250
- let example_prompt = "";
18743
+ let plan_example_list = context.variables.get("plan_example_list") || PLAN_EXAMPLE_LIST;
19251
18744
  let hasChatAgent = context.agents.filter((a) => a.Name == AGENT_NAME$5).length > 0;
18745
+ let example_prompt = "";
19252
18746
  const example_list = hasChatAgent
19253
- ? [PLAN_CHAT_EXAMPLE, ...PLAN_EXAMPLE_LIST]
19254
- : [...PLAN_EXAMPLE_LIST];
18747
+ ? [PLAN_CHAT_EXAMPLE, ...plan_example_list]
18748
+ : [...plan_example_list];
19255
18749
  for (let i = 0; i < example_list.length; i++) {
19256
18750
  example_prompt += `## Example ${i + 1}\n${example_list[i]}\n\n`;
19257
18751
  }
19258
18752
  return PLAN_SYSTEM_TEMPLATE.replace("{name}", config.name)
19259
18753
  .replace("{agents}", agents_prompt.trim())
19260
- .replace("{datetime}", new Date().toLocaleString())
19261
18754
  .replace("{example_prompt}", example_prompt)
19262
18755
  .trim();
19263
18756
  }
19264
18757
  function getPlanUserPrompt(task_prompt, task_website, ext_prompt) {
19265
18758
  let prompt = "";
19266
18759
  if (task_website) {
19267
- prompt = PLAN_USER_TASK_WEBSITE_TEMPLATE.replace("{task_prompt}", task_prompt)
19268
- .replace("{platform}", config.platform)
19269
- .replace("{task_website}", task_website);
18760
+ prompt = PLAN_USER_TASK_WEBSITE_TEMPLATE.replace("{task_website}", task_website);
19270
18761
  }
19271
18762
  else {
19272
- prompt = PLAN_USER_TEMPLATE.replace("{task_prompt}", task_prompt)
19273
- .replace("{platform}", config.platform);
18763
+ prompt = PLAN_USER_TEMPLATE;
19274
18764
  }
19275
- prompt = prompt.trim();
18765
+ prompt = prompt
18766
+ .replace("{task_prompt}", task_prompt)
18767
+ .replace("{platform}", config.platform)
18768
+ .replace("{datetime}", new Date().toLocaleString())
18769
+ .trim();
19276
18770
  if (ext_prompt) {
19277
18771
  prompt += `\n${ext_prompt.trim()}`;
19278
18772
  }
@@ -19312,7 +18806,8 @@ class Planner {
19312
18806
  messages = [
19313
18807
  {
19314
18808
  role: "system",
19315
- content: await getPlanSystemPrompt(this.context),
18809
+ content: this.context.variables.get("plan_sys_prompt") ||
18810
+ (await getPlanSystemPrompt(this.context)),
19316
18811
  },
19317
18812
  {
19318
18813
  role: "user",
@@ -19334,6 +18829,7 @@ class Planner {
19334
18829
  let result = await rlm.callStream(request);
19335
18830
  const reader = result.stream.getReader();
19336
18831
  let streamText = "";
18832
+ let thinkingText = "";
19337
18833
  try {
19338
18834
  while (true) {
19339
18835
  await this.context.checkAborted();
@@ -19343,14 +18839,17 @@ class Planner {
19343
18839
  }
19344
18840
  let chunk = value;
19345
18841
  if (chunk.type == "error") {
19346
- Log.error("Plan Error: ", chunk);
19347
- throw new Error("Plan Error");
18842
+ Log.error("Plan, LLM Error: ", chunk);
18843
+ throw new Error("LLM Error: " + chunk.error);
18844
+ }
18845
+ if (chunk.type == "reasoning") {
18846
+ thinkingText += chunk.textDelta || "";
19348
18847
  }
19349
18848
  if (chunk.type == "text-delta") {
19350
18849
  streamText += chunk.textDelta || "";
19351
18850
  }
19352
18851
  if (config.callback) {
19353
- let workflow = parseWorkflow(this.taskId, streamText, false);
18852
+ let workflow = parseWorkflow(this.taskId, streamText, false, thinkingText);
19354
18853
  if (workflow) {
19355
18854
  await config.callback.onMessage({
19356
18855
  taskId: this.taskId,
@@ -19369,7 +18868,7 @@ class Planner {
19369
18868
  }
19370
18869
  chain.planRequest = request;
19371
18870
  chain.planResult = streamText;
19372
- let workflow = parseWorkflow(this.taskId, streamText, true);
18871
+ let workflow = parseWorkflow(this.taskId, streamText, true, thinkingText);
19373
18872
  if (config.callback) {
19374
18873
  await config.callback.onMessage({
19375
18874
  taskId: this.taskId,
@@ -19509,22 +19008,28 @@ class Eko {
19509
19008
  }
19510
19009
  deleteTask(taskId) {
19511
19010
  this.abortTask(taskId);
19011
+ const context = this.taskMap.get(taskId);
19012
+ if (context) {
19013
+ context.variables.clear();
19014
+ }
19512
19015
  return this.taskMap.delete(taskId);
19513
19016
  }
19514
- abortTask(taskId) {
19017
+ abortTask(taskId, reason) {
19515
19018
  let context = this.taskMap.get(taskId);
19516
19019
  if (context) {
19517
19020
  context.paused = false;
19518
- context.controller.abort();
19021
+ this.onTaskStatus(context, "abort", reason);
19022
+ context.controller.abort(reason);
19519
19023
  return true;
19520
19024
  }
19521
19025
  else {
19522
19026
  return false;
19523
19027
  }
19524
19028
  }
19525
- pauseTask(taskId, paused) {
19029
+ pauseTask(taskId, paused, reason) {
19526
19030
  let context = this.taskMap.get(taskId);
19527
19031
  if (context) {
19032
+ this.onTaskStatus(context, paused ? "pause" : "resume-pause", reason);
19528
19033
  context.paused = paused;
19529
19034
  return true;
19530
19035
  }
@@ -19543,6 +19048,15 @@ class Eko {
19543
19048
  this.config.agents = this.config.agents || [];
19544
19049
  this.config.agents.push(agent);
19545
19050
  }
19051
+ async onTaskStatus(context, status, reason) {
19052
+ const [agent] = context.currentAgent() || [];
19053
+ if (agent) {
19054
+ const onTaskStatus = agent["onTaskStatus"];
19055
+ if (onTaskStatus) {
19056
+ await onTaskStatus.call(agent, status, reason);
19057
+ }
19058
+ }
19059
+ }
19546
19060
  }
19547
19061
 
19548
19062
  class SimpleSseMcpClient {
@@ -20337,6 +19851,120 @@ This is a computer GUI interface, observe the execution through screenshots, and
20337
19851
  }
20338
19852
  }
20339
19853
 
19854
+ function extract_page_content(max_url_length = 200) {
19855
+ let result = "";
19856
+ max_url_length = max_url_length || 200;
19857
+ try {
19858
+ function traverse(node) {
19859
+ if (node.nodeType === Node.ELEMENT_NODE) {
19860
+ const tagName = node.tagName.toLowerCase();
19861
+ if (["script", "style", "noscript"].includes(tagName)) {
19862
+ return;
19863
+ }
19864
+ const style = window.getComputedStyle(node);
19865
+ if (style.display == "none" ||
19866
+ style.visibility == "hidden" ||
19867
+ style.opacity == "0") {
19868
+ return;
19869
+ }
19870
+ }
19871
+ if (node.nodeType === Node.TEXT_NODE) {
19872
+ // text
19873
+ const text = node.textContent.trim();
19874
+ if (text) {
19875
+ result += text + " ";
19876
+ }
19877
+ }
19878
+ else if (node.nodeType === Node.ELEMENT_NODE) {
19879
+ const tagName = node.tagName.toLowerCase();
19880
+ if (["input", "select", "textarea"].includes(tagName)) {
19881
+ // input / select / textarea
19882
+ if (tagName == "input" && node.type == "checkbox") {
19883
+ result += node.checked + " ";
19884
+ }
19885
+ else if (tagName == "input" && node.type == "radio") {
19886
+ if (node.checked && node.value) {
19887
+ result += node.value + " ";
19888
+ }
19889
+ }
19890
+ else if (node.value) {
19891
+ result += node.value + " ";
19892
+ }
19893
+ }
19894
+ else if (tagName === "img") {
19895
+ // image
19896
+ const src = node.src ||
19897
+ node.getAttribute("src") ||
19898
+ node.getAttribute("data-src");
19899
+ const alt = node.alt || node.title || "";
19900
+ if (src &&
19901
+ src.length <= max_url_length &&
19902
+ node.width * node.height >= 10000 &&
19903
+ src.startsWith("http")) {
19904
+ result += `![${alt ? alt : "image"}](${src.trim()}) `;
19905
+ }
19906
+ }
19907
+ else if (tagName === "a" && node.children.length == 0) {
19908
+ // link
19909
+ const href = node.href || node.getAttribute("href");
19910
+ const text = node.innerText.trim() || node.title;
19911
+ if (text &&
19912
+ href &&
19913
+ href.length <= max_url_length &&
19914
+ href.startsWith("http")) {
19915
+ result += `[${text}](${href.trim()}) `;
19916
+ }
19917
+ else {
19918
+ result += text + " ";
19919
+ }
19920
+ }
19921
+ else if (tagName === "video" || tagName == "audio") {
19922
+ // video / audio
19923
+ let src = node.src || node.getAttribute("src");
19924
+ const sources = node.querySelectorAll("source");
19925
+ if (sources.length > 0 && sources[0].src) {
19926
+ src = sources[0].src;
19927
+ if (src && src.startsWith("http") && sources[0].type) {
19928
+ result += sources[0].type + " ";
19929
+ }
19930
+ }
19931
+ if (src && src.startsWith("http")) {
19932
+ result += src.trim() + " ";
19933
+ }
19934
+ }
19935
+ else if (tagName === "br") {
19936
+ // br
19937
+ result += "\n";
19938
+ }
19939
+ else if (["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"].includes(tagName)) {
19940
+ // block
19941
+ result += "\n";
19942
+ for (let child of node.childNodes) {
19943
+ traverse(child);
19944
+ }
19945
+ result += "\n";
19946
+ return;
19947
+ }
19948
+ else if (tagName === "hr") {
19949
+ // hr
19950
+ result += "\n--------\n";
19951
+ }
19952
+ else {
19953
+ // recursive
19954
+ for (let child of node.childNodes) {
19955
+ traverse(child);
19956
+ }
19957
+ }
19958
+ }
19959
+ }
19960
+ traverse(document.body);
19961
+ }
19962
+ catch (e) {
19963
+ result = document.body.innerText;
19964
+ }
19965
+ return result.replace(/\s*\n/g, "\n").replace(/\n+/g, "\n").trim();
19966
+ }
19967
+
20340
19968
  const AGENT_NAME = "Browser";
20341
19969
  class BaseBrowserAgent extends Agent {
20342
19970
  async go_back(agentContext) {
@@ -20349,22 +19977,17 @@ class BaseBrowserAgent extends Agent {
20349
19977
  catch (e) { }
20350
19978
  }
20351
19979
  async extract_page_content(agentContext, variable_name) {
20352
- let content = await this.execute_script(agentContext, () => {
20353
- let str = window.document.body.innerText
20354
- .replaceAll(/\n+/g, "\n")
20355
- .replaceAll(/ +/g, " ")
20356
- .trim();
20357
- if (str.length > 20000) {
20358
- str = str.substring(0, 20000) + "...";
20359
- }
20360
- return str;
20361
- }, []);
19980
+ let content = await this.execute_script(agentContext, extract_page_content, []);
20362
19981
  let pageInfo = await this.get_current_page(agentContext);
20363
19982
  let result = `title: ${pageInfo.title}\npage_url: ${pageInfo.url}\npage_content: \n${content}`;
20364
19983
  if (variable_name) {
20365
19984
  agentContext.context.variables.set(variable_name, result);
20366
19985
  }
20367
- return result;
19986
+ return {
19987
+ title: pageInfo.title || "",
19988
+ page_url: pageInfo.url,
19989
+ page_content: content,
19990
+ };
20368
19991
  }
20369
19992
  async controlMcpTools(agentContext, messages, loopNum) {
20370
19993
  if (loopNum > 0) {
@@ -21115,7 +20738,9 @@ class BaseBrowserLabelsAgent extends BaseBrowserAgent {
21115
20738
  - If stuck, try alternative approaches, don't refuse tasks
21116
20739
  - Handle popups/cookies by accepting or closing them
21117
20740
  * BROWSER OPERATION:
21118
- - Use scroll to find elements you are looking for, When extracting content, prioritize using extract_page_content, only scroll when you need to load more content`;
20741
+ - Use scroll to find elements you are looking for, When extracting content, prioritize using extract_page_content, only scroll when you need to load more content
20742
+ * During execution, please output user-friendly step information. Do not output element and index information to users, as this would cause user confusion.
20743
+ `;
21119
20744
  const _tools_ = [];
21120
20745
  super({
21121
20746
  name: AGENT_NAME,
@@ -21166,9 +20791,18 @@ class BaseBrowserLabelsAgent extends BaseBrowserAgent {
21166
20791
  }
21167
20792
  }
21168
20793
  if (extract_page_content) {
21169
- let page_content = await this.extract_page_content(agentContext);
21170
- return ("The current page content has been extracted, latest page content:\n" +
21171
- page_content);
20794
+ let page_result = await this.extract_page_content(agentContext);
20795
+ return {
20796
+ result: "The current page content has been extracted, latest page content:\n" +
20797
+ "title: " +
20798
+ page_result.title +
20799
+ "\n" +
20800
+ "page_url: " +
20801
+ page_result.page_url +
20802
+ "\n" +
20803
+ "page_content: " +
20804
+ page_result.page_content,
20805
+ };
21172
20806
  }
21173
20807
  }
21174
20808
  async hover_to_element(agentContext, index) {
@@ -21387,7 +21021,7 @@ class BaseBrowserLabelsAgent extends BaseBrowserAgent {
21387
21021
  },
21388
21022
  {
21389
21023
  name: "extract_page_content",
21390
- description: "Extract the text content of the current webpage, please use this tool to obtain webpage data.",
21024
+ description: "Extract the text content and image links of the current webpage, please use this tool to obtain webpage data.",
21391
21025
  parameters: {
21392
21026
  type: "object",
21393
21027
  properties: {},
@@ -21570,9 +21204,7 @@ class BaseBrowserLabelsAgent extends BaseBrowserAgent {
21570
21204
  if (eIdx == -1) {
21571
21205
  continue;
21572
21206
  }
21573
- line =
21574
- line.substring(0, sIdx) +
21575
- line.substring(eIdx + 1).trim();
21207
+ line = line.substring(0, sIdx) + line.substring(eIdx + 1).trim();
21576
21208
  }
21577
21209
  return line.replace('" >', '">').replace(" >", ">");
21578
21210
  })
@@ -21779,6 +21411,19 @@ function scroll_by(params) {
21779
21411
  const visibleHeight = visibleBottom - visibleTop;
21780
21412
  return visibleWidth * visibleHeight;
21781
21413
  }
21414
+ function getComputedZIndex(element) {
21415
+ while (element &&
21416
+ element !== document.body &&
21417
+ element !== document.body.parentElement) {
21418
+ const style = window.getComputedStyle(element);
21419
+ let zIndex = style.zIndex === "auto" ? 0 : parseInt(style.zIndex) || 0;
21420
+ if (zIndex > 0) {
21421
+ return zIndex;
21422
+ }
21423
+ element = element.parentElement;
21424
+ }
21425
+ return 0;
21426
+ }
21782
21427
  const scrollableElements = findScrollableElements();
21783
21428
  if (scrollableElements.length === 0) {
21784
21429
  const y = Math.max(20, Math.min((window.innerHeight || documentElement.clientHeight) / 10, 200));
@@ -21786,7 +21431,21 @@ function scroll_by(params) {
21786
21431
  return false;
21787
21432
  }
21788
21433
  const sortedElements = scrollableElements.sort((a, b) => {
21789
- return getVisibleArea(b) - getVisibleArea(a);
21434
+ let z = getComputedZIndex(b) - getComputedZIndex(a);
21435
+ if (z > 0) {
21436
+ return 1;
21437
+ }
21438
+ else if (z < 0) {
21439
+ return -1;
21440
+ }
21441
+ let v = getVisibleArea(b) - getVisibleArea(a);
21442
+ if (v > 0) {
21443
+ return 1;
21444
+ }
21445
+ else if (v < 0) {
21446
+ return -1;
21447
+ }
21448
+ return 0;
21790
21449
  });
21791
21450
  const largestElement = sortedElements[0];
21792
21451
  const viewportHeight = largestElement.clientHeight;
@@ -21969,7 +21628,7 @@ class BaseBrowserScreenAgent extends BaseBrowserAgent {
21969
21628
  },
21970
21629
  {
21971
21630
  name: "extract_page_content",
21972
- description: "Extract the text content of the current webpage, please use this tool to obtain webpage data.",
21631
+ description: "Extract the text content and image links of the current webpage, please use this tool to obtain webpage data.",
21973
21632
  parameters: {
21974
21633
  type: "object",
21975
21634
  properties: {},
@@ -22104,5 +21763,5 @@ class BaseBrowserScreenAgent extends BaseBrowserAgent {
22104
21763
  }
22105
21764
  }
22106
21765
 
22107
- export { Agent, AgentChain, AgentContext, BaseBrowserAgent, BaseBrowserLabelsAgent, BaseBrowserScreenAgent, BaseChatAgent, BaseComputerAgent, BaseFileAgent, BaseShellAgent, BaseTimerAgent, Chain, Context, Eko, ForeachTaskTool, HumanInteractTool, Log, RetryLanguageModel, SimpleSseMcpClient, TaskNodeStatusTool, VariableStorageTool, WatchTriggerTool, call_timeout, config, convertToolSchema, Eko as default, mergeTools, toImage, uuidv4 };
21766
+ export { Agent, AgentChain, AgentContext, BaseBrowserAgent, BaseBrowserLabelsAgent, BaseBrowserScreenAgent, BaseChatAgent, BaseComputerAgent, BaseFileAgent, BaseShellAgent, BaseTimerAgent, Chain, Context, Eko, ForeachTaskTool, HumanInteractTool, Log, RetryLanguageModel, SimpleSseMcpClient, TaskNodeStatusTool, VariableStorageTool, WatchTriggerTool, call_timeout, config, convertToolSchema, Eko as default, extract_page_content, mergeTools, toImage, uuidv4 };
22108
21767
  //# sourceMappingURL=index.esm.js.map